@causyne/agent 1.19.0 → 1.20.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.19.0",
3
+ "version": "1.20.0",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/cliMode.js CHANGED
@@ -382,6 +382,18 @@ export async function chatMode({ home = false } = {}) {
382
382
  if (surface) prompt.attachSurface(surface);
383
383
  prompt.attach(conn.renderer);
384
384
  prompt.start();
385
+
386
+ // If active session has prior conversation history, render it into the viewport (OpenCode architecture)
387
+ const initialHistory = loop.memoryManager ? loop.memoryManager.loadHistory() : [];
388
+ if (initialHistory.length > 0) {
389
+ conn.renderer.renderSessionHistory(initialHistory, {
390
+ id: loop.memoryManager?.sessionId,
391
+ title: loop.memoryManager?.sessionTitle,
392
+ messagesCount: initialHistory.length
393
+ });
394
+ if (surface?.viewport) surface.viewport.toBottom();
395
+ }
396
+
385
397
  // The band is blank until something paints it, so the Stage needs a first
386
398
  // frame here. The scrollback path deliberately does NOT get one: there it
387
399
  // has always waited for the first keystroke, and changing that as a side
@@ -479,20 +491,14 @@ export async function chatMode({ home = false } = {}) {
479
491
  }
480
492
 
481
493
  if (commandResult.effect === 'pick-session' && prompt) {
482
- const active = commandResult.active;
483
- prompt.openLayer(new SelectLayer({
484
- title: 'Sessions',
485
- emptyText: 'No sessions yet',
486
- items: (commandResult.items || []).map((session) => ({
487
- id: session.id,
488
- label: `${session.id === active ? `${GLYPHS.bullet} ` : ''}${session.title}`,
489
- description: `${session.messageCount} messages ${GLYPHS.dot} ${session.workspace || 'no workspace'}`,
490
- value: session
491
- })),
492
- onPick: (item) => {
493
- if (item) prompt.deliver(`/sessions switch ${item.value.id}`);
494
- }
495
- }));
494
+ const { runInteractiveSessionPicker } = await import('./tui/sessionPicker.js');
495
+ const outcome = await runInteractiveSessionPicker(prompt, {
496
+ loop,
497
+ workspace: loop?.workspaceRoot || process.cwd()
498
+ });
499
+ if (outcome) {
500
+ conn.renderer.write(`\n${outcome}\n`);
501
+ }
496
502
  continue;
497
503
  }
498
504
 
package/src/commands.js CHANGED
@@ -21,8 +21,9 @@ import {
21
21
  import { buildContextText, buildUsageText, buildCheckpointsText, buildUndoText, buildStatusText } from './reporting.js';
22
22
  import { loadConfig, saveConfig } from './config.js';
23
23
  import { resolveAvailableModels, getCuratedModels, getAvailableProvidersOverview } from './dynamicCatalogue.js';
24
- import { DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
24
+ import { DEFAULT_MODEL_BY_PROVIDER, PEER_MODEL_CATALOGUE } from './modelCatalogue.js';
25
25
  import { isAcpProvider } from './providers/acp.js';
26
+ import { listSessions, getActiveSessionId } from './sessionStore.js';
26
27
  import {
27
28
  serverStatus, grantServer, revokeServer, addServer, removeServer,
28
29
  connectServer, disconnectServer, refreshServer
@@ -581,30 +582,125 @@ export const COMMANDS = [
581
582
  }
582
583
  },
583
584
 
585
+ {
586
+ name: 'new',
587
+ aliases: ['new-session'],
588
+ scope: 'local',
589
+ usage: '/new',
590
+ description: 'Start a new clean chat session in this workspace',
591
+ dialogTitle: 'New Session',
592
+ run: async (_args = [], context = {}) => {
593
+ const store = await import('./sessionStore.js');
594
+ const memory = context.loop && context.loop.memoryManager;
595
+ const workspace = context.loop?.workspaceRoot || process.cwd();
596
+ const next = memory ? memory.startNewSession('Untitled') : store.createSession(workspace, 'Untitled', true);
597
+ if (context.loop) {
598
+ context.loop.messages = [];
599
+ context.loop.taskId = `cli_chat_${Date.now()}`;
600
+ if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
601
+ context.loop.tokenTracker.reset();
602
+ }
603
+ }
604
+ const renderer = context.prompt?.renderer || context.loop?.connection?.renderer;
605
+ if (renderer && typeof renderer.renderSessionHistory === 'function') {
606
+ renderer.renderSessionHistory([], { id: next.id, title: next.title, messagesCount: 0 });
607
+ }
608
+ if (context.prompt?.surface?.viewport && typeof context.prompt.surface.viewport.toBottom === 'function') {
609
+ context.prompt.surface.viewport.toBottom();
610
+ }
611
+ if (context.prompt?.editor?.clear) {
612
+ context.prompt.editor.clear();
613
+ if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
614
+ }
615
+ return ok(`Started new session: "${next.title}" (${next.id}).`, { effect: 'inline' });
616
+ }
617
+ },
618
+
584
619
  {
585
620
  name: 'sessions',
586
621
  aliases: ['session'],
587
622
  scope: 'local',
588
- usage: '/sessions [switch <id> | delete <id>]',
623
+ usage: '/sessions [new | switch <id> | delete <id>]',
589
624
  description: 'List chat sessions, or switch to one',
590
625
  dialogTitle: 'Sessions',
591
- // Sessions replaced ONE global chat_history.json that every directory read.
592
- // A session you cannot list or switch to is not a session, so this ships
593
- // with the store rather than after it.
626
+ complete: () => {
627
+ try {
628
+ const rows = listSessions().slice(0, 15);
629
+ return [
630
+ { value: 'new', label: 'new', description: 'start a fresh conversation in this workspace' },
631
+ ...rows.map(r => ({
632
+ value: `switch ${r.id}`,
633
+ label: `switch ${r.id}`,
634
+ description: `${r.title} (${r.messageCount} msgs)`
635
+ }))
636
+ ];
637
+ } catch (e) {
638
+ return [{ value: 'new', label: 'new', description: 'start a fresh conversation' }];
639
+ }
640
+ },
594
641
  run: async (args = [], context = {}) => {
595
642
  const store = await import('./sessionStore.js');
596
643
  const verb = String(args[0] || '').toLowerCase();
597
644
  const memory = context.loop && context.loop.memoryManager;
645
+ const workspace = context.loop?.workspaceRoot || process.cwd();
646
+
647
+ // If interactive TUI prompt is available and no sub-arguments are given, open interactive picker modal
648
+ if ((!args || args.length === 0 || (args.length === 1 && args[0] === '')) && context.prompt) {
649
+ const { runInteractiveSessionPicker } = await import('./tui/sessionPicker.js');
650
+ const message = await runInteractiveSessionPicker(context.prompt, {
651
+ loop: context.loop,
652
+ workspace
653
+ });
654
+ return ok(message, { effect: 'inline' });
655
+ }
656
+
657
+ if (verb === 'new') {
658
+ const next = memory ? memory.startNewSession('Untitled') : store.createSession(workspace, 'Untitled', true);
659
+ if (context.loop) {
660
+ context.loop.messages = [];
661
+ context.loop.taskId = `cli_chat_${Date.now()}`;
662
+ if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
663
+ context.loop.tokenTracker.reset();
664
+ }
665
+ }
666
+ if (context.prompt?.editor?.clear) {
667
+ context.prompt.editor.clear();
668
+ if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
669
+ }
670
+ return ok(`Started new session: "${next.title}" (${next.id}).`, { effect: 'inline' });
671
+ }
598
672
 
599
673
  if (verb === 'switch' && args[1]) {
600
674
  const next = memory ? memory.useSession(args[1]) : store.switchSession(args[1]);
601
675
  if (!next) return fail(`No session "${args[1]}".`);
602
- if (context.loop) context.loop.messages = next.messages.filter(m => m.role !== 'system');
603
- return ok(`Switched to "${next.title}" (${next.messages.length} messages).`);
676
+ const historyMessages = memory ? memory.loadHistory() : next.messages.filter(m => m.role !== 'system');
677
+ if (context.loop) {
678
+ context.loop.messages = historyMessages;
679
+ context.loop.taskId = `cli_chat_${Date.now()}`;
680
+ if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
681
+ context.loop.tokenTracker.reset();
682
+ }
683
+ }
684
+ const renderer = context.prompt?.renderer || context.loop?.connection?.renderer;
685
+ if (renderer && typeof renderer.renderSessionHistory === 'function') {
686
+ renderer.renderSessionHistory(historyMessages, {
687
+ id: next.id,
688
+ title: next.title,
689
+ messagesCount: next.messages.length
690
+ });
691
+ }
692
+ if (context.prompt?.surface?.viewport && typeof context.prompt.surface.viewport.toBottom === 'function') {
693
+ context.prompt.surface.viewport.toBottom();
694
+ }
695
+ if (context.prompt?.editor?.clear) {
696
+ context.prompt.editor.clear();
697
+ if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
698
+ }
699
+ return ok(`Switched to "${next.title}" (${next.messages.length} messages, ${next.id}).`, { effect: 'inline' });
604
700
  }
605
701
 
606
702
  if (verb === 'delete' && args[1]) {
607
- return store.deleteSession(args[1]) ? ok('Session deleted.') : fail(`No session "${args[1]}".`);
703
+ return store.deleteSession(args[1]) ? ok(`Deleted session "${args[1]}".`) : fail(`No session "${args[1]}".`);
608
704
  }
609
705
 
610
706
  const rows = store.listSessions();
@@ -624,7 +720,7 @@ export const COMMANDS = [
624
720
  return ok(
625
721
  `${rows.length} session${rows.length === 1 ? '' : 's'} (* = active):\n`
626
722
  + lines.join('\n')
627
- + '\n\nSwitch with /sessions switch <id>. A new directory always starts a new session.',
723
+ + '\n\nSwitch with /sessions switch <id>, or run /sessions to open interactive modal picker.',
628
724
  { effect: 'pick-session', items: rows, active }
629
725
  );
630
726
  }
@@ -737,7 +833,7 @@ export const COMMANDS = [
737
833
 
738
834
  {
739
835
  name: 'clear',
740
- aliases: ['reset', 'new'],
836
+ aliases: ['reset'],
741
837
  scope: 'local',
742
838
  usage: '/clear',
743
839
  description: 'Clear the conversation and start from a fresh context',
@@ -752,6 +848,14 @@ export const COMMANDS = [
752
848
  loop.isInitialized = false;
753
849
  if (typeof loop.rearmAbortController === 'function') loop.rearmAbortController();
754
850
  if (loop.memoryManager) loop.memoryManager.clearHistory();
851
+ const renderer = ctx.prompt?.renderer || loop.connection?.renderer;
852
+ if (renderer && typeof renderer.clearTranscript === 'function') {
853
+ renderer.clearTranscript();
854
+ }
855
+ if (ctx.prompt?.surface?.viewport && typeof ctx.prompt.surface.viewport.toBottom === 'function') {
856
+ ctx.prompt.surface.viewport.toBottom();
857
+ }
858
+ if (ctx.prompt?.scheduleDraw) ctx.prompt.scheduleDraw();
755
859
  return ok('Conversation cleared. The next task starts from a clean context.');
756
860
  }
757
861
  return fail('No active session to clear.');
@@ -954,84 +1058,127 @@ export const COMMANDS = [
954
1058
  return ok(`Refreshed ${config.provider} models (${result.models.length} available, source: ${result.source}). Run /model list to view.`);
955
1059
  }
956
1060
 
957
- const requested = argv.join(' ').trim();
1061
+ const rawRequested = argv.join(' ').trim().replace(/^\/model\s+/i, '');
958
1062
 
959
- // Check if user requested an ACP peer
960
- const acpTarget = requested.match(/^acp\/([a-z0-9_-]+)(?:\/(.+))?$/i);
961
- if (acpTarget) {
962
- const peer = acpTarget[1].toLowerCase();
963
- const nextProvider = `acp/${peer}`;
964
- const peerInfo = overview.acp.find(p => p.id === peer);
965
-
966
- if (nextProvider !== config.provider) { config.apiKey = ''; delete config.baseUrl; }
1063
+ // Helper to cleanly activate a provider + model, persist config, update live loop & prompt
1064
+ const activateModel = (nextProvider, nextModel, feedbackMessage) => {
1065
+ const isProviderChange = nextProvider !== config.provider;
1066
+ if (isProviderChange) {
1067
+ if (nextProvider === 'antigravity' || nextProvider.startsWith('acp/')) {
1068
+ config.apiKey = '';
1069
+ delete config.baseUrl;
1070
+ } else {
1071
+ config.apiKey = (config.providerKeys && config.providerKeys[nextProvider]) || '';
1072
+ delete config.baseUrl;
1073
+ }
1074
+ }
967
1075
  config.provider = nextProvider;
968
- config.model = acpTarget[2] || DEFAULT_MODEL_BY_PROVIDER[nextProvider] || peer;
1076
+ config.model = nextModel;
969
1077
  saveConfig(config);
970
- if (ctx.loop) ctx.loop.config = loadConfig();
971
1078
 
972
- if (peerInfo && !peerInfo.installed) {
973
- return ok(
974
- `⚠️ Notice: "${peerInfo.label}" CLI is not installed on this machine.\n` +
975
- `Binary "${peerInfo.id}" was not found on PATH.\n` +
976
- `Setup: ${peerInfo.setupInstruction}\n\n` +
977
- `Now using ${config.provider} / ${config.model}.`
978
- );
1079
+ if (ctx.loop) {
1080
+ ctx.loop.config = loadConfig();
1081
+ if (typeof ctx.loop.updateTierLimits === 'function') {
1082
+ ctx.loop.updateTierLimits();
1083
+ }
1084
+ }
1085
+ if (ctx.prompt) {
1086
+ if (typeof ctx.prompt.updateModel === 'function') {
1087
+ ctx.prompt.updateModel(config.provider, config.model);
1088
+ } else if (ctx.prompt.renderer?.status) {
1089
+ ctx.prompt.renderer.status.setSession({ provider: config.provider, model: config.model });
1090
+ if (typeof ctx.prompt.scheduleDraw === 'function') ctx.prompt.scheduleDraw();
1091
+ }
979
1092
  }
980
- return ok(`Now using ${config.provider} / ${config.model}.`);
1093
+ return ok(feedbackMessage || `Now using ${config.provider} / ${config.model}.`, { effect: 'inline' });
1094
+ };
1095
+
1096
+ // 1. Antigravity provider (e.g. antigravity or antigravity/Gemini 3.8 Flash (High))
1097
+ if (rawRequested.toLowerCase() === 'antigravity' || rawRequested.toLowerCase().startsWith('antigravity/')) {
1098
+ const agyModel = rawRequested.includes('/')
1099
+ ? rawRequested.slice(rawRequested.indexOf('/') + 1).trim()
1100
+ : (DEFAULT_MODEL_BY_PROVIDER['antigravity'] || 'Gemini 3.8 Flash (Low)');
1101
+ const agyPeer = overview.acp.find(p => p.id === 'antigravity');
1102
+ const notice = agyPeer && !agyPeer.installed
1103
+ ? `⚠️ Notice: Antigravity CLI (agy) is not installed on this machine.\nSetup: ${agyPeer.setupInstruction}\n\nNow using Google Antigravity / ${agyModel}.`
1104
+ : `Now using Google Antigravity / ${agyModel}.`;
1105
+ return activateModel('antigravity', agyModel, notice);
981
1106
  }
982
1107
 
983
- // If peer model is set while in ACP
984
- if (isAcpProvider(config.provider) && requested.includes('/')) {
985
- config.model = requested;
986
- saveConfig(config);
987
- if (ctx.loop) {
988
- ctx.loop.config = loadConfig();
989
- if (typeof ctx.loop.updateTierLimits === 'function') ctx.loop.updateTierLimits();
1108
+ // 2. acp/<peer> or acp/<peer>/<model>
1109
+ const acpTarget = rawRequested.match(/^acp\/([a-z0-9_-]+)(?:\/(.+))?$/i);
1110
+ if (acpTarget) {
1111
+ const peer = acpTarget[1].toLowerCase();
1112
+ const nextProvider = `acp/${peer}`;
1113
+ const peerModel = acpTarget[2] ? acpTarget[2].trim() : (DEFAULT_MODEL_BY_PROVIDER[nextProvider] || peer);
1114
+ const peerInfo = overview.acp.find(p => p.id === peer);
1115
+ const notice = peerInfo && !peerInfo.installed
1116
+ ? `⚠️ Notice: "${peerInfo.label}" CLI is not installed on this machine.\nBinary "${peerInfo.id}" was not found on PATH.\nSetup: ${peerInfo.setupInstruction}\n\nNow using ${nextProvider} / ${peerModel}.`
1117
+ : `Now using ${nextProvider} / ${peerModel}.`;
1118
+ return activateModel(nextProvider, peerModel, notice);
1119
+ }
1120
+
1121
+ // 3. Known ACP peer directly (e.g. opencode, opencode/deepseek-v4.1-flash-free, claude)
1122
+ const slashIndex = rawRequested.indexOf('/');
1123
+ const prefix = (slashIndex > 0 ? rawRequested.slice(0, slashIndex) : rawRequested).toLowerCase();
1124
+ const acpPeer = overview.acp.find(p => p.id === prefix || p.providerKey === prefix);
1125
+ if (acpPeer && acpPeer.id !== 'antigravity') {
1126
+ const nextProvider = acpPeer.providerKey;
1127
+ let peerModel;
1128
+ if (slashIndex > 0) {
1129
+ const rest = rawRequested.slice(slashIndex + 1).trim();
1130
+ if (
1131
+ (PEER_MODEL_CATALOGUE[acpPeer.id] && PEER_MODEL_CATALOGUE[acpPeer.id].includes(rawRequested)) ||
1132
+ (acpPeer.id === 'opencode' && rawRequested.startsWith('opencode/'))
1133
+ ) {
1134
+ peerModel = rawRequested;
1135
+ } else {
1136
+ peerModel = rest;
1137
+ }
1138
+ } else {
1139
+ peerModel = DEFAULT_MODEL_BY_PROVIDER[nextProvider] || acpPeer.id;
990
1140
  }
991
- return ok(`Now using ${config.provider} / ${config.model}.`, { effect: 'inline' });
1141
+ const notice = !acpPeer.installed
1142
+ ? `⚠️ Notice: "${acpPeer.label}" CLI is not installed on this machine.\nBinary "${acpPeer.id}" was not found on PATH.\nSetup: ${acpPeer.setupInstruction}\n\nNow using ${nextProvider} / ${peerModel}.`
1143
+ : `Now using ${nextProvider} / ${peerModel}.`;
1144
+ return activateModel(nextProvider, peerModel, notice);
992
1145
  }
993
1146
 
994
- // If user typed bare 'antigravity' or 'antigravity/model'
995
- if (requested === 'antigravity' || requested.startsWith('antigravity/')) {
996
- const agyModel = requested.includes('/') ? requested.split('/')[1] : (DEFAULT_MODEL_BY_PROVIDER['antigravity'] || 'Gemini 3.8 Flash (Low)');
997
- if (config.provider !== 'antigravity') { config.apiKey = ''; delete config.baseUrl; }
998
- config.provider = 'antigravity';
999
- config.model = agyModel;
1000
- saveConfig(config);
1001
- if (ctx.loop) {
1002
- ctx.loop.config = loadConfig();
1003
- if (typeof ctx.loop.updateTierLimits === 'function') ctx.loop.updateTierLimits();
1147
+ // 4. Known BYOK provider prefix (e.g. gemini/gemini-2.5-flash, anthropic/claude-3-7-sonnet)
1148
+ const byokProvider = overview.byok.find(p => p.id === prefix || (p.id === 'qwen' && prefix === 'dashscope-byok'));
1149
+ if (byokProvider) {
1150
+ const nextProvider = byokProvider.id;
1151
+ const byokModel = slashIndex > 0 ? rawRequested.slice(slashIndex + 1).trim() : (DEFAULT_MODEL_BY_PROVIDER[nextProvider] || byokProvider.defaultModel);
1152
+ return activateModel(nextProvider, byokModel, `Now using ${nextProvider} / ${byokModel}.`);
1153
+ }
1154
+
1155
+ // 5. Look up by model name across BYOK and ACP catalogues
1156
+ for (const p of overview.byok) {
1157
+ if (p.models && p.models.some(m => m.toLowerCase() === rawRequested.toLowerCase())) {
1158
+ const exactModel = p.models.find(m => m.toLowerCase() === rawRequested.toLowerCase()) || rawRequested;
1159
+ return activateModel(p.id, exactModel, `Now using ${p.id} / ${exactModel}.`);
1004
1160
  }
1005
- const agyPeer = overview.acp.find(p => p.id === 'antigravity');
1006
- if (agyPeer && !agyPeer.installed) {
1007
- return ok(
1008
- `⚠️ Notice: Antigravity CLI (agy) is not installed on this machine.\n` +
1009
- `Setup: ${agyPeer.setupInstruction}\n\n` +
1010
- `Now using antigravity / ${config.model}.`,
1011
- { effect: 'inline' }
1012
- );
1161
+ }
1162
+ for (const peer of overview.acp) {
1163
+ if (peer.models && peer.models.some(m => m.toLowerCase() === rawRequested.toLowerCase())) {
1164
+ const exactModel = peer.models.find(m => m.toLowerCase() === rawRequested.toLowerCase()) || rawRequested;
1165
+ return activateModel(peer.providerKey, exactModel, `Now using ${peer.providerKey} / ${exactModel}.`);
1013
1166
  }
1014
- return ok(`Now using antigravity / ${config.model}.`, { effect: 'inline' });
1015
1167
  }
1016
1168
 
1017
- const separator = requested.indexOf('/');
1018
- if (separator > 0) {
1019
- const provider = requested.slice(0, separator);
1020
- if (provider !== config.provider) {
1021
- config.apiKey = config.providerKeys?.[provider] || '';
1022
- delete config.baseUrl;
1023
- }
1024
- config.provider = provider;
1025
- config.model = requested.slice(separator + 1);
1026
- } else {
1027
- config.model = requested;
1169
+ // 6. If currently in ACP and model is custom for that peer
1170
+ if (isAcpProvider(config.provider)) {
1171
+ return activateModel(config.provider, rawRequested, `Now using ${config.provider} / ${rawRequested}.`);
1028
1172
  }
1029
- saveConfig(config);
1030
- if (ctx.loop) {
1031
- ctx.loop.config = loadConfig();
1032
- if (typeof ctx.loop.updateTierLimits === 'function') ctx.loop.updateTierLimits();
1173
+
1174
+ // 7. Generic provider/model separator or bare model
1175
+ if (slashIndex > 0) {
1176
+ const prov = rawRequested.slice(0, slashIndex).trim();
1177
+ const mod = rawRequested.slice(slashIndex + 1).trim();
1178
+ return activateModel(prov, mod, `Now using ${prov} / ${mod}.`);
1179
+ } else {
1180
+ return activateModel(config.provider || 'antigravity', rawRequested, `Now using ${config.provider || 'antigravity'} / ${rawRequested}.`);
1033
1181
  }
1034
- return ok(`Now using ${config.provider} / ${config.model}.`, { effect: 'inline' });
1035
1182
  }
1036
1183
  },
1037
1184
 
@@ -42,7 +42,7 @@ export async function adoptContinuumSession(target, options = {}) {
42
42
  originalWorkspace: detail.workspacePath
43
43
  });
44
44
  // 3. Create a new sovereign Causyne session
45
- const targetWorkspace = options.workspace || detail.workspacePath || process.cwd();
45
+ const targetWorkspace = options.workspace || process.cwd();
46
46
  const title = `[Adopted] ${detail.title}`;
47
47
  const newSession = createSession(targetWorkspace, title, true);
48
48
  // 4. Ingest compacted messages into journal
@@ -65,7 +65,7 @@ export async function adoptContinuumSession(
65
65
  });
66
66
 
67
67
  // 3. Create a new sovereign Causyne session
68
- const targetWorkspace = options.workspace || detail.workspacePath || process.cwd();
68
+ const targetWorkspace = options.workspace || process.cwd();
69
69
  const title = `[Adopted] ${detail.title}`;
70
70
  const newSession = createSession(targetWorkspace, title, true);
71
71
 
@@ -30,7 +30,7 @@ export class MemoryManager {
30
30
  * directory — so typing continue in a new project resumed a conversation
31
31
  * from a different one, months old. See src/sessionStore.js.
32
32
  */
33
- constructor(workspace = process.cwd(), sessionId = null) {
33
+ constructor(workspace = process.cwd(), sessionId = null, options = {}) {
34
34
  this.ensureMemoryDir();
35
35
  this.workspace = workspace;
36
36
  if (sessionId) {
@@ -38,7 +38,7 @@ export class MemoryManager {
38
38
  // resolveSession(), which could silently attach it to a different chat.
39
39
  this.session = getSession(sessionId) || createSession(workspace, 'Untitled', false);
40
40
  } else {
41
- this.session = resolveSession(workspace);
41
+ this.session = resolveSession(workspace, options);
42
42
  }
43
43
  }
44
44
 
@@ -47,8 +47,8 @@ export class MemoryManager {
47
47
  get sessionTitle() { return this.session ? this.session.title : ''; }
48
48
 
49
49
  /** Abandon this conversation and open a clean one in the same workspace. */
50
- startNewSession() {
51
- this.session = createSession(this.workspace);
50
+ startNewSession(title = 'Untitled') {
51
+ this.session = createSession(this.workspace, title, true);
52
52
  return this.session;
53
53
  }
54
54
 
@@ -67,8 +67,12 @@ export class MemoryManager {
67
67
 
68
68
  loadHistory() {
69
69
  if (!this.session || !Array.isArray(this.session.messages)) return [];
70
- // Only return non-system messages to prevent stale system prompts.
71
- return this.session.messages.filter(m => m.role !== 'system');
70
+ // Return conversation messages. Preserve Continuum context blocks, drop stale default system prompts.
71
+ return this.session.messages.filter(m => {
72
+ if (m.role !== 'system') return true;
73
+ if (typeof m.content === 'string' && m.content.startsWith('[Continuum')) return true;
74
+ return false;
75
+ });
72
76
  }
73
77
 
74
78
 
@@ -314,12 +314,25 @@ export function setActiveSession(id) {
314
314
  return false;
315
315
  }
316
316
  }
317
- export function resolveSession(workspace) {
317
+ export function resolveSession(workspace, options = {}) {
318
318
  const workspaceText = String(workspace ?? '');
319
319
  ensureDir();
320
320
  migrateLegacyHistory(workspaceText);
321
+ if (options.forceNew) {
322
+ return createSession(workspaceText);
323
+ }
321
324
  const key = workspaceKey(workspaceText);
322
325
  const now = Date.now();
326
+ // 1. Check preferred session or active.json pointer for this workspace
327
+ const targetId = options.preferredId || getActiveSessionId();
328
+ if (targetId) {
329
+ const active = readSession(targetId);
330
+ if (active && (!active.workspace || active.workspaceKey === key) && now - active.updatedAt < RESUME_WINDOW_MS) {
331
+ setActiveSession(active.id);
332
+ return active;
333
+ }
334
+ }
335
+ // 2. Resume most recent workspace conversation within resume window
323
336
  const candidate = listSessions()
324
337
  .filter((row) => row.workspace && row.workspaceKey === key)
325
338
  .find((row) => now - row.updatedAt < RESUME_WINDOW_MS);
@@ -346,12 +346,32 @@ export function setActiveSession(id: unknown): boolean {
346
346
  }
347
347
  }
348
348
 
349
- export function resolveSession(workspace: unknown): SessionRecord {
349
+ export interface ResolveSessionOptions {
350
+ forceNew?: boolean | undefined;
351
+ preferredId?: string | null | undefined;
352
+ }
353
+
354
+ export function resolveSession(workspace: unknown, options: ResolveSessionOptions = {}): SessionRecord {
350
355
  const workspaceText = String(workspace ?? '');
351
356
  ensureDir();
352
357
  migrateLegacyHistory(workspaceText);
358
+ if (options.forceNew) {
359
+ return createSession(workspaceText);
360
+ }
353
361
  const key = workspaceKey(workspaceText);
354
362
  const now = Date.now();
363
+
364
+ // 1. Check preferred session or active.json pointer for this workspace
365
+ const targetId = options.preferredId || getActiveSessionId();
366
+ if (targetId) {
367
+ const active = readSession(targetId);
368
+ if (active && (!active.workspace || active.workspaceKey === key) && now - active.updatedAt < RESUME_WINDOW_MS) {
369
+ setActiveSession(active.id);
370
+ return active;
371
+ }
372
+ }
373
+
374
+ // 2. Resume most recent workspace conversation within resume window
355
375
  const candidate = listSessions()
356
376
  .filter((row) => row.workspace && row.workspaceKey === key)
357
377
  .find((row) => now - row.updatedAt < RESUME_WINDOW_MS);
@@ -20,6 +20,7 @@ import { sessionBanner } from './banner.js';
20
20
  import { describeTool } from './toolDisplay.js';
21
21
  import { approvalDiff } from './diff.js';
22
22
  import { StatusLine } from './statusLine.js';
23
+ import { barBlock } from './block.js';
23
24
 
24
25
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
25
26
  // minified output would otherwise become thousands of rows and lock the
@@ -512,6 +513,91 @@ export class ChatRenderer {
512
513
  // Frames
513
514
  // -------------------------------------------------------------------------
514
515
 
516
+ renderUserMessage(content) {
517
+ const text = typeof content === 'string'
518
+ ? content
519
+ : (Array.isArray(content)
520
+ ? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
521
+ : String(content || ''));
522
+ if (!text.trim()) return;
523
+
524
+ this.frame('user', () => {
525
+ const width = this.measure();
526
+ const blockWidth = Math.max(8, width - 1);
527
+ const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.bar) - 1);
528
+ const rows = barBlock(
529
+ wrapBlock(safeDisplay(text), innerWidth),
530
+ { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
531
+ );
532
+ this.write();
533
+ for (const row of rows) {
534
+ this.write(row);
535
+ }
536
+ this.write();
537
+ });
538
+ }
539
+
540
+ renderAssistantMessage(content) {
541
+ const text = typeof content === 'string'
542
+ ? content
543
+ : (Array.isArray(content)
544
+ ? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
545
+ : String(content || ''));
546
+ if (!text.trim()) return;
547
+
548
+ this.onAgentMessage({ content: text });
549
+ }
550
+
551
+ renderSessionDivider(info = {}) {
552
+ this.frame('session', () => {
553
+ const width = this.measure();
554
+ const title = safeDisplay(info.title || 'Session');
555
+ const count = info.messagesCount ?? 0;
556
+ const countText = count > 0 ? ` (${count} message${count === 1 ? '' : 's'})` : '';
557
+ const badgeText = `${title}${countText}`;
558
+ const ruleWidth = Math.max(2, Math.floor((width - visibleWidth(badgeText) - 4) / 2));
559
+ this.write();
560
+ this.write(`${paint('rule', GLYPHS.hLine.repeat(ruleWidth))} ${bold(paint('accent', title))}${dim(countText)} ${paint('rule', GLYPHS.hLine.repeat(ruleWidth))}`);
561
+ this.write();
562
+ });
563
+ }
564
+
565
+ clearTranscript() {
566
+ if (this.transcript && typeof this.transcript.clear === 'function') {
567
+ this.transcript.clear();
568
+ }
569
+ }
570
+
571
+ /**
572
+ * Render conversation history frames from a selected or resumed session.
573
+ * Mirrors OpenCode's session conversation loader so prior turns are visible in viewport.
574
+ */
575
+ renderSessionHistory(messages = [], sessionInfo = null) {
576
+ this.clearTranscript();
577
+
578
+ if (sessionInfo && (sessionInfo.title || sessionInfo.id)) {
579
+ this.renderSessionDivider(sessionInfo);
580
+ }
581
+
582
+ for (const msg of messages) {
583
+ if (!msg) continue;
584
+ const role = String(msg.role || '').toLowerCase();
585
+ if (role === 'user') {
586
+ this.renderUserMessage(msg.content);
587
+ } else if (role === 'assistant') {
588
+ this.renderAssistantMessage(msg.content);
589
+ } else if (role === 'system') {
590
+ const text = typeof msg.content === 'string' ? msg.content : '';
591
+ if (text.startsWith('[Continuum Context')) {
592
+ this.frame('notice', () => {
593
+ const firstLine = text.split('\n')[0] || '[Continuum Context]';
594
+ this.write(`${paint('accent', GLYPHS.bullet)} ${dim(firstLine)}`);
595
+ });
596
+ }
597
+ }
598
+ }
599
+ }
600
+
515
601
  onAgentMessage(msg) {
516
602
  const content = safeDisplay(msg.content || '');
517
603
  this.frame('assistant', () => {