@0perator/operator 0.1.331 → 0.1.333
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/dist/acp/config-options.js +10 -1
- package/dist/auth/byo.js +90 -9
- package/dist/auth/commands.js +1 -1
- package/dist/autonomy/delegate.js +3 -2
- package/dist/autonomy/session-factory.js +1 -0
- package/dist/cli.js +210 -62
- package/dist/config/persona.js +3 -1
- package/dist/config/settings.js +38 -4
- package/dist/engine/agent.js +8 -4
- package/dist/engine/anthropic-chat.js +28 -6
- package/dist/engine/anthropic.js +1 -1
- package/dist/engine/aurora.js +5 -1
- package/dist/engine/continuation.js +1 -1
- package/dist/engine/router-adapter.js +6 -5
- package/dist/engine/verify-gate.js +30 -3
- package/dist/remote/safe-commands.js +1 -1
- package/dist/router/discovery.js +23 -4
- package/dist/router/free-models.js +191 -0
- package/dist/router/models.js +142 -60
- package/dist/services/preflight.js +17 -2
- package/dist/session.js +94 -23
- package/dist/tools/sandbox.js +1 -1
- package/dist/ui/App.js +4 -3
- package/dist/ui/Composer.js +16 -1
- package/dist/ui/QuestionPrompt.js +22 -4
- package/dist/ui/SecretPrompt.js +77 -0
- package/dist/ui/StatusRule.js +6 -6
- package/dist/ui/modelPicker.js +110 -0
- package/dist/ui/slashCommands.js +3 -1
- package/dist/util/slash.js +3 -2
- package/package.json +1 -1
- package/dist/engine/cli.js +0 -1171
- package/dist/router/models.js.bak +0 -78
- package/dist/router/models.js.bak-1791259923 +0 -78
- package/dist/router/models.js.bak-pre-gateway +0 -78
- package/dist/router/models.js.bak-pre-patch2 +0 -78
- package/dist/router/models.js.bak2 +0 -78
- package/dist/services/model-autodetect.js +0 -240
- package/dist/tools/native-redirect.js +0 -140
- package/dist/tools/power-tools.js +0 -627
- package/dist/tools/registry.js.bak-1791259948 +0 -1914
- package/dist/tools/registry.js.bak-pre-plugins +0 -1914
- package/dist/ui/BusTray.js +0 -70
- package/dist/ui/resize.js +0 -160
package/dist/session.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { runTurn, TurnAbortedError } from "./engine/agent.js";
|
|
5
5
|
import { recordTruncation } from "./observability/blackbox.js";
|
|
6
6
|
import { Conversation } from "./engine/messages.js";
|
|
7
|
-
import { chat, health, requiresOperatorToken } from "./engine/aurora.js";
|
|
7
|
+
import { chat, health, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
|
|
8
8
|
import { compact, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
|
|
9
9
|
import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
|
|
10
10
|
import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
|
|
@@ -16,7 +16,8 @@ import { fanOutProposers, labelDrafts, DEFAULT_AGGREGATOR_PROMPT } from "./engin
|
|
|
16
16
|
import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0 observability (KODE_MOA_SHADOW)
|
|
17
17
|
import { AuroraRouter } from "./router/router.js";
|
|
18
18
|
import { operatorAgentPersona } from "./config/operator-harness.js";
|
|
19
|
-
import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
|
|
19
|
+
import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
|
|
20
|
+
import { probeServedCtx, usableCtx } from "./router/discovery.js";
|
|
20
21
|
import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
|
|
21
22
|
import { getByoToken, hasByoToken } from "./auth/byo.js";
|
|
22
23
|
import { Executor } from "./tools/executor.js";
|
|
@@ -291,13 +292,18 @@ function makeSkillDeactivateTool(deactivate) {
|
|
|
291
292
|
};
|
|
292
293
|
}
|
|
293
294
|
const SUMMARY_MAX_TOKENS = 1800; // room for Aurora's reasoning AND the 9-section contract before content lands
|
|
295
|
+
const SUMMARY_MAX_TOKENS_THINKING = 8000; // a Claude summarize: adaptive thinking draws on the same budget
|
|
294
296
|
const SKILL_CAP = 4000; // max chars injected from an active skill — a huge skill must not crowd working memory
|
|
295
297
|
export class Session {
|
|
296
298
|
convo = new Conversation();
|
|
297
299
|
inner; // was readonly — /model rebuilds it for a "single" profile switch
|
|
298
300
|
router; // rebuilt alongside inner (setModel)
|
|
299
301
|
chain; // the endpoint chain the shell built (cfg.router / useRouter) — what the default local model routes through
|
|
300
|
-
registry; // /model's choices — built-ins + any settings.models
|
|
302
|
+
registry; // /model's choices — built-ins + any settings.models (liveRegistry adds the dynamic rows)
|
|
303
|
+
models; // cfg.models, kept so the dynamic rows can be merged after them
|
|
304
|
+
dynamicModels;
|
|
305
|
+
pin; // the owner's context pin (tokens); undefined = auto — read live by the engine router
|
|
306
|
+
servedByBase = new Map(); // raw n_ctx learned per base (probeServedContext)
|
|
301
307
|
moaConfig;
|
|
302
308
|
fastStartConfig;
|
|
303
309
|
fastStartEnabled;
|
|
@@ -416,9 +422,12 @@ export class Session {
|
|
|
416
422
|
this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
|
|
417
423
|
this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
|
|
418
424
|
this.localSchemas = toSchemas(reg);
|
|
425
|
+
this.setContextPin(cfg.contextPin); // before the first wrap(): the engine router reads the pin live
|
|
419
426
|
this.inner = cfg.router ?? new AuroraRouter();
|
|
420
|
-
this.router =
|
|
427
|
+
this.router = this.wrap(this.inner);
|
|
421
428
|
this.chain = cfg.router;
|
|
429
|
+
this.models = cfg.models;
|
|
430
|
+
this.dynamicModels = cfg.dynamicModels;
|
|
422
431
|
this.registry = modelRegistry(cfg.models);
|
|
423
432
|
this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
|
|
424
433
|
this.moaConfig = cfg.moa;
|
|
@@ -510,7 +519,7 @@ export class Session {
|
|
|
510
519
|
budgetDirective() {
|
|
511
520
|
let ctxWindow = 0;
|
|
512
521
|
try {
|
|
513
|
-
ctxWindow = this.
|
|
522
|
+
ctxWindow = this.effectiveContext();
|
|
514
523
|
}
|
|
515
524
|
catch { /* endpoint not ready — skip the ctx line */ }
|
|
516
525
|
return renderBudgetBlock({
|
|
@@ -597,10 +606,56 @@ export class Session {
|
|
|
597
606
|
const built = sys ? [{ role: "system", content: sys }, ...this.convo.all] : this.convo.all;
|
|
598
607
|
return globalTokenMeter.estimateRequestFor(this.meterKey(), built, this.allSchemas());
|
|
599
608
|
}
|
|
600
|
-
/** Estimated context usage of the live conversation against the
|
|
601
|
-
* Calibrated: the meter's real ratio once observations land; exactly the old
|
|
609
|
+
/** Estimated context usage of the live conversation against the window the engine runs on (the served limit
|
|
610
|
+
* under the owner's pin), 0-99. Calibrated: the meter's real ratio once observations land; exactly the old
|
|
611
|
+
* chars/4 prior cold. */
|
|
602
612
|
ctxPct() {
|
|
603
|
-
return Math.min(99, Math.round((this.requestEstimate() / this.
|
|
613
|
+
return Math.min(99, Math.round((this.requestEstimate() / this.effectiveContext()) * 100));
|
|
614
|
+
}
|
|
615
|
+
// ── context pin (/context, Ctrl+X, the /model picker step) ───────────────
|
|
616
|
+
/** The engine router for `inner`: the adapter reads the pin live, so a mid-session /context applies next round. */
|
|
617
|
+
wrap(inner) {
|
|
618
|
+
return engineRouter(inner, { contextPin: () => this.pin });
|
|
619
|
+
}
|
|
620
|
+
/** The owner's context pin (tokens), or undefined for auto (the served window). */
|
|
621
|
+
contextPin() {
|
|
622
|
+
return this.pin;
|
|
623
|
+
}
|
|
624
|
+
/** Pin the engine's window; undefined restores auto. Persisting it (settings.contextPin) is the shell's job. */
|
|
625
|
+
setContextPin(tokens) {
|
|
626
|
+
// A pin below the floor (a hand-edited settings file, an old `/context 300`) is treated as auto, never as a 300-token window.
|
|
627
|
+
this.pin = typeof tokens === "number" && Number.isFinite(tokens) && tokens >= MIN_CONTEXT_PIN ? Math.floor(tokens) : undefined;
|
|
628
|
+
}
|
|
629
|
+
/** The window the engine actually runs on: min(the active endpoint's served limit, the pin). */
|
|
630
|
+
effectiveContext() {
|
|
631
|
+
const served = this.inner.ctxLimit();
|
|
632
|
+
return this.pin ? Math.min(served, this.pin) : served;
|
|
633
|
+
}
|
|
634
|
+
/** The raw window the active endpoint's server reported (probeServedContext), else its configured limit — what
|
|
635
|
+
* "auto (served 1,048,576)" shows. */
|
|
636
|
+
servedContext() {
|
|
637
|
+
return this.servedByBase.get(this.inner.base) ?? this.inner.ctxLimit();
|
|
638
|
+
}
|
|
639
|
+
/** Learn the active route's served window NOW instead of after the first 400 (engine/selfheal): read the primary
|
|
640
|
+
* endpoint's llama.cpp `/props` and clamp the router to floor(n_ctx * margin) — observeContextLimit is monotonic
|
|
641
|
+
* down, so a pin below the served size costs nothing and a profile that claimed too much stops overflowing before
|
|
642
|
+
* it ever does. Loopback/LAN bases only: a gateway or vendor leg is never probed (no /props there, and a bearer
|
|
643
|
+
* would ride along). Best-effort — a probe that does not answer in time changes nothing. Returns the raw served
|
|
644
|
+
* window and, when the pin sits above it, the one clamp note the shell prints as a sys line (a Session has no
|
|
645
|
+
* notice channel of its own). */
|
|
646
|
+
async probeServedContext(opts = {}) {
|
|
647
|
+
const base = this.inner.list()[0]?.base ?? this.inner.base;
|
|
648
|
+
if (!base || requiresOperatorToken(base) || !operatorTrustedUrl(base))
|
|
649
|
+
return { base };
|
|
650
|
+
const served = await probeServedCtx(base, { timeoutMs: opts.timeoutMs ?? 1500, fetchImpl: opts.fetchImpl });
|
|
651
|
+
if (!served)
|
|
652
|
+
return { base };
|
|
653
|
+
this.servedByBase.set(base, served);
|
|
654
|
+
this.inner.observeContextLimit(base, usableCtx(served));
|
|
655
|
+
const out = { base, served };
|
|
656
|
+
if (this.pin && this.pin > served)
|
|
657
|
+
out.note = `context pin ${fmtCtx(this.pin)} is above the served ${served.toLocaleString("en-US")} — using ${fmtCtx(served)}`;
|
|
658
|
+
return out;
|
|
604
659
|
}
|
|
605
660
|
/** Cumulative tokens (prefill + output) across every turn this session — the Claude-Code-style running
|
|
606
661
|
* session total for the status rule, so the real spend is visible (not just the current completion). */
|
|
@@ -633,7 +688,7 @@ export class Session {
|
|
|
633
688
|
* window. Returns tokens, not message count, because elision reduces chars without dropping messages. */
|
|
634
689
|
async compactNow() {
|
|
635
690
|
const opts = {
|
|
636
|
-
ctxWindow: this.
|
|
691
|
+
ctxWindow: this.effectiveContext(),
|
|
637
692
|
systemPrompt: this.sys(),
|
|
638
693
|
summarize: this.summarize,
|
|
639
694
|
preservedState: renderActiveTasks() ?? undefined, // the active task list rides with the summary
|
|
@@ -715,11 +770,17 @@ export class Session {
|
|
|
715
770
|
currentRoute() {
|
|
716
771
|
return this.inner.currentName();
|
|
717
772
|
}
|
|
773
|
+
/** The registry as of now: built-ins + settings.models, plus whatever rows the shell has learned since boot
|
|
774
|
+
* (cfg.dynamicModels — merged last, so a fetched row wins by id). The static registry when nothing is dynamic. */
|
|
775
|
+
liveRegistry() {
|
|
776
|
+
const dyn = this.dynamicModels?.() ?? [];
|
|
777
|
+
return dyn.length ? modelRegistry([...(this.models ?? []), ...dyn]) : this.registry;
|
|
778
|
+
}
|
|
718
779
|
/** All model profiles the owner can pick between (/model) — built-ins plus any settings.models
|
|
719
|
-
* overrides passed in at construction. BYO connectors appear ONLY when their vendor
|
|
720
|
-
* connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
|
|
780
|
+
* overrides passed in at construction, plus the dynamic rows. BYO connectors appear ONLY when their vendor
|
|
781
|
+
* key is connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
|
|
721
782
|
modelRegistry() {
|
|
722
|
-
return visibleModels(this.
|
|
783
|
+
return visibleModels(this.liveRegistry(), hasByoToken, this.isOwner);
|
|
723
784
|
}
|
|
724
785
|
/** The active /model selection (id), for the status line + persistence. */
|
|
725
786
|
currentModel() {
|
|
@@ -731,7 +792,7 @@ export class Session {
|
|
|
731
792
|
* error instead of throwing, so the shell can show it inline: an unknown id, or "moa" selected
|
|
732
793
|
* with no settings.moa configured. */
|
|
733
794
|
setModel(id) {
|
|
734
|
-
const { profile, error } = selectModel(this.
|
|
795
|
+
const { profile, error } = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
|
|
735
796
|
if (error || !profile)
|
|
736
797
|
return { ok: false, error };
|
|
737
798
|
if (profile.kind === "orchestrated" && !this.moaConfig?.proposers?.length) {
|
|
@@ -742,12 +803,12 @@ export class Session {
|
|
|
742
803
|
// legs). Restore it rather than rebuilding from the profile's static :8097 endpoint, which no longer
|
|
743
804
|
// answers on a gateway box — otherwise /model away-and-back lands on a dead port.
|
|
744
805
|
this.inner = this.chain;
|
|
745
|
-
this.router =
|
|
806
|
+
this.router = this.wrap(this.inner);
|
|
746
807
|
}
|
|
747
808
|
else if (profile.kind === "single" && (profile.endpoint || profile.endpoints?.length)) {
|
|
748
809
|
// BYO connectors carry their vendor bearer (never the Operator token — see authHeaders scoping);
|
|
749
810
|
// selectModel already refused the id if the key is not connected, so resolution can't miss here.
|
|
750
|
-
const token = profile.byo ? getByoToken(profile.byo) : undefined;
|
|
811
|
+
const token = profile.byo ? getByoToken(profile.byo, profileEndpoint(profile)) : undefined;
|
|
751
812
|
// A failover `endpoints` list builds one AuroraRouter endpoint per box (same model/alias on each), so
|
|
752
813
|
// the router hops primary->standby on a busy/5xx; a lone `endpoint` is the single-box case. Names carry
|
|
753
814
|
// the host so /route reads which box answered.
|
|
@@ -763,9 +824,10 @@ export class Session {
|
|
|
763
824
|
ctxLimit: profile.ctx ?? this.inner.ctxLimit(),
|
|
764
825
|
token: token ?? (hasGatewayLeg && !requiresOperatorToken(ep) ? "" : undefined),
|
|
765
826
|
transport: profile.transport,
|
|
827
|
+
chatPath: profile.chatPath,
|
|
766
828
|
}));
|
|
767
829
|
this.inner = new AuroraRouter(eps);
|
|
768
|
-
this.router =
|
|
830
|
+
this.router = this.wrap(this.inner);
|
|
769
831
|
}
|
|
770
832
|
this.modelId = profile.id;
|
|
771
833
|
return { ok: true };
|
|
@@ -779,7 +841,7 @@ export class Session {
|
|
|
779
841
|
if (this.modelId !== DEFAULT_MODEL_ID)
|
|
780
842
|
return;
|
|
781
843
|
this.inner = router;
|
|
782
|
-
this.router =
|
|
844
|
+
this.router = this.wrap(this.inner);
|
|
783
845
|
}
|
|
784
846
|
/** The full conversation, for persistence (auto-save / --resume). */
|
|
785
847
|
snapshot() {
|
|
@@ -843,13 +905,21 @@ export class Session {
|
|
|
843
905
|
const summaryTimeoutMs = Number(process.env.KODE_COMPACTION_SUMMARY_TIMEOUT_MS) || 120_000;
|
|
844
906
|
const timeoutSignal = AbortSignal.timeout(summaryTimeoutMs);
|
|
845
907
|
const signal = this.ctrl?.signal ? AbortSignal.any([this.ctrl.signal, timeoutSignal]) : timeoutSignal;
|
|
908
|
+
// The summarize request rides the SAME leg's key, wire and chat path as the live turn: a vendor row (Claude, Gemini,
|
|
909
|
+
// a free row) went to /v1/chat/completions with no key before, so a session on it could never compact.
|
|
910
|
+
const leg = [...this.inner.list(), ...(this.chain?.list() ?? [])].find((e) => e.base === sumBase && e.model === sumModel);
|
|
846
911
|
let r;
|
|
847
912
|
try {
|
|
848
913
|
r = await chat(messages, {
|
|
849
914
|
base: sumBase, // small-ctx active model → large default (Aurora) summarizes; else the live endpoint (cache-safe)
|
|
850
915
|
model: sumModel,
|
|
916
|
+
token: leg?.token,
|
|
917
|
+
loopbackAuth: leg?.loopbackAuth,
|
|
918
|
+
transport: leg?.transport,
|
|
919
|
+
chatPath: leg?.chatPath,
|
|
851
920
|
tools: this.allSchemas(), // identical tools → the span prefix-matches the live turn's cached KV
|
|
852
|
-
|
|
921
|
+
// Claude's adaptive thinking counts toward max_tokens: 1800 can be spent before the summary text starts.
|
|
922
|
+
maxTokens: leg?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : SUMMARY_MAX_TOKENS,
|
|
853
923
|
temperature: 0,
|
|
854
924
|
background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
|
|
855
925
|
signal, // ESC during "compacting" must tear down THIS request too, not just the main generation stream —
|
|
@@ -1053,7 +1123,7 @@ export class Session {
|
|
|
1053
1123
|
if (this.ctrl.signal.aborted)
|
|
1054
1124
|
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
1055
1125
|
this.inner.resetTurn(); // re-evaluate routing from the smallest endpoint + clear last turn's unhealthy set
|
|
1056
|
-
const active = findModel(this.
|
|
1126
|
+
const active = findModel(this.liveRegistry(), this.modelId);
|
|
1057
1127
|
if (active?.kind === "orchestrated")
|
|
1058
1128
|
return await this.sendMoa(text, h, active);
|
|
1059
1129
|
const sys = this.sysWithThink();
|
|
@@ -1090,7 +1160,7 @@ export class Session {
|
|
|
1090
1160
|
const res = await this.execute(text, h, this.router, this.sysWithThink());
|
|
1091
1161
|
return { ...res, content: note + res.content };
|
|
1092
1162
|
}
|
|
1093
|
-
const aggRouter =
|
|
1163
|
+
const aggRouter = this.wrap(new AuroraRouter([
|
|
1094
1164
|
{ name: moa.aggregator.id, base: endpointBase(moa.aggregator.endpoint), model: moa.aggregator.model, ctxLimit: this.inner.ctxLimit() },
|
|
1095
1165
|
]));
|
|
1096
1166
|
const aggSys = `${this.sysWithThink() ?? ""}\n\n## MOA aggregation\n${moa.aggregator_prompt ?? DEFAULT_AGGREGATOR_PROMPT}\n\n${labelDrafts(drafts)}`;
|
|
@@ -1234,10 +1304,11 @@ export class Session {
|
|
|
1234
1304
|
// the endpoint gate (a main turn always outranks it) with a 15s abort, and routeShadowTurn swallows
|
|
1235
1305
|
// every failure — observability that can degrade the observed thing is not observability.
|
|
1236
1306
|
if (process.env.KODE_MOA_SHADOW !== "0") {
|
|
1237
|
-
const prof = findModel(this.
|
|
1238
|
-
|
|
1307
|
+
const prof = findModel(this.liveRegistry(), this.modelId);
|
|
1308
|
+
// Not on a vendor's paid wire: an 8-token classifier call per Claude turn costs money and returns nothing once the model thinks.
|
|
1309
|
+
const shadowBase = prof?.endpoint && prof.transport !== "anthropic" ? endpointBase(prof.endpoint) : undefined;
|
|
1239
1310
|
if (shadowBase) {
|
|
1240
|
-
const shadowTok = prof?.byo ? getByoToken(prof.byo) : undefined;
|
|
1311
|
+
const shadowTok = prof?.byo ? getByoToken(prof.byo, prof.endpoint) : undefined;
|
|
1241
1312
|
const shadowModel = prof?.model ?? this.modelId;
|
|
1242
1313
|
this._shadowPending = routeShadowTurn({
|
|
1243
1314
|
enabled: true,
|
package/dist/tools/sandbox.js
CHANGED
|
@@ -69,7 +69,7 @@ const SECRET_READ_FILES = [`${HOME}/.netrc`, `${HOME}/.git-credentials`];
|
|
|
69
69
|
// permissions to bypass+admin for the next launch, and one that can truncate events.jsonl erases the
|
|
70
70
|
// evidence — so the sandbox treats these exactly like ~/.ssh. Resolved per call (KODE_HOME / KODE_PROFILE
|
|
71
71
|
// can differ per process); ordinary state (memories, skills, sessions) stays writable.
|
|
72
|
-
const OP_WRITE_PROTECTED_FILES = ["settings.json", "settings.local.json", "managed-settings.json", "identity.json", "home.json", "credentials.json", "byo.json", "events.jsonl"];
|
|
72
|
+
const OP_WRITE_PROTECTED_FILES = ["settings.json", "settings.local.json", "managed-settings.json", "identity.json", "home.json", "credentials.json", "byo.json", "events.jsonl", "free-models.json"];
|
|
73
73
|
// `run` holds the per-session pidfiles util/owned-children.ts reaps from: Operator (unsandboxed) trusts them to stop processes, so the agent
|
|
74
74
|
// must not be able to plant one naming a process it wants dead.
|
|
75
75
|
const OP_WRITE_PROTECTED_DIRS = ["vault", "audit", "run"];
|
package/dist/ui/App.js
CHANGED
|
@@ -20,6 +20,7 @@ import { backgroundHint } from "./liveTools.js";
|
|
|
20
20
|
import { useTick } from "./tick.js";
|
|
21
21
|
import { ApprovalPrompt } from "./ApprovalPrompt.js";
|
|
22
22
|
import { QuestionPrompt } from "./QuestionPrompt.js";
|
|
23
|
+
import { SecretPrompt } from "./SecretPrompt.js";
|
|
23
24
|
import { ArtifactPicker } from "./ArtifactPicker.js";
|
|
24
25
|
import { SessionPicker } from "./SessionPicker.js";
|
|
25
26
|
// Cap on live rows shown at once for a parallel tool batch — keeps the dynamic (non-Static) frame
|
|
@@ -36,7 +37,7 @@ function BackgroundHint({ rows }) {
|
|
|
36
37
|
return hint ? _jsx(Text, { dimColor: true, children: ` · ${hint}` }) : null;
|
|
37
38
|
}
|
|
38
39
|
export function App(props) {
|
|
39
|
-
const { messages, live = null, status, thinkingVerb, verbs, stepLabel, prefill = "", liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, shellJobs = [], onBackground, tasks = [], onSubmit, onQueue, queuedPreview = "", onInterrupt, onCycleMode, opMode, rcConnected = false, rcActive = false, caffeinated = false, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null, artifactsPicker = null, sessionsPicker = null } = props;
|
|
40
|
+
const { messages, live = null, status, thinkingVerb, verbs, stepLabel, prefill = "", liveTools = [], route, ctxPct, ctxPin, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, shellJobs = [], onBackground, tasks = [], onSubmit, onQueue, queuedPreview = "", onInterrupt, onCycleMode, onCycleContext, opMode, rcConnected = false, rcActive = false, caffeinated = false, approval = null, onApprovalDecide, question = null, modelPicker = null, secretPrompt = null, planExitPicker = null, artifactsPicker = null, sessionsPicker = null } = props;
|
|
40
41
|
useTerminalSize(); // subscribe so the inline pinned UI (status rule, composer, footer) reflows the instant the terminal resizes
|
|
41
42
|
const thinking = status === "thinking" || status === "streaming";
|
|
42
43
|
// A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
|
|
@@ -49,9 +50,9 @@ export function App(props) {
|
|
|
49
50
|
: _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), showParallelRows && (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, paddingLeft: 1, children: [_jsxs(Text, { dimColor: true, children: ["running ", liveTools.length, " tools in parallel"] }), liveTools.slice(0, MAX_LIVE_TOOL_ROWS).map((step) => _jsx(ToolStep, { step: step }, step.id)), liveTools.length > MAX_LIVE_TOOL_ROWS ? _jsxs(Text, { dimColor: true, children: [" +", liveTools.length - MAX_LIVE_TOOL_ROWS, " more\u2026"] }) : null] })), _jsx(PlanPane, { tasks: tasks }), _jsx(BgPanel, { agents: bgAgents, jobs: shellJobs }), (thinking || status === "executing" || status === "recovering") && (_jsxs(Text, { dimColor: true, children: [` ${status === "executing" ? "running tools" : status === "recovering" ? "recovering" : status === "streaming" ? "writing" : prefill || "reasoning"} · esc to interrupt`, status === "executing" ? _jsx(BackgroundHint, { rows: liveTools }) : null] }))] }));
|
|
50
51
|
// Interactive prompts own the keyboard while up; kept out of the fullscreen clip region so they can't
|
|
51
52
|
// be scrolled off. The Composer is `suspended` (keystrokes route to the decision, not the draft).
|
|
52
|
-
const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(QuestionPrompt, { pending: planExitPicker }), _jsx(ArtifactPicker, { pending: artifactsPicker }), _jsx(SessionPicker, { pending: sessionsPicker })] }));
|
|
53
|
+
const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(SecretPrompt, { pending: secretPrompt }), _jsx(QuestionPrompt, { pending: planExitPicker }), _jsx(ArtifactPicker, { pending: artifactsPicker }), _jsx(SessionPicker, { pending: sessionsPicker })] }));
|
|
53
54
|
// The pinned bottom band: status rule, composer, bottom rule, then the mode/cycle FOOTER below the rule.
|
|
54
|
-
const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), queuedPreview ? (_jsx(Text, { color: "yellow", children: `⏎ queued · sends when this turn ends (Esc to send now): ${queuedPreview.replace(/\n/g, " / ").slice(0, 120)}${queuedPreview.length > 120 ? "…" : ""}` })) : null, _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onBackground: onBackground, onCycleMode: onCycleMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!planExitPicker || !!artifactsPicker || !!sessionsPicker }), _jsx(InputRule, {}), opMode && (_jsxs(Box, { justifyContent: "space-between", children: [_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "⎈ Autonomous" : opMode === "manual" ? "⊙ Manual" : "◑ Plan"} · shift+tab to cycle` }), _jsx(Text, { color: rcConnected ? "green" : rcActive ? "yellow" : "gray", bold: rcConnected || rcActive, dimColor: !rcConnected && !rcActive, children: `${caffeinated ? "☕ " : ""}${rcConnected ? "▮ rc live" : rcActive ? "▮ rc on" : "▯ rc"} ` })] }))] }));
|
|
55
|
+
const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, ctxPin: ctxPin, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), queuedPreview ? (_jsx(Text, { color: "yellow", children: `⏎ queued · sends when this turn ends (Esc to send now): ${queuedPreview.replace(/\n/g, " / ").slice(0, 120)}${queuedPreview.length > 120 ? "…" : ""}` })) : null, _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onBackground: onBackground, onCycleMode: onCycleMode, onCycleContext: onCycleContext, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!secretPrompt || !!planExitPicker || !!artifactsPicker || !!sessionsPicker }), _jsx(InputRule, {}), opMode && (_jsxs(Box, { justifyContent: "space-between", children: [_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "⎈ Autonomous" : opMode === "manual" ? "⊙ Manual" : "◑ Plan"} · shift+tab to cycle` }), _jsx(Text, { color: rcConnected ? "green" : rcActive ? "yellow" : "gray", bold: rcConnected || rcActive, dimColor: !rcConnected && !rcActive, children: `${caffeinated ? "☕ " : ""}${rcConnected ? "▮ rc live" : rcActive ? "▮ rc on" : "▯ rc"} ` })] }))] }));
|
|
55
56
|
// Fullscreen (opt-in): a full-terminal-height column. The transcript fills a clipped, bottom-anchored
|
|
56
57
|
// region (non-Static tail) so the newest output sits just above a composer pinned to the very bottom —
|
|
57
58
|
// no dead space. Off by default: inline keeps the terminal's native scrollback (mouse-scroll + copy).
|
package/dist/ui/Composer.js
CHANGED
|
@@ -21,8 +21,10 @@ import { matchSlashCommands } from "./slashCommands.js";
|
|
|
21
21
|
import { touchInput } from "../idle/activity.js";
|
|
22
22
|
const PASTE_START = "\x1b[200~";
|
|
23
23
|
const PASTE_END = "\x1b[201~";
|
|
24
|
-
export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended, onCycleMode, onBackground, prompt = "› " }) {
|
|
24
|
+
export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended, onCycleMode, onCycleContext, onBackground, prompt = "› " }) {
|
|
25
25
|
const [value, setValue] = useState("");
|
|
26
|
+
const suspendedRef = useRef(suspended); // read by the raw-stdin paste listener, registered once below
|
|
27
|
+
suspendedRef.current = suspended;
|
|
26
28
|
const [selIdx, setSelIdx] = useState(0); // highlighted row in the "/" command menu
|
|
27
29
|
const pasteCountRef = useRef(0);
|
|
28
30
|
const pasteBufRef = useRef(null); // non-null while inside a bracketed paste
|
|
@@ -60,6 +62,10 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
|
|
|
60
62
|
};
|
|
61
63
|
const onData = (chunk) => {
|
|
62
64
|
touchInput(); // any byte from the keyboard/paste is the owner being here (idle/activity.ts)
|
|
65
|
+
// A paste made while an overlay owns the keyboard is the overlay's (a typed reply, a provider key): capturing it
|
|
66
|
+
// here too would park a copy in the draft — and a chip expands into the next submitted turn and the history.
|
|
67
|
+
if (suspendedRef.current && pasteBufRef.current === null)
|
|
68
|
+
return;
|
|
63
69
|
const s = typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
64
70
|
if (pasteBufRef.current !== null) {
|
|
65
71
|
const end = s.indexOf(PASTE_END);
|
|
@@ -151,6 +157,11 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
|
|
|
151
157
|
onBackground?.();
|
|
152
158
|
return;
|
|
153
159
|
}
|
|
160
|
+
// ctrl+x cycles the context pin, the hotkey twin of /context. Swallowed: never lands in the draft.
|
|
161
|
+
if (isContextCycleKey(ch, key)) {
|
|
162
|
+
onCycleContext?.();
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
154
165
|
// ESC / Ctrl+C: apply the pure interruptPlan. ESC mid-turn with a pending draft flushes it into
|
|
155
166
|
// the queue (so it goes through right after the interrupt, via the turn-finally drain), then
|
|
156
167
|
// interrupts; an empty-draft ESC and every Ctrl+C are plain interrupts. See interruptPlan below.
|
|
@@ -325,3 +336,7 @@ export function interruptPlan(key, ctx) {
|
|
|
325
336
|
export function isBackgroundKey(ch, key) {
|
|
326
337
|
return !!key.ctrl && (ch === "b" || ch === "z");
|
|
327
338
|
}
|
|
339
|
+
/** ctrl+x — cycle the context pin (Ink reports it as "x" with ctrl). */
|
|
340
|
+
export function isContextCycleKey(ch, key) {
|
|
341
|
+
return !!key.ctrl && ch === "x";
|
|
342
|
+
}
|
|
@@ -16,6 +16,18 @@ export const CHAT_LABEL = "Chat about it — type your own reply";
|
|
|
16
16
|
export const DISCUSS = "Let's talk it through — I don't want to pick one of the listed options; discuss it with me.";
|
|
17
17
|
// Joins the chosen options for the model when multi-select confirms a set — a stable, readable delimiter.
|
|
18
18
|
export const MULTI_JOIN = "; ";
|
|
19
|
+
/** The state a same-picker redraw keeps: the owner's mode and typed buffer, and the highlight on the same row by its text
|
|
20
|
+
* (a leading portal marker ignored). null = a different picker (or none) — reset. */
|
|
21
|
+
export function redrawState(prev, next, st) {
|
|
22
|
+
if (!prev || !next || next.key === undefined || prev.key !== next.key)
|
|
23
|
+
return null;
|
|
24
|
+
if (st.highlight >= prev.options.length)
|
|
25
|
+
return { ...st, highlight: next.options.length }; // the chat row stays the chat row
|
|
26
|
+
const bare = (t) => t.replace(/^[●○✕?] /, "");
|
|
27
|
+
const was = bare(prev.options[st.highlight]);
|
|
28
|
+
const at = next.options.findIndex((o) => bare(o) === was);
|
|
29
|
+
return { ...st, highlight: at >= 0 ? at : Math.min(st.highlight, Math.max(0, next.options.length - 1)) };
|
|
30
|
+
}
|
|
19
31
|
// Flip option index `i` in/out of the (sorted) selection set — the Space/digit toggle in multi mode.
|
|
20
32
|
const toggleSelected = (sel, i) => sel.includes(i) ? sel.filter((x) => x !== i) : [...sel, i].sort((a, b) => a - b);
|
|
21
33
|
// Pure keystroke reducer (no React, no I/O) so the whole selection + free-text behavior is testable without
|
|
@@ -59,13 +71,13 @@ export function questionKey(st, input, key, options, multiSelect = false) {
|
|
|
59
71
|
const sel = (st.selected && st.selected.length ? st.selected : [st.highlight]).slice().sort((a, b) => a - b);
|
|
60
72
|
return { resolve: sel.map((i) => options[i]).join(MULTI_JOIN) };
|
|
61
73
|
}
|
|
62
|
-
return { resolve: options[st.highlight] };
|
|
74
|
+
return { resolve: options[st.highlight], index: st.highlight };
|
|
63
75
|
}
|
|
64
76
|
const n = Number(input);
|
|
65
77
|
if (Number.isInteger(n) && n >= 1 && n <= options.length) {
|
|
66
78
|
if (multiSelect)
|
|
67
79
|
return { state: { ...st, highlight: n - 1, selected: toggleSelected(st.selected ?? [], n - 1) } }; // digit toggles, doesn't commit
|
|
68
|
-
return { resolve: options[n - 1] };
|
|
80
|
+
return { resolve: options[n - 1], index: n - 1 };
|
|
69
81
|
}
|
|
70
82
|
if (n === options.length + 1)
|
|
71
83
|
return { state: { mode: "type", buffer: "", highlight: options.length, selected: st.selected } }; // open the free-text line
|
|
@@ -76,13 +88,19 @@ export function QuestionPrompt({ pending }) {
|
|
|
76
88
|
const [st, setSt] = useState({ mode: "choose", buffer: "", highlight: 0, selected: multi ? [] : undefined });
|
|
77
89
|
const qRef = useRef(null);
|
|
78
90
|
const [qLines, setQLines] = useState(1); // measured height of the (possibly wrapping) question line
|
|
79
|
-
|
|
91
|
+
const shownRef = useRef(null);
|
|
92
|
+
useEffect(() => {
|
|
93
|
+
// A late redraw of the SAME picker must not move the owner's place (it used to jump the highlight to row 1 under their keys).
|
|
94
|
+
const prev = shownRef.current;
|
|
95
|
+
shownRef.current = pending ? { key: pending.key, options: pending.options } : null;
|
|
96
|
+
setSt((s) => redrawState(prev, pending, s) ?? { mode: "choose", buffer: "", highlight: 0, selected: pending?.multiSelect ? [] : undefined });
|
|
97
|
+
}, [pending]); // reset for each new question
|
|
80
98
|
useInput((input, key) => {
|
|
81
99
|
if (!pending)
|
|
82
100
|
return;
|
|
83
101
|
const a = questionKey(st, input, key, pending.options, pending.multiSelect);
|
|
84
102
|
if (a.resolve !== undefined)
|
|
85
|
-
pending.resolve(a.resolve);
|
|
103
|
+
pending.resolve(a.resolve, a.index);
|
|
86
104
|
else if (a.state)
|
|
87
105
|
setSt(a.state);
|
|
88
106
|
}, { isActive: !!pending });
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// Masked key entry for /model's "+ Connect a provider key" (the reference's flow): the owner pastes a vendor API key
|
|
3
|
+
// and it goes straight to the keychain. A local overlay like QuestionPrompt — the Composer is suspended while it is up
|
|
4
|
+
// (and leaves pastes to it), and it is never relayed to remote followers. The value lives only in this component until
|
|
5
|
+
// Enter hands it to `store` (auth/byo.ts setByoToken): it never reaches the transcript, the archive, the input history,
|
|
6
|
+
// the audit trail or a log, and the frame is drawn from its LENGTH alone, so no character of it can ever be shown.
|
|
7
|
+
import { useEffect, useRef, useState } from "react";
|
|
8
|
+
import { Box, Text, useInput } from "ink";
|
|
9
|
+
// A paste arrives inside bracketed-paste markers (Ink strips a chunk's leading ESC, so "[200~" can lead it), often with a
|
|
10
|
+
// trailing newline; no vendor key carries whitespace or a control character, so all of that is dropped.
|
|
11
|
+
const PASTE_MARKER = /\x1b?\[20[01]~/g;
|
|
12
|
+
// Terminal reports reach useInput as printable text with the ESC sliced off: SGR mouse (fullscreen tracks every wheel and
|
|
13
|
+
// click) and cursor-position replies. Inside a masked field they would be stored as part of the key, unseen.
|
|
14
|
+
const TERMINAL_REPORT = /\x1b?\[<\d+;\d+;\d+[Mm]|\x1b?\[\d+;\d+R/g;
|
|
15
|
+
const NOT_KEY = /[\s\x00-\x1f\x7f]/g;
|
|
16
|
+
// Mask cells drawn at most: a 100+ character key stays on one line of an 80-column box; the count says the rest.
|
|
17
|
+
export const MASK_MAX = 32;
|
|
18
|
+
/** The characters of one input chunk that belong to the key. */
|
|
19
|
+
export function secretChars(input) {
|
|
20
|
+
return input.replace(PASTE_MARKER, "").replace(TERMINAL_REPORT, "").replace(NOT_KEY, "");
|
|
21
|
+
}
|
|
22
|
+
/** Pure keystroke reducer (no React, no I/O), like questionKey: the next value, the value to store (Enter), or a cancel
|
|
23
|
+
* (Esc / ctrl+c). ctrl+u clears; Enter on an empty value does nothing. */
|
|
24
|
+
export function secretKey(value, input, key) {
|
|
25
|
+
if (key.escape || (key.ctrl && input === "c"))
|
|
26
|
+
return { cancel: true };
|
|
27
|
+
if (key.return)
|
|
28
|
+
return value ? { submit: value } : {};
|
|
29
|
+
if (key.backspace || key.delete)
|
|
30
|
+
return { value: value.slice(0, -1) };
|
|
31
|
+
if (key.ctrl && input === "u")
|
|
32
|
+
return { value: "" };
|
|
33
|
+
if (key.ctrl || key.meta)
|
|
34
|
+
return {};
|
|
35
|
+
const add = secretChars(input);
|
|
36
|
+
return add ? { value: value + add } : {};
|
|
37
|
+
}
|
|
38
|
+
/** The mask for a value of `length` characters. */
|
|
39
|
+
export function maskFor(length) {
|
|
40
|
+
return "•".repeat(Math.min(length, MASK_MAX));
|
|
41
|
+
}
|
|
42
|
+
export function SecretPrompt({ pending }) {
|
|
43
|
+
// A ref, not state: a paste can land as several chunks (with Enter right behind them) before React re-renders, and
|
|
44
|
+
// each must extend what the last one typed. `size` is all the render ever sees.
|
|
45
|
+
const valueRef = useRef("");
|
|
46
|
+
const [size, setSize] = useState(0);
|
|
47
|
+
useEffect(() => { valueRef.current = ""; setSize(0); }, [pending]); // a new prompt never inherits the last value
|
|
48
|
+
useInput((input, key) => {
|
|
49
|
+
if (!pending)
|
|
50
|
+
return;
|
|
51
|
+
const a = secretKey(valueRef.current, input, key);
|
|
52
|
+
if (a.cancel) {
|
|
53
|
+
valueRef.current = "";
|
|
54
|
+
setSize(0);
|
|
55
|
+
pending.resolve("cancelled");
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (a.submit !== undefined) {
|
|
59
|
+
valueRef.current = "";
|
|
60
|
+
setSize(0);
|
|
61
|
+
let ok = false;
|
|
62
|
+
try {
|
|
63
|
+
ok = pending.store(a.submit);
|
|
64
|
+
}
|
|
65
|
+
catch { /* an unwritable key file is a failed store, not a crash */ }
|
|
66
|
+
pending.resolve(ok ? "stored" : "failed");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (a.value !== undefined) {
|
|
70
|
+
valueRef.current = a.value;
|
|
71
|
+
setSize(a.value.length);
|
|
72
|
+
}
|
|
73
|
+
}, { isActive: !!pending });
|
|
74
|
+
if (!pending)
|
|
75
|
+
return null;
|
|
76
|
+
return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsxs(Text, { color: "cyan", bold: true, children: ["? ", _jsx(Text, { color: "white", children: pending.title })] }), _jsxs(Text, { children: [" ", _jsx(Text, { color: "magenta", children: "› " }), maskFor(size), _jsx(Text, { color: "cyan", children: "\u258C" }), size ? _jsx(Text, { dimColor: true, children: ` ${size} characters` }) : null] }), _jsx(Text, { dimColor: true, children: " Enter to store · Esc to cancel · ctrl+u to clear — the key is never shown or logged" })] }));
|
|
77
|
+
}
|
package/dist/ui/StatusRule.js
CHANGED
|
@@ -40,7 +40,7 @@ export function truncateToWidth(s, max) {
|
|
|
40
40
|
}
|
|
41
41
|
// The dim `info` string (right of the wordmark) and the full measured `right` line, kept as one pure
|
|
42
42
|
// function so the width math is testable without a render. `info` = think · plan · seat · identity ·
|
|
43
|
-
// route · ctx% · version; `right` prefixes the ✷ OPERATOR wordmark and suffixes the trailing " ─". When
|
|
43
|
+
// route · ctx pin + ctx% · version; `right` prefixes the ✷ OPERATOR wordmark and suffixes the trailing " ─". When
|
|
44
44
|
// the terminal is too narrow to hold every badge, `info` is truncated so cellWidth(right) ≤ cols-3 —
|
|
45
45
|
// which keeps the leading fill ≥ 1 and the whole line at cols-1, so the rule never becomes the line that
|
|
46
46
|
// wraps (the creep bug) no matter how many badges are lit or how narrow the window.
|
|
@@ -51,12 +51,12 @@ export function statusRight(p, cols) {
|
|
|
51
51
|
const think = p.thinkMode === "ultrathink" ? `✲✲ ultrathink · ` : p.thinkMode === "think" ? `✲ think · ` : "";
|
|
52
52
|
const tok = p.sessionTokens && p.sessionTokens > 0 ? `Σ${fmtK(p.sessionTokens)} · ` : ""; // session token total
|
|
53
53
|
// ctx as a fill ring (○◔◑◕●) + the exact % — a glance shows how full the context window is, the number keeps precision.
|
|
54
|
-
// Show the
|
|
55
|
-
// (
|
|
56
|
-
// operator-1m into "aurora-300k",
|
|
57
|
-
// (api.axe.onl) — so the owner couldn't tell the local default from the broken remote. Route is the truth.
|
|
54
|
+
// Show the active model's id (operator-1m, cortana, claude-opus, moa, custom …), never the leg that answered
|
|
55
|
+
// ("cortana@192.168.1.103:8112" read as noise; /endpoints lists the legs). No display rewrite of the id: the old
|
|
56
|
+
// one turned operator-1m into "aurora-300k", indistinguishable from the dead cloud profile axe-aurora-300k.
|
|
58
57
|
const routeLabel = p.route;
|
|
59
|
-
|
|
58
|
+
const pin = p.ctxPin ? `ctx ${p.ctxPin} ` : "";
|
|
59
|
+
let info = `${think}${plan}${seat}${who}${routeLabel} · ${pin}${ring(p.ctxPct)} ${Math.round(p.ctxPct)}% · ${tok}v${p.version}${p.build ? ` ·${p.build}` : ""}`;
|
|
60
60
|
let right = `✷ OPERATOR · ${info} ─`;
|
|
61
61
|
const maxRight = cols - 3; // leaves fill ≥ 1 and total = cols-1
|
|
62
62
|
if (cellWidth(right) > maxRight) {
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// /model's pure half — the rows and their order, the "+ Connect a provider key" action, the context step and /context
|
|
2
|
+
// rows, the provider rows, and what a picked answer means — so cli.tsx only wires them to the Session (the same split as
|
|
3
|
+
// planExit.ts). Every picker here resolves by INDEX into the entries its rows were drawn from: row text can repeat.
|
|
4
|
+
import { BYO_PRESETS, fmtCtx, pickerRow, shortName } from "../router/models.js";
|
|
5
|
+
import { markPickerOptions, portalIdFor } from "../router/portal.js";
|
|
6
|
+
import { CONTEXT_PRESETS } from "../config/settings.js";
|
|
7
|
+
import { DISCUSS } from "./QuestionPrompt.js";
|
|
8
|
+
/** The last /model row: an action, never a ModelProfile — so the lists fed from the registry (the ACP dropdown, a
|
|
9
|
+
* follower's model list) can never offer it. */
|
|
10
|
+
export const CONNECT_ROW = "+ Connect a provider key (Anthropic, Google, Nous, OpenAI, …)";
|
|
11
|
+
/** Presets whose zero-price rows /model lists once their key is connected (router/free-models.ts) — OpenRouter's
|
|
12
|
+
* `:free` listing joins here. */
|
|
13
|
+
export const FREE_ROW_PRESETS = ["operator", "nous"];
|
|
14
|
+
// fleet → connected providers → free rows → MOA. The built-ins already list this box (JL2) before JL1.
|
|
15
|
+
const group = (m) => (m.kind === "orchestrated" ? 3 : m.tier === "free" ? 2 : m.byo ? 1 : 0);
|
|
16
|
+
/** The picker order of a visible registry: fleet rows, the connected providers, the free rows, then MOA — a stable
|
|
17
|
+
* partition, so registry order decides inside each group. */
|
|
18
|
+
export function pickerOrder(models) {
|
|
19
|
+
return models.map((m, i) => ({ m, i })).sort((a, b) => group(a.m) - group(b.m) || a.i - b.i).map(({ m }) => m);
|
|
20
|
+
}
|
|
21
|
+
/** The /model rows in picker order — pickerRow for each (the active single model shows its served window), " · cached"
|
|
22
|
+
* on free rows served from the disk cache — closed by the connect row. */
|
|
23
|
+
export function modelPickerView(models, o) {
|
|
24
|
+
const ordered = pickerOrder(models);
|
|
25
|
+
const rows = ordered.map((m) => {
|
|
26
|
+
const active = m.id === o.active;
|
|
27
|
+
const row = pickerRow(m, { servedCtx: active && m.kind === "single" ? o.servedCtx : undefined });
|
|
28
|
+
return `${row}${o.staleFree && m.tier === "free" ? " · cached" : ""}${active ? " (active)" : ""}`;
|
|
29
|
+
});
|
|
30
|
+
return {
|
|
31
|
+
rows: [...rows, CONNECT_ROW],
|
|
32
|
+
entries: [...ordered.map((profile) => ({ kind: "model", profile })), { kind: "connect" }],
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** The rows with the portal's live markers (● ○ ✕ ?) on the model rows — same count, same order; the connect row is
|
|
36
|
+
* never marked. `cat` undefined leaves them as they are. */
|
|
37
|
+
export function markModelRows(view, cat) {
|
|
38
|
+
const models = view.entries.flatMap((e) => (e.kind === "model" ? [e.profile] : []));
|
|
39
|
+
return [...markPickerOptions(view.rows.slice(0, models.length), models.map(portalIdFor), cat), ...view.rows.slice(models.length)];
|
|
40
|
+
}
|
|
41
|
+
/** Whether a /model pick earns the "Context for this session" step: a single model whose window beats the smallest
|
|
42
|
+
* pin (at or under it there is nothing to choose). */
|
|
43
|
+
export function wantsContextStep(p, window) {
|
|
44
|
+
return p.kind === "single" && window > Math.min(...CONTEXT_PRESETS);
|
|
45
|
+
}
|
|
46
|
+
/** The context rows — 1M, 600K, 300K, then "auto (served N)" — with the current choice moved to the top and marked;
|
|
47
|
+
* a pin that is no preset (KODE_CONTEXT=262144) gets its own row, so the current one is always on screen. */
|
|
48
|
+
export function contextPickerView(current, served) {
|
|
49
|
+
const choices = [...[...CONTEXT_PRESETS].sort((a, b) => b - a), undefined];
|
|
50
|
+
const pins = [current, ...choices.filter((p) => p !== current)];
|
|
51
|
+
const name = (p) => (p === undefined ? `auto (served ${served.toLocaleString("en-US")})` : fmtCtx(p));
|
|
52
|
+
return { rows: pins.map((p, i) => `${name(p)}${i === 0 ? " (current)" : ""}`), pins };
|
|
53
|
+
}
|
|
54
|
+
/** The line every context change prints: `context → 600K (served 1,048,576) · fill 12%`; a pin above the served
|
|
55
|
+
* window says the engine runs on the served one. */
|
|
56
|
+
export function contextLine(pin, served, fillPct) {
|
|
57
|
+
const clamp = pin !== undefined && pin > served ? ` — using ${fmtCtx(served)}` : "";
|
|
58
|
+
return `context → ${pin === undefined ? "auto" : fmtCtx(pin)} (served ${served.toLocaleString("en-US")}${clamp}) · fill ${fillPct}%`;
|
|
59
|
+
}
|
|
60
|
+
/** `has` (auth/byo.ts hasByoToken) asked at most once per account while one /model picker is open — a keychain miss
|
|
61
|
+
* spawns `security` (~20-50 ms), so the open looks up only the accounts a row needs, each once. */
|
|
62
|
+
export function onceEach(has) {
|
|
63
|
+
const seen = new Map();
|
|
64
|
+
return (account, endpoint) => {
|
|
65
|
+
const k = `${account}\u0000${endpoint ?? ""}`;
|
|
66
|
+
let v = seen.get(k);
|
|
67
|
+
if (v === undefined)
|
|
68
|
+
seen.set(k, (v = has(account, endpoint)));
|
|
69
|
+
return v;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** The connected accounts among the presets — one pass through `has` (pass the open's onceEach), each checked against
|
|
73
|
+
* its preset's own host so a vendor's env variable counts only there. */
|
|
74
|
+
export function connectedAccounts(has, presets = BYO_PRESETS) {
|
|
75
|
+
return new Set(Object.values(presets).filter((p) => has(p.account, p.endpoint)).map((p) => p.account));
|
|
76
|
+
}
|
|
77
|
+
/** The provider rows, from the presets in their order — never listByoAccounts, which sees only the file tier:
|
|
78
|
+
* `<label>`, plus " ✓ connected" for an account in `connected`. */
|
|
79
|
+
export function providerPickerView(connected, presets = BYO_PRESETS) {
|
|
80
|
+
const choices = Object.entries(presets).filter(([, p]) => !p.signIn).map(([preset, p]) => ({ preset, p }));
|
|
81
|
+
return { rows: choices.map(({ p }) => `${p.label}${connected.has(p.account) ? " ✓ connected" : ""}`), choices };
|
|
82
|
+
}
|
|
83
|
+
/** What a QuestionPrompt answer means for a picker whose rows were drawn from `entries`: the row picked (by index), the
|
|
84
|
+
* owner's typed reply, or null — the empty reply / ctrl+c that resolves DISCUSS is never applied as a choice. */
|
|
85
|
+
export function pickerAnswer(entries, answer, index) {
|
|
86
|
+
if (index !== undefined)
|
|
87
|
+
return index >= 0 && index < entries.length ? { entry: entries[index] } : null;
|
|
88
|
+
const typed = answer.trim();
|
|
89
|
+
return !typed || answer === DISCUSS ? null : { typed };
|
|
90
|
+
}
|
|
91
|
+
/** The /model line after a pick: `model → <id> · ctx N% · turns N`; a free row repeats its caveat instead. */
|
|
92
|
+
export function modelLine(id, chosen, ctxPct, turns) {
|
|
93
|
+
if (chosen?.tier === "free")
|
|
94
|
+
return `model → ${id} · ${chosen.desc ?? "free tier"}`;
|
|
95
|
+
return `model → ${id} · ctx ${ctxPct}% · turns ${turns}`;
|
|
96
|
+
}
|
|
97
|
+
/** After a key is stored: the rows it unlocked, by name — or why none show yet. */
|
|
98
|
+
export function keyStoredLine(account, rows, preset, free = false) {
|
|
99
|
+
if (rows.length)
|
|
100
|
+
return `${account} key stored — rows added: ${rows.map(shortName).join(", ")}`;
|
|
101
|
+
return free
|
|
102
|
+
? `${account} key stored — its free rows did not load yet; /model fetches them again`
|
|
103
|
+
: `${account} key stored — no /model row uses it yet: operator auth byo-model --preset ${preset} adds one`;
|
|
104
|
+
}
|
|
105
|
+
/** True for text that reads as a credential, not a model id (a vendor key prefix, or one long unbroken token): such text is
|
|
106
|
+
* never echoed back in an "unknown model" line, which would put it in the transcript and relay it to followers. */
|
|
107
|
+
export function looksLikeSecret(text) {
|
|
108
|
+
const t = text.trim();
|
|
109
|
+
return /^(?:sk-|sk_|ghp_|gho_|xai-|AIza|op_|key-)/.test(t) || /^[A-Za-z0-9_\-]{40,}$/.test(t);
|
|
110
|
+
}
|