korveniq 1.0.6 → 1.0.8
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 +45 -6
- package/bin/index.js +3 -0
- package/endpoints.json +2 -1
- package/lib/api.js +8 -0
- package/lib/approval-report.js +204 -0
- package/lib/approval-transport.js +115 -0
- package/lib/build-profile.json +2 -2
- package/lib/chat.js +49 -15
- package/lib/endpoints.js +2 -1
- package/lib/exec-policy.js +8 -2
- package/lib/headless.js +1 -1
- package/lib/mac-notify.js +121 -0
- package/lib/net-forward.js +27 -0
- package/lib/net-proxy.js +165 -0
- package/lib/notifier.js +18 -16
- package/lib/paste.js +330 -0
- package/lib/pkg-install.js +275 -0
- package/lib/realtime.js +48 -0
- package/lib/sandbox-net.js +243 -0
- package/lib/sandbox.js +50 -17
- package/lib/select-menu.js +27 -8
- package/lib/suggestions.js +8 -2
- package/lib/tool-parser.js +23 -49
- package/lib/tools.js +275 -46
- package/lib/update-restart.js +53 -0
- package/lib/update-source.js +14 -2
- package/lib/update-view.js +59 -1
- package/lib/update.js +123 -5
- package/lib/utils.js +59 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -81,9 +81,10 @@ korveniq --version
|
|
|
81
81
|
If `korveniq --version` still shows the old number, you have more than one installation: `which -a korveniq` lists
|
|
82
82
|
them, and `npm install -g korveniq@latest --prefix <folder>` updates the one in `<folder>/bin`.
|
|
83
83
|
|
|
84
|
-
From 1.0.4 on, a global npm installation on macOS or Linux that your user owns updates itself
|
|
85
|
-
stable release is downloaded and
|
|
86
|
-
|
|
84
|
+
From 1.0.4 on, a global npm installation on macOS or Linux that your user owns updates itself. When you start
|
|
85
|
+
`korveniq`, a newer stable release is downloaded, verified and installed, and Korveniq restarts in it. A release that
|
|
86
|
+
appears while you work is installed after you exit. (Releases up to 1.0.6 only install after you exit.) Scripts, pipes,
|
|
87
|
+
`-p` and `--agent` runs are never affected.
|
|
87
88
|
|
|
88
89
|
```bash
|
|
89
90
|
korveniq update --check # is there a newer version?
|
|
@@ -154,10 +155,15 @@ When you give the agent a task, it proposes actions. You approve each one:
|
|
|
154
155
|
| Key | Meaning |
|
|
155
156
|
| --- | --- |
|
|
156
157
|
| `y` | Yes — run this one action. |
|
|
157
|
-
| `N`
|
|
158
|
+
| `N` | No — skip it. |
|
|
158
159
|
| `a` | Yes to **all new files** in this project, for the rest of this task. |
|
|
159
160
|
| `Esc` | Stop the current command or reply. |
|
|
160
161
|
|
|
162
|
+
In a terminal the question is a menu: `↑` / `↓` (or the letters) move the highlight and only `Enter` decides. The
|
|
163
|
+
highlight starts on **Yes** in every yes/no menu, including commands, network requests, file changes and
|
|
164
|
+
deletions: read the question before pressing `Enter`. `Esc` always means no. Where answers are typed instead of
|
|
165
|
+
chosen, `Enter` on an approval means no.
|
|
166
|
+
|
|
161
167
|
### About `a` ("yes to all")
|
|
162
168
|
|
|
163
169
|
`a` is the scaffolding fast-path. After you press it once, the agent can create
|
|
@@ -409,8 +415,9 @@ on projects under version control all the same.
|
|
|
409
415
|
Everything else still applies: `Esc` stops a running command
|
|
410
416
|
or reply, warnings (outside the project, sensitive file, long-running command)
|
|
411
417
|
still print, and paths with hidden control characters are still refused.
|
|
412
|
-
|
|
413
|
-
|
|
418
|
+
Files the CLI *guesses* from Markdown code blocks still ask, since those are
|
|
419
|
+
often advice for you rather than actions. Commands in code blocks are only
|
|
420
|
+
shown, never run.
|
|
414
421
|
|
|
415
422
|
> ⚠️ Only use autonomous mode in a project you're comfortable letting the AI
|
|
416
423
|
> change freely — ideally one under version control.
|
|
@@ -503,6 +510,18 @@ The text is always one of the fixed sentences above: never your prompt, the
|
|
|
503
510
|
reply, a command, a path or a token. Scripts and CI (no terminal) never get
|
|
504
511
|
notifications unless `KORVENIQ_NOTIFICATIONS=1`.
|
|
505
512
|
|
|
513
|
+
**macOS:** notifications come from a small app named **Korveniq AI**, which the
|
|
514
|
+
CLI builds on your Mac (with the Korveniq orb as its icon) in
|
|
515
|
+
`~/.korveniq/notifier` with the system's own tools (no
|
|
516
|
+
`sudo`, nothing downloaded). The first time, macOS asks whether it may send
|
|
517
|
+
notifications: choose **Allow** (the notification that triggered the question may
|
|
518
|
+
not be shown). If you missed it, turn it on in System Settings → Notifications →
|
|
519
|
+
Korveniq AI. A Focus (Do Not Disturb) hides notifications as usual.
|
|
520
|
+
|
|
521
|
+
**Windows:** notifications are registered for your user (no administrator rights)
|
|
522
|
+
as **Korveniq AI** with the orb icon. This has not yet been verified on real
|
|
523
|
+
Windows; check it with `/notifications test`.
|
|
524
|
+
|
|
506
525
|
```bash
|
|
507
526
|
/notifications status # settings, and how (or why not) they are shown here
|
|
508
527
|
/notifications test # send one now
|
|
@@ -594,6 +613,20 @@ korveniq -p "summarize this" < notes.txt > summary.md
|
|
|
594
613
|
|
|
595
614
|
---
|
|
596
615
|
|
|
616
|
+
## 🌐 Networking: local servers and package installs
|
|
617
|
+
|
|
618
|
+
The sandbox has no external network. What works without opening it:
|
|
619
|
+
|
|
620
|
+
- **Local servers and tests (Linux).** Commands can listen and connect on `127.0.0.1` and `::1`, also between
|
|
621
|
+
commands.
|
|
622
|
+
- **macOS: not available.** The macOS sandbox cannot limit a server to this computer, so shell commands get no local
|
|
623
|
+
networking there: starting a development server or a test that binds a port fails with `EPERM`.
|
|
624
|
+
- **Installing packages.** `npm install <names>`, `npm ci` and `.venv/bin/pip install <names>` (each as its own
|
|
625
|
+
command) ask for permission every time and can then reach only the official registry. Install scripts run
|
|
626
|
+
afterwards without network.
|
|
627
|
+
|
|
628
|
+
Limits and the exact guarantees per system: [docs/security.md](docs/security.md#networking-in-the-sandbox-phase-320).
|
|
629
|
+
|
|
597
630
|
## 🛡️ Security first
|
|
598
631
|
|
|
599
632
|
Korveniq CLI runs with access to your shell and filesystem, so it's built to a
|
|
@@ -694,6 +727,12 @@ with your next message that you stopped it. In an
|
|
|
694
727
|
interactive session Ctrl+C and Esc only stop the current reply or command;
|
|
695
728
|
Ctrl+C twice on an empty prompt, Ctrl+D or `/exit` leave.
|
|
696
729
|
|
|
730
|
+
**Pasting.** Pasted text stays in the input, line breaks included, and is sent
|
|
731
|
+
only when you press Enter. A paste taller than the screen is shown as
|
|
732
|
+
`[Pasted text #1: 80 lines]` and sent in full (Backspace removes it as a whole).
|
|
733
|
+
This uses the terminal's bracketed paste mode; a terminal without it sends
|
|
734
|
+
pasted line breaks as Enter.
|
|
735
|
+
|
|
697
736
|
**Streaming and network trouble.** Replies stream over a Socket.IO connection.
|
|
698
737
|
If it drops, the CLI reconnects and resubscribes by itself; while it is down
|
|
699
738
|
(or the server refuses the subscription) the reply is fetched by polling every
|
package/bin/index.js
CHANGED
|
@@ -41,6 +41,9 @@ if (!versionOnly && require('../lib/update-state').startSession()) {
|
|
|
41
41
|
process.exit(again.status === null ? 1 : again.status);
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
// Remembers how the command was started, before anything changes the environment (for a restart after an update).
|
|
45
|
+
require('../lib/update-restart');
|
|
46
|
+
|
|
44
47
|
// Before anything is loaded, so every module sees the same mode.
|
|
45
48
|
if (process.argv.includes('--debug')) process.env.KORVENIQ_DEBUG = '1';
|
|
46
49
|
|
package/endpoints.json
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"sendMessage": "POST /api/v1/chat/{chatId}/messages",
|
|
12
12
|
"runStatus": "GET /api/v1/chat/{chatId}/runs/{requestRunId}",
|
|
13
13
|
"cancelRun": "POST /api/v1/chat/{chatId}/runs/{requestRunId}/cancel",
|
|
14
|
-
"chatCapabilities": "GET /api/v1/chat/capabilities"
|
|
14
|
+
"chatCapabilities": "GET /api/v1/chat/capabilities",
|
|
15
|
+
"chatApprovals": "POST /api/v1/chat/{chatId}/approvals"
|
|
15
16
|
}
|
|
16
17
|
}
|
package/lib/api.js
CHANGED
|
@@ -330,6 +330,13 @@ function chatCapabilities(token, opts = {}) {
|
|
|
330
330
|
return request('chatCapabilities', { token, retries: 0, ...opts });
|
|
331
331
|
}
|
|
332
332
|
|
|
333
|
+
/**
|
|
334
|
+
* POST /chat/{chatId}/approvals -> { ok, stepSeq | error }. Sent once: lib/approval-report.js decides about retries.
|
|
335
|
+
*/
|
|
336
|
+
function reportApproval(token, chatId, body, opts = {}) {
|
|
337
|
+
return request('chatApprovals', { token, params: { chatId }, body, retries: 0, ...opts });
|
|
338
|
+
}
|
|
339
|
+
|
|
333
340
|
/** GET /chat/readiness -> { ready, reason? } */
|
|
334
341
|
async function chatReadiness(token, opts = {}) {
|
|
335
342
|
const data = await request('chatReadiness', { token, ...opts });
|
|
@@ -398,6 +405,7 @@ module.exports = {
|
|
|
398
405
|
renameChat,
|
|
399
406
|
chatReadiness,
|
|
400
407
|
chatCapabilities,
|
|
408
|
+
reportApproval,
|
|
401
409
|
sendMessage,
|
|
402
410
|
runStatus,
|
|
403
411
|
cancelRun,
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* lib/approval-report.js
|
|
5
|
+
* -----------------------------------------------------------------------------
|
|
6
|
+
* What a person decided when a tool call asked for permission, as the events of the backend's approval contract
|
|
7
|
+
* (v2; docs/approval-reporting.md), and the queue that delivers them. How they travel is a "transport"
|
|
8
|
+
* (lib/approval-transport.js):
|
|
9
|
+
*
|
|
10
|
+
* { send(payload) -> Promise<{ stepSeq }> } rejects with error.permanent = true (and error.reason) when the server's
|
|
11
|
+
* answer is final; any other rejection is retried
|
|
12
|
+
*
|
|
13
|
+
* An event is made only when a person answers a question (Enter on a menu, a typed answer, or Esc / Ctrl+C, which mean
|
|
14
|
+
* no). A highlighted option, an answer given by autonomous mode, an earlier "yes to all", or a headless --allow policy is
|
|
15
|
+
* not a person's decision and makes none. It says what was decided, never whether the tool then ran or succeeded: that
|
|
16
|
+
* stays in the tool result, which is unchanged.
|
|
17
|
+
*
|
|
18
|
+
* A decision about the call itself (kind "action") and one about network access for it (kind "network") are separate
|
|
19
|
+
* events: neither replaces the other. The payload holds the contract's fields and nothing else: no token, command, path or
|
|
20
|
+
* content.
|
|
21
|
+
*
|
|
22
|
+
* Delivery never delays or blocks a tool: it runs in the background, one event at a time, in the order the decisions were
|
|
23
|
+
* made, with a bounded number of retries that reuse the event's clientEventId. The queue is held in memory, is limited,
|
|
24
|
+
* and is lost when the CLI exits.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const { randomUUID } = require('crypto');
|
|
28
|
+
|
|
29
|
+
/** The server remembers a clientEventId for the whole life of the chat, so a retry is never recorded twice. */
|
|
30
|
+
const RETRY_DELAYS_MS = Object.freeze([1_000, 5_000, 30_000, 120_000, 600_000]);
|
|
31
|
+
const MAX_QUEUED = 200;
|
|
32
|
+
const MAX_REMEMBERED = 5_000;
|
|
33
|
+
const SCOPES = Object.freeze(['once', 'new_files_in_project', 'session']);
|
|
34
|
+
const KINDS = Object.freeze(['action', 'network']);
|
|
35
|
+
/** The questions about network access; every other question is about the call itself. */
|
|
36
|
+
const NETWORK_PERMISSIONS = Object.freeze(['local_network', 'package_network', 'command_network']);
|
|
37
|
+
const TOOL_RE = /^[A-Za-z_][\w.-]{0,63}$/;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The answer of an approval question -> the contract's decision and scope. Anything that is not a clear yes is a deny.
|
|
41
|
+
* @param {string} answer 'yes' | 'always' | 'unrestricted' | anything else (no)
|
|
42
|
+
* @param {{ yes?: string, always?: string }} [reach] what "yes" and "always" grant at this question (default once / session)
|
|
43
|
+
*/
|
|
44
|
+
function decisionOf(answer, reach = {}) {
|
|
45
|
+
const scope = (s) => (SCOPES.includes(s) ? s : 'once');
|
|
46
|
+
if (answer === 'yes') return { decision: 'allow', scope: scope(reach.yes) };
|
|
47
|
+
if (answer === 'always') return { decision: 'allow', scope: scope(reach.always || 'session') };
|
|
48
|
+
// "Without the sandbox" covers this one command; the contract has no value for the sandbox itself.
|
|
49
|
+
if (answer === 'unrestricted') return { decision: 'allow', scope: 'once' };
|
|
50
|
+
return { decision: 'deny', scope: 'once' };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
class ApprovalLog {
|
|
54
|
+
constructor({ transport = null, retryDelaysMs = RETRY_DELAYS_MS, limit = MAX_QUEUED, now = () => new Date(), uuid = randomUUID, debug = () => {} } = {}) {
|
|
55
|
+
this.transport = transport;
|
|
56
|
+
this.retryDelaysMs = retryDelaysMs;
|
|
57
|
+
this.limit = limit;
|
|
58
|
+
this.now = now;
|
|
59
|
+
this.uuid = uuid;
|
|
60
|
+
this.debug = debug;
|
|
61
|
+
this.queue = []; // not yet delivered: { payload, attempts }
|
|
62
|
+
this.seen = new Set(); // one decision per call and kind
|
|
63
|
+
this.inFlight = null; // the pending delivery
|
|
64
|
+
this.timer = null;
|
|
65
|
+
this.dropped = 0;
|
|
66
|
+
this.generation = 0; // clear() makes an older delivery's outcome irrelevant
|
|
67
|
+
this.outcomes = {}; // recorded, conflict, unknown_call, forbidden, invalid, unsupported, gave_up, unaddressable
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Connect (or replace) the way events reach the backend; queued events are then delivered. */
|
|
71
|
+
setTransport(transport) {
|
|
72
|
+
this.transport = transport;
|
|
73
|
+
this.pump();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
count(what) {
|
|
77
|
+
this.outcomes[what] = (this.outcomes[what] || 0) + 1;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Record a person's answer.
|
|
82
|
+
* @param {object} i
|
|
83
|
+
* @param {{ conversation: object, call: { position: number, tool: string, byIndex: boolean, seq?: () => (number|null) } }} i.ref
|
|
84
|
+
* position: from 0 among the calls of the reply; byIndex: that position means the same call to the server; seq: the
|
|
85
|
+
* sequence number the server announced for the call, if it did
|
|
86
|
+
* @returns {object|null} the payload, or null when nothing can be reported (no run, no safe way to name the call, or a
|
|
87
|
+
* decision of this kind about this call was already made)
|
|
88
|
+
*/
|
|
89
|
+
record({ ref, answer, cancelled = false, permission = 'tool', reach }) {
|
|
90
|
+
// (A command the user started themselves, such as /verify, belongs to no reply.)
|
|
91
|
+
if (!ref || !ref.conversation || !ref.conversation.chatId || !ref.call) return null;
|
|
92
|
+
const { conversation, call } = ref;
|
|
93
|
+
const tool = String(call.tool);
|
|
94
|
+
const runId = conversation.requestRunId;
|
|
95
|
+
const kind = NETWORK_PERMISSIONS.includes(permission) ? 'network' : 'action';
|
|
96
|
+
const key = JSON.stringify([conversation.chatId, runId || conversation.clientMessageId, call.position, kind]);
|
|
97
|
+
if (this.seen.has(key)) return null;
|
|
98
|
+
this.seen.add(key);
|
|
99
|
+
if (this.seen.size > MAX_REMEMBERED) this.seen.delete(this.seen.values().next().value);
|
|
100
|
+
|
|
101
|
+
const callSeq = call.seq ? call.seq() : null;
|
|
102
|
+
const hasSeq = Number.isSafeInteger(callSeq) && callSeq >= 0;
|
|
103
|
+
// Reporting a decision against the wrong call would be worse than not reporting it.
|
|
104
|
+
if (!runId || !TOOL_RE.test(tool) || (!hasSeq && !call.byIndex)) {
|
|
105
|
+
this.count('unaddressable');
|
|
106
|
+
this.debug(`approval not reported: ${!runId ? 'the server gave no run id' : 'the call cannot be identified safely'} (${kind}, call ${call.position})`);
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
const { decision, scope } = decisionOf(cancelled ? 'no' : answer, reach);
|
|
110
|
+
const payload = Object.freeze({
|
|
111
|
+
clientEventId: this.uuid(),
|
|
112
|
+
chatId: String(conversation.chatId),
|
|
113
|
+
requestRunId: String(runId),
|
|
114
|
+
...(hasSeq ? { callSeq } : { callIndex: call.position }),
|
|
115
|
+
tool,
|
|
116
|
+
kind,
|
|
117
|
+
decision,
|
|
118
|
+
scope,
|
|
119
|
+
decidedAt: this.now().toISOString(),
|
|
120
|
+
});
|
|
121
|
+
this.queue.push({ payload, attempts: 0 });
|
|
122
|
+
while (this.queue.length > this.limit) {
|
|
123
|
+
// (never the one being sent right now)
|
|
124
|
+
this.queue.splice(this.inFlight ? 1 : 0, 1);
|
|
125
|
+
this.giveUp('the queue is full');
|
|
126
|
+
}
|
|
127
|
+
this.pump();
|
|
128
|
+
return payload;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Events still waiting to be delivered. */
|
|
132
|
+
pending() {
|
|
133
|
+
return this.queue.map((q) => q.payload);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Forget everything undelivered (the account changed). */
|
|
137
|
+
clear() {
|
|
138
|
+
this.generation++;
|
|
139
|
+
this.queue = [];
|
|
140
|
+
this.inFlight = null;
|
|
141
|
+
clearTimeout(this.timer);
|
|
142
|
+
this.timer = null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
giveUp(why) {
|
|
146
|
+
this.dropped++;
|
|
147
|
+
this.count('gave_up');
|
|
148
|
+
this.debug(`approval report given up: ${why}`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Deliver what is queued, in the background. Never throws, never keeps the process alive. */
|
|
152
|
+
pump() {
|
|
153
|
+
if (!this.transport || this.inFlight || this.timer || !this.queue.length) return;
|
|
154
|
+
// (deferred: the caller, an approval, continues first)
|
|
155
|
+
this.inFlight = new Promise((resolve) => setImmediate(resolve)).then(() => this.deliver(this.generation));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async deliver(generation) {
|
|
159
|
+
if (generation !== this.generation) return;
|
|
160
|
+
const item = this.queue[0];
|
|
161
|
+
let wait = null;
|
|
162
|
+
try {
|
|
163
|
+
await this.transport.send(item.payload);
|
|
164
|
+
if (generation !== this.generation) return;
|
|
165
|
+
this.queue.shift();
|
|
166
|
+
this.count('recorded');
|
|
167
|
+
} catch (err) {
|
|
168
|
+
if (generation !== this.generation) return;
|
|
169
|
+
if (err && err.permanent) {
|
|
170
|
+
this.queue.shift();
|
|
171
|
+
this.dropped++;
|
|
172
|
+
this.count(err.reason || 'invalid');
|
|
173
|
+
this.debug(`approval report refused (${err.reason || 'final'}) for ${item.payload.tool}: not retried`);
|
|
174
|
+
} else if (item.attempts >= this.retryDelaysMs.length) {
|
|
175
|
+
this.queue.shift();
|
|
176
|
+
this.giveUp(`${item.attempts + 1} attempts failed (${err && err.message})`);
|
|
177
|
+
} else {
|
|
178
|
+
wait = this.retryDelaysMs[item.attempts++];
|
|
179
|
+
this.debug(`approval report not delivered (${err && err.message}); retrying in ${wait} ms`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
this.inFlight = null;
|
|
183
|
+
if (wait === null) return this.pump();
|
|
184
|
+
this.timer = setTimeout(() => {
|
|
185
|
+
this.timer = null;
|
|
186
|
+
this.pump();
|
|
187
|
+
}, wait);
|
|
188
|
+
this.timer.unref();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Wait (briefly, before the CLI exits) for what is being delivered. Does not wait for retries. */
|
|
192
|
+
async flush(timeoutMs = 1_500) {
|
|
193
|
+
let timer;
|
|
194
|
+
const limit = new Promise((resolve) => (timer = setTimeout(() => resolve('late'), timeoutMs)));
|
|
195
|
+
try {
|
|
196
|
+
while (this.inFlight && (await Promise.race([this.inFlight, limit])) !== 'late');
|
|
197
|
+
} finally {
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
}
|
|
200
|
+
return this.queue.length === 0;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
module.exports = { ApprovalLog, decisionOf, SCOPES, KINDS, RETRY_DELAYS_MS, MAX_QUEUED };
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* lib/approval-transport.js
|
|
5
|
+
* -----------------------------------------------------------------------------
|
|
6
|
+
* How an approval event reaches the backend (approval contract v2):
|
|
7
|
+
*
|
|
8
|
+
* 1. Socket.IO, on the connection that carries the chat, once subscribed: emit('chat:approval', payload, ack)
|
|
9
|
+
* 2. otherwise, or without an acknowledgement: POST /api/v1/chat/{chatId}/approvals (bearer token), same payload
|
|
10
|
+
*
|
|
11
|
+
* Both answer { ok: true, stepSeq } or { ok: false, error }. Both attempts carry the same clientEventId, so the server
|
|
12
|
+
* records the decision once even if it received both.
|
|
13
|
+
*
|
|
14
|
+
* Over REST the refusals are 400 invalid, 404 forbidden, 409 conflict and 422 unknown_call. A server without the route
|
|
15
|
+
* (405 / 501) is not asked again for that chat by this process. At most 60 events per 10 s go over the socket; the next
|
|
16
|
+
* one waits for room.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const api = require('./api');
|
|
20
|
+
const { AuthError } = require('./errors');
|
|
21
|
+
|
|
22
|
+
/** The backend's approval contract v2 is deployed. There is no setting that changes this. */
|
|
23
|
+
const APPROVAL_REPORTING_ENABLED = true;
|
|
24
|
+
const ACK_TIMEOUT_MS = 5_000;
|
|
25
|
+
const REQUEST_TIMEOUT_MS = 10_000;
|
|
26
|
+
/** The server's limit on the socket. */
|
|
27
|
+
const SOCKET_LIMIT = 60;
|
|
28
|
+
const SOCKET_WINDOW_MS = 10_000;
|
|
29
|
+
const REST_ERRORS = Object.freeze({ 400: 'invalid', 403: 'forbidden', 404: 'forbidden', 409: 'conflict', 422: 'unknown_call' });
|
|
30
|
+
/** The contract's errors: each is the server's final answer about this event. */
|
|
31
|
+
const FINAL_ERRORS = Object.freeze(['unknown_call', 'conflict', 'forbidden', 'invalid']);
|
|
32
|
+
|
|
33
|
+
const final = (reason) => Object.assign(new Error(`approval refused: ${reason}`), { permanent: true, reason });
|
|
34
|
+
|
|
35
|
+
/** @returns {{ stepSeq: number|null }|null} null: not an answer in the contract's form. Throws for { ok: false }. */
|
|
36
|
+
function readAnswer(body) {
|
|
37
|
+
if (!body || typeof body !== 'object') return null;
|
|
38
|
+
if (body.ok === true) return { stepSeq: Number.isSafeInteger(body.stepSeq) ? body.stepSeq : null };
|
|
39
|
+
if (body.ok !== false) return null;
|
|
40
|
+
if (FINAL_ERRORS.includes(body.error)) throw final(body.error);
|
|
41
|
+
throw new Error('the server answered with an unknown error'); // retried, a bounded number of times
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The answer inside an error response, if it is the contract's. */
|
|
45
|
+
function bodyOf(err) {
|
|
46
|
+
try {
|
|
47
|
+
const json = JSON.parse(err.body);
|
|
48
|
+
return json && typeof json === 'object' && json.ok === false ? json : null;
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
class ApprovalTransport {
|
|
55
|
+
/**
|
|
56
|
+
* @param {object} session the chat session: its current token and realtime connection are used
|
|
57
|
+
* @param {{ ackTimeoutMs?: number, requestTimeoutMs?: number }} [opts] (tests use short timeouts)
|
|
58
|
+
*/
|
|
59
|
+
constructor(session, { ackTimeoutMs = ACK_TIMEOUT_MS, requestTimeoutMs = REQUEST_TIMEOUT_MS, socketLimit = SOCKET_LIMIT, socketWindowMs = SOCKET_WINDOW_MS } = {}) {
|
|
60
|
+
this.session = session;
|
|
61
|
+
this.ackTimeoutMs = ackTimeoutMs;
|
|
62
|
+
this.requestTimeoutMs = requestTimeoutMs;
|
|
63
|
+
this.unsupported = new Set(); // chat ids for which the server has no approval route
|
|
64
|
+
this.socketLimit = socketLimit;
|
|
65
|
+
this.socketWindowMs = socketWindowMs;
|
|
66
|
+
this.emitted = []; // when the latest events went over the socket
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Wait until one more event fits the socket's rate limit. Never keeps the CLI running. */
|
|
70
|
+
async socketRoom() {
|
|
71
|
+
for (;;) {
|
|
72
|
+
const now = Date.now();
|
|
73
|
+
while (this.emitted.length && now - this.emitted[0] >= this.socketWindowMs) this.emitted.shift();
|
|
74
|
+
if (this.emitted.length < this.socketLimit) return;
|
|
75
|
+
await new Promise((resolve) => setTimeout(resolve, this.emitted[0] + this.socketWindowMs - now).unref());
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async send(payload) {
|
|
80
|
+
if (this.unsupported.has(payload.chatId)) throw final('unsupported');
|
|
81
|
+
const realtime = this.session.realtime;
|
|
82
|
+
if (realtime && realtime.isLive(payload.chatId)) await this.socketRoom();
|
|
83
|
+
// (asked again: the connection may have dropped while waiting)
|
|
84
|
+
if (realtime && realtime.isLive(payload.chatId)) {
|
|
85
|
+
this.emitted.push(Date.now());
|
|
86
|
+
const ack = await realtime.emitWithAck('chat:approval', payload, this.ackTimeoutMs);
|
|
87
|
+
const answer = readAnswer(ack);
|
|
88
|
+
if (answer) return answer;
|
|
89
|
+
}
|
|
90
|
+
return this.post(payload);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async post(payload) {
|
|
94
|
+
if (!this.session.token) throw final('forbidden');
|
|
95
|
+
let data;
|
|
96
|
+
try {
|
|
97
|
+
data = await api.reportApproval(this.session.token, payload.chatId, payload, { timeoutMs: this.requestTimeoutMs });
|
|
98
|
+
} catch (err) {
|
|
99
|
+
const refusal = err.body ? bodyOf(err) : null;
|
|
100
|
+
if (refusal) return readAnswer(refusal);
|
|
101
|
+
if (err instanceof AuthError) throw final('forbidden');
|
|
102
|
+
if (REST_ERRORS[err.status]) throw final(REST_ERRORS[err.status]);
|
|
103
|
+
if (err.status === 405 || err.status === 501) {
|
|
104
|
+
this.unsupported.add(payload.chatId);
|
|
105
|
+
throw final('unsupported');
|
|
106
|
+
}
|
|
107
|
+
throw err; // the connection, a timeout, 408, 429 or a server error: retried
|
|
108
|
+
}
|
|
109
|
+
const answer = readAnswer(data);
|
|
110
|
+
if (!answer) throw new Error('the server sent no acknowledgement');
|
|
111
|
+
return answer;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = { ApprovalTransport, readAnswer, FINAL_ERRORS, ACK_TIMEOUT_MS, APPROVAL_REPORTING_ENABLED };
|
package/lib/build-profile.json
CHANGED
package/lib/chat.js
CHANGED
|
@@ -38,6 +38,7 @@ const compat = require('./compat');
|
|
|
38
38
|
const ui = require('./ui');
|
|
39
39
|
const auth = require('./auth');
|
|
40
40
|
const { Realtime } = require('./realtime');
|
|
41
|
+
const { ApprovalTransport, APPROVAL_REPORTING_ENABLED } = require('./approval-transport');
|
|
41
42
|
const {
|
|
42
43
|
TOOLS,
|
|
43
44
|
projectSnapshot,
|
|
@@ -122,6 +123,7 @@ class ChatSession {
|
|
|
122
123
|
this.declinedInstructions = null; // "file:hash" of instructions the user said no to this session
|
|
123
124
|
this.realtime = null;
|
|
124
125
|
this.socketWarned = false;
|
|
126
|
+
this.approvalReporting = APPROVAL_REPORTING_ENABLED; // (tests may change it)
|
|
125
127
|
this.setToken(token);
|
|
126
128
|
}
|
|
127
129
|
|
|
@@ -135,6 +137,7 @@ class ChatSession {
|
|
|
135
137
|
*/
|
|
136
138
|
setToken(token) {
|
|
137
139
|
if (this.realtime) this.realtime.close();
|
|
140
|
+
if (this.tools && this.tools.approvals && this.token && this.token !== token) this.tools.approvals.clear(); // another account's
|
|
138
141
|
this.token = token || null;
|
|
139
142
|
this.realtime = this.token ? new Realtime(this.token) : null;
|
|
140
143
|
this.socketWarned = false;
|
|
@@ -280,8 +283,8 @@ class ChatSession {
|
|
|
280
283
|
// ---------------------------------------------------------------------------
|
|
281
284
|
|
|
282
285
|
/** Clear the screen and print the logo and banner for the session's state. */
|
|
283
|
-
async function showWelcome(session) {
|
|
284
|
-
if (process.stdout.isTTY) console.clear();
|
|
286
|
+
async function showWelcome(session, { keepScreen = false } = {}) {
|
|
287
|
+
if (process.stdout.isTTY && !keepScreen) console.clear();
|
|
285
288
|
await printLogo({ version: pkg.version });
|
|
286
289
|
printBanner({ user: auth.currentUserLabel(), loggedIn: session.loggedIn });
|
|
287
290
|
}
|
|
@@ -850,7 +853,8 @@ async function compactCommand(session, args = []) {
|
|
|
850
853
|
console.log(theme.dim(` This chat has sent ~${sentTokens.toLocaleString('en-US')} tokens so far (estimate; the real context size is not visible to the CLI).`));
|
|
851
854
|
console.log();
|
|
852
855
|
const confirm = session.askYesNo || askYesNo; // (session.askYesNo: a seam for tests)
|
|
853
|
-
|
|
856
|
+
// Nothing is lost for good (the original chat stays on the server), so "Yes" is highlighted.
|
|
857
|
+
if (!(await confirm('Continue in a new chat with this summary?', { default: true }))) {
|
|
854
858
|
ui.hint('Nothing changed.\n');
|
|
855
859
|
return;
|
|
856
860
|
}
|
|
@@ -994,7 +998,10 @@ function notificationsCommand(args = []) {
|
|
|
994
998
|
if (arg === 'test') {
|
|
995
999
|
const s = mgr.status();
|
|
996
1000
|
if (!s.available) ui.warn(`Cannot show notifications: ${s.unavailableReason}.\n`);
|
|
997
|
-
else if (mgr.test())
|
|
1001
|
+
else if (mgr.test()) {
|
|
1002
|
+
ui.success(`Sent a test notification ${theme.dim(`(via ${s.backend})`)}\n`);
|
|
1003
|
+
if (s.backend === 'macos') ui.hint('Nothing appeared? Allow "Korveniq AI" in System Settings > Notifications, then try again.\n');
|
|
1004
|
+
}
|
|
998
1005
|
else ui.warn('The notification could not be sent.\n');
|
|
999
1006
|
return;
|
|
1000
1007
|
}
|
|
@@ -1141,7 +1148,7 @@ async function autoCommand(session, args = []) {
|
|
|
1141
1148
|
ui.hint(' Shell commands run in an OS sandbox: only the project can change, credentials and .env files are hidden, the network is off');
|
|
1142
1149
|
ui.hint(' unless you allow it for a command that looks like it needs it. Without a sandbox on this machine, every command asks.');
|
|
1143
1150
|
ui.hint(' Esc stops a running command or reply.');
|
|
1144
|
-
ui.hint('
|
|
1151
|
+
ui.hint(' Files written as Markdown code blocks still ask. Commands in code blocks are only shown, never run.');
|
|
1145
1152
|
let ok = false;
|
|
1146
1153
|
try {
|
|
1147
1154
|
ok = await askYesNo('Turn on autonomous mode?', { default: false });
|
|
@@ -1468,9 +1475,11 @@ function maybeDelivered(err) {
|
|
|
1468
1475
|
* same clientMessageId is never stored twice. That guarantee is not verified
|
|
1469
1476
|
* (see docs/api-versioning.md, question 1), so it is not assumed.
|
|
1470
1477
|
*/
|
|
1471
|
-
async function sendWithRetry(session, request, signal) {
|
|
1478
|
+
async function sendWithRetry(session, request, signal, onId = null) {
|
|
1479
|
+
const clientMessageId = randomUUID();
|
|
1480
|
+
if (onId) onId(clientMessageId);
|
|
1472
1481
|
const payload = {
|
|
1473
|
-
clientMessageId
|
|
1482
|
+
clientMessageId,
|
|
1474
1483
|
branchId: session.branchId,
|
|
1475
1484
|
...request.payload, // text, webSearch and, under the CLI computer contract, toolsMode / options (lib/contract.js)
|
|
1476
1485
|
};
|
|
@@ -1713,6 +1722,8 @@ async function runTurn(session, text, { plain = false, transcript, stream = fals
|
|
|
1713
1722
|
let result = null;
|
|
1714
1723
|
let requestRunId = null;
|
|
1715
1724
|
let activeRun = null;
|
|
1725
|
+
let clientMessageId = null;
|
|
1726
|
+
let acceptedRunId = null; // of any accepted message, also one answered at once
|
|
1716
1727
|
let sent = false;
|
|
1717
1728
|
let message = null;
|
|
1718
1729
|
// While a hidden tool block streams, show what it is ("Writing src/app.js…").
|
|
@@ -1798,7 +1809,8 @@ async function runTurn(session, text, { plain = false, transcript, stream = fals
|
|
|
1798
1809
|
plain: noTools,
|
|
1799
1810
|
implemented: TOOLS.map((t) => t.name),
|
|
1800
1811
|
});
|
|
1801
|
-
const accepted = await sendWithRetry(session, request, controller.signal);
|
|
1812
|
+
const accepted = await sendWithRetry(session, request, controller.signal, (id) => (clientMessageId = id));
|
|
1813
|
+
acceptedRunId = accepted.requestRunId || null;
|
|
1802
1814
|
if (request.v1) noteContractAck(session, accepted);
|
|
1803
1815
|
sent = true;
|
|
1804
1816
|
session.stats.sent += text.length;
|
|
@@ -1918,7 +1930,9 @@ async function runTurn(session, text, { plain = false, transcript, stream = fals
|
|
|
1918
1930
|
if (!plain && (started || error || interrupted)) console.log();
|
|
1919
1931
|
// A cut-off reply may still hold complete tool calls; agentTurn decides.
|
|
1920
1932
|
const incomplete = Boolean(result && result.status === 'failed' && result.kind === 'incomplete' && streamed);
|
|
1921
|
-
|
|
1933
|
+
// The identifiers of this exchange: what the calls of the reply (and the decisions about them) belong to.
|
|
1934
|
+
const ids = { chatId: session.chatId, branchId: session.branchId || null, requestRunId: acceptedRunId, clientMessageId, assistantMessageId: (message && message.id) || null };
|
|
1935
|
+
return { ok: !error && !interrupted, sent, text: streamed, message, error, incomplete, interrupted: Boolean(interrupted), ids };
|
|
1922
1936
|
}
|
|
1923
1937
|
|
|
1924
1938
|
/**
|
|
@@ -2099,7 +2113,16 @@ async function agentTurn(session, userText, { plain = false, send = runTurn, now
|
|
|
2099
2113
|
return finish({ ...res, ok: true }, { stopped: budgetStop.reason });
|
|
2100
2114
|
}
|
|
2101
2115
|
|
|
2102
|
-
const
|
|
2116
|
+
const approvals = session.tools.approvals;
|
|
2117
|
+
if (session.approvalReporting && approvals && !approvals.transport) approvals.setTransport(new ApprovalTransport(session));
|
|
2118
|
+
const runId = res.ids && res.ids.requestRunId;
|
|
2119
|
+
session.tools.replyContext = res.ids ? { ...res.ids, toolCallSteps: () => (runId && session.realtime ? session.realtime.toolCallSteps(runId) : []) } : null;
|
|
2120
|
+
let results;
|
|
2121
|
+
try {
|
|
2122
|
+
results = await session.tools.runAll(calls);
|
|
2123
|
+
} finally {
|
|
2124
|
+
session.tools.replyContext = null;
|
|
2125
|
+
}
|
|
2103
2126
|
|
|
2104
2127
|
// A headless run needed an approval nobody can give: it stops here, says what and why (never guesses, never waits).
|
|
2105
2128
|
if (session.tools.approvalBlocked) {
|
|
@@ -2529,6 +2552,17 @@ async function startChat(opts = {}) {
|
|
|
2529
2552
|
}
|
|
2530
2553
|
|
|
2531
2554
|
// ---- Interactive REPL (always starts, logged in or not) ----
|
|
2555
|
+
// Updates (interactive terminals only). Before anything else is shown or typed, a newer release is installed and the
|
|
2556
|
+
// command starts again in it. Later in the session the same object only looks and reports between turns.
|
|
2557
|
+
const { Session: UpdateSession } = require('./update');
|
|
2558
|
+
const updates = new UpdateSession();
|
|
2559
|
+
const restart = require('./update-restart');
|
|
2560
|
+
const installed = await updates.launch({ restarted: restart.restarted() });
|
|
2561
|
+
if (installed) {
|
|
2562
|
+
session.close();
|
|
2563
|
+
await restart.handoff(installed.version); // never returns
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2532
2566
|
let expired = false;
|
|
2533
2567
|
let warning = null;
|
|
2534
2568
|
if (session.loggedIn) {
|
|
@@ -2547,7 +2581,8 @@ async function startChat(opts = {}) {
|
|
|
2547
2581
|
}
|
|
2548
2582
|
}
|
|
2549
2583
|
|
|
2550
|
-
|
|
2584
|
+
// Right after an update restart the screen is kept, so what was installed stays readable above the banner.
|
|
2585
|
+
if (interactive) await showWelcome(session, { keepScreen: restart.restarted() });
|
|
2551
2586
|
if (warning) ui.warn(`${warning}\n`);
|
|
2552
2587
|
if (interactive) showCompat();
|
|
2553
2588
|
if (expired) ui.warn(`Your session has expired. ${theme.dim('Type /login to sign in again.')}\n`);
|
|
@@ -2589,10 +2624,8 @@ async function startChat(opts = {}) {
|
|
|
2589
2624
|
// The prompt says when autonomous mode is on, so it is never on unnoticed.
|
|
2590
2625
|
const promptFor = () => `${autoMode(session) ? `${theme.warn('auto')} ` : ''}${theme.userPrompt('>')} `;
|
|
2591
2626
|
|
|
2592
|
-
//
|
|
2593
|
-
//
|
|
2594
|
-
const { Session: UpdateSession } = require('./update');
|
|
2595
|
-
const updates = new UpdateSession();
|
|
2627
|
+
// Anything newer that appears from now on is downloaded in the background, announced between turns, and installed
|
|
2628
|
+
// only after the conversation has ended: nothing of it is lost.
|
|
2596
2629
|
updates.tick();
|
|
2597
2630
|
|
|
2598
2631
|
// The REPL: prompt -> answer -> prompt, until /exit, Ctrl+D or Ctrl+C twice.
|
|
@@ -2632,6 +2665,7 @@ async function startChat(opts = {}) {
|
|
|
2632
2665
|
if (bg.length && interactive) ui.hint(`Stopping ${bg.length} background process${bg.length === 1 ? '' : 'es'}…`);
|
|
2633
2666
|
if (bg.length) await session.tools.processes.stopAll();
|
|
2634
2667
|
if (interactive) ui.hint('Goodbye!');
|
|
2668
|
+
if (session.tools) await session.tools.approvals.flush(); // a decision just made may still be on its way (bounded)
|
|
2635
2669
|
session.close();
|
|
2636
2670
|
await updates.finish(); // the last thing this process does: it may replace its own files
|
|
2637
2671
|
process.exit(EXIT.OK);
|
package/lib/endpoints.js
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
* nobody has to configure anything. KORVENIQ_API_URL or "baseUrl" in ~/.korveniq/endpoints.json still override it (staging, tests).
|
|
25
25
|
*
|
|
26
26
|
* Endpoint names the CLI uses: login, me, createChat, listChats, getChat,
|
|
27
|
-
* deleteChat, renameChat, chatReadiness, chatCapabilities, sendMessage, runStatus, cancelRun.
|
|
27
|
+
* deleteChat, renameChat, chatReadiness, chatCapabilities, sendMessage, runStatus, cancelRun, chatApprovals.
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
30
|
const fs = require('fs');
|
|
@@ -52,6 +52,7 @@ const DEFAULTS = {
|
|
|
52
52
|
sendMessage: 'POST /api/v1/chat/{chatId}/messages',
|
|
53
53
|
runStatus: 'GET /api/v1/chat/{chatId}/runs/{requestRunId}',
|
|
54
54
|
cancelRun: 'POST /api/v1/chat/{chatId}/runs/{requestRunId}/cancel',
|
|
55
|
+
chatApprovals: 'POST /api/v1/chat/{chatId}/approvals', // the REST fallback of the approval contract
|
|
55
56
|
},
|
|
56
57
|
};
|
|
57
58
|
|