@milpa/comal 0.2.5 → 0.2.6

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/README.md CHANGED
@@ -28,7 +28,7 @@ comal --help
28
28
 
29
29
  Keep the PATH line in your shell startup file if you use that prefix. If your Node manager already provides a user prefix, you can omit `--prefix "$HOME/.local"`. The package registers the `comal` executable; you do not need to create a shell alias.
30
30
 
31
- You can pin a version with `npx @milpa/comal@0.2.5` or `npm install --global @milpa/comal@0.2.5`. The local release manifest preserves SHA-256 and SHA-512 integrity is checked against npm at publish time. No independent publisher signature is claimed.
31
+ You can pin a version with `npx @milpa/comal@0.2.6` or `npm install --global @milpa/comal@0.2.6`. The local release manifest preserves SHA-256 and SHA-512 integrity is checked against npm at publish time. No independent publisher signature is claimed.
32
32
 
33
33
  ## Test without account or model
34
34
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milpa/comal",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Comal: governed operations, execution receipts, and programming assistance in any language",
5
5
  "type": "module",
6
6
  "private": false,
package/src/cli.mjs CHANGED
@@ -13,6 +13,7 @@ import { remoteCommandHelp, isRemoteCommand } from './remote-commands.mjs';
13
13
  import { codeRunDefinition } from './code-run.mjs';
14
14
  import {installCodeRunSession} from './code-run-session.mjs';
15
15
  import { hasProviderSelection, loadConnection, saveConnection, existingLoginConnection, onboard, loadSavedLimits } from './onboarding.mjs';
16
+ import { loadRecentConnection, rememberConnection, recentSelection } from './recent-connections.mjs';
16
17
  import { SessionSettings, resolveStartupLimits, modelAwareLimits } from './connection-settings.mjs';
17
18
  import { loginProvider, parseLoginArguments, withoutCredentialHeaders } from './secret-login.mjs';
18
19
  import { stageImage, descriptorForStage, persistHumanImage } from './image-attachments.mjs';
@@ -252,7 +253,9 @@ async function boot(args, createScreen, setInterrupt, startupSignal, host) {
252
253
  const explicitConnection = hasProviderSelection(v, profiles);
253
254
  let savedConnection, recoveredLogin, knownLogins = [];
254
255
  if (!explicitConnection) {
255
- try { savedConnection = await loadConnection(); }
256
+ // Interactive: the project's last connection, else the last one used anywhere, else connection.json. A print run
257
+ // (scripts, cron) keeps reading only connection.json, so a model tried interactively never changes it.
258
+ try { savedConnection = (print ? null : await loadRecentConnection({ cwd })) || await loadConnection(); }
256
259
  catch (error) { stderr.write(t('Saved connection could not be loaded: ') + error.message + '\n'); }
257
260
  if (!savedConnection && !print) {
258
261
  const existing = await existingLoginConnection(authManager); knownLogins = existing.logins;
@@ -358,6 +361,9 @@ async function boot(args, createScreen, setInterrupt, startupSignal, host) {
358
361
  await store.append(session.id,row);
359
362
  Object.assign(session,{model:row.model,provider:row.provider,provider_profile:row.profile,provider_connection:row.connection});
360
363
  };
364
+ // Interactive sessions remember the connection chosen without startup flags, and each /model or /provider, for the
365
+ // next start (per project and overall). A print run, a resumed session and a one-off flag or variable never do.
366
+ const rememberActive=async()=>{if(v.demo || print || !provider)return;const selection=recentSelection(settings,provider);if(!selection)return;try{await rememberConnection(selection,{cwd});}catch(error){ui?.notice(t('Connection not remembered for the next start: ')+error.message,true);}};
361
367
  const saveProvider=async()=>{if(!v.demo)await persistProvider(provider,settings,modelCapabilities);};
362
368
  if(v.name){if(v.name.trim().length<1 || v.name.length>120)throw new Error(t("--name must be 1 to 120 characters."));session.name=clean(v.name.trim());await store.append(session.id,{type:'name',name:session.name});}
363
369
  if(v.inbound && !['accept','hold','refuse'].includes(v.inbound))throw new Error(t("--inbound must be accept, hold, or refuse."));
@@ -864,7 +870,7 @@ async function boot(args, createScreen, setInterrupt, startupSignal, host) {
864
870
  { name: 'SessionMode', description: 'Human changes the permission mode.', input_schema: { type: 'object', properties: { mode: { type: 'string', enum: PERMISSION_MODES } }, required: ['mode'], additionalProperties: false }, run: async ({ mode }) => { policy.mode = mode; await store.append(session.id, { type: 'mode', mode }); return t("Permissions: {v0}", {v0: mode}); } },
865
871
  { name:'SessionModel',description:'Human selects a model without replacing session history.',input_schema:{type:'object',properties:{model:{type:'string',minLength:1,maxLength:256}},required:['model'],additionalProperties:false},run:async({model})=>{
866
872
  if(!model.trim() || /\s/.test(model))throw new Error(t("Use /model ID, without spaces."));
867
- const verification=await replaceProvider({...settings,model,effort:'auto'},{refresh:true,validate:true});
873
+ const verification=await replaceProvider({...settings,model,effort:'auto'},{refresh:true,validate:true});await rememberActive();
868
874
  return t("Model: {v0} · effort {v1} · same session", {v0: provider.model, v1: provider.effort || 'auto'}) + (verification?.compatibilityFallback? ' · '+t('Model catalog unavailable; the active connection is unverified. No inference was sent.'):'');
869
875
  }},
870
876
  {name:'SessionEffort',description:'Human selects a supported reasoning effort for the next request.',input_schema:{type:'object',properties:{effort:{type:'string',minLength:1,maxLength:16}},required:['effort'],additionalProperties:false},run:async({effort})=>{
@@ -885,7 +891,7 @@ async function boot(args, createScreen, setInterrupt, startupSignal, host) {
885
891
  if(v.demo)throw new Error(t("The demo does not allow changing provider."));
886
892
  const selected=profiles.profiles.find(item=>item.name===profile);
887
893
  const config=selected ? {provider:selected.provider,profile:selected,namedProfile:true,authProvider:selected.authProvider,model:selected.model,baseURL:selected.baseURL,effort:selected.effort || 'auto',maxTokens:contextConfig.maxTokens} : {...authProviderDefaults(profile),effort:'auto',maxTokens:contextConfig.maxTokens};
888
- const verification=await replaceProvider(config,{validate:true});
894
+ const verification=await replaceProvider(config,{validate:true});await rememberActive();
889
895
  return t("Provider: {v0} · {v1} · {v2}", {v0: selected?.name || provider.authProvider, v1: settings.provider, v2: provider.model}) + (verification?.compatibilityFallback?' · '+t('Model catalog unavailable; the active connection is unverified. No inference was sent.'):'');
890
896
  }},
891
897
  {name:'SessionLogin',description:'Human authorizes a provider login. Only the environment variable name is recorded.',input_schema:{type:'object',properties:{provider:{type:'string',enum:AUTH_PROVIDERS.map(item=>item.id)},apiKeyEnv:{type:'string',pattern:'^[A-Za-z_][A-Za-z0-9_]*$'},hidden:{type:'boolean'}},required:['provider'],additionalProperties:false},effects:{workspace:'none',external:'unknown',process:'none',authority:'credential_control'},run:async({provider:target,apiKeyEnv,hidden})=>loginControl(target+(apiKeyEnv?' --api-key-env '+apiKeyEnv:'')+(hidden?' --key':''))},
@@ -963,7 +969,7 @@ async function boot(args, createScreen, setInterrupt, startupSignal, host) {
963
969
  try{return JSON.stringify(await loginProvider({authManager,ui,provider:target,...login,signal,onEvent:event=>{if(ui){if(event.type==='device_code')ui.notice(t("Login {v0}: {v1} · code {v2}", {v0: event.provider, v1: event.verification_uri, v2: event.user_code}));else if(event.message)ui.notice(event.message);}else authNotice(event);}}),null,2);}
964
970
  finally{authController=null;if(ui)ui.setBusy(wasBusy);}
965
971
  };
966
- const sessionSettings=new SessionSettings({limits:contextConfig,flags:{maxTokens:v['max-tokens'],contextWindow:v['context-window']},authManager,delegate:(command,arg)=>backend.control(command,arg),
972
+ const sessionSettings=new SessionSettings({persistConnection:async(selection,options)=>{await saveConnection(selection,options);try{await rememberConnection(selection,{cwd,env:options?.env});}catch{}},limits:contextConfig,flags:{maxTokens:v['max-tokens'],contextWindow:v['context-window']},authManager,delegate:(command,arg)=>backend.control(command,arg),
967
973
  applyLimits:async()=>{if(provider)provider.maxTokens=contextConfig.maxTokens;agent.compactor.contextWindow=effectiveContextWindow(modelCapabilities);await saveProvider();},
968
974
  state:()=>({demo:Boolean(v.demo),provider:settings.provider,authProvider:provider?.authProvider,profile:provider?.profileName,endpoint:provider?.baseURL || (provider?.url?String(provider.url):undefined),model:provider?.model,effort:provider?.effort,thinking:provider?.thinking,protocol:provider?.protocol,fallback:provider?.fallback,apiKeyEnv:session.provider_connection?.apiKeyEnv,modelCapabilities,mode:policy.mode,plugins:plugins.status(),paths:{profiles:profiles.configPath,plugins:plugins.status().config_path}})});
969
975
  const backend = {
@@ -1165,6 +1171,7 @@ async function boot(args, createScreen, setInterrupt, startupSignal, host) {
1165
1171
  if(peerBus.availability?.available===false && !['PEER_DISABLED','PEER_UNAVAILABLE'].includes(peerBus.availability.code)){const note=t('Cross-session messaging is unavailable on this platform. Local work remains available.');if(ui)ui.notice(note,true);else stderr.write(note+'\n');}
1166
1172
  await refreshConnections();
1167
1173
  await saveProvider();
1174
+ if (!explicitConnection) await rememberActive();
1168
1175
  await lifecycle.execute('PluginInitialize', { trust: Boolean(v['trust-plugins'] || skipPermissions) }, { signal: startupSignal });
1169
1176
  await lifecycle.execute('McpInitialize', { trust: Boolean(v['trust-mcp'] || skipPermissions) }, { signal: startupSignal });
1170
1177
  if(host.codeRunSession) {
@@ -108,5 +108,6 @@ export default Object.freeze({
108
108
  "Use /permissions default|plan|acceptEdits|auto.": "Usa /permissions default|plan|acceptEdits|auto.",
109
109
  "Model: {v0} · effort {v1}\nUse /models, /model ID, or /effort LEVEL.": "Modelo: {v0} · effort {v1}\nUsa /models, /model ID o /effort NIVEL.",
110
110
  "There are no saved sessions.\n": "No hay sesiones guardadas.\n",
111
+ "Connection not remembered for the next start: ": "La conexión no se recordó para el próximo inicio: ",
111
112
  "Comal · standalone CLI programming assistant\n\nUsage: node bin/comal.mjs [options] [prompt]\n node bin/comal.mjs sessions | evidence | audit --resume UUID\n\n -p, --print Runs a turn and exits (also accepts stdin)\n --demo Deterministic demo without credentials; allows its edits\n --cwd <path> Workspace (default: current directory)\n --provider <protocol> openai (default) | anthropic | gemini\n --profile <name> Profile from .comal/providers.json (endpoint/model/capabilities)\n --providers-config <file> Profiles file; keys only via apiKeyEnv\n --name <name> Name visible to other sessions\n --listen Keeps the CLI listening for messages and responds when idle\n --inbound <mode> accept (default) | hold | refuse\n --no-peers No cross-session bus (also COMAL_PEERS=off)\n --auth-provider <id> Comal login: codex | kimi | minimax | grok\n --effort <level> auto | off | minimal | low | medium | high | xhigh | max (if the model supports it)\n --model <id> Model; by default discovers the local one at /v1/models\n --base-url <url> Endpoint; default http://llama.local:11438/\n --permission-mode <mode> default | acceptEdits | plan | auto\n --allowed-tools <names> Authorizes comma-separated names\n --disallowed-tools <names> Denies names; overrides authorization\n --resume <uuid> Resumes session; with -p and no text continues pending work\n -c, --continue Resumes the most recent session\n --output-format <format> text | json | stream-json (with --print)\n --max-turns <n> Calls before extending work with progress (12)\n --work-max-calls <n> Total limit with task continuation (80; 0 disables)\n --context-window <n> Explicit limit; automatic based on model, fallback 45000\n --max-tokens <n> Initial maximum output tokens (8192; up to 32000 when the model allows)\n --autocompact <n|auto|off> Compaction window: N or Nk tokens, auto or off (also COMAL_AUTOCOMPACT)\n --thinking <mode> auto | on | off | low | medium | high (llama.cpp)\n --vision <mode> auto | on | off (auto queries /props when receiving images)\n --image-tokens <n> Estimated reservation per image (4096, maximum 2 images)\n --model-timeout-ms <n> Total time for each OpenAI response (600000)\n --model-idle-timeout-ms <n> Time without model token progress (180000)\n --system-prompt <text> Additional instructions\n --state-dir <path> State location; default .comal/ (reuses existing .harness/)\n --mcp-config <file> Connects MCP stdio, Streamable HTTP, or SSE from a JSON\n --trust-mcp Authorizes initial connections; changes are reviewed again\n --plugin-config <file> Local Node plugins (JSON); default .comal/plugins.json\n --lang <en|es|auto> UI language (default: en; auto opts into locale detection)\n --codemode Read-only JavaScript tool composition (default: on)\n --no-codemode Disable CodeRun for this process\n --trust-plugins Authorizes loading local code from the initial config\n --chrome-task <file.json> Explicit Chrome task; the house coordinates publication, checks, and closure\n --goal <condition> Runs a goal until verification or limit\n --goal-max-turns <n> Maximum goal turns (20)\n --goal-max-calls <n> Total calls: agent + verifiers (80)\n --goal-max-tokens <n> Goal token budget (100000)\n -h, --help Shows this help\n -v, --version Shows version\n\nVariables (HARNESS_* remains as alias): COMAL_PROVIDER, COMAL_BASE_URL, COMAL_MODEL,\n COMAL_CONTEXT_WINDOW, COMAL_MAX_TOKENS, COMAL_WORK_MAX_CALLS,\n COMAL_MODEL_TIMEOUT_MS, COMAL_MODEL_IDLE_TIMEOUT_MS,\n OPENAI_BASE_URL, OPENAI_MODEL, OPENAI_API_KEY (optional for local),\n ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL (with --provider anthropic).\nRead authorized by default; write and Bash require permission.\nIn --print without a terminal, unauthorized tools are denied.\nShift+Tab: default → acceptEdits → plan → auto → default.\nInteractive commands: /help /status /tools /house /operations /sessions /resume UUID /clear\n /compact /context /state /audit /board /work resume|recover\n /model ID /permissions MODE /goal [condition] /exit\n /queue [pause|resume|clear|edit N] /rename NAME /table FILE\nTUI: F1 help · F2 sessions · F4 queue · F5 or /select selection · F6 discover commands/tools.\n / and Tab complete; ↑/↓ chooses; Enter on suggestions only completes. Alt+C or /copy copies.\n Ctrl+G editor · Alt+Enter multiline.\nMCP: /mcp · /mcp reload [file] · /mcp add NAME {JSON} · /mcp remove NAME\n /mcp reconnect NAME. Default file: .mcp.json in the workspace.\nWeb: /search QUERY · WebSearch/WebFetch · COMAL_SEARCH_PROVIDER, SEARXNG_URL, BRAVE_SEARCH_API_KEY.\nSubagents: /agent [explore|general] TASK · /agents [UUID] · Agent/AgentBatch.\nPlugins: /plugins [list|enable ID|disable ID|reload [ID]|run ID OPERATION {JSON}].\nLive sessions: /list-agents · /send ID_OR_NAME TEXT · /inbox [accept|hold|refuse|release ID|all]\nComal account: comal cloud login|status|logout [--cloud-url ORIGIN] (separate from the model provider)\nArtifacts: comal artifacts list|inspect ID|verify ID|publish DIR --manifest JSON|release ID VERSION JOB\nLogin: comal login PROVIDER [--api-key-env VARIABLE] · comal auth status [PROVIDER] · comal logout PROVIDER\nModels: /model [ID] · /models · /effort [LEVEL] · /capabilities [refresh] · /login PROVIDER · /logout PROVIDER\nProviders: /providers · /provider PROFILE · ProviderSearch/AnalyzeMedia according to capabilities.\nCLI: comal peers | providers | message DESTINATION TEXT (use --listen to receive in CLI).\n/goal status|pause|resume|clear controls the goal; Ctrl+C pauses it.\nLocal skills: .comal/skills/<name>/SKILL.md → /<name> [task]\n\nRemote Control: /rc [start|status|stop] · TUI account: /cloud [login|status|logout] · CLI: comal cloud login\n": "Comal · asistente de programación CLI independiente\n\nUso: node bin/comal.mjs [opciones] [prompt]\n node bin/comal.mjs sessions | evidence | audit --resume UUID\n\n -p, --print Ejecuta un turno y termina (también acepta stdin)\n --demo Demo determinista sin credenciales; permite sus ediciones\n --cwd <ruta> Workspace (por defecto: directorio actual)\n --provider <protocolo> openai (predeterminado) | anthropic | gemini\n --profile <nombre> Perfil de .comal/providers.json (endpoint/modelo/capacidades)\n --providers-config <archivo> Archivo de perfiles; claves sólo vía apiKeyEnv\n --name <nombre> Nombre visible a otras sesiones\n --listen Mantiene el CLI escuchando mensajes y responde al quedar idle\n --inbound <modo> accept (predeterminado) | hold | refuse\n --no-peers Sin bus entre sesiones (también COMAL_PEERS=off)\n --auth-provider <id> Login de Comal: codex | kimi | minimax | grok\n --effort <nivel> auto | off | minimal | low | medium | high | xhigh | max (si el modelo lo admite)\n --model <id> Modelo; por defecto descubre el local en /v1/models\n --base-url <url> Endpoint; por defecto http://llama.local:11438/\n --permission-mode <modo> default | acceptEdits | plan | auto\n --allowed-tools <nombres> Autoriza nombres separados por comas\n --disallowed-tools <nombres> Deniega nombres; prevalece sobre autorización\n --resume <uuid> Reanuda sesión; con -p sin texto continúa trabajo pendiente\n -c, --continue Reanuda la sesión más reciente\n --output-format <formato> text | json | stream-json (con --print)\n --max-turns <n> Llamadas antes de extender trabajo con progreso (12)\n --work-max-calls <n> Límite total con continuación de tareas (80; 0 desactiva)\n --context-window <n> Límite explícito; automático según modelo, fallback 45000\n --max-tokens <n> Máximo inicial de tokens de salida (8192; hasta 32000 si el modelo lo admite)\n --autocompact <n|auto|off> Ventana de compactación: N o Nk tokens, auto u off (también COMAL_AUTOCOMPACT)\n --thinking <modo> auto | on | off | low | medium | high (llama.cpp)\n --vision <modo> auto | on | off (auto consulta /props al recibir imágenes)\n --image-tokens <n> Reserva estimada por imagen (4096, máximo 2 imágenes)\n --model-timeout-ms <n> Tiempo total de cada respuesta OpenAI (600000)\n --model-idle-timeout-ms <n> Tiempo sin progreso de tokens del modelo (180000)\n --system-prompt <texto> Instrucciones adicionales\n --state-dir <ruta> Ubicación del estado; por defecto .comal/ (reutiliza .harness/ existente)\n --mcp-config <archivo> Conecta MCP stdio, Streamable HTTP o SSE de un JSON\n --trust-mcp Autoriza conexiones iniciales; cambios se revisan de nuevo\n --plugin-config <archivo> Plugins Node locales (JSON); por defecto .comal/plugins.json\n --trust-plugins Autoriza cargar código local de la config inicial\n --codemode Experimental read-only JavaScript tool composition\n --chrome-task <archivo.json> Tarea Chrome explícita; la casa coordina publicación, checks y cierre\n --goal <condición> Ejecuta un objetivo hasta verificación o límite\n --goal-max-turns <n> Máximo de turnos del objetivo (20)\n --goal-max-calls <n> Llamadas totales: agente + verificadores (80)\n --goal-max-tokens <n> Presupuesto de tokens del objetivo (100000)\n -h, --help Muestra esta ayuda\n -v, --version Muestra versión\n\nVariables (HARNESS_* sigue como alias): COMAL_PROVIDER, COMAL_BASE_URL, COMAL_MODEL,\n COMAL_CONTEXT_WINDOW, COMAL_MAX_TOKENS, COMAL_WORK_MAX_CALLS,\n COMAL_MODEL_TIMEOUT_MS, COMAL_MODEL_IDLE_TIMEOUT_MS,\n OPENAI_BASE_URL, OPENAI_MODEL, OPENAI_API_KEY (opcional para local),\n ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL (con --provider anthropic).\nLectura autorizada por defecto; escritura y Bash requieren permiso.\nEn --print sin terminal, las herramientas no autorizadas se deniegan.\nShift+Tab: default → acceptEdits → plan → auto → default.\nRemote Control: /rc [start|status|stop] · TUI account: /cloud [login|status|logout] · CLI: comal cloud login\nComandos interactivos: /help /status /tools /house /operations /sessions /resume UUID /clear\n /compact /context /state /audit /board /work resume|recover\n /model ID /permissions MODO /goal [condición] /exit\n /queue [pause|resume|clear|edit N] /rename NOMBRE /table ARCHIVO\nTUI: F1 ayuda · F2 sesiones · F4 cola · F5 o /select selección · F6 descubrir comandos/herramientas.\n / y Tab completan; ↑/↓ elige; Enter en sugerencias sólo completa. Alt+C o /copy copiar.\n Ctrl+G editor · Alt+Enter multilínea.\nMCP: /mcp · /mcp reload [archivo] · /mcp add NOMBRE {JSON} · /mcp remove NOMBRE\n /mcp reconnect NOMBRE. Archivo predeterminado: .mcp.json del workspace.\nWeb: /search CONSULTA · WebSearch/WebFetch · COMAL_SEARCH_PROVIDER, SEARXNG_URL, BRAVE_SEARCH_API_KEY.\nSubagentes: /agent [explore|general] TAREA · /agents [UUID] · Agent/AgentBatch.\nPlugins: /plugins [list|enable ID|disable ID|reload [ID]|run ID OPERACIÓN {JSON}].\nSesiones vivas: /list-agents · /send ID_O_NOMBRE TEXTO · /inbox [accept|hold|refuse|release ID|all]\nCuenta Comal: comal cloud login|status|logout [--cloud-url ORIGEN] (separada del proveedor de modelos)\nArtifacts: comal artifacts list|inspect ID|verify ID|publish DIR --manifest JSON|release ID VERSION JOB\nLogin: comal login PROVEEDOR [--api-key-env VARIABLE] · comal auth status [PROVEEDOR] · comal logout PROVEEDOR\nModelos: /model [ID] · /models · /effort [NIVEL] · /capabilities [refresh] · /login PROVEEDOR · /logout PROVEEDOR\nProveedores: /providers · /provider PERFIL · ProviderSearch/AnalyzeMedia según capacidades.\nCLI: comal peers | providers | message DESTINO TEXTO (usa --listen para recibir en CLI).\n/goal status|pause|resume|clear controla el objetivo; Ctrl+C lo pausa.\nSkills locales: .comal/skills/<nombre>/SKILL.md → /<nombre> [tarea]\n\n --lang <en|es|auto> Idioma de interfaz (predeterminado: en)\n\n --no-codemode Desactiva CodeRun para este proceso\n"
112
113
  });
@@ -49,7 +49,7 @@ function normalizeFile(value) {
49
49
  if (!Object.keys(selected).length && !Object.keys(limits).length) throw Error('Invalid saved Comal connection.');
50
50
  return { selection: Object.keys(selected).length ? normalizeSelection(selected) : null, limits };
51
51
  }
52
- function normalizeConnection(value) {
52
+ export function normalizeConnection(value) {
53
53
  if (!value || Array.isArray(value) || typeof value !== 'object' || Object.keys(value).some(key => !SELECTION_KEYS.includes(key))) throw Error('Invalid saved Comal connection.');
54
54
  return normalizeSelection(value);
55
55
  }
@@ -0,0 +1,82 @@
1
+ import { readFile, mkdir, writeFile, rename, unlink, realpath } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { normalizeConnection } from './onboarding.mjs';
6
+ import { AUTH_PROVIDERS } from './provider-auth.mjs';
7
+
8
+ // The last connection used, per project and overall. Comal writes it on its own
9
+ // whenever an interactive session connects or changes provider or model; a new
10
+ // session opens with the project's last one, else the last one used anywhere.
11
+ // Startup flags, environment variables and named profiles still win. Holds the
12
+ // same routing data as connection.json (login name or endpoint, and model),
13
+ // never a key.
14
+ export const RECENT_PROJECTS_MAX = 100;
15
+ const MAX_BYTES = 65536, VERSION = 1;
16
+ export const recentConnectionsFile = (env = process.env) => path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'comal', 'recent-connections.json');
17
+
18
+ const valid = selection => { try { return normalizeConnection(selection); } catch { return null; } };
19
+ const projectKey = async cwd => { try { return await realpath(cwd); } catch { return path.resolve(cwd); } };
20
+
21
+ async function read(env) {
22
+ try {
23
+ const text = await readFile(recentConnectionsFile(env), 'utf8');
24
+ if (Buffer.byteLength(text) > MAX_BYTES) return null;
25
+ const data = JSON.parse(text);
26
+ if (!data || typeof data !== 'object' || Array.isArray(data) || data.version !== VERSION) return null;
27
+ const projects = {};
28
+ if (data.projects && typeof data.projects === 'object' && !Array.isArray(data.projects))
29
+ for (const [dir, entry] of Object.entries(data.projects)) {
30
+ const selection = valid(entry?.selection);
31
+ if (selection && path.isAbsolute(dir) && Number.isSafeInteger(entry.at)) projects[dir] = { selection, at: entry.at };
32
+ }
33
+ return { global: valid(data.global), projects };
34
+ } catch { return null; }
35
+ }
36
+
37
+ /**
38
+ * The last connection of this folder or the nearest folder above it that has one (a subfolder of a project counts as
39
+ * the project), else the last one used anywhere, else null. A damaged file reads as nothing.
40
+ */
41
+ export async function loadRecentConnection({ cwd = process.cwd(), env = process.env } = {}) {
42
+ const data = await read(env);
43
+ if (!data) return null;
44
+ for (let dir = await projectKey(cwd); ; dir = path.dirname(dir)) {
45
+ if (data.projects[dir]) return data.projects[dir].selection;
46
+ if (path.dirname(dir) === dir) return data.global || null;
47
+ }
48
+ }
49
+
50
+ /** Remembers a connection for this project and as the last one used. Throws on a selection connection.json would refuse. */
51
+ export async function rememberConnection(selection, { cwd = process.cwd(), env = process.env, now = Date.now() } = {}) {
52
+ const clean = normalizeConnection(selection);
53
+ const data = (await read(env)) || { global: null, projects: {} };
54
+ const key = await projectKey(cwd);
55
+ delete data.projects[key];
56
+ data.projects[key] = { selection: clean, at: now };
57
+ // Newest first; within the same instant, the one written last counts as newer. The file keeps them oldest first.
58
+ const kept = Object.entries(data.projects).reverse().sort((a, b) => b[1].at - a[1].at).slice(0, RECENT_PROJECTS_MAX);
59
+ // Past the size cap the oldest folders go first; this folder's own entry and the global one always stay.
60
+ const encode = () => JSON.stringify({ version: VERSION, global: clean, projects: Object.fromEntries([...kept].reverse()) }) + '\n';
61
+ let text = encode();
62
+ while (Buffer.byteLength(text) > MAX_BYTES && kept.length > 1) { kept.pop(); text = encode(); }
63
+ if (Buffer.byteLength(text) > MAX_BYTES) throw Error('Recent connections exceed 64 KiB.');
64
+ const file = recentConnectionsFile(env), temporary = file + '.' + randomUUID();
65
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
66
+ try { await writeFile(temporary, text, { flag: 'wx', mode: 0o600 }); await rename(temporary, file); }
67
+ finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
68
+ }
69
+
70
+ /**
71
+ * The routing data worth remembering for an active connection: a subscription login with its model, or an
72
+ * OpenAI-compatible endpoint with its model. A named profile is chosen by defaultProfile, and a provider that only
73
+ * reads a key from the environment is chosen by that environment: neither is remembered (null).
74
+ */
75
+ export function recentSelection(config = {}, provider = {}) {
76
+ const model = typeof provider.model === 'string' && provider.model.trim() ? { model: provider.model } : {};
77
+ if (config.namedProfile) return null;
78
+ const login = config.authProvider || provider.authProvider;
79
+ if (login) return AUTH_PROVIDERS.some(item => item.id === login) ? valid({ 'auth-provider': login, ...model }) : null;
80
+ if (config.provider === 'openai' && provider.baseURL) return valid({ provider: 'openai', 'base-url': String(provider.baseURL), ...model });
81
+ return null;
82
+ }