@milpa/comal 0.1.4 → 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 +2 -2
- package/package.json +1 -1
- package/src/cli.mjs +17 -6
- package/src/i18n/es.mjs +9 -1
- package/src/onboarding.mjs +33 -10
- package/src/provider-auth.mjs +1 -0
- package/src/tui/controller.mjs +6 -1
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
|
|
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.
|
|
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
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();
|
|
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 {
|
|
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
|
});
|
package/src/onboarding.mjs
CHANGED
|
@@ -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
|
|
40
|
-
|
|
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
|
|
51
|
-
|
|
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(
|
|
78
|
+
const status = await authManager.status(target);
|
|
56
79
|
operation.signal.throwIfAborted(); signal?.throwIfAborted();
|
|
57
|
-
if (
|
|
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':
|
|
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;
|
package/src/provider-auth.mjs
CHANGED
|
@@ -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).' } : {}),
|
package/src/tui/controller.mjs
CHANGED
|
@@ -233,7 +233,12 @@ export class InteractiveController {
|
|
|
233
233
|
if(failure){const state=this.connections.get(id);this.ui.notice(t(state.message),true);await this.recoverConnection(id,requested);}
|
|
234
234
|
}
|
|
235
235
|
scheduleConnectionRecovery(id,action){
|
|
236
|
-
|
|
236
|
+
const runner=this.runner;
|
|
237
|
+
// Finishing a queued control persists its outcome asynchronously. Wait for
|
|
238
|
+
// that boundary; one event-loop tick can still find the runner occupied.
|
|
239
|
+
Promise.resolve(runner.processing).catch(()=>{}).then(()=>{
|
|
240
|
+
if(this.runner===runner)setImmediate(()=>this.recoverConnection(id,action).catch(()=>{}));
|
|
241
|
+
});
|
|
237
242
|
}
|
|
238
243
|
async recoverConnection(id,action){
|
|
239
244
|
if(this.closed || this.ui.busy || this.runner.processing || this.modalOverlay() || this.ui.permission)return;
|