aegiscode 7.0.31 → 7.0.33
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/package.json +4 -2
- package/src/app.js +1 -1
- package/src/chatflow.js +1 -1
- package/src/commands.js +3 -1
- package/src/config.js +1 -1
- package/src/diff.js +1 -1
- package/src/diffview.js +1 -1
- package/src/engine.js +1 -1
- package/src/history.js +1 -1
- package/src/models.js +1 -1
- package/src/overlays.js +1 -1
- package/src/panels.js +1 -1
- package/vendor/client/brain-catalog.js +1 -1
- package/vendor/client/byok-catalog.js +1 -1
- package/vendor/client/credits.js +45 -0
- package/vendor/client/foreign-sessions.js +3 -0
- package/vendor/client/naming.js +1 -1
- package/vendor/client/prefs.js +1 -1
- package/vendor/client/session-search.js +3 -0
- 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/main.js +774 -37
- package/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/mcp/admission.js +3 -0
- package/vendor/mcp/server.js +1 -1
- package/vendor/one/src/child.js +1 -1
- package/vendor/one/src/permissions.js +1 -1
package/LICENSING.md
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# Licensing
|
|
2
|
+
|
|
3
|
+
**Aegiscode is licensed under the GNU Affero General Public License, version 3
|
|
4
|
+
or later (`AGPL-3.0-or-later`).** The verbatim licence text is in
|
|
5
|
+
[LICENSE](LICENSE). This document is the plain-language summary and the record
|
|
6
|
+
of the licence change; where it and `LICENSE` disagree, `LICENSE` governs.
|
|
7
|
+
|
|
8
|
+
Every manifest in this repo carries the same licence: `cli/package.json`
|
|
9
|
+
(the published `aegiscode` CLI), `desktop/package.json` (`aegis-desktop`) and
|
|
10
|
+
`online/package.json`. The first-party avatar packs under
|
|
11
|
+
`desktop/lib/avatar/packs/` carry it too. Vendored third-party code keeps its
|
|
12
|
+
own licence — see [desktop/renderer/vendor/NOTICE.md](desktop/renderer/vendor/NOTICE.md).
|
|
13
|
+
|
|
14
|
+
## Notice to apply to the program
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
Copyright (C) 2026 Niklas Borneklint
|
|
18
|
+
|
|
19
|
+
This program is free software: you can redistribute it and/or modify it under
|
|
20
|
+
the terms of the GNU Affero General Public License as published by the Free
|
|
21
|
+
Software Foundation, either version 3 of the License, or (at your option) any
|
|
22
|
+
later version.
|
|
23
|
+
|
|
24
|
+
This program is distributed in the hope that it will be useful, but WITHOUT ANY
|
|
25
|
+
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
|
|
26
|
+
PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
|
27
|
+
|
|
28
|
+
You should have received a copy of the GNU Affero General Public License along
|
|
29
|
+
with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## What you may do
|
|
33
|
+
|
|
34
|
+
Everything MIT let you do: run it, read and study the source, modify it,
|
|
35
|
+
redistribute it, bundle it into your own product, and **sell it** — the AGPL is
|
|
36
|
+
not a non-commercial licence. It adds an express patent grant that MIT never
|
|
37
|
+
had, which matters here for the transport, provider and tool-calling code.
|
|
38
|
+
|
|
39
|
+
## The obligation MIT did not have
|
|
40
|
+
|
|
41
|
+
- **§5 — distributing a modified version.** Conveying a modified copy (an npm
|
|
42
|
+
tarball, a rebuilt AppImage or `.deb`, a published fork) means the recipients
|
|
43
|
+
get the corresponding source under this same licence. Private local
|
|
44
|
+
modification triggers nothing.
|
|
45
|
+
- **§13 — Remote Network Interaction.** Operating a modified version as a
|
|
46
|
+
network service means the users of that service must be offered the
|
|
47
|
+
corresponding source. This is what stops a third party from taking this code,
|
|
48
|
+
standing up a competing hosted drain, and publishing nothing.
|
|
49
|
+
|
|
50
|
+
The desktop app is where this is most visible in practice: the thin-shell guard
|
|
51
|
+
already keeps cloud routing and brain logic out of `desktop/`, and that boundary
|
|
52
|
+
is what makes it possible for this repo to be AGPL while the hosted service
|
|
53
|
+
behind it stays a separate, proprietary product.
|
|
54
|
+
|
|
55
|
+
## Why this changed
|
|
56
|
+
|
|
57
|
+
Versions released before 2026-09-27 (npm `aegiscode` up to and including
|
|
58
|
+
`6.8.11`, `aegis-desktop` up to and including `0.8.12`) shipped under the MIT
|
|
59
|
+
License. MIT grants the right to "sublicense" and to "sell copies" and imposes
|
|
60
|
+
no obligation to give anything back: a third party could host a competing drain,
|
|
61
|
+
ship a closed fork, or resell the app, and owe this project nothing. AGPL keeps
|
|
62
|
+
the code public and free while making reuse carry a legal consequence.
|
|
63
|
+
|
|
64
|
+
This also keeps the SignPath Foundation signing grant eligible — that grant
|
|
65
|
+
requires an OSI-approved open-source licence against a public repo, which AGPL
|
|
66
|
+
is and a proprietary licence would not be. See
|
|
67
|
+
[desktop/SIGNING.md](desktop/SIGNING.md).
|
|
68
|
+
|
|
69
|
+
## What this change does not reach
|
|
70
|
+
|
|
71
|
+
- **Already-published copies stay MIT, permanently.** The MIT grant is
|
|
72
|
+
irrevocable for what is already out there: npm tarballs published before this
|
|
73
|
+
change, installers attached to releases before this change, and forks made
|
|
74
|
+
from pre-change commits. Only releases published from this commit onward are
|
|
75
|
+
AGPL.
|
|
76
|
+
- **The desktop mirror moved to `aegiscloud-devs/aegiscode-plugin`, branch
|
|
77
|
+
`desktop`** (2026-10-01, `tools/sync-desktop-mirror.mjs`). That repo is the
|
|
78
|
+
private destination the standing push directive names, and the synced tree
|
|
79
|
+
takes this repo's `LICENSE` file verbatim — so the mirror now ships **AGPL**,
|
|
80
|
+
not MIT. It is a mirror of `desktop/` only; the monorepo's own code lives on
|
|
81
|
+
that repo's `main`.
|
|
82
|
+
- **`aegiscloud/aegiscode-desktop` (org) is the legacy mirror.** It is a
|
|
83
|
+
`git subtree split` of `desktop/` that still ships the MIT `LICENSE` and
|
|
84
|
+
**has not been converted, and is no longer synced** — it is frozen at v0.8.1.
|
|
85
|
+
It survives only as the history seed for the new branch. The "Source (MIT)"
|
|
86
|
+
line in the promo copy is true *of that frozen repo* and false *of this repo
|
|
87
|
+
and of the current mirror* — which is exactly why the promo copy and
|
|
88
|
+
[docs/launch-readiness.md](docs/launch-readiness.md) are annotated rather than
|
|
89
|
+
left as-is.
|
|
90
|
+
- **Third-party code keeps its own licence** — notably `marked`
|
|
91
|
+
(MIT / MPL-2.0 dual) under `desktop/renderer/vendor/`.
|
|
92
|
+
|
|
93
|
+
## How the notice travels with the code
|
|
94
|
+
|
|
95
|
+
`LICENSE` is one file, and it is the first file a copy drops. So the notice is
|
|
96
|
+
also written into the source itself: every first-party file that ships — under
|
|
97
|
+
`cli/`, `client/`, `mcp/`, `desktop/` and `one/`, in `.js`, `.mjs`, `.cjs`,
|
|
98
|
+
`.sh`, `.ps1`, `.css` and `.html` — begins with the same five lines: the SPDX
|
|
99
|
+
identifier, the copyright holder, the product name, the source URL, and the §5/§13
|
|
100
|
+
sentence. `tools/provenance.mjs` writes them (`write`, idempotent), checks them
|
|
101
|
+
(`check`), and re-derives the list of shipped roots from each package's `files:`
|
|
102
|
+
list rather than from a list of its own. `test/provenance.test.mjs` runs the
|
|
103
|
+
sweep, plus a negative control.
|
|
104
|
+
|
|
105
|
+
The same command answers the other question a person holding an unfamiliar build
|
|
106
|
+
has — "is this still the program that was published?":
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
aegiscode provenance # licence, source, and a self-check of the safety files
|
|
110
|
+
aegiscode provenance --json # for scripts; exit 1 when a safety file has moved
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
It re-hashes the CLI files whose edit changes what the program **allows** — the
|
|
114
|
+
agent-key gate, the permission evaluator, the frozen approval classes, the
|
|
115
|
+
autonomous runner, the entry point that wires them, the silent interlock, and the
|
|
116
|
+
checker itself — against `cli/src/provenance.lock.json`, which ships in the
|
|
117
|
+
package.
|
|
118
|
+
|
|
119
|
+
Two deliberate details about what it says:
|
|
120
|
+
|
|
121
|
+
- **The manifest carries digests, not paths, and the runtime names units, not
|
|
122
|
+
files.** A report reading `src/gate.js: a1b2… → c3d4…` is a repair manual for
|
|
123
|
+
whoever neutered the gate: it names the file, the file's job, and the next move.
|
|
124
|
+
So `provenance.lock.json` keys its digests `p1…p7`, the runtime prints `p3:
|
|
125
|
+
digest moved`, and it does not print the remedy. The id-to-path table lives in
|
|
126
|
+
`cli/src/provenance.js`, where the code can resolve an id without ever showing
|
|
127
|
+
one, and in `tools/provenance.mjs`, which is a development tool and says
|
|
128
|
+
whatever a maintainer needs.
|
|
129
|
+
- **It is one of two gates.** This one speaks; the second one withholds. When the
|
|
130
|
+
sealed set does not verify as a *whole* (`cli/src/limits.js`), the build refuses
|
|
131
|
+
its own privileged subcommands — `gate`, `provenance`, `mcp` — so the half that
|
|
132
|
+
manages the agent key is unavailable to a build that failed the check, and it
|
|
133
|
+
says one bland line naming no file, no cause and no repair. The second gate has
|
|
134
|
+
**no environment variable and no flag**: anything that turns it off at runtime
|
|
135
|
+
would be documented right next to it, and a gate the manipulator can read about
|
|
136
|
+
is a gate the manipulator can open. Re-sealing is a deliberate act —
|
|
137
|
+
`node tools/provenance.mjs lock --write` re-seals the interlock and rewrites the
|
|
138
|
+
manifest in one command, so the two cannot drift apart.
|
|
139
|
+
|
|
140
|
+
A session prints the loud line to stderr when a digest has moved;
|
|
141
|
+
`AEGIS_NO_PROVENANCE_CHECK=1` silences *that* on a development tree and says so
|
|
142
|
+
when it does. It does not silence the interlock.
|
|
143
|
+
|
|
144
|
+
**What that is not.** It is not DRM and it does not measure "copying". Whoever
|
|
145
|
+
holds the bytes can edit a safety file *and* regenerate the manifest; there is no
|
|
146
|
+
key and no server, because a client that phones home to prove itself fails
|
|
147
|
+
offline. What it buys is that the manipulated build is no longer **silent** —
|
|
148
|
+
either it announces the divergence to its own user, or its author deleted a
|
|
149
|
+
check that `tools/invariant-lock.mjs` pins, which is a deliberate act with a
|
|
150
|
+
ledger entry. Removing the banner is likewise no longer a no-op: it is a
|
|
151
|
+
deletion in 160+ files, and `check` names every one.
|
|
152
|
+
|
|
153
|
+
## Commercial licence
|
|
154
|
+
|
|
155
|
+
If the AGPL's obligations do not fit your use — shipping a closed product,
|
|
156
|
+
running a hosted service without publishing modifications, or needing contract
|
|
157
|
+
terms, an indemnity or a support SLA — a commercial licence that waives them is
|
|
158
|
+
available. Contact **licensing@aegiscloud.org**. Note what this does *not* buy:
|
|
159
|
+
the paid cloud drain is a service, and paying for it has never required a
|
|
160
|
+
commercial licence, only AGPL compliance for any modified code you distribute
|
|
161
|
+
or host.
|
|
162
|
+
|
|
163
|
+
## Trademarks
|
|
164
|
+
|
|
165
|
+
The AGPL grants a copyright and a patent licence to the code. It grants **no**
|
|
166
|
+
right to the names *Aegiscode*, *AEGIS Code*, *Aegiscodex* or *Aegiscloud*, to
|
|
167
|
+
the logo, or to the npm package identities `aegiscode` / `aegis-desktop`. A fork
|
|
168
|
+
must use its own name and package name, and must not imply endorsement.
|
|
169
|
+
Nominative use — "a fork of Aegiscode" — is fine.
|
|
170
|
+
|
|
171
|
+
## Contributions
|
|
172
|
+
|
|
173
|
+
Dual licensing only works if the maintainer holds enough rights to license every
|
|
174
|
+
contribution under both the AGPL and the commercial terms, so contributions are
|
|
175
|
+
accepted under a contributor agreement (CLA), not by inbound-equals-outbound
|
|
176
|
+
default. This replaces the earlier "no CLA, no contributor agreement to sign"
|
|
177
|
+
position in [docs/reddit-drafts.md](docs/reddit-drafts.md). Until a contribution
|
|
178
|
+
carries that grant, treat it as needing explicit written permission before it is
|
|
179
|
+
merged; a pull request alone is not that permission.
|
|
180
|
+
|
|
181
|
+
## Scope note
|
|
182
|
+
|
|
183
|
+
This document records what the licence is and why. It is not legal advice. The
|
|
184
|
+
two places a lawyer's read matters most: the contribution/CLA paragraph above,
|
|
185
|
+
and whether the AGPL client and the proprietary `aegis1` backend are ever
|
|
186
|
+
distributed or operated together in a way §5 or §13 reaches.
|
package/package.json
CHANGED
|
@@ -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",
|
|
@@ -19,7 +19,9 @@
|
|
|
19
19
|
"scripts",
|
|
20
20
|
"vendor",
|
|
21
21
|
"README.md",
|
|
22
|
-
"
|
|
22
|
+
"LICENSE",
|
|
23
|
+
"SOURCE-OFFER.txt",
|
|
24
|
+
"LICENSING.md"
|
|
23
25
|
],
|
|
24
26
|
"engines": {
|
|
25
27
|
"node": ">=22.0.0"
|
package/src/app.js
CHANGED
|
@@ -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=>{if(I.thinkingTokens)I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{if(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 e;try{e=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:t,args:n}=e;if(!t)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(t,n)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const e=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),n=t||re();try{return!1!==await s.handler(n,e)}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=>{if(I.thinkingTokens)I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{if(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 e;try{e=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:t,args:n}=e;if(!t)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(t,n)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const e=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),n=t||re();try{return!1!==await s.handler(n,e)}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};
|
package/src/chatflow.js
CHANGED
|
@@ -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{getSize:getSize,span:span,padLine:padLine,paint:paint,w:w,wrapBlock:wrapBlock,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,selectionRange:selectionRange,selectionText:selectionText,applySelection:applySelection}=require("./screen.js"),{KEY:KEY,STREAM_END:STREAM_END,attachKeyStream:attachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,resetKeyStream:resetKeyStream,markSessionStart:markSessionStart,isKeyStreamSuspended:isKeyStreamSuspended}=require("./events.js"),{GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,BOLD:BOLD,BOLD_OFF:BOLD_OFF,themeOf:themeOf,RGB:RGB}=require("./theme.js"),{LineEditor:LineEditor}=require("./input.js"),{renderMarkdown:renderMarkdown}=require("./markdown.js"),overlays=require("./overlays.js"),models=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{validateApiKey:validateApiKey}=require(resolveShared(require("node:path").join("client","credentials.js"))),claudePro=require(resolveShared(require("node:path").join("desktop","lib","local","claude-pro.js"))),fuzzy=require("./fuzzy.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,pathName:pathName,feeBillable:feeBillable}=require("./format.js"),{editPreview:editPreview}=require("./diff.js"),{renderDiffBlock:renderDiffBlock,defaultOpen:defaultOpen}=require("./diffview.js"),{copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage}=require("./clipboard.js"),{transcriptToMarkdown:transcriptToMarkdown}=require("./export.js"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir,loadConfig:loadConfig}=require("./config.js"),{effortRung:effortRung}=require("./engine.js"),{usageBuckets:usageBuckets,estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{pingTurn:pingTurn}=require("./ping.js"),SUGGESTIONS=["edit <filepath> to...","refactor <filepath>","how do I log an error?","write a test for <filepath>","create a util logging.py that..."],{TITLE_SPIN:TITLE_SPIN,titleText:titleText,topicFrom:topicFrom,adoptTopic:adoptTopic,titleEnabled:titleEnabled,writeTitle:writeTitle}=require("./title.js"),{GENERIC_TITLE:GENERIC_TITLE,isGenericTitle:isGenericTitle}=require("./naming.js"),FRAME_MS=33;function isShellTool(e){return"exec"===e||"Bash"===e}function isAgentTool(e){return"task"===e||"Task"===e}function toolLabel(e,t){const n=isShellTool(e)?"shell command":isAgentTool(e)?"subagent":`${String(e).toLowerCase()} command`;return t>1?n+"s":n}function resolveToolDone(e,t){let n=-1;if(void 0!==t.id)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.id===t.id){n=r;break}}if(-1===n)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.name===t.name&&o.agent===t.agent){n=r;break}}if(-1===n)return null;const r=e[n],o=e.filter(((e,r)=>"tool"===e.role&&e.name===t.name&&e.agent===t.agent&&r<=n)).length;return r.phase="done",r.elapsed=t.elapsed,r.ok=t.ok,r.label=`Ran ${o} ${r.agent?`${r.agent} ▸ `:""}${toolLabel(t.name,o)}`,r}const MUTATING_FILES=new Set(["Edit","Write","MultiEdit","NotebookEdit","editFile","writeFile"]);function summarizeTurnTools(e,{maxNames:t=3}={}){const n=[],r=[];let o=0;for(const t of e||[]){if(!t)continue;!1===t.ok&&(o+=1);const e=t.args;if(!e||"object"!=typeof e)continue;const s=MUTATING_FILES.has(t.name)?e.file_path||e.path||e.notebook_path:null;"string"==typeof s&&s&&!n.includes(s)&&n.push(s);const i=e.command;if("string"==typeof i&&i.trim()){const e=pathName(i.trim().split(/\s+/)[0]);e&&!r.includes(e)&&r.push(e)}}return{tools:(e||[]).length,failed:o,files:n,names:n.slice(0,t).map((e=>pathName(e))),more:Math.max(0,n.length-t),commands:r}}function finalizeTurnText(e,{aborted:t,error:n,reasoned:r}={}){let o=String(null==e?"":e);if(n&&!t&&"stopped"!==n){const e=`(backend error: ${n})`;o=o.trim()?`${o.trimEnd()}\n\n${e}`:e}return t&&(o=o.trim()?`${o.trimEnd()} (stopped)`:"(stopped)"),o.trim()||(o=r?"(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)":"(no response)"),o}function historyPairs(e){return e.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})))}const PRO_ALIAS_KEYWORDS=Object.freeze(["opus","haiku","sonnet","fable"]);function overrideAnthropicByokWithPro(e,t={}){if(!e||"byok"!==e.cls)return{row:e,message:null};const n=String(e.id||""),r=n.indexOf(":");if(r<0||"anthropic"!==n.slice(0,r).trim().toLowerCase())return{row:e,message:null};if(!t.needsKey)return{row:e,message:null};if(!t.proLoggedIn)return{row:e,message:null};if(!0!==t.proEnabled)return{row:e,message:null};const o=n.slice(r+1).toLowerCase(),s=Array.isArray(t.proModels)&&t.proModels.length?t.proModels:[{id:"default",label:"Default",note:""}],i=PRO_ALIAS_KEYWORDS.find((e=>o.includes(e)))||"default",a=s.find((e=>e.id===i))||s[0];return{row:{id:a.id,label:a.label,note:a.note,cls:"pro"},message:`${n} has no Anthropic console key on this machine, but Claude Code Pro is signed in — using the subscription instead (claude --model ${a.id}). Add a real console key any time with /byok-key anthropic <key> to run this row directly.`}}function paletteQuery(e){const t=String(e||"").trim();return t.includes(" ")?t.split(/\s+/)[0]:t}function headerLine(e,t,n){const r=themeOf(n),o=` AEGIS Code v${e} `,s=Math.max(0,t-[...o].length-2),i=Math.floor(s/2);return[span(r.coral,`╭${"─".repeat(i)}${o}${"─".repeat(s-i)}╮`)]}const separatorLine=(e,t)=>[span(themeOf(t).dim,"─".repeat(e))];function effortLine(e,t){const n=themeOf(e),r=`● ${effortRung(e.effort)} · /effort`,o=" ".repeat(Math.max(0,t-[...r].length-4));return[span(n.gray,o+r)]}const SPINNER_TINT=RGB(235,159,127);function spinnerLine(e,t){const n=themeOf(t),r=Math.max(1,Math.round((e.elapsedMs||0)/1e3)),o=[...e.verb||VERBS[0]],s=Math.floor((e.frame||0)/2)%3,i=o.map(((e,t)=>span((t+s)%3==0?n.coral:SPINNER_TINT,e))),a=t&&t.thinking?span(n.gray,` (${r}s · thinking)`):span(n.gray,` (${r}s · ↓${e.streamedFloor?"≥":""}${fmtTokens(e.streamed||0)} tokens)`),l=GLYPH.spin[(e.frame||0)%GLYPH.spin.length];return[span(n.coral,l),...i,span(n.white,"… "),a]}function statusLine(e,t,n){const r=themeOf(n);let o;return o=e.inputPrompt?[span(r.gray,"enter to confirm · esc to cancel")]:e.working?[span(r.gray,` ${GLYPH.bullet} esc to interrupt`)]:e.streamJob?[span(r.gray,`${GLYPH.bullet} esc to stop`)]:e.keyNotice?[span(r.gray,` ${GLYPH.bullet} no AEGIS key: ${e.keyNotice} ${GLYPH.bullet} /key register to retry`)]:e.yolo?[span(r.gray,`${GLYPH.bullet} automode on ${GLYPH.bullet} ${autoContinueLimit()} rounds then it asks ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for manual mode`)]:[span(r.gray,`${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)],padLine(o,t)}function shortcutsGrid(e,t){const n=themeOf(t),r=(e,t,r,o)=>[span(""," "),span(n.white,e),span(n.gray," "+t),span(""," "),span(n.white,r),span(n.gray," "+o)];return[r("/","for commands","?","for shortcuts"),r("ctrl + c","to quit","ctrl + o","for permissions"),r("alt + p","to switch model","alt + t","to toggle thinking"),r("shift + ↑/↓","pins as it moves","shift + enter","runs the row"),r("esc","to interrupt a turn","ctrl + l","to clear the screen"),r("ctrl + t","to show tokens","ctrl + r","to resume a session"),r("↑ / ↓","for history","tab","to complete a command")]}const APPROVE_ONCE="once",APPROVE_SESSION="session",DENY_TOKEN="deny",APPROVAL_CHOICES=["Yes","Yes, allow for this session","No"],APPROVAL_DECISIONS=["once","session","deny"];function confirmLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${isShellTool(e.name)?"shell":e.name} command`)]),o.push([span("","")]);const s=isShellTool(e.name)?String(e.args&&e.args.command||""):String(e.args&&(e.args.file_path||e.args.pattern)||"");for(const e of wrapBlock(s,Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]),o.push([span(r.white,"Do you want to proceed?")]);const i=e.name||"this tool";return APPROVAL_CHOICES.forEach(((t,n)=>{const s=1===n?`Yes, and allow ${i} for this session`:t;o.push(((t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]})(n,s))})),o.push([span("","")]),o.push([span(r.gray,"Esc to cancel")]),o}const AUTO_CONTINUE_LIMIT=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:AUTO_CONTINUE_LIMIT}function autoContinuePlan({on:e=!1,used:t=0,limit:n=autoContinueLimit()}={}){const r=Number.isFinite(n)&&n>0?Math.floor(n):AUTO_CONTINUE_LIMIT,o=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?o>=r?{auto:!1,used:0,cap:r}:{auto:!0,used:o+1,cap:r}:{auto:!1,used:o,cap:r}}function roundsLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${e.spent}-round tool limit reached`)]),o.push([span("","")]);for(const e of wrapBlock("The turn is still working — it ended its last round on a tool call instead of an answer.",Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]);const s=(t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]};return o.push(s(0,`Yes, continue with ${e.size} more rounds`)),o.push(s(1,"No, stop here and answer with what I have")),o.push([span("","")]),o.push([span(r.gray,`extension ${e.extensions} of ${e.max} · Esc to stop`)]),o}function metaBits(e,t,{omitMs:n=!1}={}){const r=[];e.model&&r.push(span(t.blue,e.model));const o=fmtUsageSplit(e);if(o)r.push(span(t.white,o.output));else{const n=displayTokens(e);null!=n&&r.push(span(t.white,`${fmtTokens(n)} tokens`))}return null!=e.eur&&feeBillable()&&r.push(span(e.eur>0?t.coral:t.green,fmtEur(e.eur))),null==e.ms||n||r.push(span(t.gray,fmtElapsed(e.ms))),e.calls>1&&r.push(span(t.gray,`${e.calls} calls`)),r}function joinBits(e,t){const n=[];return e.forEach(((e,r)=>{r&&n.push(span(t.dim,` ${GLYPH.bullet} `)),n.push(e)})),n}const DIR_MAX=40;function shortDir(e){let t=String(null==e?"":e).trim().replace(/\/+$/,"");if(!t)return"";const n=String(process.env.HOME||process.env.USERPROFILE||"").replace(/\/+$/,"");return n&&(t===n||t.startsWith(`${n}/`))&&(t=`~${t.slice(n.length)}`),t.length>DIR_MAX&&(t=`${GLYPH.ellipse}${t.slice(-(DIR_MAX-1))}`),t}function rowLines(e,t,n,r=Date.now()){const o=themeOf(n),s=[];if("tool"===e.role){const i=String(e.label||"").replace(/(?:…|\.\.\.)+$/,""),a=e.cwd?` · ${shortDir(e.cwd)}`:"";if("run"===e.phase){const t=e.start?Math.max(1,Math.round((r-e.start)/1e3)):0;s.push([span(o.gray,`${i}${GLYPH.ellipse} · ${t}s${a}`)])}else s.push([span(o.gray,`${i}${a}`)]);if(e.diff){for(const r of renderDiffBlock(e.diff,n,t,{open:!!e.diffOpen}))s.push([span("",r)]);return s}const l="string"==typeof e.args?e.args:e.args&&"object"==typeof e.args?e.args.command??e.args.file_path??e.args.description??Object.values(e.args).find((e=>"string"==typeof e))??"":"";return l&&s.push([span(o.gray,` ${GLYPH.hook} $ ${String(l)}`)]),s}if("note"===e.role)return s.push([span(o.gray,`· ${e.text}`)]),s;if("tip"===e.role){for(const n of wrapBlock(String(e.text),t))s.push([span(o.gray,n)]);return s}if("done"===e.role){const t=[span(o.gray,GLYPH.bloom),span(o.gray,` ${e.text}`)];if(e.meta){const n=metaBits(e.meta,o,{omitMs:!0});n.length&&t.push(span(o.dim," "),...joinBits(n,o))}return s.push(t),s}if("summary"===e.role){const t=e.counts||{};if(!t.tools)return s;const n=[span(o.dim,GLYPH.hook),span(""," ")],r=[span(o.white,String(t.tools)),span(o.gray," "+(1===t.tools?"command":"commands"))];if(t.files&&t.files.length&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.white,String(t.files.length)),span(o.gray," "+(1===t.files.length?"file changed":"files changed")))),t.failed&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.coral,`${t.failed} failed`))),t.names&&t.names.length){const e=t.more?` +${t.more}`:"";r.push(span(o.dim,` ${t.names.join(", ")}${e}`))}return n.push(...r),s.push(n),s}if("meta"===e.role){const t=metaBits(e.meta||{},o);return t.length&&s.push([span(o.dim,`${GLYPH.hook} `),...joinBits(t,o)]),s}if("panel"===e.role){for(const n of e.lines||[])s.push(padLine(n,t));return s.push([span("","")]),s}if("error"===e.role)return s.push([span(o.red,`✗ ${e.text}`)]),s;if("user"===e.role)return wrapBlock(String(e.text),Math.max(8,t-2)).forEach(((e,t)=>{0===t?s.push([span(o.gray,GLYPH.cursor),span(""," "),span(o.white,e)]):s.push([span(""," "),span(o.white,e)])})),s;const i="assistant"===e.role?renderMarkdown(String(null==e.text?"":e.text),t,n):wrapBlock(String(null==e.text?"":e.text),t).map((e=>[span(o.white,e)])),a=i.length?i:[[span("","")]];for(let e=0;e<a.length;e++){const t=a[e].slice();0===e&&t.unshift(span(o.white,GLYPH.block),span(""," ")),s.push(t)}return s}function transcriptLines(e,t,n,r=Date.now(),o=null){const{cols:s,rows:i}=t,a=Math.max(1,i-6),l=[],u=[];for(const t of e){const e=o||null,i="assistant"===t.role&&t.streaming||"tool"===t.role&&"run"===t.phase;if(!e||i)for(const e of rowLines(t,s,n,r))l.push(e),u.push(t);else{const o=e.get(t);if(o&&o.text===t.text&&o.cols===s&&o.diffOpen===t.diffOpen){for(const e of o.segment)l.push(e),u.push(t);continue}const i=rowLines(t,s,n,r);e.set(t,{text:t.text,cols:s,diffOpen:t.diffOpen,segment:i});for(const e of i)l.push(e),u.push(t)}}let c=t.scroll||0,p=null==t.anchorEnd?null:t.anchorEnd;const d=l.length,f=Math.max(0,d-a);let m;c>f&&(c=f),0===c?(p=null,m=d):(null===p&&(p=Math.max(0,d-c)),m=Math.min(p,d)),d<=a&&(c=0,p=null,m=d);const h=Math.max(0,m-a);return{lines:l.slice(h,m),owners:u.slice(h,m),scroll:c,anchorEnd:p}}function inputPreviewText(e){const t=e.indexOf("\n");if(-1===t)return e;const n=e.split("\n").length-1;return`${e.slice(0,t)} … (+${n} line${1===n?"":"s"})`}const inputRowCells=e=>Math.max(1,e-3),bufCells=e=>[...e].reduce(((e,t)=>e+w(t)),0);function cursorCells(e,t){const n=[...e];let r=0;for(let e=0;e<Math.min(t,n.length);e++)r+=w(n[e]);return r}function inputScroll(e,t,n){const r=inputRowCells(n),o=bufCells(e);if(o<=r)return 0;const s=r-1;return Math.max(0,Math.min(cursorCells(e,t)-s,o-s))}function inputStart(e,t){const n=[...e];let r=0;for(let e=0;e<n.length;e++){if(r>=t)return e;r+=w(n[e])}return n.length}function inputLine(e,t,n){const r=themeOf(n),o=[span(r.gray,GLYPH.cursor),span(""," ")];if(e.inputPrompt){o.push(span(r.white,`${e.inputPrompt.title}: `));for(const t of[...e.inputPrompt.buf])o.push(span(r.white,t));const n=Math.min(3+w(e.inputPrompt.title)+2+w(e.inputPrompt.buf),t);return{line:padLine(o,t),cursorCol:n}}if(e.working)return{line:padLine(o,t),cursorCol:3};const s=e.buf||"";if(!s.length){if(e.insertMode)return{line:padLine(o,t),cursorCol:3};const n=SUGGESTIONS[(e.suggestionIdx||0)%SUGGESTIONS.length];return o.push(span(r.white+BOLD,`Try "${n}"`),span(BOLD_OFF,"")),{line:padLine(o,t),cursorCol:3}}if(s.includes("\n")){const e=inputPreviewText(s);for(const t of[...e])o.push(span(r.white,t));return{line:padLine(o,t),cursorCol:Math.min(3+w(e),t)}}const i=inputScroll(s,e.cursor,t),a=inputStart(s,i);i>0&&o.push(span(r.dim,"…"));const l=[...s];for(let e=a;e<l.length;e++)o.push(span(r.white,l[e]));const u=l.slice(a,Math.min(e.cursor,l.length)).join(""),c=Math.min(3+(i>0?1:0)+w(u),t);return{line:padLine(o,t),cursorCol:c}}async function runSession(e){const t=e.ctx,n=new LineEditor,r=e.transcript,o=new WeakMap;let s=null;function i(t){const n=paletteQuery(null==t?s&&s.query||"":t);return fuzzy.fuzzyRankWithAliases(n,e.visibleCommands(),(e=>e.name),(e=>e.aliases||[]))}let a=0,l=!1,u=null,c=0,p=null,d=0,f=VERBS[0],m=0,h=0,g=[],y=0,E=0,S=null;const T=new Map;let v=null,C=null,L=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,M=!0;try{M=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{M=!0}let A=!1,_=0;const N=e=>{if(!M)return;const t=e?TITLE_SPIN[Math.floor(c/2)%TITLE_SPIN.length]:null;writeTitle(titleText({topic:I,frame:t}),process.stdout)},D=t=>{if("function"!=typeof e.nameConversation)return;let n;R=!0;try{n=Promise.resolve(e.nameConversation(t,{signal:u?u.signal:null}))}catch{return}n.then((e=>{const t=String(e||"").trim();t&&(K=t,I=t,N(!!l),B())})).catch((()=>{}))},G=e=>{P=e,k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),B()},B=()=>{if(isKeyStreamSuspended())return;const i=getSize().cols,{lines:a,inputCol:u,rows:p,inputRow:m}=(()=>{const{cols:s,rows:i}=getSize(),a=[];a.push(headerLine(e.version,s,t));const u=Math.max(1,i-6),p=transcriptLines(r,{cols:s,rows:i,scroll:E,anchorEnd:S},t,Date.now(),o);E=p.scroll,S=p.anchorEnd,T.clear();for(let e=0;e<p.lines.length;e++)T.set(1+e,p.owners[e]);for(const e of p.lines)a.push(e);for(;a.length<u+1;)a.push([span("","")]);const m=themeOf(t);if(l)a.push(spinnerLine({verb:f,frame:c,elapsedMs:Date.now()-d,streamed:estimateTokensFromCells(W())+V,streamedFloor:V>0},t));else if(Date.now()<k)a.push([span(m.gray,` ${P}`)]);else if(x){const e=Math.max(1,Math.round((Date.now()-O)/1e3));a.push([span(m.gray,` ${x.label||"running"}… (${e}s · esc to stop)`)])}else a.push(effortLine(t,s));a.push(separatorLine(s,t));const h=inputLine({buf:n.buf,cursor:n.cursor,working:l,insertMode:b,suggestionIdx:y,inputPrompt:$},s,t);return a.push(h.line),a.push(separatorLine(s,t)),a.push(statusLine({working:l,inputPrompt:$,streamJob:x,yolo:e.isYolo&&e.isYolo(),keyNotice:e.keyNotice&&e.keyNotice()},s,t)),{lines:a,inputCol:h.cursorCol,rows:i,inputRow:i-2}})();s&&j(a,p,i),L=a,paint(v?applySelection(a,selectionRange(v.anchor,v.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},H=()=>{if(A)return;A=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout((()=>{A=!1,B()}),e)},j=(n,r,o)=>{if(!s)return;let i=null;if("palette"===s.type?i=overlays.renderPalette(e.visibleCommands(),{query:paletteQuery(s.query),sel:s.sel},o,r):"model"===s.type?i=overlays.renderModelPicker(s.items||[],s.sel||0,o,r,s.current,s.cls||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"effort"===s.type?i=overlays.renderEffortPicker(s.sel||0,o,t.effort):"class"===s.type?i=overlays.renderClassPicker(s.items||[],s.sel||0,o,s.current||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"provider"===s.type?i=overlays.renderProviderPicker(s.items||[],s.sel||0,o,s.current,s.hint):"resume"===s.type?i=overlays.renderResumeList(s.items||[],s.sel||0,o,r):"shortcuts"===s.type?i=shortcutsGrid(o,t):"confirm"===s.type?i=confirmLines(s,o,t):"rounds"===s.type?i=roundsLines(s,o,t):"panel"===s.type&&(i=s.lines||[]),!i)return;if("shortcuts"===s.type){const e=Math.max(2,r-i.length-1);for(let t=0;t<i.length;t++)n[e+t]=padLine(i[t],o);return void hideCursor()}const a=Math.max(2,Math.floor((r-i.length)/2));for(let e=0;e<i.length;e++)n[a+e]=padLine(i[e],o);hideCursor()},q=(e,t)=>(r.push(e),t&&!1===t.follow||(E=0,S=null),e),F=(e,t)=>{const n=t?r.indexOf(t):-1;return n<0?r.push(e):r.splice(n,0,e),e},U=e=>q({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z,Q=async t=>{l=!0,c=0,d=Date.now(),z=0,V=0,h=0,g=[],f=VERBS[m%VERBS.length],I=K||adoptTopic(I,t),(e=>{K?isGenericTitle(K)&&D(e):R||D(e)})(t),u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0),q({role:"user",text:t});const n=q({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),H()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,H()},tool:e=>{if(e&&void 0!==e.id){const t=g.findIndex((t=>t&&void 0!==t.id&&t.id===e.id));t>=0?g[t]=e:g.push(e)}else g.push(e);if("run"===e.phase){const t=++h,r=e.agent?`${e.agent} ▸ `:"",o=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"run",name:e.name,args:e.args,agent:e.agent,id:e.id,label:`Running ${t} ${r}${toolLabel(e.name,t)}…`,start:Date.now(),diff:o,diffOpen:defaultOpen(o)},n)}else if(!resolveToolDone(r,e)){const t=++h,r=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"done",name:e.name,args:e.args,agent:e.agent,id:e.id,ok:e.ok,label:`Ran ${t} ${e.agent?`${e.agent} ▸ `:""}${toolLabel(e.name,t)}`,diff:r,diffOpen:defaultOpen(r)},n)}H()},approval:e=>(e=>new Promise((t=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B(),(async()=>{const e=e=>{s=null,B(),t(e)};for(;;){const t=await nextKey();if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB){const e=t.name===KEY.UP?-1:1;s.sel=(s.sel+e+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(t.name===KEY.ENTER)return void e(APPROVAL_DECISIONS[s.sel]||"deny");if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e("deny");if("char"===t.name){const n=String(t.ch).trim(),r=Number(n)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void e(APPROVAL_DECISIONS[r])}}}})()})))(e),rounds:t=>(t=>new Promise((n=>{const r=Boolean(e.isYolo&&e.isYolo()),o=autoContinuePlan({on:r,used:a});if(a=o.used,o.auto)return U(`auto: ${t.spent}-round limit reached — continuing automatically (${o.used}/${o.cap}, then it asks).`),B(),void n(!0);r&&(U(`auto: ${o.cap} automatic continuations used — asking you now (answering restarts the block).`),B()),s={type:"rounds",spent:Number(t.spent)||0,extensions:Number(t.extensions)||1,max:Number(t.max)||8,size:Number(t.size)||Number(t.spent)||0,sel:1},B(),(async()=>{const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB)s.sel=1-s.sel,B();else{if(t.name===KEY.ENTER)return void e(0===s.sel);if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e(!1);if("char"===t.name){const n=String(t.ch).trim();if("1"===n)return void e(!0);if("2"===n)return void e(!1)}}}})()})))(t)};let S=null;try{S=await e.ask(t,{history:historyPairs(r),presenter:i,signal:u.signal})}catch(e){S={error:e&&e.message||String(e)}}finally{n.streaming=!1,!String(n.text||"").trim()&&S&&"string"==typeof S.text&&S.text.trim()&&(n.text=S.text),l=!1,clearInterval(p),p=null,N(!1);const r=Math.max(1,Math.round((Date.now()-d)/1e3)),s=!(!u||!u.signal.aborted);n.text=finalizeTurnText(n.text,{aborted:s,error:S&&S.error,reasoned:o}),q({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{follow:!1}),y=m+1,m++,u=null;try{const e=loadConfig(),t=pingTurn({stream:process.stdout,mode:e.ping,minSeconds:e.pingMinSeconds,elapsedMs:Date.now()-d,isTTY:!!process.stdout.isTTY,aborted:s});t&&q({role:"note",text:t},{follow:!1})}catch{}e.recordTurn(S);let i=null;try{const t=await e.refreshSpend();i=t?t.lastCost:null}catch{}e.persistTurn&&e.persistTurn(t,S,s?"stopped":S&&S.error?"error":"done",i);const a=S&&S.usage,c=e.tokensFor?e.tokensFor(a):null,f=a?usageBuckets(a):null;q({role:"meta",meta:{model:S&&S.model,tokens:c,input:f?f.input:null,output:f?f.output:null,eur:i,ms:S&&S.ms,calls:S&&S.calls||1}},{follow:!1});const w=summarizeTurnTools(g);w.tools>0&&q({role:"summary",counts:w},{follow:0===E}),B()}},X=e=>{let r=null;if(e.name===KEY.PAGE_UP)r=5;else if(e.name===KEY.PAGE_DOWN)r=-5;else if("wheel"===e.name)r="up"===e.dir?3:-3;else{if("click"===e.name||"drag"===e.name||"release"===e.name)return!(e=>{const t={col:e.col-1,row:e.row-1};if("click"===e.name)return C=t,!1;if("drag"===e.name)return v?v.head=t:v={anchor:C||t,head:t},C=null,!0;const n=C;C=null;const r=v?selectionRange(v.anchor,v.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(v=null,!o)return(e=>{const t=T.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=selectionText(L,r);if(!s)return!0;const i=copyToClipboard(s,{stdout:process.stdout,env:process.env}),a=s.split("\n").length;return P=describeCopy(i,`Marked ${a} line${1===a?"":"s"}`),k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),!0})(e)||(H(),!0);"char"!==e.name||!t.vim||b||n.buf||("j"===e.ch?r=1:"k"===e.ch&&(r=-1))}return null!==r&&(E=Math.max(0,E+r),S=null,H(),!0)},J=()=>s?"palette"===s.type?fuzzy.fuzzyRankWithAliases(paletteQuery(s.query),e.visibleCommands(),(e=>e.name),(e=>e.aliases||[])).length:"model"===s.type||"resume"===s.type||"class"===s.type||"provider"===s.type?(s.items||[]).length:"effort"===s.type?overlays.EFFORT_VALUES.length:0:0,Z=async n=>{if(n){{const t=models.modelKeyPlan(n,{hasStored:!!e.hasProviderKey&&!!e.hasProviderKey("anthropic")}),{row:r,message:o}=overrideAnthropicByokWithPro(n,{needsKey:!(!t||!t.needed),proLoggedIn:models.claudeProLoggedIn(),proEnabled:(()=>{try{return!0===loadConfig().proEnabled}catch{return!1}})(),proModels:claudePro.PRO_MODELS});n=r,o&&U(o)}if(n.cls&&"aegis"!==n.cls&&t.modelClass!==n.cls){const e="string"==typeof t.modelClass;if(await re(`/class ${n.cls}`),e&&t.modelClass!==n.cls)return void U(`${n.id} runs on the ${n.cls} class, and this session is on ${t.modelClass} — run /class ${n.cls}${"pro"===n.cls?" on":""}, then pick it again.`)}t.model=n.id,e.updateConfig({model:n.id,currentModelId:n.id,modelClass:t.modelClass}),U(`model: ${n.id}${"byok"===n.cls?" (byok)":"pro"===n.cls?" (Claude Code Pro)":""}`),await(async t=>{const n=models.modelKeyQueue(t,{accountConfigured:!!e.accountConfigured&&!!e.accountConfigured(),hasStoredFor:t=>!!e.hasProviderKey&&!!e.hasProviderKey(t)});if(!n.length)return;let r=null;try{r=e.makeCommandContext()}catch{r=null}if(r&&"function"==typeof r.readSecret)for(const e of n){const n="account"===e.role?"AEGIS account key":"claude-pro"===e.role?"Claude Code OAuth token (`claude setup-token` mints one)":`${e.provider} key`,o=String(await r.readSecret(`${n} → ${e.env} (kept off screen, Enter to skip): `)||"").trim();if(!o){U(`no key given — ${e.env} is still unset, so ${t.id} will fail until it is.`);continue}const s="account"===e.role?"AEGIS":"claude-pro"===e.role?"Claude Code OAuth":e.provider||"that provider",i=validateApiKey(o,{label:s});if(!i.ok){U(`not saved — ${i.message}. ${e.env} is still unset.`);continue}const a=models.storeModelKey(t,i.key,{env:e.env});a.ok?U(a.changed?a.foreign?`${e.env} saved to ${a.file} (0600) — read only by the Claude Code Pro transport, never exported.`:`${e.env} saved to ${a.file} (0600) — both hosts read that file; nothing to export.`:`${e.env} was already set in ${a.file}.`):U(`could not save the key: ${a.error||"unknown error"}`)}else{const e=n.map((e=>`${e.env}: ${e.why}`)).join(" · ");U(`${t.id} has no key: ${e}. Set the ones above and pick it again.`)}})(n)}},ee=async e=>{e&&e.class&&await re(`/class ${e.class}`)},te=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},ne=async o=>{if(o)if(s)await(async t=>{const n=s.type;if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return s=null,void B();if("shortcuts"===n||"panel"===n)return s=null,void B();if(t.name!==KEY.TAB||"palette"!==n)if(t.name!==KEY.TAB||"model"!==n&&"effort"!==n&&"class"!==n&&"provider"!==n){if(t.name===KEY.ENTER){if("palette"===n){const e=i()[s.sel||0],t=String(s.query||"").trim().split(/\s+/).slice(1).join(" ");return s=null,B(),void(e&&await re(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("effort"===n)return void te(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await re(`/${t} ${e.id}`))}if("resume"===n){const t=(s.items||[])[s.sel||0];return s=null,B(),void(t&&e.resumeSession&&await e.resumeSession(t))}return s=null,void B()}if(t.name===KEY.SHIFT_UP||t.name===KEY.SHIFT_DOWN){const e=t.name===KEY.SHIFT_UP?-1:1,r=Math.max(0,J()-1);if(s.sel=Math.min(r,Math.max(0,(s.sel||0)+e)),"model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await re(`/${t} ${e.id}`))}return"effort"===n?void te(s.sel||0):void B()}if(t.name===KEY.SHIFT_ENTER){if("palette"===n){const e=i()[s.sel||0];return s=null,B(),void(e&&await re(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await re(`/${t} ${e.id}`))}return"effort"===n?void te(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||J(),n=t.name===KEY.UP?-1:1;return s.sel=Math.min(Math.max(0,e-1),Math.max(0,(s.sel||0)+n)),void B()}if("char"===t.name){if("palette"===n)return s.query=(s.query||"")+t.ch,s.sel=0,void B();if("model"===n){const e=parseInt(t.ch,10),n=s.items||[];return void(Number.isFinite(e)&&e>=1&&e<=n.length&&(s.sel=e-1,B()))}if("effort"===n||"resume"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=J();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}t.name===KEY.BACKSPACE&&"palette"===n&&(s.query=String(s.query||"").slice(0,-1),B())}else{const e="model"===n||"class"===n||"provider"===n?(s.items||[]).length:overlays.EFFORT_VALUES.length;e&&(s.sel=((s.sel||0)+1)%e,B())}else{const e=i()[s.sel||0];e&&(s.query=e.name,s.sel=0,B())}})(o);else{if("char"===o.name&&!n.buf){if("/"===o.ch)return s={type:"palette",query:"",sel:0},void B();if("?"===o.ch)return s={type:"shortcuts"},void B()}if(!t.vim||b||n.buf||"char"!==o.name){if(t.vim&&b&&o.name===KEY.ESC)return b=!1,n.cursor>0&&n.cursor--,void B()}else{const e=o.ch;if("i"===e||"a"===e||"o"===e||"s"===e||"S"===e)return"s"===e&&n.substChar(),"S"===e&&n.substLine(),"a"===e&&n.right(),b=!0,void B();if("h"===e)return n.left(),void B();if("l"===e)return n.right(),void B();if("0"===e)return n.home(),void B();if("$"===e)return n.end(),void B();if("x"===e)return n.delete(),void B();if("D"===e)return n.killToEnd(),void B();if("A"===e)return n.end(),b=!0,void B();if(X(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await re(e):void B()}if(o.name!==KEY.CTRL_V)if(o.name!==KEY.CTRL_B){if("paste"===o.name)return t.vim&&(b=!0),n.insert(String(o.text)),void B();if("char"===o.name)return t.vim&&!b||n.insert(o.ch),void B();if(o.name===KEY.BACKSPACE)return n.backspace(),void B();if(o.name===KEY.DELETE)return n.delete(),void B();if(o.name===KEY.LEFT||o.name===KEY.CTRL_LEFT)return o.name===KEY.CTRL_LEFT?n.wordBack():n.left(),void B();if(o.name!==KEY.RIGHT||n.buf){if(o.name===KEY.RIGHT||o.name===KEY.CTRL_RIGHT)return n.right(),void B();if(o.name===KEY.HOME||o.name===KEY.CTRL_A)return n.home(),void B();if(o.name===KEY.END||o.name===KEY.CTRL_E)return n.end(),void B();if(o.name===KEY.UP)return n.historyUp(),void B();if(o.name===KEY.DOWN)return n.historyDown(),void B();if(o.name===KEY.TAB)return(()=>{const t=n.buf;if(!t.startsWith("/")||t.includes(" "))return!1;const r=t.slice(1),o=e.visibleCommands().flatMap((e=>[e.name,...e.aliases||[]])).filter((e=>e.startsWith(r))).sort();return!!o.length&&(Y&&Y.q===r||(Y={q:r,i:-1}),Y.i=(Y.i+1)%o.length,n.buf="/"+o[Y.i],n.end(),!0)})()||(P=n.buf?"Tab completes commands":"Use alt+t to toggle thinking",k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600)),void B();if(o.name===KEY.CTRL_U)return n.buf="",n.cursor=0,void B();if(o.name===KEY.CTRL_K)return n.killToEnd(),void B();if(o.name===KEY.CTRL_W)return n.wordBack(),void B();if(o.name===KEY.CTRL_L)return clearScreen(),void B();if(o.name===KEY.CTRL_T)return U(e.tokenSummary?e.tokenSummary():"no token usage yet this session"),void B();if(o.name!==KEY.CTRL_R)if(o.name!==KEY.CTRL_O)if("click"!==o.name&&"drag"!==o.name&&"release"!==o.name)if(o.name!==KEY.PAGE_UP&&o.name!==KEY.PAGE_DOWN&&"wheel"!==o.name)if("alt"!==o.name||"p"!==o.ch){if("alt"===o.name&&"t"===o.ch){const n=!(!0===t.thinking);return t.thinking=n,e.updateConfig({thinking:n}),U("Thinking blocks: "+(n?"expanded":"collapsed")),void B()}if(o.name!==KEY.ESC)return o.name===KEY.CTRL_C?n.buf?(n.buf="",n.cursor=0,void B()):void await ie():void(o.name!==KEY.CTRL_D||n.buf||await ie());n.buf&&(n.buf="",n.cursor=0,B())}else await re("/model");else X(o);else X(o);else await re("/permissions");else await re("/resume")}else await re(e.isYolo&&e.isYolo()?"/automode off":"/automode on")}else(()=>{if(!r.length)return void G("Nothing to copy yet");const e=copyToClipboard(transcriptToMarkdown(r),{stdout:process.stdout,env:process.env});G(describeCopy(e,"Copied the conversation"))})();else(()=>{const e=readClipboardImage({env:process.env});if(e.ok)try{const t=path.join(aegisDir(),"clipboard");fs.mkdirSync(t,{recursive:!0});const r="image/jpeg"===e.mime?"jpg":"png",o=path.join(t,`pasted-${(new Date).toISOString().replace(/[:.]/g,"-")}.${r}`);fs.writeFileSync(o,e.data,{mode:384});const s=n.buf&&!/\s$/.test(n.buf)?" ":"";return n.insert(s+o),void G(`Pasted image → ${o}`)}catch(e){return void G(`Could not save the pasted image: ${e&&e.message||e}`)}const t=readClipboardText({env:process.env});if(t.ok&&t.text)return n.insert(t.text),void G(`Pasted ${t.text.length} character${1===t.text.length?"":"s"} from the clipboard`);G(t.ok?"Clipboard is empty — nothing to paste":`Cannot read the clipboard here (${t.error}) — use your terminal's own paste shortcut instead`)})()}},re=async t=>{const r=String(t||"").trim();if("?"===r)return s={type:"shortcuts"},void B();(!1===await(async(e,t)=>{try{return await((e,t)=>{const n=[];let r,o,i=!1;return e.then((e=>{i=!0,r=e}),(e=>{i=!0,o=e})),(async()=>{for(;!i;){if(!l||s&&"confirm"===s.type){await new Promise((e=>setTimeout(e,60)));continue}const e=await nextKeyTimeout(120);if(null!==e)if(e.name===KEY.ESC||e.name===KEY.CTRL_C){const e=t&&t();e&&e.abort()}else X(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),t)}catch(e){return q({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),void B()}})((async()=>{if(r.startsWith("/")){const t=(()=>{const t=e.makeCommandContext();return Object.assign(t,{push:(e,t)=>{q(e,t),B()},note:e=>{q({role:"note",text:e}),B()},panel:e=>{q({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{s=e,B()},closeOverlay:()=>{s=null,showCursor(),B()},askInput:e=>(e=>new Promise((t=>{$={title:e,buf:""},B(),(async()=>{for(;;){const e=await nextKey();if(!$)return void t(null);if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return $=null,B(),void t(null);if(e.name===KEY.ENTER){const e=$.buf;return $=null,B(),void t(e)}e.name===KEY.BACKSPACE?$.buf=[...$.buf].slice(0,-1).join(""):"char"===e.name?$.buf+=e.ch:"paste"===e.name&&($.buf+=String(e.text).replace(/\n/g," ")),B()}})()})))(e),withWorking:e=>(async e=>{const t=u;l=!0,c=0,d=Date.now(),f=VERBS[m%VERBS.length],u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0);try{return await e(u.signal)}finally{l=!1,clearInterval(p),p=null,u=t,N(!1),B()}})(e),runPrompt:async e=>{await Q(e)},state:()=>e.buildState(),setInput:e=>{n.buf=String(null==e?"":e),n.end(),B()},exit:()=>e.requestExit(),openStream:e=>{x=e||null,O=Date.now(),B()},closeStream:e=>{e&&x!==e||(x=null),B()},showThemePicker:()=>{e.showThemePicker&&e.showThemePicker(),B()}}),t})();return e.dispatchLine(r,t)}return await Q(r),!0}),(()=>u))||e.wantsExit())&&await ie()};let oe=!1,se=null;const ie=()=>{oe||(oe=!0,se&&se(0))},ae=()=>{hideCursor(),paint([]);try{process.stdout.write("[0m")}catch{}try{M&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let le=!1;const ue=()=>{if(!le){le=!0;try{ae()}catch{}}};process.once("exit",ue);const ce=e.stdin||process.stdin;markSessionStart(),attachKeyStream(ce),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const pe=()=>B();"win32"!==process.platform?process.on("SIGWINCH",pe):process.stdout.on("resize",pe);const de=()=>{l&&u?u.abort():ie()};process.on("SIGINT",de);const fe=e=>{ae();try{process.stderr.write(`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${e&&e.stack||e}\n`)}catch{}process.exit(1)};process.on("uncaughtException",fe),process.on("unhandledRejection",fe),B();try{return await new Promise((e=>{se=e,(async()=>{for(;!oe;){const e=await nextKey();if(oe)break;if(e===STREAM_END||!e){ie();break}try{await ne(e)}catch(e){q({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()}))}finally{oe=!0,process.off("SIGINT",de),"win32"!==process.platform?process.off("SIGWINCH",pe):process.stdout.off("resize",pe),process.off("uncaughtException",fe),process.off("unhandledRejection",fe),process.off("exit",ue),ue(),resetKeyStream()}}module.exports={SUGGESTIONS:SUGGESTIONS,TITLE_SPIN:TITLE_SPIN,FRAME_MS:33,toolLabel:toolLabel,resolveToolDone:resolveToolDone,summarizeTurnTools:summarizeTurnTools,finalizeTurnText:finalizeTurnText,historyPairs:historyPairs,overrideAnthropicByokWithPro:overrideAnthropicByokWithPro,paletteQuery:paletteQuery,headerLine:headerLine,separatorLine:separatorLine,effortLine:effortLine,spinnerLine:spinnerLine,statusLine:statusLine,shortcutsGrid:shortcutsGrid,confirmLines:confirmLines,APPROVAL_CHOICES:APPROVAL_CHOICES,APPROVAL_DECISIONS:APPROVAL_DECISIONS,roundsLines:roundsLines,autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,AUTO_CONTINUE_LIMIT:AUTO_CONTINUE_LIMIT,rowLines:rowLines,transcriptLines:transcriptLines,inputPreviewText:inputPreviewText,inputRowCells:inputRowCells,inputScroll:inputScroll,inputStart:inputStart,inputLine:inputLine,runSession:runSession};
|
|
3
|
+
"use strict";const{getSize:getSize,span:span,padLine:padLine,paint:paint,w:w,wrapBlock:wrapBlock,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,selectionRange:selectionRange,selectionText:selectionText,applySelection:applySelection}=require("./screen.js"),{KEY:KEY,STREAM_END:STREAM_END,attachKeyStream:attachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,resetKeyStream:resetKeyStream,markSessionStart:markSessionStart,isKeyStreamSuspended:isKeyStreamSuspended}=require("./events.js"),{GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,BOLD:BOLD,BOLD_OFF:BOLD_OFF,themeOf:themeOf,RGB:RGB}=require("./theme.js"),{LineEditor:LineEditor}=require("./input.js"),{renderMarkdown:renderMarkdown}=require("./markdown.js"),overlays=require("./overlays.js"),models=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{validateApiKey:validateApiKey}=require(resolveShared(require("node:path").join("client","credentials.js"))),sessionSearch=require(resolveShared(require("node:path").join("client","session-search.js"))),claudePro=require(resolveShared(require("node:path").join("desktop","lib","local","claude-pro.js"))),fuzzy=require("./fuzzy.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,pathName:pathName,feeBillable:feeBillable}=require("./format.js"),{editPreview:editPreview}=require("./diff.js"),{renderDiffBlock:renderDiffBlock,defaultOpen:defaultOpen}=require("./diffview.js"),{copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage}=require("./clipboard.js"),{transcriptToMarkdown:transcriptToMarkdown}=require("./export.js"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir,loadConfig:loadConfig}=require("./config.js"),{effortRung:effortRung}=require("./engine.js"),{usageBuckets:usageBuckets,estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{pingTurn:pingTurn}=require("./ping.js"),SUGGESTIONS=["edit <filepath> to...","refactor <filepath>","how do I log an error?","write a test for <filepath>","create a util logging.py that..."],{TITLE_SPIN:TITLE_SPIN,titleText:titleText,topicFrom:topicFrom,adoptTopic:adoptTopic,titleEnabled:titleEnabled,writeTitle:writeTitle}=require("./title.js"),{GENERIC_TITLE:GENERIC_TITLE,isGenericTitle:isGenericTitle}=require("./naming.js"),FRAME_MS=33;function isShellTool(e){return"exec"===e||"Bash"===e}function isAgentTool(e){return"task"===e||"Task"===e}function toolLabel(e,t){const n=isShellTool(e)?"shell command":isAgentTool(e)?"subagent":`${String(e).toLowerCase()} command`;return t>1?n+"s":n}function resolveToolDone(e,t){let n=-1;if(void 0!==t.id)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.id===t.id){n=r;break}}if(-1===n)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.name===t.name&&o.agent===t.agent){n=r;break}}if(-1===n)return null;const r=e[n],o=e.filter(((e,r)=>"tool"===e.role&&e.name===t.name&&e.agent===t.agent&&r<=n)).length;return r.phase="done",r.elapsed=t.elapsed,r.ok=t.ok,r.label=`Ran ${o} ${r.agent?`${r.agent} ▸ `:""}${toolLabel(t.name,o)}`,r}const MUTATING_FILES=new Set(["Edit","Write","MultiEdit","NotebookEdit","editFile","writeFile"]);function summarizeTurnTools(e,{maxNames:t=3}={}){const n=[],r=[];let o=0;for(const t of e||[]){if(!t)continue;!1===t.ok&&(o+=1);const e=t.args;if(!e||"object"!=typeof e)continue;const s=MUTATING_FILES.has(t.name)?e.file_path||e.path||e.notebook_path:null;"string"==typeof s&&s&&!n.includes(s)&&n.push(s);const i=e.command;if("string"==typeof i&&i.trim()){const e=pathName(i.trim().split(/\s+/)[0]);e&&!r.includes(e)&&r.push(e)}}return{tools:(e||[]).length,failed:o,files:n,names:n.slice(0,t).map((e=>pathName(e))),more:Math.max(0,n.length-t),commands:r}}function finalizeTurnText(e,{aborted:t,error:n,reasoned:r}={}){let o=String(null==e?"":e);if(n&&!t&&"stopped"!==n){const e=`(backend error: ${n})`;o=o.trim()?`${o.trimEnd()}\n\n${e}`:e}return t&&(o=o.trim()?`${o.trimEnd()} (stopped)`:"(stopped)"),o.trim()||(o=r?"(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)":"(no response)"),o}function historyPairs(e){return e.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})))}const PRO_ALIAS_KEYWORDS=Object.freeze(["opus","haiku","sonnet","fable"]);function overrideAnthropicByokWithPro(e,t={}){if(!e||"byok"!==e.cls)return{row:e,message:null};const n=String(e.id||""),r=n.indexOf(":");if(r<0||"anthropic"!==n.slice(0,r).trim().toLowerCase())return{row:e,message:null};if(!t.needsKey)return{row:e,message:null};if(!t.proLoggedIn)return{row:e,message:null};if(!0!==t.proEnabled)return{row:e,message:null};const o=n.slice(r+1).toLowerCase(),s=Array.isArray(t.proModels)&&t.proModels.length?t.proModels:[{id:"default",label:"Default",note:""}],i=PRO_ALIAS_KEYWORDS.find((e=>o.includes(e)))||"default",a=s.find((e=>e.id===i))||s[0];return{row:{id:a.id,label:a.label,note:a.note,cls:"pro"},message:`${n} has no Anthropic console key on this machine, but Claude Code Pro is signed in — using the subscription instead (claude --model ${a.id}). Add a real console key any time with /byok-key anthropic <key> to run this row directly.`}}function paletteQuery(e){const t=String(e||"").trim();return t.includes(" ")?t.split(/\s+/)[0]:t}function headerLine(e,t,n){const r=themeOf(n),o=` AEGIS Code v${e} `,s=Math.max(0,t-[...o].length-2),i=Math.floor(s/2);return[span(r.coral,`╭${"─".repeat(i)}${o}${"─".repeat(s-i)}╮`)]}const separatorLine=(e,t)=>[span(themeOf(t).dim,"─".repeat(e))];function effortLine(e,t){const n=themeOf(e),r=`● ${effortRung(e.effort)} · /effort`,o=" ".repeat(Math.max(0,t-[...r].length-4));return[span(n.gray,o+r)]}const SPINNER_TINT=RGB(235,159,127);function spinnerLine(e,t){const n=themeOf(t),r=Math.max(1,Math.round((e.elapsedMs||0)/1e3)),o=[...e.verb||VERBS[0]],s=Math.floor((e.frame||0)/2)%3,i=o.map(((e,t)=>span((t+s)%3==0?n.coral:SPINNER_TINT,e))),a=t&&t.thinking?span(n.gray,` (${r}s · thinking)`):span(n.gray,` (${r}s · ↓${e.streamedFloor?"≥":""}${fmtTokens(e.streamed||0)} tokens)`),l=GLYPH.spin[(e.frame||0)%GLYPH.spin.length];return[span(n.coral,l),...i,span(n.white,"… "),a]}function statusLine(e,t,n){const r=themeOf(n);let o;return o=e.inputPrompt?[span(r.gray,"enter to confirm · esc to cancel")]:e.working?[span(r.gray,` ${GLYPH.bullet} esc to interrupt`)]:e.streamJob?[span(r.gray,`${GLYPH.bullet} esc to stop`)]:e.keyNotice?[span(r.gray,` ${GLYPH.bullet} no AEGIS key: ${e.keyNotice} ${GLYPH.bullet} /key register to retry`)]:e.yolo?[span(r.gray,`${GLYPH.bullet} automode on ${GLYPH.bullet} ${autoContinueLimit()} rounds then it asks ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for manual mode`)]:[span(r.gray,`${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)],padLine(o,t)}function shortcutsGrid(e,t){const n=themeOf(t),r=(e,t,r,o)=>[span(""," "),span(n.white,e),span(n.gray," "+t),span(""," "),span(n.white,r),span(n.gray," "+o)];return[r("/","for commands","?","for shortcuts"),r("ctrl + c","to quit","ctrl + o","for permissions"),r("alt + p","to switch model","alt + t","to toggle thinking"),r("shift + ↑/↓","pins as it moves","shift + enter","runs the row"),r("esc","to interrupt a turn","ctrl + l","to clear the screen"),r("ctrl + t","to show tokens","ctrl + r","to resume a session"),r("↑ / ↓","for history","tab","to complete a command")]}const APPROVE_ONCE="once",APPROVE_SESSION="session",DENY_TOKEN="deny",APPROVAL_CHOICES=["Yes","Yes, allow for this session","No"],APPROVAL_DECISIONS=["once","session","deny"];function confirmLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${isShellTool(e.name)?"shell":e.name} command`)]),o.push([span("","")]);const s=isShellTool(e.name)?String(e.args&&e.args.command||""):String(e.args&&(e.args.file_path||e.args.pattern)||"");for(const e of wrapBlock(s,Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]),o.push([span(r.white,"Do you want to proceed?")]);const i=e.name||"this tool";return APPROVAL_CHOICES.forEach(((t,n)=>{const s=1===n?`Yes, and allow ${i} for this session`:t;o.push(((t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]})(n,s))})),o.push([span("","")]),o.push([span(r.gray,"Esc to cancel")]),o}const AUTO_CONTINUE_LIMIT=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:AUTO_CONTINUE_LIMIT}function autoContinuePlan({on:e=!1,used:t=0,limit:n=autoContinueLimit()}={}){const r=Number.isFinite(n)&&n>0?Math.floor(n):AUTO_CONTINUE_LIMIT,o=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?o>=r?{auto:!1,used:0,cap:r}:{auto:!0,used:o+1,cap:r}:{auto:!1,used:o,cap:r}}function roundsLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${e.spent}-round tool limit reached`)]),o.push([span("","")]);for(const e of wrapBlock("The turn is still working — it ended its last round on a tool call instead of an answer.",Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]);const s=(t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]};return o.push(s(0,`Yes, continue with ${e.size} more rounds`)),o.push(s(1,"No, stop here and answer with what I have")),o.push([span("","")]),o.push([span(r.gray,`extension ${e.extensions} of ${e.max} · Esc to stop`)]),o}function metaBits(e,t,{omitMs:n=!1}={}){const r=[];e.model&&r.push(span(t.blue,e.model));const o=fmtUsageSplit(e);if(o)r.push(span(t.white,o.output));else{const n=displayTokens(e);null!=n&&r.push(span(t.white,`${fmtTokens(n)} tokens`))}return null!=e.eur&&feeBillable()&&r.push(span(e.eur>0?t.coral:t.green,fmtEur(e.eur))),null==e.ms||n||r.push(span(t.gray,fmtElapsed(e.ms))),e.calls>1&&r.push(span(t.gray,`${e.calls} calls`)),r}function joinBits(e,t){const n=[];return e.forEach(((e,r)=>{r&&n.push(span(t.dim,` ${GLYPH.bullet} `)),n.push(e)})),n}const DIR_MAX=40;function shortDir(e){let t=String(null==e?"":e).trim().replace(/\/+$/,"");if(!t)return"";const n=String(process.env.HOME||process.env.USERPROFILE||"").replace(/\/+$/,"");return n&&(t===n||t.startsWith(`${n}/`))&&(t=`~${t.slice(n.length)}`),t.length>DIR_MAX&&(t=`${GLYPH.ellipse}${t.slice(-(DIR_MAX-1))}`),t}function rowLines(e,t,n,r=Date.now()){const o=themeOf(n),s=[];if("tool"===e.role){const i=String(e.label||"").replace(/(?:…|\.\.\.)+$/,""),a=e.cwd?` · ${shortDir(e.cwd)}`:"";if("run"===e.phase){const t=e.start?Math.max(1,Math.round((r-e.start)/1e3)):0;s.push([span(o.gray,`${i}${GLYPH.ellipse} · ${t}s${a}`)])}else s.push([span(o.gray,`${i}${a}`)]);if(e.diff){for(const r of renderDiffBlock(e.diff,n,t,{open:!!e.diffOpen}))s.push([span("",r)]);return s}const l="string"==typeof e.args?e.args:e.args&&"object"==typeof e.args?e.args.command??e.args.file_path??e.args.description??Object.values(e.args).find((e=>"string"==typeof e))??"":"";return l&&s.push([span(o.gray,` ${GLYPH.hook} $ ${String(l)}`)]),s}if("note"===e.role)return s.push([span(o.gray,`· ${e.text}`)]),s;if("tip"===e.role){for(const n of wrapBlock(String(e.text),t))s.push([span(o.gray,n)]);return s}if("done"===e.role){const t=[span(o.gray,GLYPH.bloom),span(o.gray,` ${e.text}`)];if(e.meta){const n=metaBits(e.meta,o,{omitMs:!0});n.length&&t.push(span(o.dim," "),...joinBits(n,o))}return s.push(t),s}if("summary"===e.role){const t=e.counts||{};if(!t.tools)return s;const n=[span(o.dim,GLYPH.hook),span(""," ")],r=[span(o.white,String(t.tools)),span(o.gray," "+(1===t.tools?"command":"commands"))];if(t.files&&t.files.length&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.white,String(t.files.length)),span(o.gray," "+(1===t.files.length?"file changed":"files changed")))),t.failed&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.coral,`${t.failed} failed`))),t.names&&t.names.length){const e=t.more?` +${t.more}`:"";r.push(span(o.dim,` ${t.names.join(", ")}${e}`))}return n.push(...r),s.push(n),s}if("meta"===e.role){const t=metaBits(e.meta||{},o);return t.length&&s.push([span(o.dim,`${GLYPH.hook} `),...joinBits(t,o)]),s}if("panel"===e.role){for(const n of e.lines||[])s.push(padLine(n,t));return s.push([span("","")]),s}if("error"===e.role)return s.push([span(o.red,`✗ ${e.text}`)]),s;if("user"===e.role)return wrapBlock(String(e.text),Math.max(8,t-2)).forEach(((e,t)=>{0===t?s.push([span(o.gray,GLYPH.cursor),span(""," "),span(o.white,e)]):s.push([span(""," "),span(o.white,e)])})),s;const i="assistant"===e.role?renderMarkdown(String(null==e.text?"":e.text),t,n):wrapBlock(String(null==e.text?"":e.text),t).map((e=>[span(o.white,e)])),a=i.length?i:[[span("","")]];for(let e=0;e<a.length;e++){const t=a[e].slice();0===e&&t.unshift(span(o.white,GLYPH.block),span(""," ")),s.push(t)}return s}function transcriptLines(e,t,n,r=Date.now(),o=null){const{cols:s,rows:i}=t,a=Math.max(1,i-6),l=[],u=[];for(const t of e){const e=o||null,i="assistant"===t.role&&t.streaming||"tool"===t.role&&"run"===t.phase;if(!e||i)for(const e of rowLines(t,s,n,r))l.push(e),u.push(t);else{const o=e.get(t);if(o&&o.text===t.text&&o.cols===s&&o.diffOpen===t.diffOpen){for(const e of o.segment)l.push(e),u.push(t);continue}const i=rowLines(t,s,n,r);e.set(t,{text:t.text,cols:s,diffOpen:t.diffOpen,segment:i});for(const e of i)l.push(e),u.push(t)}}let c=t.scroll||0,p=null==t.anchorEnd?null:t.anchorEnd;const d=l.length,f=Math.max(0,d-a);let m;c>f&&(c=f),0===c?(p=null,m=d):(null===p&&(p=Math.max(0,d-c)),m=Math.min(p,d)),d<=a&&(c=0,p=null,m=d);const h=Math.max(0,m-a);return{lines:l.slice(h,m),owners:u.slice(h,m),scroll:c,anchorEnd:p}}function inputPreviewText(e){const t=e.indexOf("\n");if(-1===t)return e;const n=e.split("\n").length-1;return`${e.slice(0,t)} … (+${n} line${1===n?"":"s"})`}const inputRowCells=e=>Math.max(1,e-3),bufCells=e=>[...e].reduce(((e,t)=>e+w(t)),0);function cursorCells(e,t){const n=[...e];let r=0;for(let e=0;e<Math.min(t,n.length);e++)r+=w(n[e]);return r}function inputScroll(e,t,n){const r=inputRowCells(n),o=bufCells(e);if(o<=r)return 0;const s=r-1;return Math.max(0,Math.min(cursorCells(e,t)-s,o-s))}function inputStart(e,t){const n=[...e];let r=0;for(let e=0;e<n.length;e++){if(r>=t)return e;r+=w(n[e])}return n.length}function inputLine(e,t,n){const r=themeOf(n),o=[span(r.gray,GLYPH.cursor),span(""," ")];if(e.inputPrompt){o.push(span(r.white,`${e.inputPrompt.title}: `));for(const t of[...e.inputPrompt.buf])o.push(span(r.white,t));const n=Math.min(3+w(e.inputPrompt.title)+2+w(e.inputPrompt.buf),t);return{line:padLine(o,t),cursorCol:n}}if(e.working)return{line:padLine(o,t),cursorCol:3};const s=e.buf||"";if(!s.length){if(e.insertMode)return{line:padLine(o,t),cursorCol:3};const n=SUGGESTIONS[(e.suggestionIdx||0)%SUGGESTIONS.length];return o.push(span(r.white+BOLD,`Try "${n}"`),span(BOLD_OFF,"")),{line:padLine(o,t),cursorCol:3}}if(s.includes("\n")){const e=inputPreviewText(s);for(const t of[...e])o.push(span(r.white,t));return{line:padLine(o,t),cursorCol:Math.min(3+w(e),t)}}const i=inputScroll(s,e.cursor,t),a=inputStart(s,i);i>0&&o.push(span(r.dim,"…"));const l=[...s];for(let e=a;e<l.length;e++)o.push(span(r.white,l[e]));const u=l.slice(a,Math.min(e.cursor,l.length)).join(""),c=Math.min(3+(i>0?1:0)+w(u),t);return{line:padLine(o,t),cursorCol:c}}async function runSession(e){const t=e.ctx,n=new LineEditor,r=e.transcript,o=new WeakMap;let s=null;function i(t){const n=paletteQuery(null==t?s&&s.query||"":t);return fuzzy.fuzzyRankWithAliases(n,e.visibleCommands(),(e=>e.name),(e=>e.aliases||[]))}let a=0,l=!1,u=null,c=0,p=null,d=0,f=VERBS[0],m=0,h=0,g=[],y=0,E=0,S=null;const v=new Map;let T=null,C=null,L=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,A=!0;try{A=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{A=!0}let M=!1,_=0;const N=e=>{if(!A)return;const t=e?TITLE_SPIN[Math.floor(c/2)%TITLE_SPIN.length]:null;writeTitle(titleText({topic:I,frame:t}),process.stdout)},D=t=>{if("function"!=typeof e.nameConversation)return;let n;R=!0;try{n=Promise.resolve(e.nameConversation(t,{signal:u?u.signal:null}))}catch{return}n.then((e=>{const t=String(e||"").trim();t&&(K=t,I=t,N(!!l),B())})).catch((()=>{}))},G=e=>{P=e,k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),B()},B=()=>{if(isKeyStreamSuspended())return;const i=getSize().cols,{lines:a,inputCol:u,rows:p,inputRow:m}=(()=>{const{cols:s,rows:i}=getSize(),a=[];a.push(headerLine(e.version,s,t));const u=Math.max(1,i-6),p=transcriptLines(r,{cols:s,rows:i,scroll:E,anchorEnd:S},t,Date.now(),o);E=p.scroll,S=p.anchorEnd,v.clear();for(let e=0;e<p.lines.length;e++)v.set(1+e,p.owners[e]);for(const e of p.lines)a.push(e);for(;a.length<u+1;)a.push([span("","")]);const m=themeOf(t);if(l)a.push(spinnerLine({verb:f,frame:c,elapsedMs:Date.now()-d,streamed:estimateTokensFromCells(W())+V,streamedFloor:V>0},t));else if(Date.now()<k)a.push([span(m.gray,` ${P}`)]);else if(x){const e=Math.max(1,Math.round((Date.now()-O)/1e3));a.push([span(m.gray,` ${x.label||"running"}… (${e}s · esc to stop)`)])}else a.push(effortLine(t,s));a.push(separatorLine(s,t));const h=inputLine({buf:n.buf,cursor:n.cursor,working:l,insertMode:b,suggestionIdx:y,inputPrompt:$},s,t);return a.push(h.line),a.push(separatorLine(s,t)),a.push(statusLine({working:l,inputPrompt:$,streamJob:x,yolo:e.isYolo&&e.isYolo(),keyNotice:e.keyNotice&&e.keyNotice()},s,t)),{lines:a,inputCol:h.cursorCol,rows:i,inputRow:i-2}})();s&&H(a,p,i),L=a,paint(T?applySelection(a,selectionRange(T.anchor,T.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},q=()=>{if(M)return;M=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout((()=>{M=!1,B()}),e)},H=(n,r,o)=>{if(!s)return;let i=null;if("palette"===s.type?i=overlays.renderPalette(e.visibleCommands(),{query:paletteQuery(s.query),sel:s.sel},o,r):"model"===s.type?i=overlays.renderModelPicker(s.items||[],s.sel||0,o,r,s.current,s.cls||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"effort"===s.type?i=overlays.renderEffortPicker(s.sel||0,o,t.effort):"class"===s.type?i=overlays.renderClassPicker(s.items||[],s.sel||0,o,s.current||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"provider"===s.type?i=overlays.renderProviderPicker(s.items||[],s.sel||0,o,s.current,s.hint):"resume"===s.type?i=overlays.renderResumeList(s.items||[],s.sel||0,o,r,s.query||""):"shortcuts"===s.type?i=shortcutsGrid(o,t):"confirm"===s.type?i=confirmLines(s,o,t):"rounds"===s.type?i=roundsLines(s,o,t):"panel"===s.type&&(i=s.lines||[]),!i)return;if("shortcuts"===s.type){const e=Math.max(2,r-i.length-1);for(let t=0;t<i.length;t++)n[e+t]=padLine(i[t],o);return void hideCursor()}const a=Math.max(2,Math.floor((r-i.length)/2));for(let e=0;e<i.length;e++)n[a+e]=padLine(i[e],o);hideCursor()},j=(e,t)=>(r.push(e),t&&!1===t.follow||(E=0,S=null),e),F=(e,t)=>{const n=t?r.indexOf(t):-1;return n<0?r.push(e):r.splice(n,0,e),e},U=e=>j({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z;let Q=Promise.resolve();const X=e=>{const t=Q.then(e,e);return Q=t.then((()=>{}),(()=>{})),t},J=async t=>{l=!0,c=0,d=Date.now(),z=0,V=0,h=0,g=[],f=VERBS[m%VERBS.length],I=K||adoptTopic(I,t),(e=>{K?isGenericTitle(K)&&D(e):R||D(e)})(t),u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0),j({role:"user",text:t});const n=j({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),q()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,q()},tool:e=>{if(e&&void 0!==e.id){const t=g.findIndex((t=>t&&void 0!==t.id&&t.id===e.id));t>=0?g[t]=e:g.push(e)}else g.push(e);if("run"===e.phase){const t=++h,r=e.agent?`${e.agent} ▸ `:"",o=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"run",name:e.name,args:e.args,agent:e.agent,id:e.id,label:`Running ${t} ${r}${toolLabel(e.name,t)}…`,start:Date.now(),diff:o,diffOpen:defaultOpen(o)},n)}else if(!resolveToolDone(r,e)){const t=++h,r=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"done",name:e.name,args:e.args,agent:e.agent,id:e.id,ok:e.ok,label:`Ran ${t} ${e.agent?`${e.agent} ▸ `:""}${toolLabel(e.name,t)}`,diff:r,diffOpen:defaultOpen(r)},n)}q()},approval:e=>(e=>new Promise((t=>{X((async()=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B();const n=e=>{s=null,B(),t(e)};for(;;){const e=await nextKey();if(e===STREAM_END||!e)return void n("deny");if(e.name===KEY.UP||e.name===KEY.DOWN||e.name===KEY.TAB){const t=e.name===KEY.UP?-1:1;s.sel=(s.sel+t+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(e.name===KEY.ENTER)return void n(APPROVAL_DECISIONS[s.sel]||"deny");if(e.name===KEY.ESC||e.name===KEY.CTRL_C)return void n("deny");if("char"===e.name){const t=String(e.ch).trim(),r=Number(t)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void n(APPROVAL_DECISIONS[r])}}}}))})))(e),rounds:t=>(t=>new Promise((n=>{const r=Boolean(e.isYolo&&e.isYolo()),o=autoContinuePlan({on:r,used:a});if(a=o.used,o.auto)return U(`auto: ${t.spent}-round limit reached — continuing automatically (${o.used}/${o.cap}, then it asks).`),B(),void n(!0);r&&(U(`auto: ${o.cap} automatic continuations used — asking you now (answering restarts the block).`),B()),X((async()=>{s={type:"rounds",spent:Number(t.spent)||0,extensions:Number(t.extensions)||1,max:Number(t.max)||8,size:Number(t.size)||Number(t.spent)||0,sel:1},B();const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();if(t===STREAM_END||!t)return void e(!1);if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB)s.sel=1-s.sel,B();else{if(t.name===KEY.ENTER)return void e(0===s.sel);if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e(!1);if("char"===t.name){const n=String(t.ch).trim();if("1"===n)return void e(!0);if("2"===n)return void e(!1)}}}}))})))(t)};let S=null;try{S=await e.ask(t,{history:historyPairs(r),presenter:i,signal:u.signal})}catch(e){S={error:e&&e.message||String(e)}}finally{n.streaming=!1,!String(n.text||"").trim()&&S&&"string"==typeof S.text&&S.text.trim()&&(n.text=S.text),l=!1,clearInterval(p),p=null,N(!1);const r=Math.max(1,Math.round((Date.now()-d)/1e3)),s=!(!u||!u.signal.aborted);n.text=finalizeTurnText(n.text,{aborted:s,error:S&&S.error,reasoned:o}),j({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{follow:!1}),S&&S.pooled_notice&&j({role:"note",text:S.pooled_notice},{follow:!1}),y=m+1,m++,u=null;try{const e=loadConfig(),t=pingTurn({stream:process.stdout,mode:e.ping,minSeconds:e.pingMinSeconds,elapsedMs:Date.now()-d,isTTY:!!process.stdout.isTTY,aborted:s});t&&j({role:"note",text:t},{follow:!1})}catch{}e.recordTurn(S);let i=null;try{const t=await e.refreshSpend();i=t?t.lastCost:null}catch{}e.persistTurn&&e.persistTurn(t,S,s?"stopped":S&&S.error?"error":"done",i);const a=S&&S.usage,c=e.tokensFor?e.tokensFor(a):null,f=a?usageBuckets(a):null;j({role:"meta",meta:{model:S&&S.model,tokens:c,input:f?f.input:null,output:f?f.output:null,eur:i,ms:S&&S.ms,calls:S&&S.calls||1}},{follow:!1});const w=summarizeTurnTools(g);w.tools>0&&j({role:"summary",counts:w},{follow:0===E}),B()}},Z=e=>{let r=null;if(e.name===KEY.PAGE_UP)r=5;else if(e.name===KEY.PAGE_DOWN)r=-5;else if("wheel"===e.name)r="up"===e.dir?3:-3;else{if("click"===e.name||"drag"===e.name||"release"===e.name)return!(e=>{const t={col:e.col-1,row:e.row-1};if("click"===e.name)return C=t,!1;if("drag"===e.name)return T?T.head=t:T={anchor:C||t,head:t},C=null,!0;const n=C;C=null;const r=T?selectionRange(T.anchor,T.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(T=null,!o)return(e=>{const t=v.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=selectionText(L,r);if(!s)return!0;const i=copyToClipboard(s,{stdout:process.stdout,env:process.env}),a=s.split("\n").length;return P=describeCopy(i,`Marked ${a} line${1===a?"":"s"}`),k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),!0})(e)||(q(),!0);"char"!==e.name||!t.vim||b||n.buf||("j"===e.ch?r=1:"k"===e.ch&&(r=-1))}return null!==r&&(E=Math.max(0,E+r),S=null,q(),!0)},ee=()=>{if(!s||"resume"!==s.type)return;const e=Array.isArray(s.all)?s.all:[];s.items=sessionSearch.rankSessions(s.query||"",e),s.sel=0,B()},te=()=>s?"palette"===s.type?fuzzy.fuzzyRankWithAliases(paletteQuery(s.query),e.visibleCommands(),(e=>e.name),(e=>e.aliases||[])).length:"model"===s.type||"resume"===s.type||"class"===s.type||"provider"===s.type?(s.items||[]).length:"effort"===s.type?overlays.EFFORT_VALUES.length:0:0,ne=async n=>{if(n){{const t=models.modelKeyPlan(n,{hasStored:!!e.hasProviderKey&&!!e.hasProviderKey("anthropic")}),{row:r,message:o}=overrideAnthropicByokWithPro(n,{needsKey:!(!t||!t.needed),proLoggedIn:models.claudeProLoggedIn(),proEnabled:(()=>{try{return!0===loadConfig().proEnabled}catch{return!1}})(),proModels:claudePro.PRO_MODELS});n=r,o&&U(o)}if(n.cls&&"aegis"!==n.cls&&t.modelClass!==n.cls){const e="string"==typeof t.modelClass;if(await ie(`/class ${n.cls}`),e&&t.modelClass!==n.cls)return void U(`${n.id} runs on the ${n.cls} class, and this session is on ${t.modelClass} — run /class ${n.cls}${"pro"===n.cls?" on":""}, then pick it again.`)}t.model=n.id,e.updateConfig({model:n.id,currentModelId:n.id,modelClass:t.modelClass}),U(`model: ${n.id}${"byok"===n.cls?" (byok)":"pro"===n.cls?" (Claude Code Pro)":""}`),await(async t=>{const n=models.modelKeyQueue(t,{accountConfigured:!!e.accountConfigured&&!!e.accountConfigured(),hasStoredFor:t=>!!e.hasProviderKey&&!!e.hasProviderKey(t)});if(!n.length)return;let r=null;try{r=e.makeCommandContext()}catch{r=null}if(r&&"function"==typeof r.readSecret)for(const e of n){const n="account"===e.role?"AEGIS account key":"claude-pro"===e.role?"Claude Code OAuth token (`claude setup-token` mints one)":`${e.provider} key`,o=String(await r.readSecret(`${n} → ${e.env} (kept off screen, Enter to skip): `)||"").trim();if(!o){U(`no key given — ${e.env} is still unset, so ${t.id} will fail until it is.`);continue}const s="account"===e.role?"AEGIS":"claude-pro"===e.role?"Claude Code OAuth":e.provider||"that provider",i=validateApiKey(o,{label:s});if(!i.ok){U(`not saved — ${i.message}. ${e.env} is still unset.`);continue}const a=models.storeModelKey(t,i.key,{env:e.env});a.ok?U(a.changed?a.foreign?`${e.env} saved to ${a.file} (0600) — read only by the Claude Code Pro transport, never exported.`:`${e.env} saved to ${a.file} (0600) — both hosts read that file; nothing to export.`:`${e.env} was already set in ${a.file}.`):U(`could not save the key: ${a.error||"unknown error"}`)}else{const e=n.map((e=>`${e.env}: ${e.why}`)).join(" · ");U(`${t.id} has no key: ${e}. Set the ones above and pick it again.`)}})(n)}},re=async e=>{e&&e.class&&await ie(`/class ${e.class}`)},oe=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},se=async o=>{if(o)if(s)await(async t=>{const n=s.type;if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return s=null,void B();if("shortcuts"===n||"panel"===n)return s=null,void B();if(t.name!==KEY.TAB||"palette"!==n)if(t.name!==KEY.TAB||"model"!==n&&"effort"!==n&&"class"!==n&&"provider"!==n){if(t.name===KEY.ENTER){if("palette"===n){const e=i()[s.sel||0],t=String(s.query||"").trim().split(/\s+/).slice(1).join(" ");return s=null,B(),void(e&&await ie(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("effort"===n)return void oe(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}if("resume"===n){const t=(s.items||[])[s.sel||0];return s=null,B(),void(t&&e.resumeSession&&await e.resumeSession(t))}return s=null,void B()}if(t.name===KEY.SHIFT_UP||t.name===KEY.SHIFT_DOWN){const e=t.name===KEY.SHIFT_UP?-1:1,r=Math.max(0,te()-1);if(s.sel=Math.min(r,Math.max(0,(s.sel||0)+e)),"model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void B()}if(t.name===KEY.SHIFT_ENTER){if("palette"===n){const e=i()[s.sel||0];return s=null,B(),void(e&&await ie(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||te(),n=t.name===KEY.UP?-1:1;return s.sel=Math.min(Math.max(0,e-1),Math.max(0,(s.sel||0)+n)),void B()}if("char"===t.name){if("palette"===n)return s.query=(s.query||"")+t.ch,s.sel=0,void B();if("resume"===n)return s.query=(s.query||"")+t.ch,void ee();if("model"===n){const e=parseInt(t.ch,10),n=s.items||[];return void(Number.isFinite(e)&&e>=1&&e<=n.length&&(s.sel=e-1,B()))}if("effort"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=te();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}if(t.name===KEY.BACKSPACE&&"resume"===n)return s.query=String(s.query||"").slice(0,-1),void ee();t.name===KEY.BACKSPACE&&"palette"===n&&(s.query=String(s.query||"").slice(0,-1),B())}else{const e="model"===n||"class"===n||"provider"===n?(s.items||[]).length:overlays.EFFORT_VALUES.length;e&&(s.sel=((s.sel||0)+1)%e,B())}else{const e=i()[s.sel||0];e&&(s.query=e.name,s.sel=0,B())}})(o);else{if("char"===o.name&&!n.buf){if("/"===o.ch)return s={type:"palette",query:"",sel:0},void B();if("?"===o.ch)return s={type:"shortcuts"},void B()}if(!t.vim||b||n.buf||"char"!==o.name){if(t.vim&&b&&o.name===KEY.ESC)return b=!1,n.cursor>0&&n.cursor--,void B()}else{const e=o.ch;if("i"===e||"a"===e||"o"===e||"s"===e||"S"===e)return"s"===e&&n.substChar(),"S"===e&&n.substLine(),"a"===e&&n.right(),b=!0,void B();if("h"===e)return n.left(),void B();if("l"===e)return n.right(),void B();if("0"===e)return n.home(),void B();if("$"===e)return n.end(),void B();if("x"===e)return n.delete(),void B();if("D"===e)return n.killToEnd(),void B();if("A"===e)return n.end(),b=!0,void B();if(Z(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await ie(e):void B()}if(o.name!==KEY.CTRL_V)if(o.name!==KEY.CTRL_B){if("paste"===o.name)return t.vim&&(b=!0),n.insert(String(o.text)),void B();if("char"===o.name)return t.vim&&!b||n.insert(o.ch),void B();if(o.name===KEY.BACKSPACE)return n.backspace(),void B();if(o.name===KEY.DELETE)return n.delete(),void B();if(o.name===KEY.LEFT||o.name===KEY.CTRL_LEFT)return o.name===KEY.CTRL_LEFT?n.wordBack():n.left(),void B();if(o.name!==KEY.RIGHT||n.buf){if(o.name===KEY.RIGHT||o.name===KEY.CTRL_RIGHT)return n.right(),void B();if(o.name===KEY.HOME||o.name===KEY.CTRL_A)return n.home(),void B();if(o.name===KEY.END||o.name===KEY.CTRL_E)return n.end(),void B();if(o.name===KEY.UP)return n.historyUp(),void B();if(o.name===KEY.DOWN)return n.historyDown(),void B();if(o.name===KEY.TAB)return(()=>{const t=n.buf;if(!t.startsWith("/")||t.includes(" "))return!1;const r=t.slice(1),o=e.visibleCommands().flatMap((e=>[e.name,...e.aliases||[]])).filter((e=>e.startsWith(r))).sort();return!!o.length&&(Y&&Y.q===r||(Y={q:r,i:-1}),Y.i=(Y.i+1)%o.length,n.buf="/"+o[Y.i],n.end(),!0)})()||(P=n.buf?"Tab completes commands":"Use alt+t to toggle thinking",k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600)),void B();if(o.name===KEY.CTRL_U)return n.buf="",n.cursor=0,void B();if(o.name===KEY.CTRL_K)return n.killToEnd(),void B();if(o.name===KEY.CTRL_W)return n.wordBack(),void B();if(o.name===KEY.CTRL_L)return clearScreen(),void B();if(o.name===KEY.CTRL_T)return U(e.tokenSummary?e.tokenSummary():"no token usage yet this session"),void B();if(o.name!==KEY.CTRL_R)if(o.name!==KEY.CTRL_O)if("click"!==o.name&&"drag"!==o.name&&"release"!==o.name)if(o.name!==KEY.PAGE_UP&&o.name!==KEY.PAGE_DOWN&&"wheel"!==o.name)if("alt"!==o.name||"p"!==o.ch){if("alt"===o.name&&"t"===o.ch){const n=!(!0===t.thinking);return t.thinking=n,e.updateConfig({thinking:n}),U("Thinking blocks: "+(n?"expanded":"collapsed")),void B()}if(o.name!==KEY.ESC)return o.name===KEY.CTRL_C?n.buf?(n.buf="",n.cursor=0,void B()):void await ue():void(o.name!==KEY.CTRL_D||n.buf||await ue());n.buf&&(n.buf="",n.cursor=0,B())}else await ie("/model");else Z(o);else Z(o);else await ie("/permissions");else await ie("/resume")}else await ie(e.isYolo&&e.isYolo()?"/automode off":"/automode on")}else(()=>{if(!r.length)return void G("Nothing to copy yet");const e=copyToClipboard(transcriptToMarkdown(r),{stdout:process.stdout,env:process.env});G(describeCopy(e,"Copied the conversation"))})();else(()=>{const e=readClipboardImage({env:process.env});if(e.ok)try{const t=path.join(aegisDir(),"clipboard");fs.mkdirSync(t,{recursive:!0});const r="image/jpeg"===e.mime?"jpg":"png",o=path.join(t,`pasted-${(new Date).toISOString().replace(/[:.]/g,"-")}.${r}`);fs.writeFileSync(o,e.data,{mode:384});const s=n.buf&&!/\s$/.test(n.buf)?" ":"";return n.insert(s+o),void G(`Pasted image → ${o}`)}catch(e){return void G(`Could not save the pasted image: ${e&&e.message||e}`)}const t=readClipboardText({env:process.env});if(t.ok&&t.text)return n.insert(t.text),void G(`Pasted ${t.text.length} character${1===t.text.length?"":"s"} from the clipboard`);G(t.ok?"Clipboard is empty — nothing to paste":`Cannot read the clipboard here (${t.error}) — use your terminal's own paste shortcut instead`)})()}},ie=async t=>{const r=String(t||"").trim();if("?"===r)return s={type:"shortcuts"},void B();(!1===await(async(e,t)=>{try{return await((e,t)=>{const n=[];let r,o,i=!1;return e.then((e=>{i=!0,r=e}),(e=>{i=!0,o=e})),(async()=>{for(;!i;){if(!l||s&&"confirm"===s.type){await new Promise((e=>setTimeout(e,60)));continue}const e=await nextKeyTimeout(120);if(null!==e)if(e.name===KEY.ESC||e.name===KEY.CTRL_C){const e=t&&t();e&&e.abort()}else Z(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),t)}catch(e){return j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),void B()}})((async()=>{if(r.startsWith("/")){const t=(()=>{const t=e.makeCommandContext();return Object.assign(t,{push:(e,t)=>{j(e,t),B()},note:e=>{j({role:"note",text:e}),B()},panel:e=>{j({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{if(e&&"resume"===e.type){const t=Array.isArray(e.items)?e.items:[];return s={...e,all:t,query:"string"==typeof e.query?e.query:"",items:sessionSearch.rankSessions("string"==typeof e.query?e.query:"",t),sel:0},void B()}s=e,B()},closeOverlay:()=>{s=null,showCursor(),B()},askInput:e=>(e=>new Promise((t=>{$={title:e,buf:""},B(),(async()=>{for(;;){const e=await nextKey();if(!$)return void t(null);if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return $=null,B(),void t(null);if(e.name===KEY.ENTER){const e=$.buf;return $=null,B(),void t(e)}e.name===KEY.BACKSPACE?$.buf=[...$.buf].slice(0,-1).join(""):"char"===e.name?$.buf+=e.ch:"paste"===e.name&&($.buf+=String(e.text).replace(/\n/g," ")),B()}})()})))(e),withWorking:e=>(async e=>{const t=u;l=!0,c=0,d=Date.now(),f=VERBS[m%VERBS.length],u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0);try{return await e(u.signal)}finally{l=!1,clearInterval(p),p=null,u=t,N(!1),B()}})(e),runPrompt:async e=>{await J(e)},state:()=>e.buildState(),setInput:e=>{n.buf=String(null==e?"":e),n.end(),B()},exit:()=>e.requestExit(),openStream:e=>{x=e||null,O=Date.now(),B()},closeStream:e=>{e&&x!==e||(x=null),B()},showThemePicker:()=>{e.showThemePicker&&e.showThemePicker(),B()}}),t})();return e.dispatchLine(r,t)}return await J(r),!0}),(()=>u))||e.wantsExit())&&await ue()};let ae=!1,le=null;const ue=()=>{ae||(ae=!0,le&&le(0))},ce=()=>{hideCursor(),paint([]);try{process.stdout.write("[0m")}catch{}try{A&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let pe=!1;const de=()=>{if(!pe){pe=!0;try{ce()}catch{}}};process.once("exit",de);const fe=e.stdin||process.stdin;markSessionStart(),attachKeyStream(fe),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const me=()=>B();"win32"!==process.platform?process.on("SIGWINCH",me):process.stdout.on("resize",me);const he=()=>{l&&u?u.abort():ue()};process.on("SIGINT",he);const ge=e=>{ce();try{process.stderr.write(`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${e&&e.stack||e}\n`)}catch{}process.exit(1)};process.on("uncaughtException",ge),process.on("unhandledRejection",ge),B();try{return await new Promise((e=>{le=e,(async()=>{for(;!ae;){const e=await nextKey();if(ae)break;if(e===STREAM_END||!e){ue();break}try{await se(e)}catch(e){j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()}))}finally{ae=!0,process.off("SIGINT",he),"win32"!==process.platform?process.off("SIGWINCH",me):process.stdout.off("resize",me),process.off("uncaughtException",ge),process.off("unhandledRejection",ge),process.off("exit",de),de(),resetKeyStream()}}module.exports={SUGGESTIONS:SUGGESTIONS,TITLE_SPIN:TITLE_SPIN,FRAME_MS:33,toolLabel:toolLabel,resolveToolDone:resolveToolDone,summarizeTurnTools:summarizeTurnTools,finalizeTurnText:finalizeTurnText,historyPairs:historyPairs,overrideAnthropicByokWithPro:overrideAnthropicByokWithPro,paletteQuery:paletteQuery,headerLine:headerLine,separatorLine:separatorLine,effortLine:effortLine,spinnerLine:spinnerLine,statusLine:statusLine,shortcutsGrid:shortcutsGrid,confirmLines:confirmLines,APPROVAL_CHOICES:APPROVAL_CHOICES,APPROVAL_DECISIONS:APPROVAL_DECISIONS,roundsLines:roundsLines,autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,AUTO_CONTINUE_LIMIT:AUTO_CONTINUE_LIMIT,rowLines:rowLines,transcriptLines:transcriptLines,inputPreviewText:inputPreviewText,inputRowCells:inputRowCells,inputScroll:inputScroll,inputStart:inputStart,inputLine:inputLine,runSession:runSession};
|