dsh-tg-bridge 1.31.1 → 1.32.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/callbacks.mjs +8 -6
- package/commands-registry.mjs +1 -1
- package/control/cmd-endpoint.mjs +89 -0
- package/control/cmd-views.mjs +36 -12
- package/control/endpoint.mjs +272 -0
- package/control/model-card.mjs +194 -0
- package/control/models.mjs +68 -0
- package/control.mjs +2 -1
- package/i18n/en/core.mjs +265 -260
- package/i18n/en/ctrl.mjs +1 -1
- package/i18n/en/endpoint.mjs +32 -0
- package/i18n/en/model.mjs +19 -0
- package/i18n/en.mjs +3 -1
- package/i18n/ru/core.mjs +265 -260
- package/i18n/ru/ctrl.mjs +1 -1
- package/i18n/ru/endpoint.mjs +32 -0
- package/i18n/ru/model.mjs +19 -0
- package/i18n/ru.mjs +3 -1
- package/i18n/zh/core.mjs +265 -260
- package/i18n/zh/ctrl.mjs +1 -1
- package/i18n/zh/endpoint.mjs +32 -0
- package/i18n/zh/model.mjs +19 -0
- package/i18n/zh.mjs +3 -1
- package/menu-card.mjs +3 -2
- package/package.json +4 -1
- package/settings-card.mjs +14 -0
package/callbacks.mjs
CHANGED
|
@@ -15,6 +15,7 @@ import { approvals, enqueue, lastPrompt, maxParallel, redeliver, rewindUsed } fr
|
|
|
15
15
|
import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.mjs';
|
|
16
16
|
import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
|
|
17
17
|
import { diffPressRouter } from './control/cmd-diff.mjs';
|
|
18
|
+
import { handleModelPress, MODEL_PREFIX, modelPressRouter } from './control/model-card.mjs';
|
|
18
19
|
import { runCommandFromButton } from './run-command.mjs';
|
|
19
20
|
import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
|
|
20
21
|
import { config, done, log, saveConfig, saveState, state } from './state.mjs';
|
|
@@ -288,13 +289,14 @@ export async function handleCallback(query) {
|
|
|
288
289
|
return;
|
|
289
290
|
}
|
|
290
291
|
|
|
292
|
+
// Two card presses, one rule each: what the card said is re-read from the
|
|
293
|
+
// thing it described before acting, never trusted from the button. The diff
|
|
294
|
+
// checks its hunk hash, the model card checks the route its profile declares.
|
|
291
295
|
if (data.startsWith('df:')) {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
const press = diffPressRouter({ chatId, threadId, key, lang, config, state, answer, clearKeyboard, log, enqueue, handleMessage });
|
|
297
|
-
if (await press(data)) return;
|
|
296
|
+
if (await diffPressRouter({ chatId, threadId, key, lang, config, state, answer, clearKeyboard, log, enqueue, handleMessage })(data)) return;
|
|
297
|
+
}
|
|
298
|
+
if (data.startsWith(MODEL_PREFIX)) {
|
|
299
|
+
if (await modelPressRouter({ chatId, threadId, messageId, key, lang, answer, log })(data)) return;
|
|
298
300
|
}
|
|
299
301
|
|
|
300
302
|
if (data.startsWith('t:')) {
|
package/commands-registry.mjs
CHANGED
|
@@ -12,7 +12,7 @@ export const CONTROL_COMMANDS = [
|
|
|
12
12
|
'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
|
|
13
13
|
'prices', 'cost', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
|
|
14
14
|
'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
|
|
15
|
-
'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff',
|
|
15
|
+
'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint',
|
|
16
16
|
];
|
|
17
17
|
|
|
18
18
|
/**
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// `/endpoint` — the provider list, read and edited from the chat.
|
|
2
|
+
//
|
|
3
|
+
// Adding an endpoint is four facts typed once. Sending them through an AI turn
|
|
4
|
+
// would mean a slow answer, a paraphrase of a URL that has to be exact, and a
|
|
5
|
+
// token spent on what a text edit does — so the command parses and writes the
|
|
6
|
+
// patch itself, and says in the chat what it changed.
|
|
7
|
+
import { t } from '../i18n.mjs';
|
|
8
|
+
import { endpointRows, parseEndpointArgs, applyEndpoint } from './endpoint.mjs';
|
|
9
|
+
import { routesOf, modelOf } from './models.mjs';
|
|
10
|
+
|
|
11
|
+
/** Why a line was refused, in words a person can act on. */
|
|
12
|
+
function whyText(lang, why, parsed) {
|
|
13
|
+
const key = `ctrl.endpoint.why.${String(why).replace('.', '_')}`;
|
|
14
|
+
const vars = {
|
|
15
|
+
id: parsed?.id || '',
|
|
16
|
+
model: parsed?.model || '',
|
|
17
|
+
form: t(lang, 'ctrl.endpoint.addForm'),
|
|
18
|
+
};
|
|
19
|
+
// An unknown reason must not print a key at the person: the generic line still
|
|
20
|
+
// says what to type, which is the only thing the answer is for.
|
|
21
|
+
const text = t(lang, key, vars);
|
|
22
|
+
return text.startsWith('ctrl.endpoint.') ? t(lang, 'ctrl.endpoint.why.usage', vars) : text;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function listText(lang, profile) {
|
|
26
|
+
const rows = endpointRows(profile);
|
|
27
|
+
const current = modelOf(profile);
|
|
28
|
+
if (rows.length === 0) return t(lang, 'ctrl.endpoint.empty', { profile });
|
|
29
|
+
const lines = [t(lang, 'ctrl.endpoint.listHead', { profile, n: rows.length }), ''];
|
|
30
|
+
for (const row of rows) {
|
|
31
|
+
const live = row.id === current.provider ? t(lang, 'ctrl.endpoint.inUse') : '';
|
|
32
|
+
lines.push(`${live}${row.id} · ${row.models.length} ${t(lang, 'ctrl.endpoint.models')}`);
|
|
33
|
+
lines.push(` ${row.baseURL || t(lang, 'ctrl.endpoint.noUrl')}${row.keyEnv ? ` · ${row.keyEnv}` : ''}`);
|
|
34
|
+
}
|
|
35
|
+
lines.push('', t(lang, 'ctrl.endpoint.listHint'));
|
|
36
|
+
return lines.join('\n');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function handleEndpointCommands(ctx) {
|
|
40
|
+
const { effective, arg, lang, reply, log, profile, config } = ctx;
|
|
41
|
+
if (effective !== '/endpoint') return false;
|
|
42
|
+
const activeProfile = profile || config?.profile || 'headless';
|
|
43
|
+
const parsed = parseEndpointArgs(arg);
|
|
44
|
+
if (!parsed.ok) {
|
|
45
|
+
await reply(whyText(lang, parsed.why, parsed));
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
if (parsed.verb === 'list') {
|
|
49
|
+
await reply(listText(lang, activeProfile));
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
const result = applyEndpoint(activeProfile, parsed);
|
|
53
|
+
if (!result.ok) {
|
|
54
|
+
// `unchanged` is not a failure: the person re-typed what was already there,
|
|
55
|
+
// and saying so is more useful than reporting an error on a no-op.
|
|
56
|
+
await reply(parsed.verb === 'add' && result.why === 'unchanged'
|
|
57
|
+
? t(lang, 'ctrl.endpoint.unchanged', { id: parsed.id })
|
|
58
|
+
: whyText(lang, result.why, parsed));
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
log(`endpoint ${parsed.verb} ${result.id} in ${activeProfile}`);
|
|
62
|
+
if (parsed.verb === 'rm') {
|
|
63
|
+
await reply(t(lang, 'ctrl.endpoint.removed', { id: result.id, profile: activeProfile }));
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
const added = result.modelsAdded?.length || 0;
|
|
67
|
+
if (added === 0) {
|
|
68
|
+
await reply(t(lang, result.added ? 'ctrl.endpoint.addedNoModels' : 'ctrl.endpoint.updatedNoModels', {
|
|
69
|
+
id: result.id,
|
|
70
|
+
profile: activeProfile,
|
|
71
|
+
}));
|
|
72
|
+
} else {
|
|
73
|
+
await reply(
|
|
74
|
+
t(lang, result.added ? 'ctrl.endpoint.added' : 'ctrl.endpoint.updated', {
|
|
75
|
+
id: result.id,
|
|
76
|
+
profile: activeProfile,
|
|
77
|
+
n: added,
|
|
78
|
+
models: result.modelsAdded.join(', '),
|
|
79
|
+
}),
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
// A new route is a new button on the `/model` card, so the next line points at
|
|
83
|
+
// it instead of leaving the person to discover it on their own.
|
|
84
|
+
const routes = routesOf(activeProfile).filter((route) => route.provider === result.id);
|
|
85
|
+
if (routes.length > 0) {
|
|
86
|
+
await reply(t(lang, 'ctrl.endpoint.nowPick', { n: routes.length, id: result.id }));
|
|
87
|
+
}
|
|
88
|
+
return true;
|
|
89
|
+
}
|
package/control/cmd-views.mjs
CHANGED
|
@@ -25,13 +25,15 @@ import { UPDATE_DEFAULTS, describeUpdate, modeChange, updateState } from '../upd
|
|
|
25
25
|
import { isNewer, pluginInfo, rowLine, searchPlugins } from '../plugin-search.mjs';
|
|
26
26
|
import { COMMAND_ALIASES, CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from '../commands-registry.mjs';
|
|
27
27
|
import { APP, CLI_JS, DSH_CMD, DSH_HOME, EXE, HOME, PROFILES, THOUGHT_DIR } from '../paths.mjs';
|
|
28
|
-
import { read, readJson, patchPath, pkgPath, OVERLAY_MARK, modelsOf, modelOf, windowOf, modelIndent, depthOf, modelsReport, setModel, disabledIds, setDisabled, writePatch } from './models.mjs';
|
|
28
|
+
import { read, readJson, patchPath, pkgPath, OVERLAY_MARK, modelsOf, modelOf, windowOf, modelIndent, depthOf, modelsReport, setModel, disabledIds, setDisabled, writePatch, routesOf } from './models.mjs';
|
|
29
|
+
import { modelCard } from './model-card.mjs';
|
|
29
30
|
import { listPids, waitForExit, waitForStart, pluginsOf, bundleRowIds, addBundle, removeBundle, createProfile, dshPlugin } from './plugins.mjs';
|
|
30
31
|
import { cwdSlug, bareId, stamp, recentSessions, sessionTitle } from './sessions.mjs';
|
|
31
32
|
import { agentsOf, fleetOf, patchRows, skillsOf, AGENTS, PERSONA_HEADING, soulOf, setSoul } from './agents.mjs';
|
|
32
33
|
import { fmt, AGENTSETS, agentset, agentsetOf, profileRowOf, bindAgentset, agentsetCard, agentsetKeyboard } from './agentsets.mjs';
|
|
33
34
|
import { taskKeyboard, goalView, taskView, filterLogLines } from './tasks.mjs';
|
|
34
35
|
import { reasoningMode } from '../notes.mjs';
|
|
36
|
+
import { saveConfig } from '../state.mjs';
|
|
35
37
|
import { updatePolicy, bridgeRoot, copyRelease, installRelease, bridgeVersion, newestModuleMtime, npmLatest, npmLatestAsync } from './release.mjs';
|
|
36
38
|
import { presetOf } from '../profile-view.mjs';
|
|
37
39
|
import { costReport } from '../cost.mjs';
|
|
@@ -114,10 +116,13 @@ export async function handleViewCommands(ctx) {
|
|
|
114
116
|
case '/model': {
|
|
115
117
|
const [wanted = '', scope = ''] = (arg || '').split(/\s+/);
|
|
116
118
|
if (!wanted) {
|
|
117
|
-
// One command, two states: bare `/model`
|
|
118
|
-
// `/model <
|
|
119
|
-
//
|
|
120
|
-
|
|
119
|
+
// One command, two states: bare `/model` offers the routes as buttons,
|
|
120
|
+
// and `/model <route>` picks one. The list is provider + model, not the
|
|
121
|
+
// ids alone: `deepseek-v4.1-flash` is declared by two providers, so a
|
|
122
|
+
// list of ids showed the same name twice and said nothing about where
|
|
123
|
+
// the answers would come from.
|
|
124
|
+
const card = modelCard({ profile: activeProfile, routes: routesOf(activeProfile), t: (k, v) => t(lang, k, v) });
|
|
125
|
+
say(card.text, { keyboard: card.keyboard });
|
|
121
126
|
return true;
|
|
122
127
|
}
|
|
123
128
|
if (!setModel(activeProfile, wanted)) {
|
|
@@ -283,19 +288,38 @@ export async function handleViewCommands(ctx) {
|
|
|
283
288
|
// One switch for "how much of the decision trail reaches me": off, the
|
|
284
289
|
// progress card, or the chat itself. Anything else prints the current
|
|
285
290
|
// state, so a bare /reasoning never guesses.
|
|
286
|
-
|
|
291
|
+
//
|
|
292
|
+
// Two scopes, because the question has two answers: a topic you want to
|
|
293
|
+
// watch closely and every other topic that should stay quiet. `all` sets
|
|
294
|
+
// the default the other topics inherit; without it the change is this
|
|
295
|
+
// topic only, which is the smaller change and the safer default.
|
|
296
|
+
const words = String(arg || '').trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
297
|
+
const global = words.length > 1 && (words[1] === 'all' || words[1] === 'global');
|
|
298
|
+
const wanted = words[0] || '';
|
|
287
299
|
const mode = reasoningMode(state, config, key);
|
|
288
300
|
const next = { on: 'card', card: 'card', chat: 'chat', off: 'off' }[wanted];
|
|
289
301
|
if (!next) {
|
|
290
|
-
say(t(lang, 'msg.
|
|
302
|
+
say(t(lang, global ? 'msg.reasoningGlobalState' : 'msg.reasoningState', {
|
|
303
|
+
state: t(lang, `msg.reasoningMode.${mode}`),
|
|
304
|
+
all: t(lang, `msg.reasoningMode.${reasoningMode(state, config, '')}`),
|
|
305
|
+
}));
|
|
291
306
|
return true;
|
|
292
307
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
308
|
+
if (global) {
|
|
309
|
+
// The default lives in the config, not in state: it is what a topic with
|
|
310
|
+
// no opinion reads, and it has to survive a cleared state.json.
|
|
311
|
+
config.reasoning = next;
|
|
312
|
+
ctx.saveConfig?.() ?? saveConfig();
|
|
313
|
+
} else {
|
|
314
|
+
state.reasoning = state.reasoning || {};
|
|
315
|
+
// `on` is the old spelling of the card and stays accepted: it is the word
|
|
316
|
+
// the previous release printed, and a chat is full of those instructions.
|
|
317
|
+
state.reasoning[key] = next;
|
|
318
|
+
}
|
|
297
319
|
ctx.saveState();
|
|
298
|
-
|
|
320
|
+
const suffix = global ? 'All' : next === 'off' ? 'Off' : next === 'chat' ? 'Chat' : 'On';
|
|
321
|
+
say(t(lang, `msg.reasoning${suffix}`));
|
|
322
|
+
if (global) say(t(lang, 'msg.reasoningTopicWins'));
|
|
299
323
|
return true;
|
|
300
324
|
}
|
|
301
325
|
case '/pin': {
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// Adding an endpoint to a profile from the chat, without a model in the loop.
|
|
2
|
+
//
|
|
3
|
+
// "I have a new provider, here is its URL and its key" is a configuration edit,
|
|
4
|
+
// not a conversation: it is four facts typed once, and routing it through an AI
|
|
5
|
+
// turn means a slow answer, a paraphrase of a URL that must be exact, and a
|
|
6
|
+
// token spent on what a `sed` could do. So `/endpoint add` parses the line and
|
|
7
|
+
// writes the patch itself.
|
|
8
|
+
//
|
|
9
|
+
// What it refuses matters more than what it does. A provider row that is
|
|
10
|
+
// malformed, duplicated, or missing its key variable turns a working profile
|
|
11
|
+
// into one that cannot start, and the failure would show up on the next turn as
|
|
12
|
+
// "the bot is broken" rather than "the line you typed has a typo". Every check
|
|
13
|
+
// below exists because that class of silent breakage is expensive to trace.
|
|
14
|
+
import { read, writePatch, patchPath } from './models.mjs';
|
|
15
|
+
import { providerRows } from '../model-probe.mjs';
|
|
16
|
+
|
|
17
|
+
/** A provider id the patch can carry and a button can name. */
|
|
18
|
+
const ID = /^[a-z][a-z0-9-]{1,30}$/;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A base URL that a request can be built on.
|
|
22
|
+
*
|
|
23
|
+
* https only: an endpoint is where API keys are sent, and a plain-http one
|
|
24
|
+
* would leak the key on every turn. localhost is the one exception that earns
|
|
25
|
+
* it — a model server on the same machine never crosses the network.
|
|
26
|
+
*/
|
|
27
|
+
export function checkBaseUrl(value) {
|
|
28
|
+
const text = String(value || '').trim();
|
|
29
|
+
if (!text) return { ok: false, why: 'empty' };
|
|
30
|
+
let url;
|
|
31
|
+
try {
|
|
32
|
+
url = new URL(text);
|
|
33
|
+
} catch {
|
|
34
|
+
return { ok: false, why: 'notUrl' };
|
|
35
|
+
}
|
|
36
|
+
const local = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(url.hostname);
|
|
37
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) return { ok: false, why: 'insecure' };
|
|
38
|
+
if (!url.hostname) return { ok: false, why: 'notUrl' };
|
|
39
|
+
return { ok: true, url: text.replace(/\/+$/, ''), local };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The env var a key is read from: a name, never the key itself. */
|
|
43
|
+
export function checkKeyEnv(value) {
|
|
44
|
+
const name = String(value || '').trim();
|
|
45
|
+
if (!name) return { ok: false, why: 'empty' };
|
|
46
|
+
if (!/^[A-Z][A-Z0-9_]{2,60}$/.test(name)) return { ok: false, why: 'notName' };
|
|
47
|
+
return { ok: true, name };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Parse `/endpoint add <id> <baseURL> <keyEnv> [model,model,...]`.
|
|
52
|
+
*
|
|
53
|
+
* The model list is optional: an endpoint is worth declaring before a model is
|
|
54
|
+
* known, because the id of a model is often what the first request reveals.
|
|
55
|
+
* Declaring the endpoint first and the model after is two honest steps; making
|
|
56
|
+
* the model mandatory would mean a person guesses an id and the guess ships.
|
|
57
|
+
*/
|
|
58
|
+
export function parseEndpointArgs(args) {
|
|
59
|
+
const parts = String(args || '').trim().split(/\s+/).filter(Boolean);
|
|
60
|
+
if (parts.length === 0) return { ok: false, why: 'usage' };
|
|
61
|
+
const verb = parts[0].toLowerCase();
|
|
62
|
+
if (verb === 'list' || verb === 'check') return { ok: true, verb, rest: parts.slice(1) };
|
|
63
|
+
if (verb === 'rm' || verb === 'remove') {
|
|
64
|
+
if (parts.length !== 2) return { ok: false, why: 'usage' };
|
|
65
|
+
const id = parts[1].toLowerCase();
|
|
66
|
+
if (!ID.test(id)) return { ok: false, why: 'badId' };
|
|
67
|
+
return { ok: true, verb: 'rm', id };
|
|
68
|
+
}
|
|
69
|
+
if (verb !== 'add') return { ok: false, why: 'usage' };
|
|
70
|
+
if (parts.length < 4) return { ok: false, why: 'usage' };
|
|
71
|
+
const id = parts[1].toLowerCase();
|
|
72
|
+
if (!ID.test(id)) return { ok: false, why: 'badId' };
|
|
73
|
+
const url = checkBaseUrl(parts[2]);
|
|
74
|
+
if (!url.ok) return { ok: false, why: `url.${url.why}` };
|
|
75
|
+
const key = checkKeyEnv(parts[3]);
|
|
76
|
+
if (!key.ok) return { ok: false, why: `key.${key.why}` };
|
|
77
|
+
const models = parts.slice(4).join(',').split(',').map((s) => s.trim()).filter(Boolean);
|
|
78
|
+
for (const model of models) {
|
|
79
|
+
if (!/^[\w.:-]+$/.test(model) || model.length > 80) return { ok: false, why: 'badModel', model };
|
|
80
|
+
}
|
|
81
|
+
return { ok: true, verb: 'add', id, baseURL: url.url, keyEnv: key.name, models };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The provider block as text, or '' when the profile has no provider with that id. */
|
|
85
|
+
export function providerBlock(text, id) {
|
|
86
|
+
const lines = String(text || '').split('\n');
|
|
87
|
+
const at = lines.findIndex((line) => /^\s*providers:\s*$/.test(line));
|
|
88
|
+
if (at < 0) return { ok: false, why: 'noProviders' };
|
|
89
|
+
const rowIndent = (/^(\s*)/.exec(lines.slice(at + 1).find((line) => line.trim() && !/^\s*#/.test(line)) || '') || [])[1]?.length;
|
|
90
|
+
if (!Number.isFinite(rowIndent)) return { ok: false, why: 'noProviders' };
|
|
91
|
+
let start = -1;
|
|
92
|
+
for (let i = at + 1; i < lines.length; i += 1) {
|
|
93
|
+
const line = lines[i];
|
|
94
|
+
if (!line.trim() || /^\s*#/.test(line)) continue;
|
|
95
|
+
const indent = (/^\s*/.exec(line) || [''])[0].length;
|
|
96
|
+
if (indent < rowIndent) break;
|
|
97
|
+
if (indent !== rowIndent) continue;
|
|
98
|
+
const row = /^\s*([\w.-]+):\s*$/.exec(line);
|
|
99
|
+
if (!row) continue;
|
|
100
|
+
if (start >= 0) return { ok: true, start, end: i, rowIndent };
|
|
101
|
+
if (row[1] !== id) continue;
|
|
102
|
+
start = i;
|
|
103
|
+
}
|
|
104
|
+
if (start < 0) return { ok: false, why: 'missing' };
|
|
105
|
+
// The last provider's block ends where the provider list ends, which is the
|
|
106
|
+
// first line shallower than a provider row — not the end of the file. Reading
|
|
107
|
+
// the end of the file as its end would delete every plugin row below it.
|
|
108
|
+
let end = start + 1;
|
|
109
|
+
for (let i = start + 1; i < lines.length; i += 1) {
|
|
110
|
+
const line = lines[i];
|
|
111
|
+
if (!line.trim()) {
|
|
112
|
+
end = i + 1;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const indent = (/^\s*/.exec(line) || [''])[0].length;
|
|
116
|
+
if (/^\s*#/.test(line)) {
|
|
117
|
+
end = i + 1;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (indent < rowIndent) break;
|
|
121
|
+
end = i + 1;
|
|
122
|
+
}
|
|
123
|
+
return { ok: true, start, end, rowIndent };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The provider rows a profile declares, with the facts the list shows. */
|
|
127
|
+
export function endpointRows(profile) {
|
|
128
|
+
const text = read(patchPath(profile));
|
|
129
|
+
const lines = text.split('\n');
|
|
130
|
+
const models = new Map();
|
|
131
|
+
let current = '';
|
|
132
|
+
let inModels = false;
|
|
133
|
+
for (const line of lines) {
|
|
134
|
+
const row = /^ {6}([\w.-]+):\s*$/.exec(line);
|
|
135
|
+
if (row) {
|
|
136
|
+
current = row[1];
|
|
137
|
+
inModels = false;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (/^\s*models:\s*$/.test(line)) {
|
|
141
|
+
inModels = true;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const id = /^\s*-\s*id:\s*(\S+)/.exec(line);
|
|
145
|
+
if (id && inModels && current) {
|
|
146
|
+
models.set(current, [...(models.get(current) || []), id[1]]);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (line.trim() && (/^\s*/.exec(line) || [''])[0].length <= 6) inModels = false;
|
|
150
|
+
}
|
|
151
|
+
return providerRows(text).map((row) => {
|
|
152
|
+
const baseURL = /^\s*baseURL:\s*(\S+)/m.exec(row.lines.join('\n'));
|
|
153
|
+
const apiKeyEnv = /^\s*apiKeyEnv:\s*(\S+)/m.exec(row.lines.join('\n'));
|
|
154
|
+
return {
|
|
155
|
+
id: row.id,
|
|
156
|
+
baseURL: baseURL ? baseURL[1] : '',
|
|
157
|
+
keyEnv: apiKeyEnv ? apiKeyEnv[1] : '',
|
|
158
|
+
models: models.get(row.id) || [],
|
|
159
|
+
};
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Rebuild the patch with one provider added, replaced, or removed.
|
|
165
|
+
*
|
|
166
|
+
* Returns the new text instead of writing it, so the caller can show the diff it
|
|
167
|
+
* is about to save and a test can hold the whole transformation without touching
|
|
168
|
+
* a profile directory.
|
|
169
|
+
*/
|
|
170
|
+
export function withEndpoint(text, { verb, id, baseURL, keyEnv, models }) {
|
|
171
|
+
const span = providerBlock(text, id);
|
|
172
|
+
if (verb === 'rm') {
|
|
173
|
+
if (!span.ok) return { ok: false, why: span.why === 'missing' ? 'missing' : span.why };
|
|
174
|
+
const lines = text.split('\n');
|
|
175
|
+
return { ok: true, text: [...lines.slice(0, span.start), ...lines.slice(span.end)].join('\n'), id };
|
|
176
|
+
}
|
|
177
|
+
// A new provider is written the way every shipped one is: the same keys in the
|
|
178
|
+
// same order, so a file edited from the chat and a file edited by hand stay
|
|
179
|
+
// readable next to each other.
|
|
180
|
+
const block = (indent, extra) => {
|
|
181
|
+
const pad = ' '.repeat(indent);
|
|
182
|
+
const out = [
|
|
183
|
+
`${pad}${id}:`,
|
|
184
|
+
`${pad} displayName: ${id}`,
|
|
185
|
+
`${pad} apiKeyEnv: ${keyEnv}`,
|
|
186
|
+
`${pad} api: openai-responses`,
|
|
187
|
+
`${pad} baseURL: ${baseURL}`,
|
|
188
|
+
`${pad} defaultContextWindow: 1000000`,
|
|
189
|
+
];
|
|
190
|
+
if (extra.length > 0) {
|
|
191
|
+
out.push(`${pad} models:`);
|
|
192
|
+
for (const model of extra) out.push(`${pad} - id: ${model}`, `${pad} name: ${model}`);
|
|
193
|
+
}
|
|
194
|
+
return out;
|
|
195
|
+
};
|
|
196
|
+
const lines = text.split('\n');
|
|
197
|
+
if (!span.ok) {
|
|
198
|
+
if (span.why === 'noProviders') return { ok: false, why: 'noProviders' };
|
|
199
|
+
if (span.why === 'missing') {
|
|
200
|
+
const at = lines.findIndex((line) => /^\s*providers:\s*$/.test(line));
|
|
201
|
+
if (at < 0) return { ok: false, why: 'noProviders' };
|
|
202
|
+
const next = lines.slice(at + 1).find((line) => line.trim() && !/^\s*#/.test(line));
|
|
203
|
+
const indent = next ? (/^(\s*)/.exec(next) || [''])[0].length : 6;
|
|
204
|
+
// Appended after the last provider line of the block: a reader scrolling
|
|
205
|
+
// the file finds the new endpoint with the others, not at the bottom.
|
|
206
|
+
const end = lines.findIndex((line, i) => i > at && line.trim() && (/^\s*/.exec(line) || [''])[0].length < indent);
|
|
207
|
+
const stop = end < 0 ? lines.length : end;
|
|
208
|
+
return { ok: true, text: [...lines.slice(0, stop), ...block(indent, models), ...lines.slice(stop)].join('\n'), id, added: true, modelsAdded: models };
|
|
209
|
+
}
|
|
210
|
+
return { ok: false, why: span.why };
|
|
211
|
+
}
|
|
212
|
+
// Replacing an existing provider keeps its line position and replaces only the
|
|
213
|
+
// keys this command owns, so a hand-added `retryPolicy` or `models` list the
|
|
214
|
+
// person curated is not wiped by a typo fix.
|
|
215
|
+
const existing = lines.slice(span.start, span.end).join('\n');
|
|
216
|
+
let next = existing;
|
|
217
|
+
next = /^\s*baseURL:\s*\S+/m.test(next)
|
|
218
|
+
? next.replace(/^(\s*baseURL:\s*)\S+/m, `$1${baseURL}`)
|
|
219
|
+
: next.replace(/^(\s*apiKeyEnv:.*)$/m, `$1\n${' '.repeat(span.rowIndent + 2)}baseURL: ${baseURL}`);
|
|
220
|
+
next = /^\s*apiKeyEnv:\s*\S+/m.test(next)
|
|
221
|
+
? next.replace(/^(\s*apiKeyEnv:\s*)\S+/m, `$1${keyEnv}`)
|
|
222
|
+
: next.replace(/^(\s*displayName:.*)$/m, `$1\n${' '.repeat(span.rowIndent + 2)}apiKeyEnv: ${keyEnv}`);
|
|
223
|
+
const missing = models.filter((model) => !new RegExp(`^\\s*-\\s*id:\\s*${model.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`, 'm').test(next));
|
|
224
|
+
if (missing.length > 0) {
|
|
225
|
+
const pad = ' '.repeat(span.rowIndent + 4);
|
|
226
|
+
const row = missing.map((model) => `\n${pad}- id: ${model}\n${' '.repeat(span.rowIndent + 6)}name: ${model}`).join('');
|
|
227
|
+
// The new models go after the last model of the list, not before it: the
|
|
228
|
+
// list is ordered by the patch's author and appending is the one edit that
|
|
229
|
+
// cannot reorder what is already there. `replace` with a string keeps the
|
|
230
|
+
// surviving prefix intact, so the last `- id:` line anchors the insert.
|
|
231
|
+
const head = /^(\s*models:)[^\n]*$/m.exec(next);
|
|
232
|
+
if (head) {
|
|
233
|
+
// Append after the last line of the last model, not after the last `- id:`
|
|
234
|
+
// match: a model has more keys below it (`name`, `contextWindow`), and
|
|
235
|
+
// inserting at the id would cut one model in two, which YAML reads as a
|
|
236
|
+
// model with two names and a stray key.
|
|
237
|
+
const rows = [...next.matchAll(/^\s*-\s*id:.*$/gm)];
|
|
238
|
+
const lastRow = rows[rows.length - 1];
|
|
239
|
+
const tail = next.slice(lastRow.index).split('\n');
|
|
240
|
+
let depth = 1;
|
|
241
|
+
while (depth + 1 < tail.length) {
|
|
242
|
+
const line = tail[depth + 1];
|
|
243
|
+
if (!line.trim()) break;
|
|
244
|
+
const indent = (/^\s*/.exec(line) || [''])[0].length;
|
|
245
|
+
if (indent <= span.rowIndent + 4) break;
|
|
246
|
+
depth += 1;
|
|
247
|
+
}
|
|
248
|
+
const consumed = tail.slice(0, depth + 1).join('\n').length;
|
|
249
|
+
const at = lastRow.index + consumed;
|
|
250
|
+
next = `${next.slice(0, at)}${row}${next.slice(at)}`;
|
|
251
|
+
} else {
|
|
252
|
+
next = next.replace(/^(\s*defaultContextWindow:.*)$/m, `$1\n${' '.repeat(span.rowIndent + 2)}models:${row}`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (next === existing) return { ok: false, why: 'unchanged' };
|
|
256
|
+
return {
|
|
257
|
+
ok: true,
|
|
258
|
+
text: [...lines.slice(0, span.start), ...next.split('\n'), ...lines.slice(span.end)].join('\n'),
|
|
259
|
+
id,
|
|
260
|
+
replaced: true,
|
|
261
|
+
modelsAdded: missing,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Apply a parsed `/endpoint` command to a profile. */
|
|
266
|
+
export function applyEndpoint(profile, parsed) {
|
|
267
|
+
if (parsed.verb !== 'add' && parsed.verb !== 'rm') return { ok: false, why: 'usage' };
|
|
268
|
+
const result = withEndpoint(read(patchPath(profile)), parsed);
|
|
269
|
+
if (!result.ok) return result;
|
|
270
|
+
writePatch(profile, result.text);
|
|
271
|
+
return result;
|
|
272
|
+
}
|