aegisone 1.0.39 → 1.0.41
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/LICENSING.md +186 -0
- package/README.md +2 -2
- package/bin/aegis.js +1 -1
- package/package.json +3 -2
- package/scripts/predist.mjs +1 -1
- package/src/child.js +1 -1
- package/src/permissions.js +1 -1
- package/vendor/cli/package.json +4 -2
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/commands.js +3 -1
- package/vendor/cli/src/config.js +1 -1
- package/vendor/cli/src/diff.js +1 -1
- package/vendor/cli/src/diffview.js +1 -1
- package/vendor/cli/src/engine.js +1 -1
- package/vendor/cli/src/history.js +1 -1
- package/vendor/cli/src/models.js +1 -1
- package/vendor/cli/src/overlays.js +1 -1
- package/vendor/cli/src/panels.js +1 -1
- package/vendor/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/cli/vendor/client/credits.js +45 -0
- package/vendor/cli/vendor/client/foreign-sessions.js +3 -0
- package/vendor/cli/vendor/client/naming.js +1 -1
- package/vendor/cli/vendor/client/prefs.js +1 -1
- package/vendor/cli/vendor/client/session-search.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +42 -2
- package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/cli/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/cli/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +774 -37
- package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/cli/vendor/mcp/admission.js +3 -0
- package/vendor/cli/vendor/mcp/server.js +1 -1
- package/vendor/cli/vendor/one/src/child.js +1 -1
- package/vendor/cli/vendor/one/src/permissions.js +1 -1
- package/vendor/desktop/bin/aegis.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +42 -2
- package/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/lib/sync/memory-store.js +3 -0
- package/vendor/desktop/main.js +774 -37
- package/vendor/desktop/package.json +19 -7
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +5 -1
- package/vendor/desktop/renderer/diff.js +1 -1
- package/vendor/desktop/renderer/diffview.js +1 -1
- package/vendor/desktop/renderer/index.html +221 -5
- package/vendor/desktop/renderer/provider-mark.js +1 -1
- package/vendor/desktop/renderer/provider-toolbar.js +1 -1
- package/vendor/desktop/renderer/providers.js +1 -1
- package/vendor/desktop/renderer/style.css +223 -6
- package/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/credits.js +45 -0
- package/vendor/desktop/vendor/faces/cli/package.json +3 -2
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -1
- package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +45 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-bwrap.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -2
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +1 -1
- package/vendor/desktop/vendor/foreign-sessions.js +3 -0
- package/vendor/desktop/vendor/naming.js +1 -1
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/sandbox/provenance.json +20 -0
- package/vendor/desktop/vendor/sandbox/x64-linux/bwrap +0 -0
- package/vendor/desktop/vendor/session-search.js +3 -0
|
@@ -2200,17 +2200,37 @@ label {
|
|
|
2200
2200
|
justify-content: center;
|
|
2201
2201
|
}
|
|
2202
2202
|
|
|
2203
|
+
/* A hexagon faceted into 6 triangles, not the four-point sparkle this used to
|
|
2204
|
+
be — the sparkle is Google's Gemini mark at a glance, and this app has no
|
|
2205
|
+
relationship to Gemini to be implying. The gradient, the glow and the
|
|
2206
|
+
`shimmer` sweep are UNCHANGED from the glyph this replaced; only how the
|
|
2207
|
+
shape is cut is different, because that glyph was TEXT ('✦', clipped out of
|
|
2208
|
+
the gradient via `background-clip: text`) and a drawn icon has no glyph
|
|
2209
|
+
outline to clip to. `mask-image` is the same trick for arbitrary shapes:
|
|
2210
|
+
the gradient background paints the whole box and the SVG mask decides which
|
|
2211
|
+
pixels of it survive.
|
|
2212
|
+
The mask SVG is six SEPARATELY FILLED triangles, each inset ~8% toward its
|
|
2213
|
+
own centroid — not one hexagon with lines stroked on top. `mask-image`
|
|
2214
|
+
composites by ALPHA, not luminance (confirmed by rendering both ways): an
|
|
2215
|
+
opaque black line over an opaque white fill is still 100% opaque everywhere
|
|
2216
|
+
and vanishes from the mask, so the facets have to be real transparent gaps,
|
|
2217
|
+
which only separately-shrunk shapes produce. */
|
|
2203
2218
|
.chat-welcome .glyph {
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2219
|
+
width: 34px;
|
|
2220
|
+
height: 34px;
|
|
2221
|
+
flex: none;
|
|
2207
2222
|
background: linear-gradient(135deg, #b0d4ee, #5a7fd4, var(--teal));
|
|
2208
2223
|
background-size: 200%;
|
|
2209
|
-
-webkit-background-clip: text;
|
|
2210
|
-
background-clip: text;
|
|
2211
|
-
-webkit-text-fill-color: transparent;
|
|
2212
2224
|
filter: drop-shadow(0 0 14px rgba(0, 229, 192, 0.3));
|
|
2213
2225
|
animation: shimmer 5s linear infinite;
|
|
2226
|
+
-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='%23fff' d='M12.40 12.23 21.60 12.23 17.00 20.20Z'/%3E%3Cpath fill='%23fff' d='M12.00 12.46 16.60 20.43 7.40 20.43Z'/%3E%3Cpath fill='%23fff' d='M11.60 12.23 7.00 20.20 2.40 12.23Z'/%3E%3Cpath fill='%23fff' d='M11.60 11.77 2.40 11.77 7.00 3.80Z'/%3E%3Cpath fill='%23fff' d='M12.00 11.54 7.40 3.57 16.60 3.57Z'/%3E%3Cpath fill='%23fff' d='M12.40 11.77 17.00 3.80 21.60 11.77Z'/%3E%3C/svg%3E");
|
|
2227
|
+
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='%23fff' d='M12.40 12.23 21.60 12.23 17.00 20.20Z'/%3E%3Cpath fill='%23fff' d='M12.00 12.46 16.60 20.43 7.40 20.43Z'/%3E%3Cpath fill='%23fff' d='M11.60 12.23 7.00 20.20 2.40 12.23Z'/%3E%3Cpath fill='%23fff' d='M11.60 11.77 2.40 11.77 7.00 3.80Z'/%3E%3Cpath fill='%23fff' d='M12.00 11.54 7.40 3.57 16.60 3.57Z'/%3E%3Cpath fill='%23fff' d='M12.40 11.77 17.00 3.80 21.60 11.77Z'/%3E%3C/svg%3E");
|
|
2228
|
+
-webkit-mask-size: contain;
|
|
2229
|
+
mask-size: contain;
|
|
2230
|
+
-webkit-mask-repeat: no-repeat;
|
|
2231
|
+
mask-repeat: no-repeat;
|
|
2232
|
+
-webkit-mask-position: center;
|
|
2233
|
+
mask-position: center;
|
|
2214
2234
|
}
|
|
2215
2235
|
|
|
2216
2236
|
.chat-welcome .title {
|
|
@@ -2880,6 +2900,35 @@ body.is-scrolled .composer {
|
|
|
2880
2900
|
filter: brightness(1.2);
|
|
2881
2901
|
}
|
|
2882
2902
|
|
|
2903
|
+
/* The per-row Undo affordance (app.js appendUndoRow), same font/size/padding
|
|
2904
|
+
as .diff-summary so the two read as one continuous block rather than a
|
|
2905
|
+
bolted-on control. */
|
|
2906
|
+
.diff-undo-row {
|
|
2907
|
+
font-family: var(--font-mono);
|
|
2908
|
+
font-size: 11px;
|
|
2909
|
+
line-height: 1.45;
|
|
2910
|
+
padding: 1px 0;
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2913
|
+
.diff-undo-link {
|
|
2914
|
+
cursor: pointer;
|
|
2915
|
+
color: #787878;
|
|
2916
|
+
}
|
|
2917
|
+
|
|
2918
|
+
.diff-undo-link:hover {
|
|
2919
|
+
filter: brightness(1.3);
|
|
2920
|
+
}
|
|
2921
|
+
|
|
2922
|
+
.diff-undo-done {
|
|
2923
|
+
color: #50c850;
|
|
2924
|
+
cursor: default;
|
|
2925
|
+
}
|
|
2926
|
+
|
|
2927
|
+
.diff-undo-failed {
|
|
2928
|
+
color: #dc5a5a;
|
|
2929
|
+
cursor: default;
|
|
2930
|
+
}
|
|
2931
|
+
|
|
2883
2932
|
.diff-body {
|
|
2884
2933
|
display: block;
|
|
2885
2934
|
}
|
|
@@ -3259,6 +3308,15 @@ body.keys-open {
|
|
|
3259
3308
|
outline: 2px solid currentColor;
|
|
3260
3309
|
outline-offset: 2px;
|
|
3261
3310
|
}
|
|
3311
|
+
.pt-head {
|
|
3312
|
+
display: flex;
|
|
3313
|
+
align-items: center;
|
|
3314
|
+
gap: 6px;
|
|
3315
|
+
}
|
|
3316
|
+
.pt-mark {
|
|
3317
|
+
flex: none;
|
|
3318
|
+
color: var(--text2);
|
|
3319
|
+
}
|
|
3262
3320
|
.pt-model {
|
|
3263
3321
|
font-weight: 600;
|
|
3264
3322
|
}
|
|
@@ -3311,3 +3369,162 @@ body.keys-open {
|
|
|
3311
3369
|
#companion-card[hidden] {
|
|
3312
3370
|
display: none;
|
|
3313
3371
|
}
|
|
3372
|
+
|
|
3373
|
+
/* ── Permission rules (Settings › Tool approvals › Rules) ──────────────────
|
|
3374
|
+
A list of rules the engine's gate consults before it raises a card. Laid out
|
|
3375
|
+
as rows rather than prose because the list is scanned, not read: tag, pattern,
|
|
3376
|
+
remove. `deny` is rendered first and carries the only alarming colour — it is
|
|
3377
|
+
the floor, and an allow cannot override it, so the visual weight has to match
|
|
3378
|
+
the precedence or the card teaches the wrong order. */
|
|
3379
|
+
.rules-block {
|
|
3380
|
+
margin-top: 10px;
|
|
3381
|
+
border-top: 1px solid var(--line, rgba(128, 128, 128, 0.25));
|
|
3382
|
+
padding-top: 10px;
|
|
3383
|
+
}
|
|
3384
|
+
.rules-title {
|
|
3385
|
+
font-size: 12px;
|
|
3386
|
+
font-weight: 600;
|
|
3387
|
+
text-transform: uppercase;
|
|
3388
|
+
letter-spacing: 0.04em;
|
|
3389
|
+
opacity: 0.75;
|
|
3390
|
+
margin: 0 0 6px;
|
|
3391
|
+
}
|
|
3392
|
+
.rules-list {
|
|
3393
|
+
list-style: none;
|
|
3394
|
+
margin: 0 0 8px;
|
|
3395
|
+
padding: 0;
|
|
3396
|
+
display: flex;
|
|
3397
|
+
flex-direction: column;
|
|
3398
|
+
gap: 4px;
|
|
3399
|
+
max-height: 220px;
|
|
3400
|
+
overflow-y: auto;
|
|
3401
|
+
}
|
|
3402
|
+
.rules-row {
|
|
3403
|
+
display: flex;
|
|
3404
|
+
align-items: center;
|
|
3405
|
+
gap: 8px;
|
|
3406
|
+
padding: 3px 6px;
|
|
3407
|
+
border-radius: 4px;
|
|
3408
|
+
background: rgba(128, 128, 128, 0.08);
|
|
3409
|
+
}
|
|
3410
|
+
.rules-row-muted {
|
|
3411
|
+
opacity: 0.6;
|
|
3412
|
+
font-style: italic;
|
|
3413
|
+
background: none;
|
|
3414
|
+
padding-left: 0;
|
|
3415
|
+
}
|
|
3416
|
+
.rules-tag {
|
|
3417
|
+
flex: 0 0 auto;
|
|
3418
|
+
font-size: 10px;
|
|
3419
|
+
font-weight: 700;
|
|
3420
|
+
text-transform: uppercase;
|
|
3421
|
+
letter-spacing: 0.05em;
|
|
3422
|
+
padding: 1px 5px;
|
|
3423
|
+
border-radius: 3px;
|
|
3424
|
+
background: rgba(128, 128, 128, 0.22);
|
|
3425
|
+
}
|
|
3426
|
+
/* The three lists read in precedence order, so the colours do too: deny is the
|
|
3427
|
+
only one that means "never", allow means "without asking", ask is a deliberate
|
|
3428
|
+
prompt that would otherwise have run unattended. */
|
|
3429
|
+
.rules-tag-deny { color: #ff8f8f; background: rgba(255, 90, 90, 0.16); }
|
|
3430
|
+
.rules-tag-allow { color: #8fd6a0; background: rgba(90, 200, 120, 0.14); }
|
|
3431
|
+
.rules-tag-ask { color: #e8c07a; background: rgba(230, 180, 90, 0.14); }
|
|
3432
|
+
.rules-pattern {
|
|
3433
|
+
flex: 1 1 auto;
|
|
3434
|
+
font-family: var(--font-mono);
|
|
3435
|
+
font-size: 12px;
|
|
3436
|
+
word-break: break-all;
|
|
3437
|
+
}
|
|
3438
|
+
.rules-remove {
|
|
3439
|
+
flex: 0 0 auto;
|
|
3440
|
+
font-size: 11px;
|
|
3441
|
+
padding: 1px 6px;
|
|
3442
|
+
}
|
|
3443
|
+
.rules-add {
|
|
3444
|
+
display: flex;
|
|
3445
|
+
gap: 6px;
|
|
3446
|
+
align-items: center;
|
|
3447
|
+
}
|
|
3448
|
+
.rules-add select {
|
|
3449
|
+
flex: 0 0 auto;
|
|
3450
|
+
}
|
|
3451
|
+
.rules-input {
|
|
3452
|
+
flex: 1 1 auto;
|
|
3453
|
+
min-width: 0;
|
|
3454
|
+
font-family: var(--font-mono);
|
|
3455
|
+
font-size: 12px;
|
|
3456
|
+
}
|
|
3457
|
+
|
|
3458
|
+
/* ─────────────────────────────────────────────────────── import sheet
|
|
3459
|
+
The toolbar's "Import session" surface. Same panel/backdrop primitives as the
|
|
3460
|
+
memory inspector and session search (one sheet look in the app), plus the two
|
|
3461
|
+
pieces only this sheet needs: a compact toolbar button that does not shout
|
|
3462
|
+
next to "New chat", and a footer where the two import actions live. */
|
|
3463
|
+
|
|
3464
|
+
.toolbar-import {
|
|
3465
|
+
margin-right: 8px;
|
|
3466
|
+
border-color: color-mix(in srgb, var(--teal) 45%, var(--border));
|
|
3467
|
+
color: color-mix(in srgb, var(--teal) 80%, var(--text));
|
|
3468
|
+
}
|
|
3469
|
+
|
|
3470
|
+
.import-overlay .memory-panel {
|
|
3471
|
+
width: min(720px, 100%);
|
|
3472
|
+
}
|
|
3473
|
+
|
|
3474
|
+
.import-row {
|
|
3475
|
+
display: flex;
|
|
3476
|
+
align-items: baseline;
|
|
3477
|
+
gap: 10px;
|
|
3478
|
+
padding: 7px 2px;
|
|
3479
|
+
border-bottom: 1px solid color-mix(in srgb, var(--border) 55%, transparent);
|
|
3480
|
+
}
|
|
3481
|
+
|
|
3482
|
+
.import-row:last-child {
|
|
3483
|
+
border-bottom: 0;
|
|
3484
|
+
}
|
|
3485
|
+
|
|
3486
|
+
.import-row .import-source {
|
|
3487
|
+
font-size: 12px;
|
|
3488
|
+
color: var(--text);
|
|
3489
|
+
}
|
|
3490
|
+
|
|
3491
|
+
.import-row .session-meta {
|
|
3492
|
+
margin-left: auto;
|
|
3493
|
+
font-family: var(--font-mono);
|
|
3494
|
+
font-size: 11px;
|
|
3495
|
+
color: var(--text2);
|
|
3496
|
+
}
|
|
3497
|
+
|
|
3498
|
+
/* Not installed / not readable: still listed, visibly secondary. A source that
|
|
3499
|
+
is absent must not read as a failure — it is the normal answer on a machine
|
|
3500
|
+
that never installed that tool. */
|
|
3501
|
+
.import-row.import-absent .import-source,
|
|
3502
|
+
.import-row.import-absent .session-meta {
|
|
3503
|
+
color: var(--text3, var(--text2));
|
|
3504
|
+
opacity: 0.7;
|
|
3505
|
+
}
|
|
3506
|
+
|
|
3507
|
+
.import-actions {
|
|
3508
|
+
display: flex;
|
|
3509
|
+
align-items: center;
|
|
3510
|
+
gap: 10px;
|
|
3511
|
+
padding: 12px 16px;
|
|
3512
|
+
border-top: 1px solid var(--border);
|
|
3513
|
+
}
|
|
3514
|
+
|
|
3515
|
+
.import-actions .spacer {
|
|
3516
|
+
flex: 1;
|
|
3517
|
+
}
|
|
3518
|
+
|
|
3519
|
+
.import-sync {
|
|
3520
|
+
display: flex;
|
|
3521
|
+
align-items: center;
|
|
3522
|
+
gap: 6px;
|
|
3523
|
+
font-size: 11px;
|
|
3524
|
+
color: var(--text2);
|
|
3525
|
+
}
|
|
3526
|
+
|
|
3527
|
+
.import-actions .btn-block {
|
|
3528
|
+
width: auto;
|
|
3529
|
+
margin: 0;
|
|
3530
|
+
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({"nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
|
|
3
|
+
"use strict";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({nexus:"auto-routing id: aegis1 picks the tier and settles the charge","nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)&&!isHiddenEntry(e)&&null===aliasOfEntry(e)))||i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)))||i.find((e=>NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))))||null}function filterAegisCatalog(e){const i=selectBrainEntry(e);if(!i)return[];const{hidden:
|
|
3
|
+
"use strict";const NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus",AUTO_MODEL_ID="nexus";function isAutoModelId(e){return"nexus"===String(null==e?"":e).trim().toLowerCase()}const AUTO_LABEL="Nexus — auto-route",AUTO_NOTE="server picks fast/smart/neo from the ask";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)&&!isHiddenEntry(e)&&null===aliasOfEntry(e)))||i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)))||i.find((e=>NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))))||null}function filterAegisCatalog(e){const i=selectBrainEntry(e);if(!i)return[];const{hidden:t,alias_of:n,aliasOf:r,...s}=i;return[{...s,label:"Nexus"}]}function isAegisCloudModel(e){const i="string"==typeof e?e.trim():e&&"object"==typeof e&&"string"==typeof e.id?e.id.trim():"";return!!AEGIS_CLOUD_MODEL_IDS.includes(i)||!!AEGIS_CLOUD_MODEL_RE.test(i)||NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))}function omitAegisCloudModels(e){return(Array.isArray(e)?e:[]).filter((e=>{if(!e)return!1;if("string"==typeof e)return!isAegisCloudModel(e);const i="string"==typeof e.id?e.id.trim():"";return Boolean(i)&&!isAegisCloudModel(e)}))}function offerableCatalog(e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return[];const t=selectBrainEntry(i),n=[],r=new Set;if(t){const{hidden:e,alias_of:i,aliasOf:s,...o}=t;n.push({...o,label:"Nexus"});for(const e of NEXUS_BRAIN_IDS)r.add(e);"string"==typeof t.id&&r.add(t.id)}const s=new Set(i.map((e=>"string"==typeof e.id?e.id.trim():"")).filter(Boolean)),o=new Set(i.map((e=>aliasOfEntry(e))).filter((e=>e&&s.has(e))));for(const e of i){const i="string"==typeof e.id?e.id.trim():"";i&&!r.has(i)&&(aliasOfEntry(e)&&o.has(aliasOfEntry(e))||(r.add(i),n.push(e)))}return n}module.exports={NEXUS_BRAIN_IDS:NEXUS_BRAIN_IDS,NEXUS_LABEL:"Nexus",AUTO_MODEL_ID:"nexus",AUTO_LABEL:AUTO_LABEL,AUTO_NOTE:AUTO_NOTE,isAutoModelId:isAutoModelId,AEGIS_CLOUD_MODEL_IDS:AEGIS_CLOUD_MODEL_IDS,isAegisCloudModel:isAegisCloudModel,omitAegisCloudModels:omitAegisCloudModels,selectBrainEntry:selectBrainEntry,filterAegisCatalog:filterAegisCatalog,offerableCatalog:offerableCatalog};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro","deepseek-v4.1-flash-1017":"deepseek-flash","deepseek-v4-pro-0813":"deepseek-v4-pro"})}),SNAPSHOT_SUFFIX_RE=/-(?:\d{4}|\d{8})$/;function knownWireId(e,r){return Object.prototype.hasOwnProperty.call(e,r)?e[r]:Object.values(e).includes(r)?r:""}function canonicalModelId(e,r){const
|
|
3
|
+
"use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro","deepseek-v4.1-flash-1017":"deepseek-flash","deepseek-v4-pro-0813":"deepseek-v4-pro"})}),SNAPSHOT_SUFFIX_RE=/-(?:\d{4}|\d{8})$/;function knownWireId(e,r){return Object.prototype.hasOwnProperty.call(e,r)?e[r]:Object.values(e).includes(r)?r:""}function canonicalModelId(e,r){const o="string"==typeof r?r.trim():"";if(!o)return o;const s="string"==typeof e?e.trim():"",n=s?WIRE_MODEL_ALIASES[s]:null;if(!n)return o;const t=knownWireId(n,o);if(t)return t;const i=o.replace(SNAPSHOT_SUFFIX_RE,"");if(i!==o){const e=knownWireId(n,i);if(e)return e}return o}function addedModelsFor(e){const r="string"==typeof e?e.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(o)?o.slice():[]}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function withByokAdditions(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null;if(!r)return[];const o=[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",s=r?BYOK_MODEL_ADDITIONS[r]:null;if(!Array.isArray(s)||!s.length){o.push(e);continue}const n=new Set(modelIdsOf(e)),t=s.filter((e=>!n.has(e)));if(!t.length){o.push(e);continue}const i=Array.isArray(e.models)?e.models:[];o.push({...e,models:[...i,...t]})}return o}const NEXUS_ELIGIBLE_PROVIDERS=Object.freeze(["deepseek","openai","groq","gemini","openrouter","together","grok","xai","mistral","cerebras","fireworks"]),NEXUS_POOLED_PROVIDER_ID=Object.freeze({xai:"grok"});function nexusFallbackProvider(e){const r="string"==typeof e?e.trim().toLowerCase():"";return r&&NEXUS_ELIGIBLE_PROVIDERS.includes(r)?NEXUS_POOLED_PROVIDER_ID[r]||r:""}function nexusFallbackModel({provider:e,providerKey:r,aegisKey:o,providerKeyRefused:s}={}){return r||s?"":o?nexusFallbackProvider(e):""}function nexusFallbackNotice(e){const r=e&&e.pooled_from;return r?`no ${r} key — answered through your AEGIS account${e.pooled_model?` (${e.pooled_model})`:""}`:""}module.exports={BYOK_MODEL_ADDITIONS:BYOK_MODEL_ADDITIONS,WIRE_MODEL_ALIASES:WIRE_MODEL_ALIASES,NEXUS_ELIGIBLE_PROVIDERS:NEXUS_ELIGIBLE_PROVIDERS,NEXUS_POOLED_PROVIDER_ID:NEXUS_POOLED_PROVIDER_ID,addedModelsFor:addedModelsFor,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel,nexusFallbackNotice:nexusFallbackNotice,nexusFallbackProvider:nexusFallbackProvider,withByokAdditions:withByokAdditions};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";
|
|
4
|
+
/**
|
|
5
|
+
* credits.js — the in-app "Credits & licence" content, built from ONE source.
|
|
6
|
+
*
|
|
7
|
+
* Neither host had a licence surface at all: `AGPL-3.0-or-later` lived in the
|
|
8
|
+
* file headers and in `LICENSE`, `LICENSING.md` held the plain-language
|
|
9
|
+
* summary, and the third-party attributions were split across
|
|
10
|
+
* `desktop/renderer/vendor/NOTICE.md` and `desktop/renderer/fonts/NOTICE.md` —
|
|
11
|
+
* three documents a user could only read by finding a checkout. The desktop's
|
|
12
|
+
* About panel showed a name and a version number; the terminal had no
|
|
13
|
+
* `/license` and no `/credits`.
|
|
14
|
+
*
|
|
15
|
+
* The fix is not to retype the attribution into a renderer (which would drift
|
|
16
|
+
* the moment a vendored file is bumped). It is to PARSE the files that already
|
|
17
|
+
* are the record, in one place, and hand both hosts a list of rows. When
|
|
18
|
+
* `marked` goes from 18.0.12 to 18.0.13 that NOTICE is the only file that
|
|
19
|
+
* changes, and both faces follow.
|
|
20
|
+
*
|
|
21
|
+
* Everything here is pure and filesystem-read-only; `buildCredits` takes the
|
|
22
|
+
* document texts rather than reading them, so it is assertable without the
|
|
23
|
+
* files and the two hosts can source them differently (the desktop reads them
|
|
24
|
+
* out of the packaged app dir, the CLI out of `cli/vendor/`).
|
|
25
|
+
*/const path=require("node:path"),fs=require("node:fs"),LICENCE_ID="AGPL-3.0-or-later",LICENCE_NAME="GNU Affero General Public License v3.0 or later",LICENCE_URL="https://www.gnu.org/licenses/agpl-3.0.html",SOURCE_URL="https://github.com/aegisinfo/aegiscode-plugin",COPYRIGHT="Copyright (C) 2026 Niklas Borneklint",DOCUMENTS=[{id:"licensing",title:"Licensing",file:path.join("LICENSING.md"),applies:"this program"},{id:"vendor",title:"Vendored third-party code",file:path.join("desktop","renderer","vendor","NOTICE.md"),applies:"renderer"},{id:"fonts",title:"Vendored webfonts",file:path.join("desktop","renderer","fonts","NOTICE.md"),applies:"renderer"}];function candidateRoots(){const t=__dirname;return[path.join(t,".."),path.join(t,"..",".."),path.join(t,"..","..","..")]}function readDocument(t){for(const e of candidateRoots()){const n=path.join(e,t.file);try{const e=fs.readFileSync(n,"utf8");return{...t,path:n,text:e}}catch{}}return null}function unwrapBullets(t){const e=[];let n=null;for(const r of String(t||"").split("\n")){const t=r.replace(/\s+$/,"");/^-\s+/.test(t)?(n&&e.push(n),n=t.replace(/^-\s+/,"").trim()):n&&/^\s{2,}\S/.test(t)?n+=" "+t.trim():n&&(e.push(n),n=null)}return n&&e.push(n),e}const LICENCE_RE=/((?:AGPL-3\.0-or-later|Apache-2\.0|MPL-2\.0|BSD-\d-Clause|OFL\s*1\.1|MIT|ISC)(?:\s*\/\s*(?:Apache-2\.0|MPL-2\.0|MIT|ISC))*)/i;function parseAttributions(t){const e=[];for(const n of unwrapBullets(t)){const t=/^`([^`]+)`\s*[—–-]\s*(.*)$/.exec(n);if(!t)continue;const r=t[1].trim(),i=t[2].trim(),s=/\[[^\]]*\]\((https?:\/\/[^)]+)\)/.exec(i),o=s?s[1]:null,c=LICENCE_RE.exec(i),l=/\bv(\d+\.\d+\.\d+)\b/.exec(i);e.push({name:r,version:l?l[1]:null,url:o,licence:c?c[1].replace(/\s+/g," ").trim():null,note:i})}return e}
|
|
26
|
+
/**
|
|
27
|
+
* Pull the `- \`Family\` — © …` rows out of the fonts NOTICE. Kept separate
|
|
28
|
+
* from parseAttributions because a font row's identifying token is a family
|
|
29
|
+
* name in backticks with a copyright line, not a file name with a version —
|
|
30
|
+
* merging them produced rows whose `licence` column said "© 2018 The Syne
|
|
31
|
+
* Project Authors".
|
|
32
|
+
*/function parseFonts(t){const e=[];for(const n of unwrapBullets(t)){const t=/^`([^`]+)`\s*[—–-]\s*(©[^()<]*[^\s()<])\s*\(\s*<?([^)\s>]+)>?\s*\)\s*[,.]?\s*(.*)$/.exec(n);if(!t)continue;const r=LICENCE_RE.exec(n);e.push({name:t[1].trim(),copyright:t[2].trim(),url:t[3]&&/^https?:\/\//.test(t[3].trim())?t[3].trim():null,licence:r?r[1].replace(/\s+/g," ").trim():null,note:t[4]?t[4].trim():null})}return e}
|
|
33
|
+
/**
|
|
34
|
+
* The whole credits payload. Both hosts render this list; neither invents a
|
|
35
|
+
* row of its own.
|
|
36
|
+
*
|
|
37
|
+
* Shape (all strings/null, so it survives IPC and JSON):
|
|
38
|
+
* {
|
|
39
|
+
* program: { licence, name, url, source, copyright, notice },
|
|
40
|
+
* documents: [{ id, title, applies, found, path }],
|
|
41
|
+
* code: [{ name, url, licence, note }],
|
|
42
|
+
* fonts: [{ name, copyright, url, licence }],
|
|
43
|
+
* missing: [id…]
|
|
44
|
+
* }
|
|
45
|
+
*/function buildCredits(t){const e={};for(const n of Array.isArray(t)?t:[])n&&n.id&&(e[n.id]=n);const n=e.vendor||null,r=e.fonts||null,i=e.licensing||null,s=i?extractNotice(i.text):"Copyright (C) 2026 Niklas Borneklint";return{program:{licence:LICENCE_ID,name:LICENCE_NAME,url:LICENCE_URL,source:SOURCE_URL,copyright:COPYRIGHT,notice:s},documents:DOCUMENTS.map((t=>({id:t.id,title:t.title,applies:t.applies,found:Boolean(e[t.id]),path:e[t.id]?e[t.id].path:null}))),code:n?parseAttributions(n.text):[],fonts:r?parseFonts(r.text):[],missing:DOCUMENTS.filter((t=>!e[t.id])).map((t=>t.id))}}function extractNotice(t){const e=String(t||""),n=e.indexOf("## Notice to apply to the program");if(-1===n)return"Copyright (C) 2026 Niklas Borneklint";const r=/```([\s\S]*?)```/.exec(e.slice(n));return r&&r[1].trim()||"Copyright (C) 2026 Niklas Borneklint"}function creditsFromDisk(t){const e=[];for(const n of DOCUMENTS){const r=t&&"function"==typeof t.readText?t.readText(n.file):readDocument(n);r&&e.push(r)}return buildCredits(e)}module.exports={LICENCE_ID:LICENCE_ID,LICENCE_NAME:LICENCE_NAME,LICENCE_URL:LICENCE_URL,SOURCE_URL:SOURCE_URL,COPYRIGHT:COPYRIGHT,DOCUMENTS:DOCUMENTS,buildCredits:buildCredits,creditsFromDisk:creditsFromDisk,parseAttributions:parseAttributions,parseFonts:parseFonts,unwrapBullets:unwrapBullets,readDocument:readDocument,extractNotice:extractNotice};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.33",
|
|
5
5
|
"description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
"src",
|
|
19
19
|
"scripts",
|
|
20
20
|
"vendor",
|
|
21
|
-
"README.md"
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE"
|
|
22
23
|
],
|
|
23
24
|
"engines": {
|
|
24
25
|
"node": ">=22.0.0"
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{TOOLS:s,toolList:i}=e.tools||createTools(o);let a=!1,l="";async function c(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return l=e.key?"":provisionFailureText(e),e}async function d(){if(o.apiKey||a)return;a=!0;const e=await c();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let u=!1!==e.confirmMode,m=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const f=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return u;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return u}}}),p=e=>"function"==typeof f.classLabel?f.classLabel(e):String(e||"");let y=null;const h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function P(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function x(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function A(){try{return memoryPersistEnabled()}catch{return!0}}function L(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function _(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const M=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof f.userModels)return"";const e=(f.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map((t=>[t,e[t]])))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<M&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof f.listModels)return[];const r=await f.listModels("byok");return $.models=(r&&r.models||[]).map((e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`}))),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=H();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await F()}catch{}return q(e,n)}if("pro"===n){const e=await f.listModels("pro");return(e&&e.models||[]).map((e=>({...e,cls:"pro"})))}if("aegis"!==n){const e=await f.listModels(n);return e&&e.models||[]}return await F()}catch{return[]}}function j(){return pickerEntries(R.models).map((e=>({...e,cls:"aegis"})))}function q(e,t){const n=H(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note})))).map((e=>({...e,cls:"pro"})));if("byok"!==r)return j();const o=Array.isArray(e)?e.map((e=>({...e,cls:"byok"}))):pickerEntries($.models).map((e=>({...e,cls:"byok"})));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map((e=>String(e.id).toLowerCase())))}function H(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function F({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<M;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function U(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((e=>e.id)).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await F()}catch{return null}return t.length?catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,p=0,k=VERBS[Math.floor(Math.random()*VERBS.length)],v=!1,S=!1;const E=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:k,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+p,streamedFloor:p>0})])},C=l?setInterval(E,90):null;C&&C.unref&&C.unref(),E();const I=s||{},N=new Map,P=randomUUID();T=P;let x=!1;const A=()=>{x=!0,f.cancel(P)},L=()=>A();process.once("SIGINT",L),i&&(i.aborted?A():i.addEventListener("abort",A,{once:!0}));const O=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),_=()=>Promise.resolve(!1),M=e=>{if(e){if(e.thinkingTokens&&(p+=e.thinkingTokens,v||(v=!0,k="Reasoning"),(e=>{I.thinkingTokens&&I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{I.reasoning&&I.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(I.text)return I.text(e);l&&c%2==0&&E()})(e.delta)),e.tool&&(S=!0,(e=>{if(I.tool)return I.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return N.has(t)||N.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),N.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),E()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=I.approval||y||O;Promise.resolve(n(t)).catch((()=>"deny")).then((e=>f.respondApproval(t.id,normalizeDecision(e))))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=I.rounds||_;Promise.resolve(n(t)).catch((()=>!1)).then((e=>f.respondRoundsAsk(t.id,!0===e)))}}};try{const n=await f.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:P,sessionKey:g.sessionId,roundsAsk:Boolean(I.rounds)},M),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:x,reasoningChars:m,usedTools:S}}catch(e){if(x&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:S};throw e}finally{C&&clearInterval(C),process.removeListener("SIGINT",L),i&&i.removeEventListener("abort",A),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await d(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=s[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await d(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map((e=>e&&(e.s||"")+(null==e.t?"":e.t)||"")).join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,p):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,p):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map((e=>[te(e)]))),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{m=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>f.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=H();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>p(e),classes:()=>"function"==typeof f.listClasses?f.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:s,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>P(e,t),forgetApiKey:()=>x(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:c()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>A(),cloudSyncState:()=>L(),setCloudSync:e=>O(e),adoptLegacyKey:()=>_()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{f&&"function"==typeof f.clearSessionApprovals&&f.clearSessionApprovals(g.sessionId)},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach(((e,t)=>{void 0!==o[t]&&(s[e]=o[t])})),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(f&&"function"==typeof f.unloadLocalModels)try{await f.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}A()&&o.apiKey&&Promise.resolve().then((()=>cloudsync.push(o))).then((e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}})).catch((()=>{}))}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:s,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>F(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then((e=>e&&e.text||null))}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":l,isYolo:()=>{if(!m)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{m=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise((e=>{t.on("line",(async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()})),t.on("close",(()=>{E||n.write("\n"),e(0)}))}))}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(H().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!H().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${H().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:s,toolList:i,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),_(),!o.apiKey&&!a){a=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],l=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find((t=>t.id===e.id&&!0!==t.settled))||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,l?{presenter:l}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),_(),o.apiKey||await d();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>P(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!L().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await U(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),await chatflow.runSession(ue()),0}return fe(),_(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:F,validatePinnedModel:U,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:P,forgetApiKey:x,adoptLegacyKeyOnce:_,cloudSyncEnabled:A,cloudSyncState:L,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|
|
3
|
+
"use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture,permissionMode:permissionMode}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{TOOLS:s,toolList:i}=e.tools||createTools(o);let a=!1,l="";async function c(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return l=e.key?"":provisionFailureText(e),e}async function d(){if(o.apiKey||a)return;a=!0;const e=await c();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let u=!1!==e.confirmMode,m=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const f=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return u;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return u}},getPermissionMode:()=>{try{return permissionMode()}catch{return null}}}),p=e=>"function"==typeof f.classLabel?f.classLabel(e):String(e||"");let y=null;const h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function P(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function A(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function x(){try{return memoryPersistEnabled()}catch{return!0}}function O(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function L(e){return setMemoryPersist(e)}function M(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const _=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof f.userModels)return"";const e=(f.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map((t=>[t,e[t]])))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<_&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof f.listModels)return[];const r=await f.listModels("byok");return $.models=(r&&r.models||[]).map((e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`}))),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=U();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await H()}catch{}return q(e,n)}if("pro"===n){const e=await f.listModels("pro");return(e&&e.models||[]).map((e=>({...e,cls:"pro"})))}if("aegis"!==n){const e=await f.listModels(n);return e&&e.models||[]}return await H()}catch{return[]}}function j(){return withAutoRow(pickerEntries(R.models)).map((e=>({...e,cls:"aegis"})))}function q(e,t){const n=U(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note})))).map((e=>({...e,cls:"pro"})));if("byok"!==r)return j();const o=Array.isArray(e)?e.map((e=>({...e,cls:"byok"}))):pickerEntries($.models).map((e=>({...e,cls:"byok"})));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map((e=>String(e.id).toLowerCase())))}function U(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function H({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<_;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function F(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((e=>e.id)).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await H()}catch{return null}return t.length?String(e).trim().toLowerCase()===AUTO_MODEL_ID||catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,p=0,k=VERBS[Math.floor(Math.random()*VERBS.length)],v=!1,S=!1;const E=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:k,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+p,streamedFloor:p>0})])},C=l?setInterval(E,90):null;C&&C.unref&&C.unref(),E();const I=s||{},N=new Map,P=randomUUID();T=P;let A=!1;const x=()=>{A=!0,f.cancel(P)},O=()=>x();process.once("SIGINT",O),i&&(i.aborted?x():i.addEventListener("abort",x,{once:!0}));const L=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),M=()=>Promise.resolve(!1),_=e=>{if(e){if(e.thinkingTokens&&(p+=e.thinkingTokens,v||(v=!0,k="Reasoning"),(e=>{I.thinkingTokens&&I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{I.reasoning&&I.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(I.text)return I.text(e);l&&c%2==0&&E()})(e.delta)),e.tool&&(S=!0,(e=>{if(I.tool)return I.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return N.has(t)||N.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),N.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),E()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=I.approval||y||L;Promise.resolve(n(t)).catch((()=>"deny")).then((e=>f.respondApproval(t.id,normalizeDecision(e))))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=I.rounds||M;Promise.resolve(n(t)).catch((()=>!1)).then((e=>f.respondRoundsAsk(t.id,!0===e)))}}};try{const n=await f.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:P,sessionKey:g.sessionId,rootSessionId:g.sessionId,roundsAsk:Boolean(I.rounds)},_),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:A,reasoningChars:m,usedTools:S}}catch(e){if(A&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:S};throw e}finally{C&&clearInterval(C),process.removeListener("SIGINT",O),i&&i.removeEventListener("abort",x),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await d(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=s[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await d(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map((e=>e&&(e.s||"")+(null==e.t?"":e.t)||"")).join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,p):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,p):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map((e=>[te(e)]))),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{m=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>f.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=U();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>p(e),classes:()=>"function"==typeof f.listClasses?f.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:s,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>P(e,t),forgetApiKey:()=>A(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:c()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>x(),cloudSyncState:()=>O(),setCloudSync:e=>L(e),adoptLegacyKey:()=>M()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{f&&"function"==typeof f.clearSessionApprovals&&f.clearSessionApprovals(g.sessionId)},e.listUndoable=()=>f&&"function"==typeof f.listUndoable?f.listUndoable(g.sessionId):[],e.undoMutation=e=>f&&"function"==typeof f.undoMutation?f.undoMutation(g.sessionId,e):{ok:!1,error:"undo is not available on this engine"},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach(((e,t)=>{void 0!==o[t]&&(s[e]=o[t])})),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(f&&"function"==typeof f.unloadLocalModels)try{await f.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}x()&&o.apiKey&&Promise.resolve().then((()=>cloudsync.push(o))).then((e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}})).catch((()=>{}))}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:s,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>H(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then((e=>e&&e.text||null))}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":l,isYolo:()=>{if(!m)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{m=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise((e=>{t.on("line",(async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()})),t.on("close",(()=>{E||n.write("\n"),e(0)}))}))}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(U().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!U().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${U().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:s,toolList:i,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),M(),!o.apiKey&&!a){a=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],l=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find((t=>t.id===e.id&&!0!==t.settled))||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,l?{presenter:l}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),M(),o.apiKey||await d();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>P(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!O().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await F(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),await chatflow.runSession(ue()),0}return fe(),M(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:H,validatePinnedModel:F,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:P,forgetApiKey:A,adoptLegacyKeyOnce:M,cloudSyncEnabled:x,cloudSyncState:O,setCloudSync:L,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|