fwdloop 0.11.0 → 0.12.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/bin/fwdloop +115 -9
- package/package.json +1 -1
- package/src/authoring.js +3 -1
- package/src/config.js +255 -0
- package/src/drafter.js +12 -8
- package/src/keysfile.js +180 -0
- package/src/model-step.js +13 -4
- package/src/monthly.js +231 -0
- package/src/panel/index.html +331 -0
- package/src/panel/resume.js +9 -4
- package/src/panel/server.js +38 -5
- package/src/panel/settings.js +268 -0
- package/src/provider.js +194 -43
- package/src/providershapes.js +19 -0
- package/types/config.d.ts +51 -0
- package/types/drafter.d.ts +4 -2
- package/types/keysfile.d.ts +90 -0
- package/types/model-step.d.ts +3 -1
- package/types/monthly.d.ts +109 -0
- package/types/panel/resume.d.ts +8 -1
- package/types/panel/server.d.ts +10 -2
- package/types/panel/settings.d.ts +23 -0
- package/types/provider.d.ts +126 -70
- package/types/providershapes.d.ts +11 -0
package/src/panel/index.html
CHANGED
|
@@ -486,6 +486,39 @@
|
|
|
486
486
|
td.am-detail .am-d{margin:0 0 3px;}
|
|
487
487
|
td.am-detail .am-d b{color:var(--text);font-weight:600;}
|
|
488
488
|
}
|
|
489
|
+
|
|
490
|
+
/* M4d piece 4: the Settings view (a sibling of #main-view, opened from the header). Layout borrowed from bareloop:
|
|
491
|
+
one provider table inside a scrolling .table-wrap, a KEYS strip, a money strip. Inputs are 16px so a phone does not zoom. */
|
|
492
|
+
/* borrowed-from: bareloop src/panel/index.html@5a5a811 */
|
|
493
|
+
.settings-view{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;min-width:0;}
|
|
494
|
+
.settings-view .pane-body{flex:none;overflow:visible;}
|
|
495
|
+
.settings-header{display:flex;align-items:center;gap:12px;padding:10px 16px;border-bottom:2px solid var(--border-strong);background:var(--panel);}
|
|
496
|
+
.settings-header h2{margin:0;font-size:15px;display:inline;}
|
|
497
|
+
.settings-header h2::before{content:"┤ ";color:var(--text-faint);}
|
|
498
|
+
.settings-header h2::after{content:" ├";color:var(--text-faint);}
|
|
499
|
+
.money-strip{display:grid;grid-template-columns:repeat(3, 1fr);gap:12px;align-items:end;padding:10px;border:1px solid var(--border-strong);background:var(--panel2);}
|
|
500
|
+
.money-item{min-width:0;}
|
|
501
|
+
.money-item label{display:block;font-size:11px;font-weight:700;color:var(--text-dim);margin-bottom:2px;}
|
|
502
|
+
.money-value{font-size:16px;font-weight:700;padding:6px 0;overflow-wrap:anywhere;}
|
|
503
|
+
.money-item input{width:100%;height:44px;box-sizing:border-box;}
|
|
504
|
+
.keyfile-strip{position:relative;border:1px solid var(--border-strong);padding:12px 12px 8px;background:var(--panel2);margin:14px 0;font-size:12px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;}
|
|
505
|
+
.keyfile-strip::before{content:"┤ KEYS ├";position:absolute;top:-9px;left:10px;background:var(--panel2);padding:0 4px;font-size:11px;color:var(--text-faint);letter-spacing:0.08em;}
|
|
506
|
+
.keyfile-strip-main{display:flex;flex-direction:column;gap:3px;flex:1;min-width:0;overflow-wrap:anywhere;}
|
|
507
|
+
.keyfile-strip-actions{display:flex;gap:6px;flex:none;}
|
|
508
|
+
.keyfile-strip code{background:var(--bg);border:1px solid var(--border-strong);padding:1px 5px;font-size:11px;color:var(--amber);overflow-wrap:anywhere;}
|
|
509
|
+
.settings-view input,.settings-view select{font:inherit;padding:6px 8px;border:1px solid var(--border-strong);border-radius:0;background:var(--bg);color:var(--text);}
|
|
510
|
+
.pv-table td,.pv-table th{white-space:nowrap;vertical-align:top;}
|
|
511
|
+
.pv-table select,.pv-table input{min-height:32px;max-width:190px;box-sizing:border-box;}
|
|
512
|
+
.pv-table .hint{display:block;margin-top:3px;}
|
|
513
|
+
/* the Test cell keeps ONE width whatever the result says ("testing…", "OK · 312 ms", a long failure note) */
|
|
514
|
+
.pv-table td.pv-test-cell{width:180px;min-width:180px;max-width:180px;}
|
|
515
|
+
.pv-table .pv-test-result,.pv-table .pv-msg,.pv-table .pv-balance-result{white-space:normal;overflow-wrap:anywhere;}
|
|
516
|
+
.pv-table td.pv-price-cell{width:170px;min-width:170px;max-width:170px;}
|
|
517
|
+
.hint.bad{color:var(--red);}
|
|
518
|
+
.table-wrap{overflow-x:auto;border:1px solid var(--border-strong);background:var(--panel2);max-width:100%;}
|
|
519
|
+
@media (max-width: 899px){
|
|
520
|
+
.money-strip{grid-template-columns:1fr 1fr;}
|
|
521
|
+
}
|
|
489
522
|
</style>
|
|
490
523
|
</head>
|
|
491
524
|
<body>
|
|
@@ -499,10 +532,73 @@
|
|
|
499
532
|
</div>
|
|
500
533
|
<div class="topbar-right">
|
|
501
534
|
<span class="hint" id="host-line"></span>
|
|
535
|
+
<button class="btn small" id="settings-open" type="button" data-testid="settings-open">⚙ Settings</button>
|
|
502
536
|
<button class="theme-toggle" id="theme-toggle" type="button" aria-label="Toggle light/dark theme">☽</button>
|
|
503
537
|
</div>
|
|
504
538
|
</header>
|
|
505
539
|
|
|
540
|
+
<!-- borrowed-from: bareloop src/panel/index.html@5a5a811 -->
|
|
541
|
+
<div class="settings-view" id="settings-view" data-testid="settings-view" hidden>
|
|
542
|
+
<div class="settings-header">
|
|
543
|
+
<button class="btn small" id="settings-back" type="button" data-testid="settings-back">← Back</button>
|
|
544
|
+
<h2>Settings</h2>
|
|
545
|
+
</div>
|
|
546
|
+
<div class="tabrow" role="tablist" aria-label="Settings views">
|
|
547
|
+
<button role="tab" id="stab-providers" aria-controls="spanel-providers" aria-selected="true" data-testid="settings-tab-providers">Providers</button>
|
|
548
|
+
<button role="tab" id="stab-money" aria-controls="spanel-money" aria-selected="false" data-testid="settings-tab-money">Money & limits</button>
|
|
549
|
+
</div>
|
|
550
|
+
<div class="pane-body">
|
|
551
|
+
<section id="spanel-providers" class="tabpanel active" role="tabpanel" aria-labelledby="stab-providers">
|
|
552
|
+
<div class="keyfile-strip" data-testid="keys-strip">
|
|
553
|
+
<div class="keyfile-strip-main">
|
|
554
|
+
<span>Put <code>NAME=key</code> lines in <code id="keys-path" data-testid="keys-path">~/.config/fwdloop/.env</code>, then Reload keys — each row below says whether its key is set. Only names are listed; keys never reach this page.</span>
|
|
555
|
+
<span class="hint bad" id="keys-refusal" data-testid="keys-refusal"></span>
|
|
556
|
+
</div>
|
|
557
|
+
<div class="keyfile-strip-actions">
|
|
558
|
+
<button class="btn small" id="reload-keys" type="button" data-testid="reload-keys">Reload keys</button>
|
|
559
|
+
</div>
|
|
560
|
+
</div>
|
|
561
|
+
<div class="table-wrap" data-testid="provider-table-wrap">
|
|
562
|
+
<table class="pv-table" data-testid="provider-table">
|
|
563
|
+
<thead>
|
|
564
|
+
<tr><th>Key</th><th>Name</th><th>API shape</th><th>Base URL</th><th>Test</th><th>Tokens used</th><th>Balance</th><th>In $/1M</th><th>Cached in $/1M</th><th>Out $/1M</th></tr>
|
|
565
|
+
</thead>
|
|
566
|
+
<tbody id="pv-rows"></tbody>
|
|
567
|
+
</table>
|
|
568
|
+
</div>
|
|
569
|
+
<div class="hint" id="pv-note" data-testid="pv-note" style="margin-top:6px;">Test asks the provider for its model list — it costs nothing. A price left empty uses the default; a typed price applies from the next model call on.</div>
|
|
570
|
+
</section>
|
|
571
|
+
<section id="spanel-money" class="tabpanel" role="tabpanel" aria-labelledby="stab-money" hidden>
|
|
572
|
+
<div class="money-strip" data-testid="money-strip">
|
|
573
|
+
<div class="money-item">
|
|
574
|
+
<label>$ month / to date</label>
|
|
575
|
+
<div class="money-value" id="ml-usd" data-testid="ml-usd">…</div>
|
|
576
|
+
</div>
|
|
577
|
+
<div class="money-item">
|
|
578
|
+
<label>Tokens month / to date</label>
|
|
579
|
+
<div class="money-value" id="ml-tokens" data-testid="ml-tokens">…</div>
|
|
580
|
+
</div>
|
|
581
|
+
<div class="money-item">
|
|
582
|
+
<label for="ml-money">Monthly money limit ($)</label>
|
|
583
|
+
<input id="ml-money" type="text" inputmode="decimal" placeholder="blank = no limit" data-testid="ml-money">
|
|
584
|
+
</div>
|
|
585
|
+
</div>
|
|
586
|
+
<div class="hint" id="ml-note" data-testid="ml-note" style="margin-top:6px;">Limits are yours. The agent can never change them. A run whose cap is more than what is left this month does not start.</div>
|
|
587
|
+
<div class="hint" id="ml-extra" data-testid="ml-extra"></div>
|
|
588
|
+
<div class="hint" id="ml-msg" data-testid="ml-msg"></div>
|
|
589
|
+
<h4 style="margin-top:20px;font-size:13px;">Per-provider breakdown</h4>
|
|
590
|
+
<div class="table-wrap">
|
|
591
|
+
<table data-testid="provider-breakdown-table">
|
|
592
|
+
<thead>
|
|
593
|
+
<tr><th>Provider</th><th>$ month / to date</th><th>minutes month / to date</th><th>tokens</th></tr>
|
|
594
|
+
</thead>
|
|
595
|
+
<tbody id="ml-breakdown"></tbody>
|
|
596
|
+
</table>
|
|
597
|
+
</div>
|
|
598
|
+
</section>
|
|
599
|
+
</div>
|
|
600
|
+
</div>
|
|
601
|
+
|
|
506
602
|
<div class="main" id="main-view">
|
|
507
603
|
|
|
508
604
|
<nav class="left-pane" aria-label="Job navigation" id="left-pane-anchor">
|
|
@@ -3129,6 +3225,241 @@
|
|
|
3129
3225
|
return true;
|
|
3130
3226
|
}
|
|
3131
3227
|
|
|
3228
|
+
// ---- M4d piece 4: Settings. Nothing here is re-rendered by the page's refresh tick: the Settings DOM is
|
|
3229
|
+
// painted only when it is opened, a tab is chosen, or a button here is pressed — and a price/limit box the
|
|
3230
|
+
// person has typed in ("dirty") is never overwritten by a repaint. No key value ever reaches this page. ----
|
|
3231
|
+
function fmtUsd(n, atLeast){
|
|
3232
|
+
if(typeof n !== "number" || !isFinite(n)) return "unknown";
|
|
3233
|
+
return (atLeast ? "≥" : "") + "$" + n.toFixed(4);
|
|
3234
|
+
}
|
|
3235
|
+
function fmtMinutes(m, atLeast){
|
|
3236
|
+
if(typeof m !== "number" || !isFinite(m)) return "not recorded";
|
|
3237
|
+
return (atLeast ? "≥" : "") + (m < 10 ? m.toFixed(1) : String(Math.round(m))) + " min";
|
|
3238
|
+
}
|
|
3239
|
+
// borrowed-from: bareloop src/panel/index.html@5a5a811 (tokensText)
|
|
3240
|
+
function tokensText(n){
|
|
3241
|
+
if(!n) return "0";
|
|
3242
|
+
if(n >= 1e6) return (n / 1e6).toFixed(1) + "M";
|
|
3243
|
+
if(n >= 1e3) return (n / 1e3).toFixed(1) + "k";
|
|
3244
|
+
return String(n);
|
|
3245
|
+
}
|
|
3246
|
+
// The server's own plain sentence (`say`) when it sent one; else the same words every other refusal uses.
|
|
3247
|
+
function settingsRefusal(r){
|
|
3248
|
+
var b = r && r.body;
|
|
3249
|
+
if(b && typeof b.say === "string" && b.say) return b.say;
|
|
3250
|
+
return refusalText(r, null);
|
|
3251
|
+
}
|
|
3252
|
+
// borrowed-from: bareloop src/panel/index.html@5a5a811 (Settings: one provider table, a money strip)
|
|
3253
|
+
// A hint line: plain text, red when it is a refusal. Empty text hides nothing and shows nothing.
|
|
3254
|
+
function setNote(el, bad, text){
|
|
3255
|
+
el.className = "hint" + (bad ? " bad" : "");
|
|
3256
|
+
el.textContent = text || "";
|
|
3257
|
+
}
|
|
3258
|
+
var settingsView = document.getElementById("settings-view");
|
|
3259
|
+
var mainView = document.getElementById("main-view");
|
|
3260
|
+
var pvRows = document.getElementById("pv-rows");
|
|
3261
|
+
var pvNote = document.getElementById("pv-note");
|
|
3262
|
+
var PV_NOTE_DEFAULT = pvNote.textContent;
|
|
3263
|
+
document.getElementById("settings-open").addEventListener("click", function(){
|
|
3264
|
+
mainView.hidden = true; settingsView.hidden = false;
|
|
3265
|
+
loadProviders(); loadMoney();
|
|
3266
|
+
});
|
|
3267
|
+
document.getElementById("settings-back").addEventListener("click", function(){
|
|
3268
|
+
settingsView.hidden = true; mainView.hidden = false;
|
|
3269
|
+
});
|
|
3270
|
+
wireTabs([document.getElementById("stab-providers"), document.getElementById("stab-money")]);
|
|
3271
|
+
document.getElementById("stab-money").addEventListener("click", function(){ loadMoney(); });
|
|
3272
|
+
document.getElementById("stab-providers").addEventListener("click", function(){ loadProviders(); });
|
|
3273
|
+
|
|
3274
|
+
function loadProviders(){
|
|
3275
|
+
return getJSON("/api/settings/providers").then(paintProviders, function(e){
|
|
3276
|
+
setNote(document.getElementById("keys-refusal"), true, loadFailureText(e));
|
|
3277
|
+
});
|
|
3278
|
+
}
|
|
3279
|
+
document.getElementById("reload-keys").addEventListener("click", function(){ loadProviders(); });
|
|
3280
|
+
|
|
3281
|
+
function sourceWord(src){
|
|
3282
|
+
if(src === "table") return "default";
|
|
3283
|
+
if(src === "ceiling") return "highest known rate, the model has no listed price";
|
|
3284
|
+
if(src === "default-multiplier") return "default, 0.1 x input";
|
|
3285
|
+
return "set here";
|
|
3286
|
+
}
|
|
3287
|
+
var PRICE_FIELDS = ["inPerM", "cachedInPerM", "outPerM"];
|
|
3288
|
+
// Name, API shape and Base URL are editable (M4d amendment 1), saved on change one field at a time.
|
|
3289
|
+
var PROV_FIELDS = ["name", "shape", "baseUrl"];
|
|
3290
|
+
function buildProviderRow(row){
|
|
3291
|
+
var tr = document.createElement("tr");
|
|
3292
|
+
tr.setAttribute("data-slot", row.slot);
|
|
3293
|
+
tr.setAttribute("data-testid", "provider-row-" + row.slot);
|
|
3294
|
+
var balance = row.canBalance
|
|
3295
|
+
? '<button class="btn small" type="button" data-act="balance" data-testid="prov-balance">Check</button><div class="hint pv-balance-result" data-f="balance-result"></div>'
|
|
3296
|
+
: '<span class="hint">not offered by this provider</span>';
|
|
3297
|
+
var prices = PRICE_FIELDS.map(function(f){
|
|
3298
|
+
return '<td class="pv-price-cell"><input type="text" inputmode="decimal" data-field="' + f + '" data-testid="price-' + f + '" aria-label="' + escapeXml(row.label + " " + f) + '">' +
|
|
3299
|
+
'<div class="hint pv-msg" data-f="msg-' + f + '" data-testid="price-msg-' + f + '"></div></td>';
|
|
3300
|
+
}).join("");
|
|
3301
|
+
tr.innerHTML =
|
|
3302
|
+
'<td><code>' + escapeXml(row.envVar) + '</code><div class="hint" data-f="status" data-testid="pv-status-' + escapeXml(row.slot) + '"></div></td>' +
|
|
3303
|
+
'<td class="pv-price-cell"><input type="text" data-prov="name" data-testid="prov-name" aria-label="' + escapeXml(row.label + " name") + '" autocomplete="off" spellcheck="false"><div class="hint pv-msg" data-f="msg-name" data-testid="prov-msg-name"></div></td>' +
|
|
3304
|
+
'<td class="pv-price-cell"><select data-prov="shape" data-testid="prov-shape" aria-label="' + escapeXml(row.label + " API shape") + '"></select><div class="hint pv-msg" data-f="msg-shape" data-testid="prov-msg-shape"></div></td>' +
|
|
3305
|
+
'<td class="pv-price-cell"><input type="text" data-prov="baseUrl" data-testid="prov-baseurl" aria-label="' + escapeXml(row.label + " Base URL") + '" autocomplete="off" spellcheck="false"><div class="hint pv-msg" data-f="msg-baseUrl" data-testid="prov-msg-baseUrl"></div></td>' +
|
|
3306
|
+
'<td class="pv-test-cell"><button class="btn small" type="button" data-act="test" data-testid="prov-test">Test</button><div class="hint pv-test-result" data-f="test" data-testid="prov-test-result"></div></td>' +
|
|
3307
|
+
'<td data-f="tokens" data-testid="pv-tokens-' + escapeXml(row.slot) + '"></td>' +
|
|
3308
|
+
'<td>' + balance + '</td>' + prices;
|
|
3309
|
+
tr.querySelectorAll("input").forEach(function(inp){
|
|
3310
|
+
inp.addEventListener("input", function(){ inp.setAttribute("data-dirty", "1"); });
|
|
3311
|
+
});
|
|
3312
|
+
return tr;
|
|
3313
|
+
}
|
|
3314
|
+
var STATUS_WORD = { "set in file": "set in file", "found in shell": "found in shell", "not set": "not set", "refused": "refused — see above" };
|
|
3315
|
+
function paintProviders(data){
|
|
3316
|
+
var path = data.keysFile && data.keysFile.path ? data.keysFile.path : "~/.config/fwdloop/.env";
|
|
3317
|
+
document.getElementById("keys-path").textContent = path;
|
|
3318
|
+
setNote(document.getElementById("keys-refusal"), true, data.keysFile && data.keysFile.refusal);
|
|
3319
|
+
setNote(pvNote, !!data.configProblem, data.configProblem || PV_NOTE_DEFAULT);
|
|
3320
|
+
data.rows.forEach(function(row){
|
|
3321
|
+
var tr = pvRows.querySelector('[data-slot="' + row.slot + '"]');
|
|
3322
|
+
if(!tr){ tr = buildProviderRow(row); pvRows.appendChild(tr); }
|
|
3323
|
+
tr.querySelector("[data-f=status]").textContent = STATUS_WORD[row.keyStatus] || row.keyStatus;
|
|
3324
|
+
var nameIn = tr.querySelector('[data-prov=name]');
|
|
3325
|
+
var shapeSel = tr.querySelector('[data-prov=shape]');
|
|
3326
|
+
var urlIn = tr.querySelector('[data-prov=baseUrl]');
|
|
3327
|
+
if(shapeSel.options.length !== data.shapes.length){
|
|
3328
|
+
shapeSel.innerHTML = "";
|
|
3329
|
+
data.shapes.forEach(function(sh){
|
|
3330
|
+
var o = document.createElement("option");
|
|
3331
|
+
o.value = sh.id; o.textContent = sh.label; shapeSel.appendChild(o);
|
|
3332
|
+
});
|
|
3333
|
+
}
|
|
3334
|
+
nameIn.placeholder = row.defaults.model;
|
|
3335
|
+
urlIn.placeholder = row.defaults.baseUrl !== "" ? row.defaults.baseUrl : "the vendor's own address";
|
|
3336
|
+
// a box the person is typing in is never overwritten by a repaint
|
|
3337
|
+
if(nameIn.getAttribute("data-dirty") !== "1") nameIn.value = row.model;
|
|
3338
|
+
if(urlIn.getAttribute("data-dirty") !== "1") urlIn.value = row.savedBaseUrl;
|
|
3339
|
+
if(document.activeElement !== shapeSel) shapeSel.value = row.shape;
|
|
3340
|
+
tr.querySelector("[data-f=tokens]").textContent = tokensText(row.tokens);
|
|
3341
|
+
PRICE_FIELDS.forEach(function(f){
|
|
3342
|
+
var inp = tr.querySelector('input[data-field="' + f + '"]');
|
|
3343
|
+
var pr = row.price[f];
|
|
3344
|
+
inp.placeholder = String(pr.value) + " (" + sourceWord(pr.source) + ")";
|
|
3345
|
+
inp.title = inp.placeholder;
|
|
3346
|
+
// a box the person has typed in is never overwritten by a repaint
|
|
3347
|
+
if(inp.getAttribute("data-dirty") !== "1") inp.value = pr.source === "settings" ? String(pr.value) : "";
|
|
3348
|
+
});
|
|
3349
|
+
});
|
|
3350
|
+
}
|
|
3351
|
+
pvRows.addEventListener("click", function(ev){
|
|
3352
|
+
var b = ev.target.closest && ev.target.closest("button[data-act]");
|
|
3353
|
+
if(!b) return;
|
|
3354
|
+
var tr = b.closest("tr");
|
|
3355
|
+
if(b.getAttribute("data-act") === "test") runTest(tr, tr.getAttribute("data-slot"));
|
|
3356
|
+
else if(b.getAttribute("data-act") === "balance") runBalance(tr, tr.getAttribute("data-slot"));
|
|
3357
|
+
});
|
|
3358
|
+
// Saved like bareloop saves a row field: on change (blur or Enter), no Save button.
|
|
3359
|
+
pvRows.addEventListener("change", function(ev){
|
|
3360
|
+
var inp = ev.target;
|
|
3361
|
+
if(!inp.getAttribute) return;
|
|
3362
|
+
if(inp.getAttribute("data-prov")){ saveProvider(inp.closest("tr"), inp); return; }
|
|
3363
|
+
if(!inp.getAttribute("data-field")) return;
|
|
3364
|
+
savePrice(inp.closest("tr"), inp.getAttribute("data-field"));
|
|
3365
|
+
});
|
|
3366
|
+
function runTest(tr, slot){
|
|
3367
|
+
var out = tr.querySelector("[data-f=test]");
|
|
3368
|
+
out.textContent = "testing…";
|
|
3369
|
+
postJSON("/api/settings/test", { slot: slot }).then(function(r){
|
|
3370
|
+
var b = r.body;
|
|
3371
|
+
out.textContent = b && b.ok ? "OK · " + b.ms + " ms" : (b && b.why ? b.why : settingsRefusal(r));
|
|
3372
|
+
}, function(){ out.textContent = networkText(); });
|
|
3373
|
+
}
|
|
3374
|
+
// Balance is read on a click, never on render (signed M4d: "read on a click").
|
|
3375
|
+
function runBalance(tr, slot){
|
|
3376
|
+
var out = tr.querySelector("[data-f=balance-result]");
|
|
3377
|
+
out.textContent = "checking…";
|
|
3378
|
+
getJSON("/api/settings/balance?slot=" + encodeURIComponent(slot)).then(function(b){
|
|
3379
|
+
if(b.ok) out.textContent = b.balances.map(function(x){ return x.total + " " + x.currency; }).join(" + ");
|
|
3380
|
+
else out.textContent = b.why || "Could not check the balance.";
|
|
3381
|
+
}, function(e){ out.textContent = loadFailureText(e); });
|
|
3382
|
+
}
|
|
3383
|
+
// A box the person typed: empty = back to the default (null); a number is sent as a number; anything else is
|
|
3384
|
+
// sent as the text typed, so the server refuses it by naming the box.
|
|
3385
|
+
function priceValue(text){
|
|
3386
|
+
var t = String(text).trim();
|
|
3387
|
+
if(t === "") return null;
|
|
3388
|
+
var n = Number(t);
|
|
3389
|
+
return isFinite(n) ? n : t;
|
|
3390
|
+
}
|
|
3391
|
+
function savePrice(tr, changed){
|
|
3392
|
+
var msg = tr.querySelector("[data-f=msg-" + changed + "]");
|
|
3393
|
+
var payload = { slot: tr.getAttribute("data-slot") };
|
|
3394
|
+
tr.querySelectorAll("input[data-field]").forEach(function(inp){ payload[inp.getAttribute("data-field")] = priceValue(inp.value); });
|
|
3395
|
+
postJSON("/api/settings/price", payload).then(function(r){
|
|
3396
|
+
if(r.body && r.body.ok){
|
|
3397
|
+
tr.querySelectorAll("input[data-field]").forEach(function(inp){ inp.removeAttribute("data-dirty"); });
|
|
3398
|
+
loadProviders();
|
|
3399
|
+
setNote(msg, false, "saved — applies from the next model call");
|
|
3400
|
+
} else setNote(msg, true, settingsRefusal(r));
|
|
3401
|
+
}, function(){ setNote(msg, true, networkText()); });
|
|
3402
|
+
}
|
|
3403
|
+
|
|
3404
|
+
// One field per save: {slot, name|shape|baseUrl}. An empty Base URL means the default; a refusal is the cell's hint line.
|
|
3405
|
+
function saveProvider(tr, inp){
|
|
3406
|
+
var key = inp.getAttribute("data-prov");
|
|
3407
|
+
var msg = tr.querySelector("[data-f=msg-" + key + "]");
|
|
3408
|
+
var payload = { slot: tr.getAttribute("data-slot") };
|
|
3409
|
+
payload[key] = inp.value.trim();
|
|
3410
|
+
postJSON("/api/settings/provider", payload).then(function(r){
|
|
3411
|
+
if(r.body && r.body.ok){
|
|
3412
|
+
inp.removeAttribute("data-dirty");
|
|
3413
|
+
loadProviders();
|
|
3414
|
+
setNote(msg, false, "saved — applies from the next model call");
|
|
3415
|
+
} else setNote(msg, true, settingsRefusal(r));
|
|
3416
|
+
}, function(){ setNote(msg, true, networkText()); });
|
|
3417
|
+
}
|
|
3418
|
+
|
|
3419
|
+
function loadMoney(){
|
|
3420
|
+
return getJSON("/api/settings/money").then(paintMoney, function(e){
|
|
3421
|
+
setNote(document.getElementById("ml-msg"), true, loadFailureText(e));
|
|
3422
|
+
});
|
|
3423
|
+
}
|
|
3424
|
+
var mlLimit = document.getElementById("ml-money");
|
|
3425
|
+
function paintMoney(d){
|
|
3426
|
+
var m = d.month, t = d.total;
|
|
3427
|
+
document.getElementById("ml-usd").textContent = fmtUsd(m.usd, m.atLeast) + " / " + fmtUsd(t.usd, t.atLeast);
|
|
3428
|
+
document.getElementById("ml-tokens").textContent = tokensText(m.tokens) + " / " + tokensText(t.tokens);
|
|
3429
|
+
var notes = [];
|
|
3430
|
+
if(d.preM4dRunsNotCounted) notes.push("Runs from before Settings existed are not counted here.");
|
|
3431
|
+
if(d.undatedRows > 0) notes.push(d.undatedRows + (d.undatedRows === 1 ? " older spend row has no date; it counts in to date only." : " older spend rows have no date; they count in to date only."));
|
|
3432
|
+
document.getElementById("ml-extra").textContent = notes.join(" ");
|
|
3433
|
+
if(document.activeElement !== mlLimit && mlLimit.getAttribute("data-dirty") !== "1") mlLimit.value = typeof d.monthlyLimitUsd === "number" ? String(d.monthlyLimitUsd) : "";
|
|
3434
|
+
if(d.configProblem) setNote(document.getElementById("ml-msg"), true, d.configProblem);
|
|
3435
|
+
var names = Object.keys(d.byProvider || {});
|
|
3436
|
+
document.getElementById("ml-breakdown").innerHTML = names.length ? names.map(function(k){
|
|
3437
|
+
var p = d.byProvider[k];
|
|
3438
|
+
return '<tr data-testid="break-row"><td>' + escapeXml(p.label) + '</td>' +
|
|
3439
|
+
'<td>' + escapeXml(fmtUsd(p.month.usd, p.month.atLeast) + " / " + fmtUsd(p.total.usd, p.total.atLeast)) + '</td>' +
|
|
3440
|
+
'<td>' + escapeXml(breakMinutes(p.month) + " / " + breakMinutes(p.total)) + '</td>' +
|
|
3441
|
+
'<td>' + escapeXml(tokensText(p.total.tokens)) + '</td></tr>';
|
|
3442
|
+
}).join("") : '<tr><td colspan="4" class="hint">no spend yet</td></tr>';
|
|
3443
|
+
}
|
|
3444
|
+
// "not recorded" only when there was spend but no minutes; a period with no spend at all is "0 min".
|
|
3445
|
+
function breakMinutes(b){
|
|
3446
|
+
if(b.modelMinutes === null && b.usd === 0 && !b.atLeast && b.tokens === 0) return "0 min";
|
|
3447
|
+
return fmtMinutes(b.modelMinutes, b.modelMinutesAtLeast);
|
|
3448
|
+
}
|
|
3449
|
+
mlLimit.addEventListener("input", function(){ this.setAttribute("data-dirty", "1"); });
|
|
3450
|
+
// Saved like bareloop saves it: on change (blur or Enter).
|
|
3451
|
+
mlLimit.addEventListener("change", function(){
|
|
3452
|
+
var msg = document.getElementById("ml-msg");
|
|
3453
|
+
postJSON("/api/settings/money", { monthlyLimitUsd: priceValue(mlLimit.value) }).then(function(r){
|
|
3454
|
+
if(r.body && r.body.ok){
|
|
3455
|
+
mlLimit.removeAttribute("data-dirty");
|
|
3456
|
+
loadMoney().then(function(){
|
|
3457
|
+
setNote(msg, false, r.body.monthlyLimitUsd === null ? "saved — no monthly limit" : "saved — the limit is now $" + r.body.monthlyLimitUsd);
|
|
3458
|
+
});
|
|
3459
|
+
} else setNote(msg, true, settingsRefusal(r));
|
|
3460
|
+
}, function(){ setNote(msg, true, networkText()); });
|
|
3461
|
+
});
|
|
3462
|
+
|
|
3132
3463
|
// theme toggle
|
|
3133
3464
|
(function(){
|
|
3134
3465
|
var root = document.documentElement;
|
package/src/panel/resume.js
CHANGED
|
@@ -76,8 +76,10 @@ function ensureLogDir(dir) {
|
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
/**
|
|
79
|
-
* @param {{ root: string, env?: Record<string, string|undefined>, bin?: string, logDir?: string,
|
|
79
|
+
* @param {{ root: string, env?: Record<string, string|undefined>, loadEnv?: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string, logDir?: string,
|
|
80
80
|
* maxTries?: number, windowMs?: number, slotMs?: number }} opts
|
|
81
|
+
* `loadEnv` (M4d: the keys-file door, called before EVERY spawn so editing the file needs no panel restart) returns the merged env
|
|
82
|
+
* that is BOTH the child's spawn env AND its scrub list, or a refusal sentence that becomes the attempt's refusal (nothing spawns).
|
|
81
83
|
* `env`/`bin`/`logDir`/`maxTries`/`windowMs`/`slotMs` are injectable so tests neither sleep 10 s
|
|
82
84
|
* nor need a live key; production passes none of them. `slotMs` (default `windowMs / maxTries`,
|
|
83
85
|
* i.e. 2000 ms) is only the spacing between tries: a test sets it small and `windowMs` (the
|
|
@@ -86,7 +88,7 @@ function ensureLogDir(dir) {
|
|
|
86
88
|
*/
|
|
87
89
|
export function createResumer(opts) {
|
|
88
90
|
const {
|
|
89
|
-
root, env = process.env, bin = BIN, maxTries = RESUME_MAX_TRIES, windowMs = RESUME_WINDOW_MS, slotMs = windowMs / maxTries,
|
|
91
|
+
root, env = process.env, loadEnv, bin = BIN, maxTries = RESUME_MAX_TRIES, windowMs = RESUME_WINDOW_MS, slotMs = windowMs / maxTries,
|
|
90
92
|
} = opts;
|
|
91
93
|
const rootTag = createHash('sha256').update(root).digest('hex').slice(0, 8);
|
|
92
94
|
/** @type {Map<string, any>} */
|
|
@@ -100,10 +102,13 @@ export function createResumer(opts) {
|
|
|
100
102
|
* or the child exited, or `deadline` passed — never waits for a long resume. */
|
|
101
103
|
function tryOnce({ flow, runId, runDir, askId, logPath, deadline }) {
|
|
102
104
|
const consumedPath = join(runDir, `answer.${askId}.consumed.json`);
|
|
105
|
+
const loaded = loadEnv ? loadEnv() : { ok: true, env, refusal: null };
|
|
106
|
+
if (!loaded.ok) return Promise.resolve({ kind: 'exited', code: null, sig: null, text: String(loaded.refusal) });
|
|
107
|
+
const runEnv = loaded.env; // ONE object: the spawn env below AND the scrub list further down (POC (a) wiring rule)
|
|
103
108
|
const fd = openSync(logPath, 'a', 0o600);
|
|
104
109
|
const offset = statSync(logPath).size;
|
|
105
110
|
const child = spawn(process.execPath, [bin, 'resume', runId, '--flow', flow, '--root', root], {
|
|
106
|
-
detached: true, stdio: ['ignore', fd, fd], env,
|
|
111
|
+
detached: true, stdio: ['ignore', fd, fd], env: runEnv,
|
|
107
112
|
});
|
|
108
113
|
child.unref();
|
|
109
114
|
closeSync(fd);
|
|
@@ -120,7 +125,7 @@ export function createResumer(opts) {
|
|
|
120
125
|
child.once('error', release);
|
|
121
126
|
// The child's output is quoted in a refusal (`reason`) that reaches HTTP responses and the books: the
|
|
122
127
|
// provider key(s) of this panel's env are scrubbed here, the one place that reads the log slice (amendment 1 (e)(3)).
|
|
123
|
-
const keys = Object.values(PROVIDER_SLOTS).map((p) =>
|
|
128
|
+
const keys = Object.values(PROVIDER_SLOTS).map((p) => runEnv[p.envVar]).filter(Boolean);
|
|
124
129
|
const sliceOfLog = () => {
|
|
125
130
|
try { return scrub(readFileSync(logPath).subarray(offset).toString('utf8').trim(), keys); } catch { return ''; } // offset is in BYTES
|
|
126
131
|
};
|
package/src/panel/server.js
CHANGED
|
@@ -64,6 +64,9 @@ import {
|
|
|
64
64
|
listRuns, getRunDetail, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
|
|
65
65
|
} from './data.js';
|
|
66
66
|
import { createResumer } from './resume.js';
|
|
67
|
+
import { keysForDoor } from '../keysfile.js';
|
|
68
|
+
import { configDoorHome } from '../config.js';
|
|
69
|
+
import { createSettings } from './settings.js';
|
|
67
70
|
import { removeOldLock } from './lock.js';
|
|
68
71
|
|
|
69
72
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
@@ -173,6 +176,15 @@ export function writeTokenFile({
|
|
|
173
176
|
return file;
|
|
174
177
|
}
|
|
175
178
|
|
|
179
|
+
/** Send a Settings handler's `{status, body}`; a throw is a plain 500, never a stack. @param {any} res @param {Promise<{status:number, body:any}>} pending @param {boolean} [headOnly] */
|
|
180
|
+
function settingsReply(res, pending, headOnly = false) {
|
|
181
|
+
pending.then((r) => {
|
|
182
|
+
if (!headOnly) { sendJson(res, r.status, r.body); return; }
|
|
183
|
+
res.writeHead(r.status, { 'content-type': 'application/json; charset=utf-8' });
|
|
184
|
+
res.end();
|
|
185
|
+
}, () => sendJson(res, 500, { ok: false, refused: 'internal', say: 'Something went wrong inside the panel. Nothing was changed.' }));
|
|
186
|
+
}
|
|
187
|
+
|
|
176
188
|
/** @param {any} res */
|
|
177
189
|
function refuseBusy(res) {
|
|
178
190
|
refuse(res, 409, 'already-resuming', 'already resuming — this run has a resume in progress; wait for it to end');
|
|
@@ -334,7 +346,7 @@ function resumeRoute(res, body, root, resumer) {
|
|
|
334
346
|
* real listening socket where that is simpler.
|
|
335
347
|
* @param {import('node:http').IncomingMessage} req
|
|
336
348
|
* @param {import('node:http').ServerResponse} res
|
|
337
|
-
* @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer> }} opts
|
|
349
|
+
* @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings> }} opts
|
|
338
350
|
*/
|
|
339
351
|
export function handleRequest(req, res, opts) {
|
|
340
352
|
const method = req.method ?? 'GET';
|
|
@@ -383,7 +395,9 @@ export function handleRequest(req, res, opts) {
|
|
|
383
395
|
return;
|
|
384
396
|
}
|
|
385
397
|
|
|
386
|
-
|
|
398
|
+
// M4d piece 4: every `/api/settings/...` POST (a known one or not) goes through the same Origin + body-cap gates.
|
|
399
|
+
const isSettingsPost = method === 'POST' && String(req.url).startsWith('/api/settings/');
|
|
400
|
+
if (method === 'POST' && (isSettingsPost || req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock')) {
|
|
387
401
|
const isResume = req.url === '/api/resume';
|
|
388
402
|
const isReopen = req.url === '/api/reopen';
|
|
389
403
|
const isRemoveLock = req.url === '/api/remove-lock';
|
|
@@ -412,6 +426,7 @@ export function handleRequest(req, res, opts) {
|
|
|
412
426
|
if (tooBig) return;
|
|
413
427
|
let body;
|
|
414
428
|
try { body = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { refuse(res, 400, 'body-not-json'); return; }
|
|
429
|
+
if (isSettingsPost) { settingsReply(res, opts.settings.handle({ method, pathname: String(req.url), query: new URLSearchParams(), body })); return; }
|
|
415
430
|
if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
|
|
416
431
|
else if (isReopen) reopenRoute(res, body, opts.root, opts.resumer);
|
|
417
432
|
else if (isRemoveLock) removeLockRoute(res, body, opts.root, opts.resumer);
|
|
@@ -447,6 +462,13 @@ export function handleRequest(req, res, opts) {
|
|
|
447
462
|
sendJson(res, code, body);
|
|
448
463
|
};
|
|
449
464
|
|
|
465
|
+
if (pathname.startsWith('/api/settings/')) {
|
|
466
|
+
settingsReply(res, opts.settings.handle({
|
|
467
|
+
method: 'GET', pathname, query: url.searchParams, body: null,
|
|
468
|
+
}), method === 'HEAD');
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
|
|
450
472
|
if (pathname === '/' || pathname === '/index.html') {
|
|
451
473
|
const indexPath = join(HERE, 'index.html');
|
|
452
474
|
let html;
|
|
@@ -544,7 +566,7 @@ export function handleRequest(req, res, opts) {
|
|
|
544
566
|
* header). Resolves once actually listening; rejects on a bind error
|
|
545
567
|
* (including `EADDRINUSE`) with a `.port` field on the error for the
|
|
546
568
|
* caller's message.
|
|
547
|
-
* @param {{ port?: number, root: string, token?: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
|
|
569
|
+
* @param {{ port?: number, root: string, token?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
|
|
548
570
|
* `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
|
|
549
571
|
* @returns {Promise<{ server: import('node:http').Server, port: number, token: string, close: () => Promise<void> }>}
|
|
550
572
|
*/
|
|
@@ -555,7 +577,14 @@ export function createPanelServer(opts) {
|
|
|
555
577
|
const requestedPort = opts.port ?? DEFAULT_PORT;
|
|
556
578
|
const { root } = opts;
|
|
557
579
|
// One resumer per server: the one owner of every run's resume-attempt record.
|
|
558
|
-
|
|
580
|
+
// M4d: the keys file is re-read before EVERY resume spawn (editing it needs no restart); an env injected by a test is the shell side.
|
|
581
|
+
const resumer = createResumer({ root, loadEnv: () => keysForDoor({ env: opts.resume?.env }), ...opts.resume });
|
|
582
|
+
// Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
|
|
583
|
+
// process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
|
|
584
|
+
const door = configDoorHome();
|
|
585
|
+
const settings = createSettings({
|
|
586
|
+
home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now,
|
|
587
|
+
});
|
|
559
588
|
// One token per server process, made once, held only here and in the served
|
|
560
589
|
// page — never logged, never in any /api response.
|
|
561
590
|
const token = typeof opts.token === 'string' && /^[0-9a-f]{64}$/.test(opts.token) ? opts.token : randomBytes(32).toString('hex');
|
|
@@ -569,7 +598,7 @@ export function createPanelServer(opts) {
|
|
|
569
598
|
const server = createServer((req, res) => {
|
|
570
599
|
try {
|
|
571
600
|
handleRequest(req, res, {
|
|
572
|
-
root, port: boundPort, token, resumer,
|
|
601
|
+
root, port: boundPort, token, resumer, settings,
|
|
573
602
|
});
|
|
574
603
|
} catch (e) {
|
|
575
604
|
sendText(res, 500, 'internal error');
|
|
@@ -618,6 +647,10 @@ export async function panelMain(argv, ctx) {
|
|
|
618
647
|
try {
|
|
619
648
|
const { port: boundPort, token } = await createPanelServer({ port, root, token: loadOrMakeToken({ port }) });
|
|
620
649
|
writeTokenFile({ port: boundPort, token });
|
|
650
|
+
// M4d: read the keys file at start (creates it when missing). The panel itself needs no key, so a file other users can
|
|
651
|
+
// read is only announced here; every resume re-reads it and refuses by itself.
|
|
652
|
+
const keys = keysForDoor();
|
|
653
|
+
if (!keys.ok) ctx.err(String(keys.refusal));
|
|
621
654
|
ctx.out(`fwdloop panel — (root: ${root}) (Ctrl-C to stop)`);
|
|
622
655
|
ctx.out(`open this link (it sets the panel's cookie): http://127.0.0.1:${boundPort}/?t=${token}`);
|
|
623
656
|
// never resolves on its own — the process stays up until killed, same
|