@milpa/comal 0.1.5 → 0.1.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
@@ -10,7 +10,7 @@ The `@milpa/comal` package includes its JavaScript dependencies; it has no insta
10
10
  npx @milpa/comal
11
11
  ```
12
12
 
13
- An interactive first start opens setup inside the TUI. Press Enter to try the offline demo, choose Codex to authorize the subscription in your browser, or enter an OpenAI-compatible endpoint and let Comal discover its model. A failed connection returns to setup in the same terminal. Successful connection routing is remembered in `~/.config/comal/connection.json` (or `$XDG_CONFIG_HOME/comal/connection.json`); keys are never stored there. Explicit flags, environment settings, profiles and resumed sessions take precedence. Noninteractive invocations retain plain output.
13
+ An interactive start reuses saved routing. If routing was never saved but exactly one Comal provider login exists, Comal reconnects with that login and opens the composer. Renewable authorization uses the existing refresh flow. Multiple saved logins show a connection choice. Guided first-run setup appears when no prior connection is available. Press Enter to try the offline demo, choose Codex to authorize the subscription in your browser, or enter an OpenAI-compatible endpoint and let Comal discover its model. A failed connection returns to setup in the same terminal. Successful connection routing is remembered in `~/.config/comal/connection.json` (or `$XDG_CONFIG_HOME/comal/connection.json`); keys are never stored there. Explicit flags, environment settings, profiles and resumed sessions take precedence. Noninteractive invocations retain plain output.
14
14
 
15
15
  npm keeps its cache; Comal's state and credentials remain in your workspace and your configuration, outside that cache. No repository checkout is required.
16
16
 
@@ -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.1.5` or `npm install --global @milpa/comal@0.1.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.1.6` or `npm install --global @milpa/comal@0.1.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.1.5",
3
+ "version": "0.1.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
@@ -4,7 +4,7 @@ registerMessages(cliSpanish);
4
4
  import { RemoteHost } from './remote-control.mjs';
5
5
  import { remoteCommandHelp, isRemoteCommand } from './remote-commands.mjs';
6
6
  import { codeRunDefinition } from './code-run.mjs';
7
- import { hasProviderSelection, loadConnection, onboard } from './onboarding.mjs';
7
+ import { hasProviderSelection, loadConnection, saveConnection, existingLoginConnection, onboard } from './onboarding.mjs';
8
8
  import { stageImage, descriptorForStage, persistHumanImage } from './image-attachments.mjs';
9
9
  import { artifactPlugin } from './artifact-tools.mjs';
10
10
  import { CloudClient, publishArtifact } from './cloud-client.mjs';
@@ -173,10 +173,15 @@ async function boot(args, createScreen, setInterrupt, startupSignal) {
173
173
  const timing = modelTimingSettings({ timeoutMs: v['model-timeout-ms'], idleTimeoutMs: v['model-idle-timeout-ms'] });
174
174
  const chooseSettings = current => sessionProviderSettings({current, profiles, options:v, maxTokens:contextConfig.maxTokens});
175
175
  const explicitConnection = hasProviderSelection(v, profiles);
176
- let savedConnection;
176
+ let savedConnection, recoveredLogin, knownLogins = [];
177
177
  if (!explicitConnection) {
178
- try { savedConnection = await loadConnection(); if (savedConnection) Object.assign(v, savedConnection); }
178
+ try { savedConnection = await loadConnection(); }
179
179
  catch (error) { stderr.write(t('Saved connection could not be loaded: ') + error.message + '\n'); }
180
+ if (!savedConnection && !print) {
181
+ const existing = await existingLoginConnection(authManager); knownLogins = existing.logins;
182
+ recoveredLogin = existing.connection; savedConnection = recoveredLogin;
183
+ }
184
+ if (savedConnection) Object.assign(v, savedConnection);
180
185
  }
181
186
  let settings;
182
187
  try { settings = v.demo ? { provider: 'openai' } : chooseSettings(session); }
@@ -236,11 +241,17 @@ async function boot(args, createScreen, setInterrupt, startupSignal) {
236
241
  };
237
242
  let connected;
238
243
  if (ui && !explicitConnection && !savedConnection) {
239
- const result = await onboard({ ui, profiles, authManager, connect, signal: startupSignal });
244
+ const result = await onboard({ ui, profiles, authManager, connect, signal: startupSignal, logins: knownLogins });
240
245
  if (!result) return;
241
246
  Object.assign(v, result.options); connected = result.connection;
242
247
  } else if (!v.demo) {
243
- try { connected = await connect({}); }
248
+ try {
249
+ connected = await connect({});
250
+ if (recoveredLogin) {
251
+ try { await saveConnection({...recoveredLogin, model: connected.provider.model}); }
252
+ catch (error) { ui?.notice(t('Connected, but settings could not be saved: ') + error.message, true); }
253
+ }
254
+ }
244
255
  catch (error) {
245
256
  if (!ui || startupSignal.aborted) throw error;
246
257
  const action = await ui.setupChoice({ title: t('Connection not ready'), description: error.message, signal: startupSignal, items: [
@@ -248,7 +259,7 @@ async function boot(args, createScreen, setInterrupt, startupSignal) {
248
259
  { id: 'exit', label: t('Exit'), description: t('Keep your saved settings.') },
249
260
  ] });
250
261
  if (action !== 'setup') return;
251
- const result = await onboard({ ui, profiles, authManager, connect: options => connect(options), signal: startupSignal });
262
+ const result = await onboard({ ui, profiles, authManager, connect: options => connect(options), signal: startupSignal, logins: knownLogins });
252
263
  if (!result) return;
253
264
  // A new choice replaces the failed selector rather than mixing endpoints.
254
265
  for (const key of ['provider','base-url','model','profile','auth-provider']) delete v[key];
package/src/i18n/es.mjs CHANGED
@@ -309,5 +309,13 @@ export default Object.freeze({
309
309
  "Esc back": "Esc vuelve",
310
310
  "Working…": "Trabajando…",
311
311
  "Checking…": "Comprobando…",
312
- "The draft changed while preparing the image. Press Enter again to send the current draft.": "El borrador cambió mientras se preparaba la imagen. Pulsa Enter de nuevo para enviar el borrador actual."
312
+ "The draft changed while preparing the image. Press Enter again to send the current draft.": "El borrador cambió mientras se preparaba la imagen. Pulsa Enter de nuevo para enviar el borrador actual.",
313
+ "Saved logins found. Choose the provider for this session.": "Se encontraron logins guardados. Elige el proveedor para esta sesión.",
314
+ "Use your saved login. No new browser authorization is needed.": "Usa tu login guardado. No necesitas otra autorización en el navegador.",
315
+ "This login expired. Sign in again to reconnect.": "Este login caducó. Inicia sesión otra vez para reconectar.",
316
+ "Connecting {provider}": "Conectando {provider}",
317
+ "Authorize {provider}": "Autoriza {provider}",
318
+ "Sign in again to {provider}": "Vuelve a iniciar sesión con {provider}",
319
+ "Start a new sign-in only if you choose this option.": "Inicia otra autenticación solo si eliges esta opción."
320
+
313
321
  });
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import os from 'node:os';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { t } from './i18n/index.mjs';
6
+ import { AUTH_PROVIDERS } from './provider-auth.mjs';
6
7
 
7
8
  const selectors = ['provider', 'base-url', 'model', 'profile', 'providers-config', 'auth-provider'];
8
9
  export function hasProviderSelection(options = {}, profiles = {}, env = process.env) {
@@ -32,35 +33,57 @@ export async function saveConnection(value, { env = process.env } = {}) {
32
33
  finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
33
34
  }
34
35
 
36
+ // Local status only: never starts OAuth or imports credentials from another CLI.
37
+ // Authorization can predate connection.json. Multiple known logins are a choice,
38
+ // even if only one is currently usable; do not guess which account is intended.
39
+ export async function existingLoginConnection(authManager) {
40
+ const results = await Promise.allSettled(AUTH_PROVIDERS.map(provider => authManager.status(provider.id)));
41
+ const logins = results.flatMap((result, index) => {
42
+ if (result.status !== 'fulfilled' || !['authenticated', 'configured', 'expired'].includes(result.value?.status)) return [];
43
+ const {status, canRefresh} = result.value;
44
+ return [{id: AUTH_PROVIDERS[index].id, label: AUTH_PROVIDERS[index].label,
45
+ usable: status !== 'expired' || canRefresh === true}];
46
+ });
47
+ return {logins, connection: logins.length === 1 && logins[0].usable ? {'auth-provider': logins[0].id} : null};
48
+ }
49
+
35
50
  // The terminal stays owned by the caller. Only a successfully validated connection
36
51
  // is remembered; credentials live in AuthManager/environment, never in this file.
37
- export async function onboard({ ui, profiles, authManager, connect, signal, env = process.env }) {
52
+ export async function onboard({ ui, profiles, authManager, connect, signal, env = process.env, logins = [] }) {
38
53
  while (!signal?.aborted && !ui.closed) {
39
- const choice = await ui.setupChoice({ title: t('Your first turn'), description: t('Choose how to start. Stay here while Comal connects.'), signal, items: [
40
- { id: 'demo', label: t('Try the offline demo'), description: t('No account or model. A scripted tool cycle; no inference.') },
54
+ const returning = logins.length > 0;
55
+ const demo = {id: 'demo', label: t('Try the offline demo'), description: t('No account or model. A scripted tool cycle; no inference.')};
56
+ const choice = await ui.setupChoice({ title: t(returning ? 'Choose a connection' : 'Your first turn'), description: t(returning ? 'Saved logins found. Choose the provider for this session.' : 'Choose how to start. Stay here while Comal connects.'), signal, items: [
57
+ ...(!returning ? [demo] : []),
58
+ ...logins.map(login => ({id: 'saved:' + login.id, label: login.label, description: t(login.usable ? 'Use your saved login. No new browser authorization is needed.' : 'This login expired. Sign in again to reconnect.')})),
59
+ ...logins.filter(login => login.usable).map(login => ({id: 'login:' + login.id, label: t('Sign in again to {provider}', {provider: login.label}), description: t('Start a new sign-in only if you choose this option.')})),
41
60
  ...profiles.profiles.map(profile => ({ id: 'profile:' + profile.name, label: profile.name, description: `${profile.provider} · ${profile.model || t('discover model')}` })),
42
- { id: 'codex', label: t('Connect Codex'), description: t('Sign in with your existing subscription in the browser.') },
61
+ ...(!logins.some(login => login.id === 'codex') ? [{ id: 'codex', label: t('Connect Codex'), description: t('Sign in with your existing subscription in the browser.') }] : []),
43
62
  { id: 'server', label: t('Connect a model server'), description: t('OpenAI-compatible endpoint. API keys stay in your environment.') },
63
+ ...(returning ? [demo] : []),
44
64
  ] });
45
65
  if (!choice || signal?.aborted || ui.closed) return null;
46
66
  if (choice === 'demo') { ui.clearSetup(); return { options: { demo: true } }; }
47
67
  let options;
48
68
  try {
49
69
  if (choice.startsWith('profile:')) options = { profile: choice.slice(8) };
50
- else if (choice === 'codex') {
51
- ui.setupStatus({ title: t('Connecting Codex'), description: t('Waiting for browser authorization. Esc cancels this connection.') });
70
+ else if (choice.startsWith('saved:') && logins.some(login => 'saved:' + login.id === choice && login.usable)) options = {'auth-provider': choice.slice(6)};
71
+ else if (choice === 'codex' || choice.startsWith('saved:') || choice.startsWith('login:')) {
72
+ const target = choice === 'codex' ? 'codex' : logins.find(login => ['saved:' + login.id, 'login:' + login.id].includes(choice))?.id;
73
+ if (!target) throw Error('Unknown saved login.');
74
+ ui.setupStatus({ title: target === 'codex' ? t('Connecting Codex') : t('Connecting {provider}', {provider: target}), description: t('Waiting for browser authorization. Esc cancels this connection.') });
52
75
  const operation = new AbortController();
53
76
  ui.callbacks.onSetupCancel = () => operation.abort();
54
77
  try {
55
- const status = await authManager.status('codex');
78
+ const status = await authManager.status(target);
56
79
  operation.signal.throwIfAborted(); signal?.throwIfAborted();
57
- if (status.status !== 'authenticated') await authManager.login('codex', { signal: signal ? AbortSignal.any([signal, operation.signal]) : operation.signal, onEvent: event => {
80
+ if (choice.startsWith('login:') || !['authenticated', 'configured'].includes(status.status)) await authManager.login(target, { signal: signal ? AbortSignal.any([signal, operation.signal]) : operation.signal, onEvent: event => {
58
81
  if (operation.signal.aborted || signal?.aborted || ui.closed) return;
59
- if (event.type === 'device_code') ui.setupStatus({ title: t('Authorize Codex'), description: `${event.verification_uri}\n\n${t('Code')}: ${event.user_code}\n\n${t('Approve only if you started this connection. Esc cancels.')}` });
82
+ if (event.type === 'device_code') ui.setupStatus({ title: target === 'codex' ? t('Authorize Codex') : t('Authorize {provider}', {provider: target}), description: `${event.verification_uri}\n\n${t('Code')}: ${event.user_code}\n\n${t('Approve only if you started this connection. Esc cancels.')}` });
60
83
  } });
61
84
  operation.signal.throwIfAborted(); signal?.throwIfAborted();
62
85
  } finally { delete ui.callbacks.onSetupCancel; }
63
- options = { 'auth-provider': 'codex' };
86
+ options = { 'auth-provider': target };
64
87
  } else {
65
88
  const endpoint = await ui.setupInput({ title: t('Model server'), description: t('Endpoint URL. No API key or password in the URL.'), value: 'http://127.0.0.1:8080/v1', signal, validate: text => { try { normalizeConnection({ provider: 'openai', 'base-url': text }); return true; } catch (error) { return error.message; } } });
66
89
  if (!endpoint) continue;
@@ -99,6 +99,7 @@ export class AuthManager {
99
99
  const p = definition(name), record = await this._read(p.id);
100
100
  return { provider: p.id, method: record?.method || p.method, subscription: p.subscription,
101
101
  status: !record ? 'logged_out' : record.expiresAt && record.expiresAt <= this.now() ? 'expired' : record.method === 'device_code' ? 'authenticated' : 'configured',
102
+ ...(record?.method === 'device_code' ? {canRefresh: secret(record.refreshToken)} : {}),
102
103
  ...(record?.expiresAt ? { expiresAt: record.expiresAt } : {}),
103
104
  ...(p.apiKeyEnv ? { apiKeyEnv: p.apiKeyEnv } : {}), documentation: p.documentation,
104
105
  ...(p.experimental ? { experimental: true, note: 'OAuth compatible with the public Kimi CLI code; the documented route for external clients is a Kimi Code key (--api-key-env KIMI_CODE_API_KEY).' } : {}),