lazyclaw 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.ko.md +88 -25
  2. package/README.md +121 -190
  3. package/channels/handoff.mjs +18 -5
  4. package/channels/matrix.mjs +23 -5
  5. package/channels/slack.mjs +83 -50
  6. package/channels/slack_env.mjs +45 -0
  7. package/channels/telegram.mjs +49 -6
  8. package/channels-discord/index.mjs +76 -0
  9. package/channels-discord/package.json +14 -0
  10. package/channels-email/index.mjs +109 -0
  11. package/channels-email/package.json +14 -0
  12. package/channels-signal/index.mjs +69 -0
  13. package/channels-signal/package.json +9 -0
  14. package/channels-voice/index.mjs +81 -0
  15. package/channels-voice/package.json +9 -0
  16. package/channels-whatsapp/index.mjs +70 -0
  17. package/channels-whatsapp/package.json +13 -0
  18. package/cli.mjs +10 -21
  19. package/commands/agents.mjs +669 -0
  20. package/commands/auth_nodes.mjs +323 -0
  21. package/commands/automation.mjs +582 -0
  22. package/commands/channels.mjs +254 -0
  23. package/commands/chat.mjs +1253 -0
  24. package/commands/config.mjs +315 -0
  25. package/commands/daemon.mjs +275 -0
  26. package/commands/gateway.mjs +194 -0
  27. package/commands/misc.mjs +128 -0
  28. package/commands/providers.mjs +490 -0
  29. package/commands/service.mjs +113 -0
  30. package/commands/sessions.mjs +343 -0
  31. package/commands/setup.mjs +742 -0
  32. package/commands/setup_channels.mjs +207 -0
  33. package/commands/skills.mjs +218 -0
  34. package/commands/workflow.mjs +661 -0
  35. package/config_features.mjs +106 -0
  36. package/daemon/lib/auth.mjs +58 -0
  37. package/daemon/lib/cost.mjs +30 -0
  38. package/daemon/lib/inbound_dedup.mjs +108 -0
  39. package/daemon/lib/learn_queue.mjs +46 -0
  40. package/daemon/lib/provider.mjs +69 -0
  41. package/daemon/lib/respond.mjs +83 -0
  42. package/daemon/route_table.mjs +96 -0
  43. package/daemon/routes/_deps.mjs +42 -0
  44. package/daemon/routes/config.mjs +99 -0
  45. package/daemon/routes/conversation.mjs +435 -0
  46. package/daemon/routes/meta.mjs +239 -0
  47. package/daemon/routes/ops.mjs +165 -0
  48. package/daemon/routes/providers.mjs +211 -0
  49. package/daemon/routes/rates.mjs +90 -0
  50. package/daemon/routes/registry.mjs +223 -0
  51. package/daemon/routes/sessions.mjs +213 -0
  52. package/daemon/routes/skills.mjs +260 -0
  53. package/daemon/routes/workflows.mjs +224 -0
  54. package/dotenv_min.mjs +51 -0
  55. package/first_run.mjs +24 -0
  56. package/goals_cron.mjs +37 -0
  57. package/lib/args.mjs +216 -0
  58. package/lib/config.mjs +113 -0
  59. package/lib/gateway_guard.mjs +100 -0
  60. package/lib/inbound_client.mjs +108 -0
  61. package/lib/registry_boot.mjs +55 -0
  62. package/lib/service_install.mjs +207 -0
  63. package/package.json +15 -3
  64. package/providers/probe.mjs +28 -0
  65. package/secure_write.mjs +46 -0
  66. package/tui/editor.mjs +18 -2
  67. package/tui/repl.mjs +25 -4
  68. package/tui/slash_commands.mjs +4 -0
  69. package/tui/slash_dispatcher.mjs +118 -0
  70. package/tui/splash_props.mjs +52 -0
  71. package/web/dashboard.css +6 -12
  72. package/web/dashboard.html +2 -34
  73. package/web/dashboard.js +3 -3
@@ -0,0 +1,1253 @@
1
+ // commands/chat.mjs — interactive chat REPL (cmdChat), extracted from cli.mjs (D7).
2
+ // Verbatim move: the Ink/React path, the readline loop, and in-chat slash
3
+ // handling are unchanged. Only dynamic-import paths were rebased ./ -> ../,
4
+ // and the single cmdSetup call now lazy-imports ./setup.mjs so the
5
+ // chat <-> setup cycle is broken at the dynamic-import boundary.
6
+ import path from 'node:path';
7
+ import {
8
+ configPath, readConfig, writeConfig,
9
+ _resolveAuthKey, _resolveBaseUrl, readVersionFromRepo,
10
+ } from '../lib/config.mjs';
11
+ import { ensureRegistry, requireRegistry, getRegistry } from '../lib/registry_boot.mjs';
12
+ import { SUBCOMMANDS, parseArgs, AGENT_REG_SUBS } from '../lib/args.mjs';
13
+ import {
14
+ _attachGhostAutocomplete, _fetchModelsForProvider, _pauseChatForSubMenu,
15
+ _pickModelInteractive, _pickProviderInteractive, _printChatBanner,
16
+ _quickPrompt, _renderBanner, _renderV5Banner,
17
+ } from '../tui/pickers.mjs';
18
+ import { firstRunMode as _firstRunMode, hasConfiguredProvider } from '../first_run.mjs';
19
+ import { applyChatWindow as _applyChatWindow, CHAT_WINDOW_TURNS, CHAT_WINDOW_TOKEN_BUDGET } from '../chat_window.mjs';
20
+ import { makeRunTurn as _chatRunTurnFactory } from '../tui/run_turn.mjs';
21
+ import { dispatchSlash as _dispatchSlash, parseSlashLine as _parseSlashLine } from '../tui/slash_dispatcher.mjs';
22
+ import { SLASH_COMMANDS } from '../tui/slash_commands.mjs';
23
+
24
+ // Legacy (non-Ink) slash routing for dispatcher-style, ctx-only commands.
25
+ // The Ink REPL routes every slash through _dispatchSlash/SLASH_HANDLERS, but
26
+ // the legacy readline path uses a hand-written switch (in cmdChat). Commands
27
+ // like /config only mutate ctx and return a sentinel, so we keep that wiring
28
+ // in one exported helper that BOTH the legacy switch and the regression test
29
+ // drive — this is the seam that proves /config reaches setup on the legacy
30
+ // path (the post-loop guard re-runs cmdSetup when ctx.requestSetup is set).
31
+ // Returns 'EXIT' when the loop must break, or undefined when the command is
32
+ // not one this helper owns (caller falls through to its own handling).
33
+ export function legacySlashRoute(cmd, ctx) {
34
+ switch (cmd) {
35
+ case '/config':
36
+ // Mirror tui/slash_dispatcher.mjs '/config': signal the host, unmount.
37
+ ctx.requestSetup = true;
38
+ return 'EXIT';
39
+ default:
40
+ return undefined;
41
+ }
42
+ }
43
+
44
+ // Dispatcher commands the legacy readline path's default branch may delegate to
45
+ // _dispatchSlash. Kept to ctx-safe handlers only (no _inkCtx-only setters /
46
+ // openPicker / version), so legacy doesn't silently degrade. /channels has a
47
+ // lib/config fallback so it's safe; add others only after confirming ctx-safety.
48
+ const LEGACY_DELEGATED_SLASHES = new Set(['/channels', '/orchestrator', '/context']);
49
+
50
+ export async function cmdChat(flags = {}) {
51
+ await ensureRegistry();
52
+ const sessionsMod = await import('../sessions.mjs');
53
+ const skillsMod = await import('../skills.mjs');
54
+ let cfg = readConfig();
55
+ // Mutable in-REPL state: /provider and /model edit these without
56
+ // touching config.json on disk. The CLI flag form (`chat --provider X`)
57
+ // would normally seed these via cfg, but we leave that to a future
58
+ // iteration; today the slash commands work against the on-disk default.
59
+ let activeProvName = cfg.provider || '';
60
+ let activeModel = cfg.model || null;
61
+ const lookupProv = (name) => getRegistry().PROVIDERS[name];
62
+ // First-run routing: a genuine fresh install (no provider, interactive)
63
+ // gets the full 5-step guided setup (provider+model, workspace, skills) —
64
+ // not just the provider picker. `chat --pick` stays a lightweight re-pick.
65
+ const _mode = _firstRunMode({
66
+ hasProvider: hasConfiguredProvider(activeProvName),
67
+ flagPick: !!flags.pick,
68
+ isTTY: !!process.stdin.isTTY,
69
+ });
70
+ if (_mode === 'setup') {
71
+ try { await (await import('./setup.mjs')).cmdSetup(undefined, [], {}); }
72
+ catch (e) { if (process.env.LAZYCLAW_DEBUG) console.error('[setup] fell through:', e?.message); }
73
+ // Re-read the config the wizard just wrote so this session uses it.
74
+ cfg = readConfig();
75
+ activeProvName = cfg.provider || activeProvName;
76
+ activeModel = cfg.model || activeModel;
77
+ } else if (_mode === 'pick') {
78
+ const picked = await _pickProviderInteractive();
79
+ if (picked && picked.provider) {
80
+ activeProvName = picked.provider;
81
+ if (picked.model) activeModel = picked.model;
82
+ }
83
+ }
84
+ // Last-resort safety net. v5.3.2 stopped falling through to 'mock' (which
85
+ // silently degraded a wiped config into garbage replies); default to the
86
+ // keyless claude-cli, but say so instead of switching silently.
87
+ if (!activeProvName) {
88
+ if (process.stdout.isTTY) {
89
+ process.stdout.write(' setup not completed — defaulting to claude-cli (keyless subscription). Run `lazyclaw setup` to configure a provider/model, workspace, and skills.\n');
90
+ }
91
+ activeProvName = 'claude-cli';
92
+ }
93
+ let prov = lookupProv(activeProvName);
94
+ if (!prov) { console.error(`unknown provider: ${activeProvName}`); process.exit(2); }
95
+
96
+ // Top-of-session banner so the user can see at a glance what they're
97
+ // talking to. Cheap (no provider call) and TTY-only.
98
+ // v5 ink splash + REPL when stdin is a real TTY and the user has not
99
+ // opted out via LAZYCLAW_NO_INK=1. Non-TTY pipelines and the opt-out
100
+ // env var fall through to the v4 figlet + readline path unchanged.
101
+ const __useInkSplash = process.stdout.isTTY && !process.env.LAZYCLAW_NO_INK;
102
+ if (__useInkSplash) {
103
+ try {
104
+ const React = (await import('react')).default;
105
+ const { render } = await import('ink');
106
+ const { ReplApp } = await import('../tui/repl.mjs');
107
+ const { renderSplashToString } = await import('../tui/splash.mjs');
108
+ // narrow-terminal fallback: <60 cols falls back to v4
109
+ if ((process.stdout.columns || 80) < 60) throw new Error('narrow-terminal');
110
+
111
+ // Tool + skill groups for the splash panel — shared with the setup
112
+ // wizard via tui/splash_props.mjs so both surfaces render the same panel.
113
+ const { gatherToolAndSkillGroups } = await import('../tui/splash_props.mjs');
114
+ const { tools: toolGroups, skills: skillGroups } =
115
+ await gatherToolAndSkillGroups(path.dirname(configPath()));
116
+
117
+ const splashProps = {
118
+ provider: activeProvName, model: activeModel,
119
+ trainer: {}, sessionId: flags.session || '',
120
+ cwd: process.cwd(),
121
+ version: readVersionFromRepo(),
122
+ tools: toolGroups,
123
+ skills: skillGroups,
124
+ };
125
+ void renderSplashToString; // surfaced for tests; runtime uses <Splash/>
126
+
127
+ // C7 — minimal chat-session state for the ink path so runTurn can
128
+ // talk to the provider (the legacy readline path below sets up the
129
+ // same shape — kept duplicated here intentionally so the ink branch
130
+ // remains self-contained and the legacy path stays byte-identical).
131
+ // Slash commands aren't wired into the ink REPL yet (v5.1 follow-up);
132
+ // until then, system-prompt composition / --session resume happen
133
+ // identically to the legacy path.
134
+ let _inkSandboxSpec = null;
135
+ if (flags.sandbox) {
136
+ const sb = await import('../sandbox.mjs');
137
+ try { _inkSandboxSpec = sb.parseSandboxSpec(flags.sandbox, flags); }
138
+ catch (err) { console.error(`error: ${err.message}`); process.exit(2); }
139
+ }
140
+ let _inkSessionId = flags.session || null;
141
+ const _inkCfgDir = path.dirname(configPath());
142
+ let _inkMessages = _inkSessionId
143
+ ? sessionsMod.loadTurns(_inkSessionId, _inkCfgDir).map((t) => ({ role: t.role, content: t.content }))
144
+ : [];
145
+ if (_inkMessages.length > 0) {
146
+ const cfgChat = cfg.chat || {};
147
+ const winTurns = Number(cfgChat.windowTurns) || CHAT_WINDOW_TURNS;
148
+ const winTokens = Number(cfgChat.windowTokens) || CHAT_WINDOW_TOKEN_BUDGET;
149
+ const { messages: trimmed } = _applyChatWindow(_inkMessages, { turns: winTurns, tokens: winTokens });
150
+ _inkMessages = trimmed;
151
+ }
152
+ // System prompt composition — mirrors the legacy path's sysParts logic.
153
+ const _inkSkillNames = (flags.skill ? String(flags.skill) : (Array.isArray(cfg.skills) ? cfg.skills.join(',') : ''))
154
+ .split(',').map((s) => s.trim()).filter(Boolean);
155
+ const _inkWorkspaceName = flags.workspace || cfg.workspace || '';
156
+ const _inkSysParts = [];
157
+ try {
158
+ const { composePromptStack } = await import('../mas/prompt_stack.mjs');
159
+ const stacked = composePromptStack({
160
+ cfgDir: _inkCfgDir,
161
+ agent: { name: 'chat', role: '' },
162
+ workspace: _inkWorkspaceName,
163
+ });
164
+ if (stacked && stacked.trim()) _inkSysParts.push(stacked);
165
+ } catch { /* never block chat start on stack composition */ }
166
+ if (_inkWorkspaceName && !_inkMessages.some((m) => m.role === 'system')) {
167
+ try {
168
+ const ws = await import('../workspace.mjs');
169
+ const wsPrompt = ws.composeWorkspacePrompt(_inkCfgDir, _inkWorkspaceName);
170
+ if (wsPrompt) _inkSysParts.push(wsPrompt);
171
+ } catch (err) { console.error(`workspace error: ${err.message}`); process.exit(2); }
172
+ }
173
+ if (_inkSkillNames.length > 0 && !_inkMessages.some((m) => m.role === 'system')) {
174
+ try {
175
+ const sys = skillsMod.composeSystemPrompt(_inkSkillNames, _inkCfgDir);
176
+ if (sys) _inkSysParts.push(sys);
177
+ } catch (err) { console.error(`skill error: ${err.message}`); process.exit(2); }
178
+ }
179
+ if (_inkSysParts.length && !_inkMessages.some((m) => m.role === 'system')) {
180
+ const merged = _inkSysParts.join('\n\n---\n\n');
181
+ _inkMessages.unshift({ role: 'system', content: merged });
182
+ if (_inkSessionId) sessionsMod.appendTurn(_inkSessionId, 'system', merged, _inkCfgDir);
183
+ }
184
+ let _inkRunningUsage = null;
185
+ const _inkAccumulateUsage = (u) => {
186
+ if (!u) return;
187
+ if (!_inkRunningUsage) _inkRunningUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0, turnsWithUsage: 0 };
188
+ _inkRunningUsage.inputTokens += Number(u.inputTokens) || 0;
189
+ _inkRunningUsage.outputTokens += Number(u.outputTokens) || 0;
190
+ _inkRunningUsage.totalTokens += Number(u.totalTokens) || ((Number(u.inputTokens) || 0) + (Number(u.outputTokens) || 0));
191
+ _inkRunningUsage.turnsWithUsage += 1;
192
+ };
193
+ const _inkChatStartedAt = Date.now();
194
+ const _inkSyntheticChatSessionId = `chat-${process.pid}-${_inkChatStartedAt}`;
195
+ const _inkPersistTurn = (role, content) => {
196
+ if (_inkSessionId) {
197
+ sessionsMod.appendTurn(_inkSessionId, role, content, _inkCfgDir);
198
+ return;
199
+ }
200
+ try {
201
+ import('../memory.mjs').then((m) => {
202
+ try { m.appendRecent(_inkSyntheticChatSessionId, role, content, _inkCfgDir); }
203
+ catch { /* swallow */ }
204
+ }).catch(() => {});
205
+ } catch { /* swallow */ }
206
+ };
207
+ // v5.4: chars-sent counter for the Ink chat path. Mirrors the legacy
208
+ // path's `charsSent` so /usage in Ink reports the same number.
209
+ let _inkCharsSent = 0;
210
+ const _inkCtx = {
211
+ cfg,
212
+ cfgDir: _inkCfgDir,
213
+ sandboxSpec: _inkSandboxSpec,
214
+ syntheticChatSessionId: _inkSyntheticChatSessionId,
215
+ version: readVersionFromRepo(),
216
+ registryMod: getRegistry(),
217
+ sessionsMod,
218
+ // Pre-imported so dispatcher avoids a dynamic import per /skill call.
219
+ skillsMod,
220
+ getMessages: () => _inkMessages,
221
+ setMessages: (next) => { _inkMessages = Array.isArray(next) ? next : []; },
222
+ getProv: () => prov,
223
+ setProv: (next) => { prov = next; },
224
+ getActiveProvName: () => activeProvName,
225
+ setActiveProvName: (name) => { activeProvName = name; },
226
+ getActiveModel: () => activeModel,
227
+ setActiveModel: (name) => { activeModel = name; },
228
+ getSessionId: () => _inkSessionId,
229
+ setSessionId: (id) => { _inkSessionId = id; },
230
+ getCharsSent: () => _inkCharsSent,
231
+ setCharsSent: (n) => { _inkCharsSent = Number(n) || 0; },
232
+ getRunningUsage: () => _inkRunningUsage,
233
+ setRunningUsage: (u) => { _inkRunningUsage = u; },
234
+ persistTurn: _inkPersistTurn,
235
+ accumulateUsage: _inkAccumulateUsage,
236
+ resolveAuthKey: (providerName) => _resolveAuthKey(cfg, providerName),
237
+ resolveBaseUrl: (providerName) => _resolveBaseUrl(providerName),
238
+ onCharsSent: (n) => { _inkCharsSent += Number(n) || 0; },
239
+ // P2 — let /provider add register a custom OpenAI-compatible endpoint
240
+ // by read-merge-writing config.json from inside the Ink session.
241
+ readConfig: () => readConfig(),
242
+ writeConfig: (next) => writeConfig(next),
243
+ };
244
+ // v5.4.3 — ReplApp exposes an openPicker(opts) → Promise<id|null>
245
+ // via this ref. The slash dispatcher reads it through ctx.openPicker
246
+ // to drive /provider, /model, /personality without forking off raw
247
+ // stdin from Ink. When ReplApp hasn't populated the ref yet (early
248
+ // mount / non-Ink path) the dispatcher falls back to its hint
249
+ // string so users aren't stranded.
250
+ const _inkPickerRef = { current: null };
251
+ _inkCtx.openPicker = (opts) => {
252
+ const api = _inkPickerRef.current;
253
+ return api && typeof api.openPicker === 'function'
254
+ ? api.openPicker(opts)
255
+ : Promise.resolve(null);
256
+ };
257
+ // Route streamed chunks through ReplApp's injected writeFn: chunks
258
+ // land in React state (liveAssistant) → live region → committed to
259
+ // the <Static/> scrollback on turn-complete, so Ink owns all output.
260
+ // Writing straight to process.stdout (the old v5.1 hack) put replies
261
+ // in Ink's live frame, which the next render erased — replies vanished.
262
+ const _inkRunTurnFactory = (writeFn) => _chatRunTurnFactory({
263
+ ctx: _inkCtx,
264
+ writeFn,
265
+ });
266
+ // v5.4: full slash-command dispatch via tui/slash_dispatcher.mjs.
267
+ // Dispatcher returns a string (rendered to scrollback by ReplApp),
268
+ // 'EXIT' (caller unmounts), or void (streamed via write). /exit and
269
+ // /quit are also intercepted earlier inside ReplApp.handleSubmit so
270
+ // either path terminates cleanly.
271
+ const _inkSlashHandler = async (line, signal) => {
272
+ const { cmd, args } = _parseSlashLine(line);
273
+ // Thread the REPL's abort signal so Esc/Ctrl-C can stop a /loop.
274
+ _inkCtx.loopSignal = signal || null;
275
+ return _dispatchSlash(cmd, args, _inkCtx, (chunk) => {
276
+ try { process.stdout.write(chunk); } catch { /* swallow */ }
277
+ });
278
+ };
279
+ // v5.4.1: splash renders INSIDE the alt-buffer (not pre-printed to
280
+ // primary). The v5.4.0 pre-print made the screen go blank during
281
+ // chat because alt-buffer cleared it on enter. Splash lives in the
282
+ // Static scrollback now regardless of alt-buffer state.
283
+ const ink = render(/* @__PURE__ */ React.createElement(ReplApp, {
284
+ splashProps,
285
+ statusInfo: { provider: activeProvName, model: activeModel },
286
+ // P3 — live status: read the current provider/model + token gauge so
287
+ // the StatusBar refreshes after a /provider or /model switch and each
288
+ // turn, instead of showing the values captured at mount.
289
+ getStatus: () => ({
290
+ provider: activeProvName,
291
+ model: activeModel,
292
+ ctxUsed: _inkRunningUsage ? _inkRunningUsage.totalTokens : undefined,
293
+ ctxTotal: Number((cfg.chat || {}).windowTokens) || CHAT_WINDOW_TOKEN_BUDGET,
294
+ }),
295
+ runTurnFactory: _inkRunTurnFactory,
296
+ onSlashCommand: _inkSlashHandler,
297
+ pickerRef: _inkPickerRef,
298
+ }), { exitOnCtrlC: true, patchConsole: true });
299
+ await ink.waitUntilExit();
300
+ // /config asks to (re)run the wizard: now that Ink has released stdin,
301
+ // run setup, then return to the shell (re-launch `lazyclaw` to chat).
302
+ if (_inkCtx.requestSetup) await (await import('./setup.mjs')).cmdSetup(undefined, [], {});
303
+ return;
304
+ } catch (e) {
305
+ // Fall through to legacy path on any ink failure (missing import,
306
+ // narrow terminal, sandboxed stdout).
307
+ if (process.env.LAZYCLAW_DEBUG) console.error('[ink] fallback:', e.message);
308
+ }
309
+ }
310
+ // ─── legacy v4 path (unchanged) ─────────────────────────────────
311
+ _printChatBanner(activeProvName, activeModel, readVersionFromRepo());
312
+
313
+ const readline = await import('node:readline');
314
+ // Use terminal:true when we're attached to a TTY so the prompt shows
315
+ // and ghost-text autocomplete (below) can render. Falls back to the
316
+ // plain non-terminal mode for piped/non-TTY callers.
317
+ const useTerminal = !!process.stdin.isTTY;
318
+ // The readline interface is created *adjacent* to the for-await loop below
319
+ // (after all the async setup), not here. On node 20 a piped (non-TTY)
320
+ // stdin emits its lines + EOF during the `await import(...)` setup that
321
+ // runs before the loop; if the interface already exists, the async
322
+ // iterator hasn't attached yet and those lines are dropped — the chat
323
+ // produced no output on Linux CI (node 20) while passing on macOS (node
324
+ // 22, which tolerates the gap). Declaring rl/_ghost here keeps handleSlash's
325
+ // closures resolvable; the actual createInterface happens just-in-time.
326
+ let rl;
327
+ let _ghost = { dispose: () => {}, suspend: () => {}, resume: () => {} };
328
+
329
+ // --sandbox docker:<image> wraps subprocess-providers (claude-cli)
330
+ // in a docker container. Parsed once up front so a slash-command
331
+ // model switch doesn't have to re-parse every turn.
332
+ let sandboxSpec = null;
333
+ if (flags.sandbox) {
334
+ const sb = await import('../sandbox.mjs');
335
+ try { sandboxSpec = sb.parseSandboxSpec(flags.sandbox, flags); }
336
+ catch (e) { console.error(`error: ${e.message}`); process.exit(2); }
337
+ }
338
+
339
+ // Persistent session ID. When --session is set we hydrate prior turns from
340
+ // <configDir>/sessions/<id>.jsonl and append every new turn back to it.
341
+ // Without --session, chat is in-memory only (matches phase 4 behavior).
342
+ // Mutable so /goal <name> can switch the working context mid-session.
343
+ let sessionId = flags.session || null;
344
+ // Currently-active goal name when the user has switched context via
345
+ // /goal <name>. Tracked so /status can surface it and so future ticks
346
+ // know which goal to attribute new turns to.
347
+ let activeGoalName = null;
348
+ const cfgDir = path.dirname(configPath());
349
+ let messages = sessionId
350
+ ? sessionsMod.loadTurns(sessionId, cfgDir).map(t => ({ role: t.role, content: t.content }))
351
+ : [];
352
+
353
+ // M6 — apply sliding window at session start. Long-running sessions
354
+ // (50+ turns) used to ship every prior turn to the provider every
355
+ // request; we now keep at most CHAT_WINDOW_TURNS turns (default 20)
356
+ // plus the system message. Operators can override via env. The
357
+ // per-session log on disk is untouched — only the in-memory prompt
358
+ // window is trimmed. We log to stderr once at session start so the
359
+ // user knows context was dropped.
360
+ if (messages.length > 0) {
361
+ const cfgChat = cfg.chat || {};
362
+ const winTurns = Number(cfgChat.windowTurns) || CHAT_WINDOW_TURNS;
363
+ const winTokens = Number(cfgChat.windowTokens) || CHAT_WINDOW_TOKEN_BUDGET;
364
+ const { messages: trimmed, dropped } = _applyChatWindow(messages, { turns: winTurns, tokens: winTokens });
365
+ if (dropped > 0) {
366
+ process.stderr.write(`[chat] sliding window: dropped ${dropped} older turn(s), ${trimmed.length} kept\n`);
367
+ }
368
+ messages = trimmed;
369
+ }
370
+
371
+ // --skill (comma-separated names) composes into a system message at the
372
+ // head of the conversation. Same shape as `agent --skill`. Defaults from
373
+ // config.skills array when --skill not passed. We only inject if no
374
+ // system message is already present (so resuming a session doesn't
375
+ // double-prepend skills that the prior invocation already added).
376
+ const skillNames = (flags.skill ? String(flags.skill) : (Array.isArray(cfg.skills) ? cfg.skills.join(',') : ''))
377
+ .split(',').map(s => s.trim()).filter(Boolean);
378
+ // --workspace <name> sits at the head of the system prompt, then
379
+ // any --skill block. The two compose with the same `\n---\n`
380
+ // separator the agent path uses, so `lazyclaw workspace show` is
381
+ // a faithful preview.
382
+ const workspaceName = flags.workspace || cfg.workspace || '';
383
+ const sysParts = [];
384
+ // v5 (canonical decision C5) — prepend the 8-layer composePromptStack
385
+ // output. Falls back silently to no-op when the configDir has none of
386
+ // the source files present (fresh install) so chat-start stays
387
+ // byte-identical to the v4 shape until a user authors USER.md or a
388
+ // personality. Wrapped in try/catch — chat start must never break on
389
+ // a stack composition error.
390
+ try {
391
+ const { composePromptStack } = await import('../mas/prompt_stack.mjs');
392
+ const stacked = composePromptStack({
393
+ cfgDir,
394
+ agent: { name: 'chat', role: '' },
395
+ workspace: workspaceName,
396
+ });
397
+ if (stacked && stacked.trim()) sysParts.push(stacked);
398
+ } catch { /* never block chat start on stack composition */ }
399
+ if (workspaceName && !messages.some(m => m.role === 'system')) {
400
+ try {
401
+ const ws = await import('../workspace.mjs');
402
+ const wsPrompt = ws.composeWorkspacePrompt(cfgDir, workspaceName);
403
+ if (wsPrompt) sysParts.push(wsPrompt);
404
+ } catch (e) { console.error(`workspace error: ${e.message}`); process.exit(2); }
405
+ }
406
+ if (skillNames.length > 0 && !messages.some(m => m.role === 'system')) {
407
+ try {
408
+ const sys = skillsMod.composeSystemPrompt(skillNames, cfgDir);
409
+ if (sys) sysParts.push(sys);
410
+ } catch (e) {
411
+ console.error(`skill error: ${e.message}`);
412
+ process.exit(2);
413
+ }
414
+ }
415
+ if (sysParts.length && !messages.some(m => m.role === 'system')) {
416
+ const merged = sysParts.join('\n\n---\n\n');
417
+ messages.unshift({ role: 'system', content: merged });
418
+ if (sessionId) sessionsMod.appendTurn(sessionId, 'system', merged, cfgDir);
419
+ }
420
+
421
+ let charsSent = messages.reduce((n, m) => n + (m.role === 'user' ? String(m.content || '').length : 0), 0);
422
+ if (sessionId && messages.length > (skillNames.length > 0 ? 1 : 0)) {
423
+ process.stdout.write(`resumed session ${sessionId} with ${messages.length} prior turn(s)\n`);
424
+ }
425
+ // Running usage accumulator. /usage reports both the cheap local
426
+ // estimate (messageCount + charsSent) AND the provider-reported
427
+ // totals when the provider emits them on each turn. Mock provider
428
+ // doesn't emit usage, so usage stays null there — no surprise.
429
+ /** @type {{ inputTokens: number, outputTokens: number, totalTokens: number, turnsWithUsage: number } | null} */
430
+ let runningUsage = null;
431
+ const accumulateUsage = (u) => {
432
+ if (!u) return;
433
+ if (!runningUsage) runningUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0, turnsWithUsage: 0 };
434
+ runningUsage.inputTokens += Number(u.inputTokens) || 0;
435
+ runningUsage.outputTokens += Number(u.outputTokens) || 0;
436
+ runningUsage.totalTokens += Number(u.totalTokens) || ((Number(u.inputTokens) || 0) + (Number(u.outputTokens) || 0));
437
+ runningUsage.turnsWithUsage += 1;
438
+ };
439
+ // v5 Group A (M2): always-on synthetic session id so an unsessioned
440
+ // chat still populates memory/recent.jsonl. Without this, the nudge
441
+ // loop never saw repeated prompts in chat sessions that didn't pass
442
+ // --session, and `nudge.suggest_skill` clusters silently lost ~95%
443
+ // of their evidence. The `chat-<pid>-<startTs>` prefix keeps the
444
+ // synthetic id distinguishable from real session ids on disk.
445
+ const chatStartedAt = Date.now();
446
+ const _syntheticChatSessionId = `chat-${process.pid}-${chatStartedAt}`;
447
+ const persistTurn = (role, content) => {
448
+ if (sessionId) {
449
+ sessionsMod.appendTurn(sessionId, role, content, cfgDir);
450
+ return;
451
+ }
452
+ // No --session: don't touch sessions/<id>.jsonl, but DO append to
453
+ // memory/recent.jsonl directly so the nudge loop can cluster on
454
+ // unsessioned chats. Best-effort — a broken memory module must not
455
+ // break a chat turn.
456
+ try {
457
+ import('../memory.mjs').then((m) => {
458
+ try { m.appendRecent(_syntheticChatSessionId, role, content, cfgDir); }
459
+ catch { /* swallow */ }
460
+ }).catch(() => {});
461
+ } catch { /* swallow */ }
462
+ };
463
+
464
+ // C7 — shared runTurn closure for the legacy path. The same factory
465
+ // backs the ink path above; both call sites get one set of bugs.
466
+ // Getters close over the *current* binding of sessionId, prov,
467
+ // activeProvName, activeModel — so a mid-session /provider switch
468
+ // takes effect on the very next turn.
469
+ const _legacyCtx = {
470
+ cfg,
471
+ cfgDir,
472
+ sandboxSpec,
473
+ syntheticChatSessionId: _syntheticChatSessionId,
474
+ getMessages: () => messages,
475
+ getProv: () => prov,
476
+ getActiveProvName: () => activeProvName,
477
+ getActiveModel: () => activeModel,
478
+ getSessionId: () => sessionId,
479
+ persistTurn,
480
+ accumulateUsage,
481
+ resolveAuthKey: (providerName) => _resolveAuthKey(cfg, providerName),
482
+ onCharsSent: (n) => { charsSent += n; },
483
+ };
484
+ const runTurn = _chatRunTurnFactory({
485
+ ctx: _legacyCtx,
486
+ writeFn: (chunk) => process.stdout.write(chunk),
487
+ });
488
+
489
+ const handleSlash = async (line) => {
490
+ const cmd = line.split(/\s+/)[0];
491
+ switch (cmd) {
492
+ case '/help': {
493
+ process.stdout.write('slash commands:\n');
494
+ for (const c of SLASH_COMMANDS) process.stdout.write(` ${c.cmd.padEnd(8)} — ${c.help}\n`);
495
+ return true;
496
+ }
497
+ case '/status': {
498
+ const out = {
499
+ provider: activeProvName,
500
+ model: activeModel,
501
+ keyMasked: getRegistry().maskApiKey(cfg['api-key']),
502
+ messageCount: messages.length,
503
+ };
504
+ process.stdout.write(JSON.stringify(out) + '\n');
505
+ return true;
506
+ }
507
+ case '/provider': {
508
+ // `/provider <name>` switches the active provider for subsequent
509
+ // turns. The conversation history stays put — the next user
510
+ // message goes to the new provider with the existing context.
511
+ // `/provider` (no arg) opens the family/provider/model picker so
512
+ // the user can switch with arrow keys instead of memorising names.
513
+ const arg = line.slice('/provider'.length).trim();
514
+ if (!arg) {
515
+ if (!useTerminal) {
516
+ process.stdout.write(`provider: ${activeProvName}\n`);
517
+ return true;
518
+ }
519
+ await _pauseChatForSubMenu(rl, _ghost, async () => {
520
+ const picked = await _pickProviderInteractive();
521
+ if (picked && picked.provider) {
522
+ const next = lookupProv(picked.provider);
523
+ if (!next) {
524
+ process.stdout.write(`unknown provider: ${picked.provider}\n`);
525
+ return;
526
+ }
527
+ activeProvName = picked.provider;
528
+ prov = next;
529
+ if (picked.model) activeModel = picked.model;
530
+ process.stdout.write(`provider → ${activeProvName}${picked.model ? ` · model → ${picked.model}` : ''}\n`);
531
+ }
532
+ });
533
+ return true;
534
+ }
535
+ const next = lookupProv(arg);
536
+ if (!next) {
537
+ process.stdout.write(`unknown provider: ${arg} (known: ${Object.keys(getRegistry().PROVIDERS).join(', ')})\n`);
538
+ return true;
539
+ }
540
+ activeProvName = arg;
541
+ prov = next;
542
+ process.stdout.write(`provider → ${arg}\n`);
543
+ return true;
544
+ }
545
+ case '/model': {
546
+ // `/model <name>` updates the active model without touching the
547
+ // provider. `/model` (no arg) opens the per-provider model picker
548
+ // — same UX as setup step 3, scoped to the active provider.
549
+ const arg = line.slice('/model'.length).trim();
550
+ if (!arg) {
551
+ if (!useTerminal) {
552
+ process.stdout.write(`model: ${activeModel || '(default)'}\n`);
553
+ return true;
554
+ }
555
+ await _pauseChatForSubMenu(rl, _ghost, async () => {
556
+ const chosen = await _pickModelInteractive(activeProvName, { titlePrefix: 'LazyClaw chat —' });
557
+ if (chosen === 'CANCEL' || chosen === 'BACK' || !chosen) return;
558
+ activeModel = chosen;
559
+ process.stdout.write(`model → ${activeModel}\n`);
560
+ });
561
+ return true;
562
+ }
563
+ // Honor unified provider/model: `/model anthropic/claude-opus-4-7`
564
+ // splits and switches both.
565
+ const { parseSlashProviderModel } = getRegistry();
566
+ const parsed = parseSlashProviderModel(arg);
567
+ if (parsed.provider) {
568
+ const next = lookupProv(parsed.provider);
569
+ if (!next) {
570
+ process.stdout.write(`unknown provider: ${parsed.provider}\n`);
571
+ return true;
572
+ }
573
+ activeProvName = parsed.provider;
574
+ prov = next;
575
+ }
576
+ activeModel = parsed.model || arg;
577
+ process.stdout.write(`model → ${activeModel}${parsed.provider ? ` (provider → ${parsed.provider})` : ''}\n`);
578
+ return true;
579
+ }
580
+ case '/new':
581
+ case '/reset':
582
+ case '/clear': {
583
+ // /clear is dispatcher-only (no explicit legacy case before this),
584
+ // so without it /clear fell through to `default:` → _dispatchSlash →
585
+ // _newReset, which clears via ctx.set* setters that _legacyCtx does
586
+ // NOT expose — returning 'cleared' while the closure's messages/
587
+ // charsSent/runningUsage stayed intact (a lying no-op). Alias /clear
588
+ // to the /new+/reset direct-mutation body, matching the dispatcher's
589
+ // /clear → /new/reset session-reset aliasing.
590
+ messages = [];
591
+ charsSent = 0;
592
+ runningUsage = null;
593
+ if (sessionId) {
594
+ const sm = await import('../sessions.mjs');
595
+ sm.resetSession(sessionId, cfgDir);
596
+ }
597
+ process.stdout.write('cleared — new conversation\n');
598
+ return true;
599
+ }
600
+ case '/usage': {
601
+ const out = { messageCount: messages.length, charsSent };
602
+ if (runningUsage) out.tokens = runningUsage;
603
+ // When cfg.rates has a card for the active provider/model AND
604
+ // we accumulated real usage, surface the running cost too. The
605
+ // computation is local (pure arithmetic), no extra network.
606
+ if (runningUsage && cfg.rates && typeof cfg.rates === 'object') {
607
+ try {
608
+ const { costFromUsage } = await import('../providers/rates.mjs');
609
+ const r = costFromUsage(
610
+ { provider: activeProvName, model: activeModel, usage: runningUsage },
611
+ cfg.rates,
612
+ );
613
+ if (r) out.cost = r;
614
+ } catch { /* never let cost-card lookup fail the slash */ }
615
+ }
616
+ process.stdout.write(JSON.stringify(out) + '\n');
617
+ return true;
618
+ }
619
+ case '/skill': {
620
+ // `/skill name1,name2` — replace the active system message with a
621
+ // composition of the named skills. `/skill` (no arg) clears the
622
+ // system message. The replacement happens in-place on the
623
+ // messages array; the prior system turn (if any) is dropped so
624
+ // we don't end up with two stacked system messages talking past
625
+ // each other. When --session is set we persist the new system
626
+ // message so the next invocation resumes with the same context.
627
+ const arg = line.slice('/skill'.length).trim();
628
+ const names = arg.split(',').map(s => s.trim()).filter(Boolean);
629
+ const sysIdx = messages.findIndex(m => m.role === 'system');
630
+ if (names.length === 0) {
631
+ if (sysIdx >= 0) messages.splice(sysIdx, 1);
632
+ if (sessionId) {
633
+ // Persistent session: rewrite the file from scratch so the
634
+ // dropped system turn doesn't linger as a stale entry.
635
+ const sm = await import('../sessions.mjs');
636
+ sm.resetSession(sessionId, cfgDir);
637
+ for (const m of messages) sm.appendTurn(sessionId, m.role, m.content, cfgDir);
638
+ }
639
+ process.stdout.write('cleared system prompt (no active skills)\n');
640
+ return true;
641
+ }
642
+ try {
643
+ const sys = await (async () => {
644
+ const mod = await import('../skills.mjs');
645
+ return mod.composeSystemPrompt(names, cfgDir);
646
+ })();
647
+ if (!sys) {
648
+ process.stdout.write('no skill content composed (empty input?)\n');
649
+ return true;
650
+ }
651
+ if (sysIdx >= 0) messages[sysIdx] = { role: 'system', content: sys };
652
+ else messages.unshift({ role: 'system', content: sys });
653
+ if (sessionId) {
654
+ const sm = await import('../sessions.mjs');
655
+ sm.resetSession(sessionId, cfgDir);
656
+ for (const m of messages) sm.appendTurn(sessionId, m.role, m.content, cfgDir);
657
+ }
658
+ process.stdout.write(`active skills: ${names.join(', ')}\n`);
659
+ } catch (e) {
660
+ process.stdout.write(`skill error: ${e?.message || e}\n`);
661
+ }
662
+ return true;
663
+ }
664
+ case '/loop': {
665
+ // `/loop <prompt> [--max N] [--until "<regex>"]` — repeats one
666
+ // user prompt against the active provider in the current session.
667
+ // Default --max 3, hard cap 50. --until short-circuits when its
668
+ // regex matches the latest assistant turn. Ctrl+C aborts the
669
+ // current stream AND the whole loop (not just the in-flight
670
+ // turn). Implementation lives in loop-engine.mjs; here we wire
671
+ // it to the same provider streaming + buffered-writer used by a
672
+ // normal user turn.
673
+ const arg = line.slice('/loop'.length).trim();
674
+ const loopMod = await import('../loop-engine.mjs');
675
+ if (!arg) {
676
+ process.stdout.write(`usage: /loop <prompt> [--max N] [--until "<regex>"]\n`);
677
+ process.stdout.write(` default --max ${loopMod.LOOP_MAX_DEFAULT}, ceiling ${loopMod.LOOP_MAX_CEILING}\n`);
678
+ process.stdout.write(` session: ${sessionId || '(none — turns will not be persisted)'}\n`);
679
+ return true;
680
+ }
681
+ let parsed;
682
+ try { parsed = loopMod.parseLoopArgs(arg); }
683
+ catch (e) { process.stdout.write(`loop error: ${e?.message || e}\n`); return true; }
684
+ let untilRe = null;
685
+ try { untilRe = loopMod.compileUntil(parsed.until); }
686
+ catch (e) { process.stdout.write(`loop error: ${e?.message || e}\n`); return true; }
687
+
688
+ // Per-loop AbortController. Ctrl+C aborts the current provider
689
+ // call (via signal) AND prevents the next iteration (the engine
690
+ // sees signal.aborted on its loop check). Same handler shape as
691
+ // the normal-turn path; symmetry keeps `/exit` clean afterwards.
692
+ const loopAc = new AbortController();
693
+ const onSigint = () => {
694
+ loopAc.abort();
695
+ process.stdout.write('\n^C interrupted — loop aborted\n');
696
+ };
697
+ process.on('SIGINT', onSigint);
698
+
699
+ const sendOnce = async (msgs, signal) => {
700
+ let acc = '';
701
+ let _writeBuf = '';
702
+ let _writeTimer = null;
703
+ const _flush = () => {
704
+ if (_writeBuf) { process.stdout.write(_writeBuf); _writeBuf = ''; }
705
+ _writeTimer = null;
706
+ };
707
+ const _writeChunk = (s) => {
708
+ _writeBuf += s;
709
+ if (!_writeTimer) _writeTimer = setTimeout(_flush, 30);
710
+ };
711
+ try {
712
+ for await (const chunk of prov.sendMessage(msgs, {
713
+ apiKey: _resolveAuthKey(cfg, activeProvName),
714
+ model: activeModel,
715
+ sandbox: sandboxSpec,
716
+ signal,
717
+ onUsage: accumulateUsage,
718
+ })) {
719
+ _writeChunk(chunk);
720
+ acc += chunk;
721
+ }
722
+ if (_writeTimer) clearTimeout(_writeTimer);
723
+ _flush();
724
+ process.stdout.write('\n');
725
+ return acc;
726
+ } catch (err) {
727
+ if (_writeTimer) clearTimeout(_writeTimer);
728
+ _flush();
729
+ throw err;
730
+ }
731
+ };
732
+
733
+ if (useTerminal) _ghost.suspend();
734
+ // Capture the chat's existing system message (workspace / skill
735
+ // composition) before we let the engine touch it; we restore it
736
+ // after the loop so the chat continues with the same system.
737
+ const _sysBefore = messages.find(m => m.role === 'system')?.content ?? null;
738
+ const memMod = (parsed.useMemory || parsed.recall) ? await import('../memory.mjs') : null;
739
+ const buildSystem = memMod ? (() => {
740
+ // Called per iteration: memory.loadCore + recall re-read from
741
+ // disk every call so a parallel writer mutating core.md /
742
+ // episodic/* between iterations is reflected immediately.
743
+ const parts = [];
744
+ if (parsed.useMemory) {
745
+ const core = memMod.loadCore(cfgDir);
746
+ if (core && core.trim()) parts.push(core);
747
+ }
748
+ if (parsed.recall) {
749
+ const text = memMod.recall(parsed.recall, { topN: 3 }, cfgDir);
750
+ if (text && text.trim()) parts.push(text);
751
+ }
752
+ if (_sysBefore) parts.push(_sysBefore);
753
+ return parts.join('\n\n---\n\n');
754
+ }) : null;
755
+ try {
756
+ const result = await loopMod.runLoop({
757
+ prompt: parsed.prompt,
758
+ max: parsed.max,
759
+ until: untilRe,
760
+ messages,
761
+ sendOnce,
762
+ persist: (role, content) => persistTurn(role, content),
763
+ onIteration: ({ i, max }) => {
764
+ process.stderr.write(`\x1b[2m ↻ loop iteration ${i}/${max}\x1b[22m\n`);
765
+ },
766
+ signal: loopAc.signal,
767
+ buildSystem,
768
+ });
769
+ charsSent += parsed.prompt.length * result.iterations;
770
+ if (result.stoppedBy === 'until') {
771
+ process.stderr.write(`\x1b[2m ✓ loop stopped by --until\x1b[22m\n`);
772
+ } else if (result.stoppedBy === 'abort') {
773
+ process.stderr.write(`\x1b[2m ⊘ loop aborted after ${result.iterations}/${parsed.max} iteration(s)\x1b[22m\n`);
774
+ }
775
+ } catch (err) {
776
+ process.stdout.write(`loop error: ${err?.message || String(err)}\n`);
777
+ } finally {
778
+ process.off('SIGINT', onSigint);
779
+ if (useTerminal) _ghost.resume();
780
+ // Restore the chat's prior system message. The engine may have
781
+ // overwritten messages[0] with the per-iter memory composition;
782
+ // we put the original (workspace / skill) back so the
783
+ // subsequent free-form chat turn sees the same system the user
784
+ // configured before /loop ran.
785
+ if (buildSystem) {
786
+ const sysIdx = messages.findIndex(m => m.role === 'system');
787
+ if (_sysBefore) {
788
+ if (sysIdx >= 0) messages[sysIdx] = { role: 'system', content: _sysBefore };
789
+ else messages.unshift({ role: 'system', content: _sysBefore });
790
+ } else if (sysIdx >= 0) {
791
+ messages.splice(sysIdx, 1);
792
+ }
793
+ }
794
+ }
795
+ return true;
796
+ }
797
+ case '/goal': {
798
+ // /goal → list active goals
799
+ // /goal <name> → switch chat context to goal:<name>
800
+ // /goal add <name> [--desc "..."] [--cron "<spec>"]
801
+ // /goal list → JSON of all goals
802
+ // /goal show <name> → JSON of one
803
+ // /goal close <name> [done|abandoned]
804
+ const rawArg = line.slice('/goal'.length).trim();
805
+ const goalsMod = await import('../goals.mjs');
806
+ const loopMod = await import('../loop-engine.mjs');
807
+ if (!rawArg) {
808
+ const items = goalsMod.listGoals(cfgDir).filter(g => g.status === 'active');
809
+ if (!items.length) { process.stdout.write('no active goals\n'); }
810
+ else {
811
+ for (const g of items) {
812
+ process.stdout.write(` ${g.name}${g.description ? ' — ' + g.description : ''}${g.schedule ? ' (cron: ' + g.schedule + ')' : ''}\n`);
813
+ }
814
+ }
815
+ return true;
816
+ }
817
+ let tokens;
818
+ try { tokens = loopMod.splitArgs(rawArg); }
819
+ catch (e) { process.stdout.write(`goal error: ${e?.message || e}\n`); return true; }
820
+ const sub = tokens[0];
821
+ const rest = tokens.slice(1);
822
+ if (sub === 'add') {
823
+ let name = null, desc = '', cron = null;
824
+ for (let i = 0; i < rest.length; i++) {
825
+ const t = rest[i];
826
+ if (t === '--desc') desc = rest[++i] || '';
827
+ else if (t === '--cron') cron = rest[++i] || null;
828
+ else if (t.startsWith('--')) { process.stdout.write(`goal error: unknown flag ${t}\n`); return true; }
829
+ else if (!name) name = t;
830
+ else { process.stdout.write(`goal error: unexpected arg "${t}"\n`); return true; }
831
+ }
832
+ if (!name) { process.stdout.write('usage: /goal add <name> [--desc "..."] [--cron "<spec>"]\n'); return true; }
833
+ try {
834
+ const g = goalsMod.registerGoal({ name, description: desc, schedule: cron }, cfgDir);
835
+ if (cron) {
836
+ try { await (await import('../commands/automation.mjs'))._attachGoalCron(name, cron); }
837
+ catch (e) { process.stdout.write(`goal warning: cron attach failed (${e?.message || e})\n`); }
838
+ }
839
+ process.stdout.write(`✓ goal ${g.name} added (status: active${cron ? `, cron: ${cron}` : ''})\n`);
840
+ } catch (e) { process.stdout.write(`goal error: ${e?.message || e}\n`); }
841
+ return true;
842
+ }
843
+ if (sub === 'list') {
844
+ process.stdout.write(JSON.stringify(goalsMod.listGoals(cfgDir), null, 2) + '\n');
845
+ return true;
846
+ }
847
+ if (sub === 'show') {
848
+ const name = rest[0];
849
+ if (!name) { process.stdout.write('usage: /goal show <name>\n'); return true; }
850
+ const g = goalsMod.getGoal(name, cfgDir);
851
+ if (!g) { process.stdout.write(`no goal "${name}"\n`); return true; }
852
+ process.stdout.write(JSON.stringify(g, null, 2) + '\n');
853
+ return true;
854
+ }
855
+ if (sub === 'close') {
856
+ const name = rest[0];
857
+ const outcome = rest[1] || 'done';
858
+ if (!name) { process.stdout.write('usage: /goal close <name> [done|abandoned]\n'); return true; }
859
+ try {
860
+ const g = goalsMod.closeGoal(name, outcome, cfgDir);
861
+ try { await (await import('../commands/automation.mjs'))._detachGoalCron(name); }
862
+ catch (e) { process.stdout.write(`goal warning: cron detach failed (${e?.message || e})\n`); }
863
+ process.stdout.write(`✓ goal ${g.name} closed (status: ${g.status})\n`);
864
+ } catch (e) { process.stdout.write(`goal error: ${e?.message || e}\n`); }
865
+ return true;
866
+ }
867
+ // Single-arg branch: switch context to goal:<name>.
868
+ const goalName = sub;
869
+ const g = goalsMod.getGoal(goalName, cfgDir);
870
+ if (!g) {
871
+ process.stdout.write(`no goal "${goalName}" — try: /goal add ${goalName} --desc "..."\n`);
872
+ return true;
873
+ }
874
+ if (g.status !== 'active') {
875
+ process.stdout.write(`goal "${goalName}" is ${g.status}; cannot switch\n`);
876
+ return true;
877
+ }
878
+ // Switch: replace the chat's active session id and reload turns
879
+ // from the goal's session. The provider, model, workspace, and
880
+ // skill state stay put — only the conversation surface changes.
881
+ sessionId = g.sessionId;
882
+ activeGoalName = g.name;
883
+ const prior = sessionsMod.loadTurns(sessionId, cfgDir);
884
+ messages = prior.map(t => ({ role: t.role, content: t.content }));
885
+ // Prepend a one-line goal note to the system message so the
886
+ // model sees the current objective without us having to mutate
887
+ // any persistent record on every switch.
888
+ const sysIdx = messages.findIndex(m => m.role === 'system');
889
+ const goalNote = `## Goal: ${g.description || g.name}`;
890
+ if (sysIdx >= 0) {
891
+ messages[sysIdx] = { role: 'system', content: `${goalNote}\n\n${messages[sysIdx].content}` };
892
+ } else {
893
+ messages.unshift({ role: 'system', content: goalNote });
894
+ }
895
+ process.stdout.write(`✓ switched to goal: ${g.name} (session: ${sessionId}, ${prior.length} prior turn(s))\n`);
896
+ return true;
897
+ }
898
+ case '/memory': {
899
+ const arg = line.slice('/memory'.length).trim();
900
+ const memMod = await import('../memory.mjs');
901
+ const tokens = arg.split(/\s+/).filter(Boolean);
902
+ const which = tokens[0] || 'core';
903
+ if (which === 'core') {
904
+ const body = memMod.loadCore(cfgDir);
905
+ process.stdout.write(body || '(empty core memory)\n');
906
+ return true;
907
+ }
908
+ if (which === 'recent') {
909
+ const items = memMod.loadRecent(20, cfgDir);
910
+ process.stdout.write(JSON.stringify(items, null, 2) + '\n');
911
+ return true;
912
+ }
913
+ if (which === 'episodic') {
914
+ const topic = tokens[1];
915
+ if (topic) {
916
+ const body = memMod.loadEpisodic(topic, cfgDir);
917
+ process.stdout.write(body || `(no episodic file "${topic}")\n`);
918
+ } else {
919
+ process.stdout.write(JSON.stringify(memMod.listEpisodic(cfgDir), null, 2) + '\n');
920
+ }
921
+ return true;
922
+ }
923
+ process.stdout.write('usage: /memory [core|recent|episodic [topic]]\n');
924
+ return true;
925
+ }
926
+ case '/dream': {
927
+ const memMod = await import('../memory.mjs');
928
+ process.stdout.write(' ↯ dreaming…\n');
929
+ try {
930
+ const r = await memMod.dream(sessionId, {
931
+ provider: prov,
932
+ model: activeModel,
933
+ apiKey: _resolveAuthKey(cfg, activeProvName),
934
+ }, cfgDir);
935
+ process.stdout.write(`✓ wrote ${r.topics.length} episodic file(s): ${r.topics.join(', ') || '(none)'}\n`);
936
+ } catch (e) { process.stdout.write(`dream error: ${e?.message || e}\n`); }
937
+ return true;
938
+ }
939
+ case '/agent': {
940
+ const rawArg = line.slice('/agent'.length).trim();
941
+ const agentsMod = await import('../agents.mjs');
942
+ const loopMod = await import('../loop-engine.mjs');
943
+ let tokens;
944
+ try { tokens = loopMod.splitArgs(rawArg); }
945
+ catch (e) { process.stdout.write(`/agent error: ${e?.message || e}\n`); return true; }
946
+ const sub = tokens[0];
947
+ const rest = tokens.slice(1);
948
+ const aname = rest[0];
949
+ try {
950
+ if (!sub || sub === 'list') {
951
+ const agents = agentsMod.listAgents(cfgDir);
952
+ if (agents.length === 0) process.stdout.write('no agents registered. /agent add <name> [...] to create.\n');
953
+ else for (const a of agents) {
954
+ const provLine = a.model ? `${a.provider}/${a.model}` : a.provider;
955
+ process.stdout.write(`• ${a.name} — ${a.displayName} — ${provLine} — tools=[${(a.tools || []).join(',')}]\n`);
956
+ }
957
+ } else if (sub === 'show') {
958
+ if (!aname) { process.stdout.write('usage: /agent show <name>\n'); return true; }
959
+ const a = agentsMod.getAgent(aname, cfgDir);
960
+ if (!a) process.stdout.write(`no agent "${aname}"\n`);
961
+ else process.stdout.write(JSON.stringify(a, null, 2) + '\n');
962
+ } else if (sub === 'add') {
963
+ if (!aname) { process.stdout.write('usage: /agent add <name> [role text…]\n'); return true; }
964
+ const roleText = rest.slice(1).join(' ').trim();
965
+ const a = agentsMod.registerAgent({ name: aname, role: roleText }, cfgDir);
966
+ process.stdout.write(`✓ added agent ${a.name} (tools=${a.tools.join(',')})\n`);
967
+ } else if (sub === 'remove' || sub === 'rm' || sub === 'delete') {
968
+ if (!aname) { process.stdout.write('usage: /agent remove <name>\n'); return true; }
969
+ agentsMod.removeAgent(aname, cfgDir);
970
+ process.stdout.write(`✓ removed agent ${aname}\n`);
971
+ } else {
972
+ process.stdout.write(`/agent: unknown sub "${sub}" — list|show|add|remove\n`);
973
+ }
974
+ } catch (e) {
975
+ process.stdout.write(`/agent error: ${e?.message || e}\n`);
976
+ }
977
+ return true;
978
+ }
979
+ case '/team': {
980
+ const rawArg = line.slice('/team'.length).trim();
981
+ const teamsMod = await import('../teams.mjs');
982
+ const loopMod = await import('../loop-engine.mjs');
983
+ let tokens;
984
+ try { tokens = loopMod.splitArgs(rawArg); }
985
+ catch (e) { process.stdout.write(`/team error: ${e?.message || e}\n`); return true; }
986
+ const sub = tokens[0];
987
+ const rest = tokens.slice(1);
988
+ const tname = rest[0];
989
+ try {
990
+ if (!sub || sub === 'list') {
991
+ const teams = teamsMod.listTeams(cfgDir);
992
+ if (teams.length === 0) process.stdout.write('no teams registered. /team add <name> --agents a,b --lead a [--channel #x]\n');
993
+ else for (const t of teams) {
994
+ const chLine = t.slackChannel ? ` — ${t.slackChannel}` : '';
995
+ process.stdout.write(`• ${t.name} — ${t.displayName} — lead=${t.lead} — agents=[${t.agents.join(',')}]${chLine}\n`);
996
+ }
997
+ } else if (sub === 'show') {
998
+ if (!tname) { process.stdout.write('usage: /team show <name>\n'); return true; }
999
+ const t = teamsMod.getTeam(tname, cfgDir);
1000
+ if (!t) process.stdout.write(`no team "${tname}"\n`);
1001
+ else process.stdout.write(JSON.stringify(t, null, 2) + '\n');
1002
+ } else if (sub === 'add') {
1003
+ // /team add <name> --agents a,b,c [--lead a] [--channel #x]
1004
+ if (!tname) { process.stdout.write('usage: /team add <name> --agents a,b,c [--lead a] [--channel #x]\n'); return true; }
1005
+ let agentsCsv = null, lead = null, channel = '';
1006
+ for (let i = 1; i < rest.length; i++) {
1007
+ const t = rest[i];
1008
+ if (t === '--agents') agentsCsv = rest[++i] || '';
1009
+ else if (t === '--lead') lead = rest[++i] || null;
1010
+ else if (t === '--channel') channel = rest[++i] || '';
1011
+ else { process.stdout.write(`/team error: unknown token "${t}"\n`); return true; }
1012
+ }
1013
+ if (!agentsCsv) { process.stdout.write('/team add: --agents is required\n'); return true; }
1014
+ const agents = teamsMod.parseListFlag(agentsCsv);
1015
+ const ch = channel ? await teamsMod.resolveSlackChannel(channel, {
1016
+ botToken: process.env.SLACK_BOT_TOKEN || null,
1017
+ apiBase: process.env.SLACK_API_BASE || 'https://slack.com/api',
1018
+ logger: () => {},
1019
+ }) : '';
1020
+ const team = teamsMod.registerTeam({ name: tname, agents, lead, slackChannel: ch }, cfgDir);
1021
+ process.stdout.write(`✓ added team ${team.name} (lead=${team.lead}, agents=${team.agents.join(',')})\n`);
1022
+ } else if (sub === 'remove' || sub === 'rm' || sub === 'delete') {
1023
+ if (!tname) { process.stdout.write('usage: /team remove <name>\n'); return true; }
1024
+ teamsMod.removeTeam(tname, cfgDir);
1025
+ process.stdout.write(`✓ removed team ${tname}\n`);
1026
+ } else {
1027
+ process.stdout.write(`/team: unknown sub "${sub}" — list|show|add|remove\n`);
1028
+ }
1029
+ } catch (e) {
1030
+ process.stdout.write(`/team error: ${e?.message || e}\n`);
1031
+ }
1032
+ return true;
1033
+ }
1034
+ case '/handoff': {
1035
+ // /handoff <target-channel> <externalId> [--note=...] — migrates the
1036
+ // active thread (bound to replState.channel / replState.externalId)
1037
+ // to a new channel and posts transition stubs on both sides. In the
1038
+ // local-only chat REPL there is no bound channel, so we surface a
1039
+ // clear error and stay in the REPL (acceptance test §F).
1040
+ const parts = line.trim().split(/\s+/).slice(1);
1041
+ if (parts.length < 2) {
1042
+ process.stderr.write('usage: /handoff <target-channel> <externalId> [--note=...]\n');
1043
+ return true;
1044
+ }
1045
+ const target = parts[0];
1046
+ const externalId = parts[1];
1047
+ const note = (parts.find(p => p.startsWith('--note=')) || '').slice(7);
1048
+ try {
1049
+ const { openThreads } = await import('../channels/threads.mjs');
1050
+ const { runHandoff } = await import('../channels/handoff.mjs');
1051
+ const threads = openThreads(cfgDir);
1052
+ const replState = globalThis.__lazyclawReplState || {};
1053
+ const cur = replState.channel && replState.externalId
1054
+ ? threads.findByExternal(replState.channel, replState.externalId)
1055
+ : null;
1056
+ if (!cur) {
1057
+ process.stderr.write(
1058
+ `handoff: no thread bound to ${replState.channel || '(none)'}:${replState.externalId || '(none)'}\n`,
1059
+ );
1060
+ return true;
1061
+ }
1062
+ const next = await runHandoff({
1063
+ threads, channels: replState.channels || {},
1064
+ threadId: cur.threadId, target, externalId, note,
1065
+ });
1066
+ process.stdout.write(`handoff -> ${next.channel}:${next.externalId} (session ${next.sessionId})\n`);
1067
+ replState.channel = next.channel;
1068
+ replState.externalId = next.externalId;
1069
+ } catch (e) {
1070
+ process.stderr.write(`handoff failed: ${e.code || 'ERR'}: ${e.message}\n`);
1071
+ }
1072
+ return true;
1073
+ }
1074
+ case '/personality': {
1075
+ // Phase G: thin slash wrapper over cmdPersonality.
1076
+ const tail = line.slice('/personality'.length).trim();
1077
+ const parts = tail.split(/\s+/).filter(Boolean);
1078
+ await (await import('../commands/config.mjs')).cmdPersonality(parts[0] || 'list', parts[1], parts[2]);
1079
+ return true;
1080
+ }
1081
+ case '/exit': {
1082
+ // v5 Group A (C4): fire one updateUserModel call before exit so
1083
+ // the Honcho-style USER.md captures the durable facts surfaced
1084
+ // in this session. Wrapped in a 3-second timeout so a slow
1085
+ // trainer never makes /exit hang. Best-effort: failure logs are
1086
+ // suppressed so we don't disturb the clean shutdown.
1087
+ try {
1088
+ const turns = sessionId
1089
+ ? sessionsMod.loadTurns(sessionId, cfgDir)
1090
+ : messages.map((t) => ({ role: t.role, content: t.content }));
1091
+ if (turns && turns.length) {
1092
+ const trainer = (typeof getRegistry()?.resolveTrainer === 'function')
1093
+ ? getRegistry().resolveTrainer(cfg)
1094
+ : { provider: activeProvName, model: activeModel };
1095
+ const userModelPromise = import('../mas/user_modeler.mjs').then((m) =>
1096
+ m.updateUserModel({
1097
+ sessionTurns: turns,
1098
+ provider: trainer.provider,
1099
+ model: trainer.model,
1100
+ apiKey: _resolveAuthKey(cfg, trainer.provider),
1101
+ baseUrl: _resolveBaseUrl(trainer.provider),
1102
+ configDir: cfgDir,
1103
+ }),
1104
+ ).catch(() => null);
1105
+ await Promise.race([
1106
+ userModelPromise,
1107
+ new Promise((resolve) => setTimeout(resolve, 3000)),
1108
+ ]);
1109
+ }
1110
+ } catch { /* /exit must never hang or throw */ }
1111
+ return 'EXIT';
1112
+ }
1113
+ case '/config': {
1114
+ // Route through the shared legacySlashRoute helper (covered by
1115
+ // tests/f-config-slash-splash.test.mjs) so the legacy path's /config
1116
+ // wiring is the exact code the regression test exercises. It sets
1117
+ // _legacyCtx.requestSetup and returns 'EXIT'; the post-loop guard at the
1118
+ // bottom of cmdChat re-runs the setup wizard when requestSetup is set.
1119
+ // Without this case the legacy readline path fell through to `default:`
1120
+ // and printed "unknown slash" instead of launching setup.
1121
+ return legacySlashRoute(cmd, _legacyCtx);
1122
+ }
1123
+ default: {
1124
+ // Delegate ONLY ctx-safe dispatcher commands to the shared handler.
1125
+ // _legacyCtx is intentionally thin (no setters / openPicker / version),
1126
+ // so a blanket delegation would silently degrade picker- or setter-
1127
+ // driven handlers (/menu, /clear, /version, …). /channels is ctx-safe
1128
+ // (it has a lib/config fallback); everything else stays an honest
1129
+ // "unknown slash". 'EXIT' breaks the loop; a returned string prints.
1130
+ if (LEGACY_DELEGATED_SLASHES.has(cmd)) {
1131
+ const { args } = _parseSlashLine(line);
1132
+ const r = await _dispatchSlash(cmd, args, _legacyCtx, (s) => process.stdout.write(s));
1133
+ if (r === 'EXIT') return 'EXIT';
1134
+ if (typeof r === 'string' && r.length) process.stdout.write(r + '\n');
1135
+ return true;
1136
+ }
1137
+ process.stdout.write(`unknown slash: ${cmd} (try /help)\n`);
1138
+ return true;
1139
+ }
1140
+ }
1141
+ };
1142
+
1143
+ // Create the readline interface here — immediately before iterating, with
1144
+ // no `await` between — so a non-TTY pipe's buffered lines reach the async
1145
+ // iterator (see the note at the rl/_ghost declaration above).
1146
+ rl = readline.createInterface({
1147
+ input: process.stdin,
1148
+ output: useTerminal ? process.stdout : undefined,
1149
+ terminal: useTerminal,
1150
+ prompt: useTerminal ? '\x1b[38;5;208m›\x1b[0m ' : '',
1151
+ });
1152
+ if (useTerminal) {
1153
+ // Cursor-style ghost autocomplete: when the buffer starts with `/`,
1154
+ // render the longest matching command after the cursor in dim grey.
1155
+ // Right-arrow at end-of-line accepts. Tab still cycles via the existing
1156
+ // handleSlash branch; this only adds the inline preview.
1157
+ _ghost = _attachGhostAutocomplete(rl) || _ghost;
1158
+ rl.prompt();
1159
+ }
1160
+ try { for await (const line of rl) {
1161
+ const text = line.trim();
1162
+ if (!text) { if (useTerminal) rl.prompt(); continue; }
1163
+ if (text.startsWith('/')) {
1164
+ const r = await handleSlash(text);
1165
+ if (r === 'EXIT') break;
1166
+ if (useTerminal) rl.prompt();
1167
+ continue;
1168
+ }
1169
+ // Per-turn AbortController. Ctrl+C during a stream aborts THIS turn
1170
+ // and returns to the prompt instead of killing the process. Outside
1171
+ // a stream, Ctrl+C still terminates (we restore the default handler
1172
+ // below, after the try/finally).
1173
+ const turnAc = new AbortController();
1174
+ const onSigint = () => {
1175
+ turnAc.abort();
1176
+ process.stdout.write('\n^C interrupted — prompt is back\n');
1177
+ };
1178
+ process.on('SIGINT', onSigint);
1179
+ // Pause the ghost-autocomplete keypress handler while the
1180
+ // provider is streaming. Without this, every stale stdin event
1181
+ // would trigger `\x1b[s\x1b[K\x1b[u` cursor save/restore writes
1182
+ // that interleave with the streamed text and surface as visible
1183
+ // gaps between CJK characters (visible in user-reported screen
1184
+ // captures of Korean replies).
1185
+ if (useTerminal) _ghost.suspend();
1186
+ try {
1187
+ // C7 — single source of truth for the streaming + persist +
1188
+ // post-task learning loop. The factory handles the user-msg push,
1189
+ // 30 ms buffered writer (CJK-safe), assistant-msg push,
1190
+ // persistTurn for both turns, and the post-task learning hook.
1191
+ await runTurn(text, turnAc.signal);
1192
+ } finally {
1193
+ process.off('SIGINT', onSigint);
1194
+ if (useTerminal) _ghost.resume();
1195
+ }
1196
+ if (useTerminal) rl.prompt();
1197
+ } } finally {
1198
+ // Clean shutdown — without this, /exit "worked" but the process
1199
+ // hung for ~3-5 s while Node waited for stdin's keypress listener
1200
+ // and raw mode to release. Tearing them down explicitly drops the
1201
+ // exit time to <100 ms.
1202
+ try { _ghost.dispose(); } catch (_) {}
1203
+ try { rl.close(); } catch (_) {}
1204
+ if (useTerminal && process.stdin.isTTY && process.stdin.setRawMode) {
1205
+ try { process.stdin.setRawMode(false); } catch (_) {}
1206
+ }
1207
+ // process.stdin keeps the event loop alive in raw / readline mode.
1208
+ // Pause + unref releases the hold so the process can exit cleanly
1209
+ // from natural completion (no need for a hard process.exit).
1210
+ try { process.stdin.pause(); } catch (_) {}
1211
+ try { process.stdin.unref(); } catch (_) {}
1212
+ }
1213
+ // /config in the legacy path: re-run the wizard after the readline loop closes.
1214
+ if (_legacyCtx.requestSetup) await (await import('./setup.mjs')).cmdSetup(undefined, [], {});
1215
+ }
1216
+
1217
+ // Light wrapper around the daemon — meant for users who installed
1218
+ // via npm and don't want to remember `daemon` flags. Boots the
1219
+ // daemon on a fixed default port (override with --port), then opens
1220
+ // the dashboard URL in the user's default browser.
1221
+ //
1222
+ // Why a separate command: typing `lazyclaw daemon` works too, but
1223
+ // `dashboard` is the discoverable name and it auto-opens the browser
1224
+ // (which the bare daemon doesn't, since most daemon callers are
1225
+ // scripts).
1226
+ // Best-effort port-occupant kill — macOS / Linux only. Returns true when
1227
+ // at least one PID was signalled. Used by cmdDashboard so a leftover
1228
+ // listener from a previous run doesn't crash the launch with EADDRINUSE.
1229
+ // Mirrors the Python server's auto-kill behaviour described in CLAUDE.md.
1230
+
1231
+
1232
+
1233
+ // sandbox subcommands — list/test/add/use (Phase D).
1234
+
1235
+
1236
+ // Interactive launcher — fired when the user types `lazyclaw` with
1237
+ // no subcommand AND we're attached to a TTY. OpenClaw's launcher
1238
+ // pattern: ASCII banner + provider/model status + arrow-key menu of
1239
+ // every common action. Selecting a row drops the user into the
1240
+ // matching subcommand via process.argv mutation + main() re-entry,
1241
+ // so chat / agent / etc. behave bit-identically to typing them
1242
+ // directly. Non-TTY (piped, scripted) callers still see the
1243
+ // classic "Usage: …" line so automation isn't surprised.
1244
+ // Multi-step setup wizard — OpenClaw-style first-run experience.
1245
+ // Provider/model/key + optional workspace + optional sample skill
1246
+ // + reachability ping. Each step can be skipped (Enter on prompt /
1247
+ // "n" on yes-no). Re-runnable safely: existing state is reused, not
1248
+ // clobbered, except when the user explicitly opts in.
1249
+ //
1250
+ // `lazyclaw setup` exposes this directly so users can re-run the
1251
+ // wizard any time. The first-run code path also funnels through it
1252
+ // so a fresh install sees the same flow whether they typed
1253
+ // `lazyclaw` or `lazyclaw setup`.