hermesdesk-agent 0.1.0-alpha.5 → 0.1.0-alpha.6
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/README.md +8 -4
- package/bin/hermesdesk.js +3 -4
- package/npm-shrinkwrap.json +4 -3
- package/package.json +3 -2
- package/src/agent.js +12 -1
- package/src/commands.js +87 -31
- package/src/config.js +1 -1
- package/src/policy.js +5 -32
- package/src/ui/approval.js +215 -0
- package/src/ui/chrome.js +175 -0
- package/src/ui/extension.js +75 -0
- package/src/ui/format.js +137 -0
- package/src/ui/interactive.js +14 -0
- package/src/ui/layout.js +63 -0
- package/src/ui/menu.js +56 -0
- package/src/ui/pi.js +5 -0
- package/src/ui/themes/hermesdesk-dark.json +81 -0
- package/src/ui/themes/hermesdesk-light.json +81 -0
- package/src/ui/tools.js +159 -0
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://github.com/NKocur/hermesdesk-agent/actions/workflows/ci.yml)
|
|
4
4
|
|
|
5
|
-
**Windows alpha: 0.1.0-alpha.
|
|
5
|
+
**Windows alpha: 0.1.0-alpha.6.** Community client built on Pi; not affiliated with or endorsed by Earendil Works or Nous Research.
|
|
6
6
|
|
|
7
7
|
A running HermesDesk inference gateway is required. This client does not include a hosted model service, server access, or API keys.
|
|
8
8
|
|
|
@@ -18,7 +18,7 @@ hermesdesk.cmd connect
|
|
|
18
18
|
hermesdesk.cmd doctor
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
Alternatively, download and extract a Windows alpha bundle from [Releases](https://github.com/NKocur/hermesdesk-agent/releases) and run `Install Agent.cmd`. A tarball can also be installed directly with `npm.cmd install -g --ignore-scripts ./hermesdesk-agent-0.1.0-alpha.
|
|
21
|
+
Alternatively, download and extract a Windows alpha bundle from [Releases](https://github.com/NKocur/hermesdesk-agent/releases) and run `Install Agent.cmd`. A tarball can also be installed directly with `npm.cmd install -g --ignore-scripts ./hermesdesk-agent-0.1.0-alpha.6.tgz`.
|
|
22
22
|
|
|
23
23
|
There is no default server address. `connect` asks for your HTTPS model endpoint ending in `/v1`. When the server supports browser sign-in, it opens your browser: sign in to HermesDesk and approve the computer. The CLI receives a short-lived, single-use authorization code on a loopback listener and redeems it with PKCE over HTTPS, then discovers the model and saves the credentials encrypted. You do not copy passwords, API keys, or connection codes. The browser and CLI must be on the same computer. Use `--no-browser` to open the printed browser link yourself. On legacy servers without browser sign-in, the API-key setup remains available; `--manual` explicitly selects it. No server credentials are included in this package.
|
|
24
24
|
|
|
@@ -39,7 +39,11 @@ hermesdesk.cmd chat --session SESSION_ID
|
|
|
39
39
|
hermesdesk.cmd chat --read-only
|
|
40
40
|
```
|
|
41
41
|
|
|
42
|
-
The interactive terminal uses Pi's UI, streaming, diffs, tool displays, session history and compaction
|
|
42
|
+
The interactive terminal uses Pi's UI, streaming, diffs, tool displays, session history and compaction, with a HermesDesk presentation layer (`src/ui/`). A compact header shows the safety mode and key commands; a two-line footer shows the workspace and git branch, model, thinking effort, output limit, approval mode, token totals and context fill. Tool calls appear as one line with a status mark (`●` running, `✓` done, `✗` failed or declined) and their output sits behind a quiet gutter; `ctrl+o` expands long output. Edits, writes and commands open an approval panel with a diff, file preview or highlighted command: `y` allows once, `n` or Escape denies.
|
|
43
|
+
|
|
44
|
+
Colors follow the terminal background automatically, using the HermesDesk light or dark palette. Body text keeps the terminal's own foreground color, and fonts and sizes always come from the terminal. Set `HERMESDESK_THEME` to `light` or `dark` to force a palette (for terminals that do not report their background), or `terminal` to use Pi's palette derived from your terminal colors.
|
|
45
|
+
|
|
46
|
+
Escape interrupts work. `/quit` exits; `/new` starts a new conversation and `/resume` opens Pi's session selector. The first interactive startup may download Pi's `fd` helper to this client's own Pi cache. Windows Terminal is recommended. Pi's inherited help and exit hints may still mention `pi`; resume this client with `hermesdesk chat --continue` or `--session ID`.
|
|
43
47
|
|
|
44
48
|
File tools are restricted to the chosen project and reject outside links and protected paths such as `.env`, `.git`, credential files and agent configurations. Each edit and shell command asks for approval. Shell commands execute as your user and are **not OS-sandboxed**; after approval they can access anything your account can access. Direct `!` shell shortcuts are disabled so commands use the managed approval path. Project JavaScript extensions, MCP servers and packages are not automatically loaded.
|
|
45
49
|
|
|
@@ -70,7 +74,7 @@ Use these inside interactive chat. Commands run locally, consume no model tokens
|
|
|
70
74
|
/limits save
|
|
71
75
|
```
|
|
72
76
|
|
|
73
|
-
`/limits` opens a
|
|
77
|
+
`/limits` opens a settings menu for the same controls, showing each current value; `/profile` and `/think` without a value open menus that mark the active choice. Profiles are `fast` (32K, thinking off), `balanced` (64K, xhigh), and `extended` (131K, xhigh). Output counts include thinking and answer. The model can stop before the allowance is used, and Strata can reduce the thinking cap to preserve answer room. Individual controls keep your other sampler settings; profiles apply the recommended sampler values.
|
|
74
78
|
|
|
75
79
|
Changes last for the current CLI session. `/limits save` keeps generation defaults for future launches; `/limits reset` restores saved defaults. Escape cancels a menu without applying changes. Changes are blocked while the agent is working. Pi's existing `/thinking off|low|medium|high` and keyboard thinking controls now also reach Strata (`high` maps to `xhigh`). Credentials, file permissions and command approvals are unaffected.
|
|
76
80
|
|
package/bin/hermesdesk.js
CHANGED
|
@@ -303,11 +303,10 @@ async function main() {
|
|
|
303
303
|
if (command === "run") {
|
|
304
304
|
await runPrompt(runtime, p.join(" "), { json: !!v.json });
|
|
305
305
|
} else {
|
|
306
|
-
const {
|
|
307
|
-
"
|
|
306
|
+
const { createInteractiveMode } = await import(
|
|
307
|
+
"../src/ui/interactive.js"
|
|
308
308
|
);
|
|
309
|
-
const ui =
|
|
310
|
-
verbose: false,
|
|
309
|
+
const ui = await createInteractiveMode(runtime, {
|
|
311
310
|
initialMessage: p.length ? p.join(" ") : undefined,
|
|
312
311
|
});
|
|
313
312
|
await ui.run();
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hermesdesk-agent",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.6",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "hermesdesk-agent",
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.6",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@earendil-works/pi-coding-agent": "1.5.0"
|
|
12
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
13
|
+
"@earendil-works/pi-tui": "1.5.0"
|
|
13
14
|
},
|
|
14
15
|
"bin": {
|
|
15
16
|
"hermesdesk": "bin/hermesdesk.js",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hermesdesk-agent",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.6",
|
|
4
4
|
"description": "Pi-based terminal coding client for HermesDesk and Strata",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"LICENSE"
|
|
26
26
|
],
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@earendil-works/pi-coding-agent": "1.5.0"
|
|
28
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
29
|
+
"@earendil-works/pi-tui": "1.5.0"
|
|
29
30
|
},
|
|
30
31
|
"devDependencies": {
|
|
31
32
|
"prettier": "3.6.2"
|
package/src/agent.js
CHANGED
|
@@ -2,10 +2,11 @@ import fs from "node:fs";
|
|
|
2
2
|
import { generationPayload } from "./generation.js";
|
|
3
3
|
import { generationCommands } from "./commands.js";
|
|
4
4
|
import path from "node:path";
|
|
5
|
-
import { projectSessionDir, validateConfig } from "./config.js";
|
|
5
|
+
import { VERSION, projectSessionDir, validateConfig } from "./config.js";
|
|
6
6
|
import { searchTool } from "./search.js";
|
|
7
7
|
import { modelFetch } from "./transport.js";
|
|
8
8
|
import { policyExtension, workspacePath } from "./policy.js";
|
|
9
|
+
import { THEME_DIR, interfaceExtension, themeSetting } from "./ui/extension.js";
|
|
9
10
|
export async function createRuntime({
|
|
10
11
|
config,
|
|
11
12
|
home,
|
|
@@ -117,6 +118,9 @@ export async function createRuntime({
|
|
|
117
118
|
enableInstallTelemetry: false,
|
|
118
119
|
packages: [],
|
|
119
120
|
cacheWarming: "off",
|
|
121
|
+
// HermesDesk draws its own header; skip Pi's resource listing at startup.
|
|
122
|
+
quietStartup: "header",
|
|
123
|
+
theme: themeSetting(),
|
|
120
124
|
retry: { enabled: false },
|
|
121
125
|
providerRetry: { maxRetries: 0, timeoutMs: 1800000 },
|
|
122
126
|
compaction: {
|
|
@@ -146,6 +150,7 @@ export async function createRuntime({
|
|
|
146
150
|
noSkills: true,
|
|
147
151
|
noPromptTemplates: true,
|
|
148
152
|
noThemes: true,
|
|
153
|
+
additionalThemePaths: [THEME_DIR],
|
|
149
154
|
noContextFiles: true,
|
|
150
155
|
appendSystemPrompt: [
|
|
151
156
|
"You are HermesDesk Agent, a coding assistant powered by a locally hosted model. Inspect before editing, preserve unrelated work, verify changes with appropriate checks, and report results honestly. File tools are restricted to the selected workspace; never bypass a declined action. Shell commands require approval and are not OS-sandboxed.",
|
|
@@ -200,6 +205,12 @@ export async function createRuntime({
|
|
|
200
205
|
requestCount = 0;
|
|
201
206
|
},
|
|
202
207
|
}),
|
|
208
|
+
interfaceExtension({
|
|
209
|
+
version: VERSION,
|
|
210
|
+
readOnly,
|
|
211
|
+
approveWrites,
|
|
212
|
+
read: syncThinking,
|
|
213
|
+
}),
|
|
203
214
|
],
|
|
204
215
|
},
|
|
205
216
|
});
|
package/src/commands.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { loadConfig, saveConfig, validateConfig } from "./config.js";
|
|
2
|
-
import { profile } from "./generation.js";
|
|
2
|
+
import { PROFILES, profile } from "./generation.js";
|
|
3
|
+
import { limitText } from "./ui/format.js";
|
|
4
|
+
import { chooseItem } from "./ui/menu.js";
|
|
3
5
|
|
|
4
6
|
const GENERATION_KEYS = [
|
|
5
7
|
"maxTokens",
|
|
@@ -25,18 +27,38 @@ export function tokenValue(value, automatic = false) {
|
|
|
25
27
|
}
|
|
26
28
|
export function generationSummary(config) {
|
|
27
29
|
return [
|
|
28
|
-
|
|
29
|
-
`
|
|
30
|
-
`Thinking
|
|
31
|
-
`Sampling
|
|
32
|
-
"
|
|
30
|
+
"Generation settings",
|
|
31
|
+
`Output ${number(config.maxTokens)} tokens, thinking + answer`,
|
|
32
|
+
`Thinking ${config.thinking ? config.reasoningEffort : "off"} · budget ${config.thinkingBudget ? number(config.thinkingBudget) : "automatic"}${config.thinking ? "" : " (unused while off)"}`,
|
|
33
|
+
`Sampling temperature ${config.temperature} · top-p ${config.topP} · top-k ${config.topK}`,
|
|
34
|
+
"Applies to this session now. /limits save keeps it for future launches.",
|
|
33
35
|
].join("\n");
|
|
34
36
|
}
|
|
37
|
+
const PROFILE_NOTES = {
|
|
38
|
+
fast: "quick answers",
|
|
39
|
+
balanced: "everyday work",
|
|
40
|
+
extended: "long tasks",
|
|
41
|
+
};
|
|
42
|
+
const THINK_NOTES = {
|
|
43
|
+
off: "answer directly",
|
|
44
|
+
low: "brief reasoning",
|
|
45
|
+
medium: "moderate reasoning",
|
|
46
|
+
xhigh: "deepest reasoning",
|
|
47
|
+
};
|
|
48
|
+
/** The profile whose settings exactly match the configuration, if any. */
|
|
49
|
+
export function currentProfile(config) {
|
|
50
|
+
return Object.keys(PROFILES).find((name) =>
|
|
51
|
+
Object.entries(PROFILES[name]).every(
|
|
52
|
+
([key, value]) => config[key] === value,
|
|
53
|
+
),
|
|
54
|
+
);
|
|
55
|
+
}
|
|
35
56
|
export function generationCommands({ home, read, apply }) {
|
|
36
57
|
return (pi) => {
|
|
58
|
+
// Interactive chat shows these settings in the HermesDesk footer; other UI hosts get a status.
|
|
37
59
|
const status = (ctx) => {
|
|
38
60
|
const c = read();
|
|
39
|
-
if (ctx.hasUI)
|
|
61
|
+
if (ctx.hasUI && ctx.mode !== "tui")
|
|
40
62
|
ctx.ui.setStatus(
|
|
41
63
|
"hermesdesk-generation",
|
|
42
64
|
`${number(c.maxTokens)} tokens | thinking ${c.thinking ? c.reasoningEffort : "off"} | /limits`,
|
|
@@ -72,22 +94,28 @@ export function generationCommands({ home, read, apply }) {
|
|
|
72
94
|
},
|
|
73
95
|
});
|
|
74
96
|
};
|
|
75
|
-
const choose = async (ctx, title,
|
|
97
|
+
const choose = async (ctx, title, items, subtitle) => {
|
|
76
98
|
if (!ctx.hasUI)
|
|
77
99
|
throw Error(
|
|
78
100
|
"Provide a value, or open interactive chat to use the settings menu.",
|
|
79
101
|
);
|
|
80
|
-
return ctx
|
|
102
|
+
return chooseItem(ctx, { title, subtitle, items });
|
|
81
103
|
};
|
|
82
104
|
const selectProfile = async (args, ctx) => {
|
|
83
105
|
idle(ctx);
|
|
84
106
|
const value =
|
|
85
107
|
args ||
|
|
86
|
-
(await choose(
|
|
87
|
-
|
|
88
|
-
"
|
|
89
|
-
|
|
90
|
-
|
|
108
|
+
(await choose(
|
|
109
|
+
ctx,
|
|
110
|
+
"Generation profile",
|
|
111
|
+
Object.entries(PROFILES).map(([name, p]) => ({
|
|
112
|
+
value: name,
|
|
113
|
+
label: name,
|
|
114
|
+
description: `${limitText(p.maxTokens)} output · thinking ${p.thinking ? p.reasoningEffort : "off"} · ${PROFILE_NOTES[name]}`,
|
|
115
|
+
current: currentProfile(read()) === name,
|
|
116
|
+
})),
|
|
117
|
+
"Sets output size, thinking and sampling together.",
|
|
118
|
+
));
|
|
91
119
|
if (value === undefined) return;
|
|
92
120
|
await update(profile(value.toLowerCase()), ctx);
|
|
93
121
|
};
|
|
@@ -111,12 +139,18 @@ export function generationCommands({ home, read, apply }) {
|
|
|
111
139
|
idle(ctx);
|
|
112
140
|
const value =
|
|
113
141
|
args ||
|
|
114
|
-
(await choose(
|
|
115
|
-
|
|
116
|
-
"
|
|
117
|
-
"medium",
|
|
118
|
-
|
|
119
|
-
|
|
142
|
+
(await choose(
|
|
143
|
+
ctx,
|
|
144
|
+
"Thinking effort",
|
|
145
|
+
["off", "low", "medium", "xhigh"].map((value) => ({
|
|
146
|
+
value,
|
|
147
|
+
label: value,
|
|
148
|
+
description: THINK_NOTES[value],
|
|
149
|
+
current:
|
|
150
|
+
value === (read().thinking ? read().reasoningEffort : "off"),
|
|
151
|
+
})),
|
|
152
|
+
"Thinking shares the total output limit with the answer.",
|
|
153
|
+
));
|
|
120
154
|
if (value === undefined) return;
|
|
121
155
|
const setting = value.toLowerCase();
|
|
122
156
|
if (!["on", "off", "low", "medium", "high", "xhigh"].includes(setting))
|
|
@@ -198,19 +232,41 @@ export function generationCommands({ home, read, apply }) {
|
|
|
198
232
|
if (args) throw Error("Usage: /limits [show|save|reset]");
|
|
199
233
|
idle(ctx);
|
|
200
234
|
const c = read();
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
"
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
235
|
+
const budget = c.thinkingBudget
|
|
236
|
+
? number(c.thinkingBudget)
|
|
237
|
+
: "automatic";
|
|
238
|
+
// Values stay as the plain labels used by non-interactive hosts; the menu shows label + detail.
|
|
239
|
+
const items = [
|
|
240
|
+
["Choose profile", "Profile", currentProfile(c) ?? "custom"],
|
|
241
|
+
[
|
|
242
|
+
`Total output: ${number(c.maxTokens)}`,
|
|
243
|
+
"Total output",
|
|
244
|
+
`${number(c.maxTokens)} tokens · thinking + answer`,
|
|
245
|
+
],
|
|
246
|
+
[
|
|
247
|
+
`Thinking: ${c.thinking ? c.reasoningEffort : "off"}`,
|
|
248
|
+
"Thinking",
|
|
249
|
+
c.thinking ? c.reasoningEffort : "off",
|
|
250
|
+
],
|
|
251
|
+
[
|
|
252
|
+
`Thinking budget: ${budget}`,
|
|
253
|
+
"Thinking budget",
|
|
254
|
+
budget + (c.thinking ? "" : " · unused while off"),
|
|
255
|
+
],
|
|
256
|
+
["Show current settings", "Show summary", "print every setting"],
|
|
257
|
+
["Save as defaults", "Save as defaults", "keep for future launches"],
|
|
258
|
+
[
|
|
259
|
+
"Restore saved defaults",
|
|
260
|
+
"Restore defaults",
|
|
261
|
+
"undo session changes",
|
|
262
|
+
],
|
|
263
|
+
].map(([value, label, description]) => ({ value, label, description }));
|
|
264
|
+
const actions = items.map((item) => item.value);
|
|
210
265
|
const selected = await choose(
|
|
211
266
|
ctx,
|
|
212
|
-
"
|
|
213
|
-
|
|
267
|
+
"Generation settings",
|
|
268
|
+
items,
|
|
269
|
+
"Changes apply now; save to keep them for future launches.",
|
|
214
270
|
);
|
|
215
271
|
if (selected === undefined) return;
|
|
216
272
|
switch (actions.indexOf(selected)) {
|
package/src/config.js
CHANGED
package/src/policy.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
-
import { VERSION } from "./config.js";
|
|
3
2
|
import path from "node:path";
|
|
3
|
+
import { requestApproval } from "./ui/approval.js";
|
|
4
4
|
const protectedPart = (p) =>
|
|
5
5
|
/^\.env(?:\.|$)/i.test(p) ||
|
|
6
6
|
[".git", ".ssh", ".aws", ".codex", ".claude", ".pi", "node_modules"].includes(
|
|
@@ -94,7 +94,9 @@ export function policyExtension({
|
|
|
94
94
|
mutation = shell || ["edit", "write"].includes(name);
|
|
95
95
|
if (readOnly && mutation)
|
|
96
96
|
return { block: true, reason: "Read-only mode is enabled." };
|
|
97
|
-
|
|
97
|
+
const target = shell
|
|
98
|
+
? undefined
|
|
99
|
+
: workspacePath(root, input.path || ".");
|
|
98
100
|
if (mutation) {
|
|
99
101
|
if (!shell && approveWrites) return;
|
|
100
102
|
if (!ctx.hasUI)
|
|
@@ -104,18 +106,7 @@ export function policyExtension({
|
|
|
104
106
|
? "Shell commands require interactive approval."
|
|
105
107
|
: "File changes require interactive approval, or explicit --approve-writes.",
|
|
106
108
|
};
|
|
107
|
-
const
|
|
108
|
-
? "This command runs with your Windows account permissions, without an OS sandbox.\n\n" +
|
|
109
|
-
String(input.command || "")
|
|
110
|
-
: String(input.path) +
|
|
111
|
-
"\n\n" +
|
|
112
|
-
(name === "write"
|
|
113
|
-
? String(input.content || "")
|
|
114
|
-
: JSON.stringify(input.edits || input));
|
|
115
|
-
const yes = await ctx.ui.confirm(
|
|
116
|
-
shell ? "Approve shell command?" : "Approve " + name + "?",
|
|
117
|
-
detail,
|
|
118
|
-
);
|
|
109
|
+
const yes = await requestApproval(ctx, name, input, target);
|
|
119
110
|
if (!yes)
|
|
120
111
|
return { block: true, reason: "The user declined this action." };
|
|
121
112
|
}
|
|
@@ -134,23 +125,5 @@ export function policyExtension({
|
|
|
134
125
|
},
|
|
135
126
|
};
|
|
136
127
|
});
|
|
137
|
-
pi.on("session_start", (_e, ctx) => {
|
|
138
|
-
if (ctx.hasUI) {
|
|
139
|
-
ctx.ui.setStatus(
|
|
140
|
-
"hermesdesk",
|
|
141
|
-
readOnly
|
|
142
|
-
? "HermesDesk | read only"
|
|
143
|
-
: "HermesDesk | ask before edits and commands",
|
|
144
|
-
);
|
|
145
|
-
ctx.ui.setHeader(() => ({
|
|
146
|
-
render: () => [
|
|
147
|
-
`HermesDesk Agent ${VERSION} | powered by Pi`,
|
|
148
|
-
"Strata models run remotely. File tools act in this workspace.",
|
|
149
|
-
"Use /limits for output and thinking settings; /profile extended selects 131K.",
|
|
150
|
-
],
|
|
151
|
-
invalidate() {},
|
|
152
|
-
}));
|
|
153
|
-
}
|
|
154
|
-
});
|
|
155
128
|
};
|
|
156
129
|
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// Approval dialog for edits, writes and shell commands.
|
|
2
|
+
// The decision is the only output: true allows this one action; anything else declines it.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import { matchesKey } from "@earendil-works/pi-tui";
|
|
5
|
+
import { approvalText, editList, editStats } from "./format.js";
|
|
6
|
+
import {
|
|
7
|
+
rule,
|
|
8
|
+
spread,
|
|
9
|
+
truncateToWidth,
|
|
10
|
+
visibleWidth,
|
|
11
|
+
wrapTextWithAnsi,
|
|
12
|
+
} from "./layout.js";
|
|
13
|
+
import { loadPi } from "./pi.js";
|
|
14
|
+
|
|
15
|
+
const SHELLS = new Set(["powershell", "bash"]);
|
|
16
|
+
const BOM = String.fromCharCode(0xfeff);
|
|
17
|
+
|
|
18
|
+
function diffLines(theme, input) {
|
|
19
|
+
return approvalText("edit", input)
|
|
20
|
+
.split("\n")
|
|
21
|
+
.slice(2)
|
|
22
|
+
.map((line) =>
|
|
23
|
+
line.startsWith("+ ")
|
|
24
|
+
? theme.fg("toolDiffAdded", line)
|
|
25
|
+
: line.startsWith("- ")
|
|
26
|
+
? theme.fg("toolDiffRemoved", line)
|
|
27
|
+
: theme.fg("dim", line),
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Describe one request for the dialog. Reads only the target path the policy already validated. */
|
|
32
|
+
export function describeRequest(pi, name, input = {}, target) {
|
|
33
|
+
if (SHELLS.has(name))
|
|
34
|
+
return {
|
|
35
|
+
tone: "warning",
|
|
36
|
+
title: "Run command",
|
|
37
|
+
subject: name === "powershell" ? "PowerShell" : "bash",
|
|
38
|
+
note: "Runs with your account permissions, without an OS sandbox.",
|
|
39
|
+
body: () => pi.highlightCode(String(input.command ?? ""), name),
|
|
40
|
+
};
|
|
41
|
+
const exists = !!target && fs.existsSync(target);
|
|
42
|
+
if (name === "write") {
|
|
43
|
+
const content = String(input.content ?? "").replace(/\r?\n$/, "");
|
|
44
|
+
const count = content.split("\n").length;
|
|
45
|
+
return {
|
|
46
|
+
tone: exists ? "warning" : "accent",
|
|
47
|
+
title: exists ? "Overwrite file" : "Create file",
|
|
48
|
+
subject: String(input.path),
|
|
49
|
+
stats: `${count} line${count === 1 ? "" : "s"}`,
|
|
50
|
+
note: exists ? "Replaces the existing contents." : undefined,
|
|
51
|
+
body: (theme) =>
|
|
52
|
+
pi
|
|
53
|
+
.highlightCode(content, pi.getLanguageFromPath(String(input.path)))
|
|
54
|
+
.map(
|
|
55
|
+
(line, i) =>
|
|
56
|
+
theme.fg("dim", String(i + 1).padStart(String(count).length)) +
|
|
57
|
+
" " +
|
|
58
|
+
line,
|
|
59
|
+
),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const edits = editList(input);
|
|
63
|
+
return {
|
|
64
|
+
tone: "accent",
|
|
65
|
+
title: "Edit file",
|
|
66
|
+
subject: String(input.path),
|
|
67
|
+
stats: editStats(edits),
|
|
68
|
+
body: (theme) => {
|
|
69
|
+
try {
|
|
70
|
+
const before = fs.readFileSync(target, "utf8").replace(BOM, "");
|
|
71
|
+
let after = before;
|
|
72
|
+
for (const edit of edits) {
|
|
73
|
+
const at = edit.oldText ? after.indexOf(edit.oldText) : -1;
|
|
74
|
+
if (at < 0) throw Error("no exact match");
|
|
75
|
+
after =
|
|
76
|
+
after.slice(0, at) +
|
|
77
|
+
edit.newText +
|
|
78
|
+
after.slice(at + edit.oldText.length);
|
|
79
|
+
}
|
|
80
|
+
return pi
|
|
81
|
+
.renderDiff(pi.generateDiffString(before, after, 2).diff)
|
|
82
|
+
.split("\n");
|
|
83
|
+
} catch {
|
|
84
|
+
// Show the requested replacements when an exact file preview is not possible.
|
|
85
|
+
return diffLines(theme, input);
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const CHOICES = [
|
|
92
|
+
{ value: true, label: "Allow once", key: "y" },
|
|
93
|
+
{ value: false, label: "Deny", key: "n · esc" },
|
|
94
|
+
];
|
|
95
|
+
|
|
96
|
+
export class ApprovalDialog {
|
|
97
|
+
constructor(tui, theme, keybindings, request, done) {
|
|
98
|
+
Object.assign(this, { tui, theme, keybindings, request, done });
|
|
99
|
+
this.index = 0;
|
|
100
|
+
this.scroll = 0;
|
|
101
|
+
}
|
|
102
|
+
body() {
|
|
103
|
+
this.bodyLines ??= this.request.body(this.theme);
|
|
104
|
+
return this.bodyLines;
|
|
105
|
+
}
|
|
106
|
+
/** The preview takes at most about half the screen so the transcript stays visible. */
|
|
107
|
+
previewHeight() {
|
|
108
|
+
const rows = this.tui?.terminal?.rows ?? 24;
|
|
109
|
+
return Math.max(3, Math.min(18, Math.floor(rows / 2) - 6));
|
|
110
|
+
}
|
|
111
|
+
render(width) {
|
|
112
|
+
const t = this.theme,
|
|
113
|
+
r = this.request;
|
|
114
|
+
const risky = r.tone === "warning";
|
|
115
|
+
const stats =
|
|
116
|
+
typeof r.stats === "object"
|
|
117
|
+
? t.fg("success", `+${r.stats.added}`) +
|
|
118
|
+
" " +
|
|
119
|
+
t.fg("error", `−${r.stats.removed}`)
|
|
120
|
+
: r.stats
|
|
121
|
+
? t.fg("dim", r.stats)
|
|
122
|
+
: "";
|
|
123
|
+
const lines = [
|
|
124
|
+
rule(
|
|
125
|
+
t,
|
|
126
|
+
width,
|
|
127
|
+
t.fg(r.tone, t.bold(r.title)),
|
|
128
|
+
risky ? "warning" : "borderAccent",
|
|
129
|
+
),
|
|
130
|
+
spread(" " + t.bold(r.subject), stats + " ", width),
|
|
131
|
+
];
|
|
132
|
+
if (r.note) lines.push(" " + t.fg(risky ? "warning" : "muted", r.note));
|
|
133
|
+
|
|
134
|
+
const wrapped = [];
|
|
135
|
+
for (const line of this.body())
|
|
136
|
+
wrapped.push(...wrapTextWithAnsi(line, Math.max(4, width - 4)));
|
|
137
|
+
const height = this.previewHeight();
|
|
138
|
+
this.maxScroll = Math.max(0, wrapped.length - height);
|
|
139
|
+
this.scroll = Math.min(this.scroll, this.maxScroll);
|
|
140
|
+
const view = wrapped.slice(this.scroll, this.scroll + height);
|
|
141
|
+
lines.push("");
|
|
142
|
+
for (const line of view) lines.push(" " + t.fg("borderMuted", "│ ") + line);
|
|
143
|
+
if (this.maxScroll)
|
|
144
|
+
lines.push(
|
|
145
|
+
" " +
|
|
146
|
+
t.fg(
|
|
147
|
+
"dim",
|
|
148
|
+
`lines ${this.scroll + 1}–${this.scroll + view.length} of ${wrapped.length} · pgup/pgdn to scroll`,
|
|
149
|
+
),
|
|
150
|
+
);
|
|
151
|
+
lines.push("");
|
|
152
|
+
CHOICES.forEach((choice, i) => {
|
|
153
|
+
const active = i === this.index;
|
|
154
|
+
lines.push(
|
|
155
|
+
(active ? " " + t.fg("accent", "›") + " " : " ") +
|
|
156
|
+
(active
|
|
157
|
+
? t.fg(choice.value ? "success" : "error", t.bold(choice.label))
|
|
158
|
+
: t.fg("muted", choice.label)) +
|
|
159
|
+
" ".repeat(Math.max(2, 13 - visibleWidth(choice.label))) +
|
|
160
|
+
t.fg("dim", choice.key),
|
|
161
|
+
);
|
|
162
|
+
});
|
|
163
|
+
lines.push(" " + t.fg("dim", "↑↓ choose · enter confirm"));
|
|
164
|
+
return lines.map((line) => truncateToWidth(line, width, "…"));
|
|
165
|
+
}
|
|
166
|
+
handleInput(data) {
|
|
167
|
+
const is = (id, key) =>
|
|
168
|
+
this.keybindings?.matches
|
|
169
|
+
? this.keybindings.matches(data, id)
|
|
170
|
+
: matchesKey(data, key);
|
|
171
|
+
if (data === "y" || data === "Y") return this.done(true);
|
|
172
|
+
if (data === "n" || data === "N" || is("tui.select.cancel", "escape"))
|
|
173
|
+
return this.done(false);
|
|
174
|
+
if (is("tui.select.confirm", "enter"))
|
|
175
|
+
return this.done(CHOICES[this.index].value);
|
|
176
|
+
if (is("tui.select.up", "up") || is("tui.select.down", "down"))
|
|
177
|
+
this.index = 1 - this.index;
|
|
178
|
+
else if (is("tui.select.pageDown", "pageDown"))
|
|
179
|
+
this.scroll = Math.min(
|
|
180
|
+
this.maxScroll ?? 0,
|
|
181
|
+
this.scroll + this.previewHeight(),
|
|
182
|
+
);
|
|
183
|
+
else if (is("tui.select.pageUp", "pageUp"))
|
|
184
|
+
this.scroll = Math.max(0, this.scroll - this.previewHeight());
|
|
185
|
+
else return;
|
|
186
|
+
this.tui?.requestRender?.();
|
|
187
|
+
}
|
|
188
|
+
invalidate() {
|
|
189
|
+
this.bodyLines = undefined;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Ask for approval: interactive chat gets the dialog above; other UI hosts get a plain confirm. */
|
|
194
|
+
export async function requestApproval(ctx, name, input, target) {
|
|
195
|
+
if (ctx.mode === "tui" && typeof ctx.ui.custom === "function") {
|
|
196
|
+
const request = describeRequest(await loadPi(), name, input, target);
|
|
197
|
+
const answer = await ctx.ui.custom(
|
|
198
|
+
(tui, theme, keybindings, done) =>
|
|
199
|
+
new ApprovalDialog(tui, theme, keybindings, request, done),
|
|
200
|
+
{
|
|
201
|
+
blocked: {
|
|
202
|
+
kind: "permission",
|
|
203
|
+
message: `${request.title}: ${request.subject}`,
|
|
204
|
+
},
|
|
205
|
+
},
|
|
206
|
+
);
|
|
207
|
+
return answer === true;
|
|
208
|
+
}
|
|
209
|
+
return (
|
|
210
|
+
(await ctx.ui.confirm(
|
|
211
|
+
SHELLS.has(name) ? "Approve shell command?" : `Approve ${name}?`,
|
|
212
|
+
approvalText(name, input),
|
|
213
|
+
)) === true
|
|
214
|
+
);
|
|
215
|
+
}
|