korveniq 1.0.5 → 1.0.7

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 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: during an interactive session a newer
85
- stable release is downloaded and verified, and it is installed after you exit. Scripts, pipes, `-p` and `--agent` runs
86
- are never affected.
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` *(default)* | No — skip it. Pressing Enter also means no. |
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
- Commands the CLI *guesses* from Markdown code blocks still ask, since those
413
- are often advice for you rather than actions.
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.
@@ -594,6 +601,20 @@ korveniq -p "summarize this" < notes.txt > summary.md
594
601
 
595
602
  ---
596
603
 
604
+ ## 🌐 Networking: local servers and package installs
605
+
606
+ The sandbox has no external network. What works without opening it:
607
+
608
+ - **Local servers and tests (Linux).** Commands can listen and connect on `127.0.0.1` and `::1`, also between
609
+ commands.
610
+ - **macOS: not available.** The macOS sandbox cannot limit a server to this computer, so shell commands get no local
611
+ networking there: starting a development server or a test that binds a port fails with `EPERM`.
612
+ - **Installing packages.** `npm install <names>`, `npm ci` and `.venv/bin/pip install <names>` (each as its own
613
+ command) ask for permission every time and can then reach only the official registry. Install scripts run
614
+ afterwards without network.
615
+
616
+ Limits and the exact guarantees per system: [docs/security.md](docs/security.md#networking-in-the-sandbox-phase-320).
617
+
597
618
  ## 🛡️ Security first
598
619
 
599
620
  Korveniq CLI runs with access to your shell and filesystem, so it's built to a
@@ -694,6 +715,12 @@ with your next message that you stopped it. In an
694
715
  interactive session Ctrl+C and Esc only stop the current reply or command;
695
716
  Ctrl+C twice on an empty prompt, Ctrl+D or `/exit` leave.
696
717
 
718
+ **Pasting.** Pasted text stays in the input, line breaks included, and is sent
719
+ only when you press Enter. A paste taller than the screen is shown as
720
+ `[Pasted text #1: 80 lines]` and sent in full (Backspace removes it as a whole).
721
+ This uses the terminal's bracketed paste mode; a terminal without it sends
722
+ pasted line breaks as Enter.
723
+
697
724
  **Streaming and network trouble.** Replies stream over a Socket.IO connection.
698
725
  If it drops, the CLI reconnects and resubscribes by itself; while it is down
699
726
  (or the server refuses the subscription) the reply is fetched by polling every
@@ -823,11 +850,12 @@ commands, the browser) inherits it.
823
850
  terminal may be left in raw mode (type `stty sane` or `reset` to fix it), and
824
851
  commands the agent was running keep running in their own process group.
825
852
 
826
- **Tested runtimes.** For 1.0.4 (1.0.5 has the same program code) the full suite runs on Node.js 24.11.1 (macOS and
827
- Ubuntu 24.04), and the updater tests also on 18.17, 20.18 and 22.12 (Linux). On
828
- Node.js 18.17 some of the project's test and benchmark tooling does not run (the
829
- CLI's tests pass on Linux when that is worked around). To run the end-to-end
830
- tests against an installed package: `KORVENIQ_TEST_BIN=$(which korveniq) npm test`.
853
+ **Tested runtimes.** The full suite last ran for 1.0.4, on Node.js 24.11.1 (macOS
854
+ and Ubuntu 24.04). The updater tests also run on 18.17 (and, for 1.0.4, on 20.18
855
+ and 22.12) on Linux. On Node.js 18.17 some of the project's test and benchmark
856
+ tooling does not run (the CLI's tests pass on Linux when that is worked around).
857
+ To run the end-to-end tests against an installed package:
858
+ `KORVENIQ_TEST_BIN=$(which korveniq) npm test`.
831
859
 
832
860
  ---
833
861
 
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,215 @@
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
+ * (draft of 2026-11-27; 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
+ * The payload holds the contract's fields and nothing else: no token, command, path or content.
19
+ *
20
+ * Delivery never delays or blocks a tool: it runs in the background, one event at a time, in the order the decisions were
21
+ * made, with a bounded number of retries that reuse the event's clientEventId. The queue is held in memory, is limited,
22
+ * and is lost when the CLI exits.
23
+ */
24
+
25
+ const { randomUUID } = require('crypto');
26
+
27
+ /** All far inside the 24 hours for which the server remembers a clientEventId. */
28
+ const RETRY_DELAYS_MS = Object.freeze([1_000, 5_000, 30_000, 120_000, 600_000]);
29
+ const MAX_QUEUED = 200;
30
+ const MAX_REMEMBERED = 5_000;
31
+ const SCOPES = Object.freeze(['once', 'new_files_in_project', 'session', 'network_registry']);
32
+ const TOOL_RE = /^[A-Za-z_][\w.-]{0,63}$/;
33
+
34
+ /**
35
+ * The answer of an approval question -> the contract's decision and scope. Anything that is not a clear yes is a deny.
36
+ * @param {string} answer 'yes' | 'always' | 'unrestricted' | anything else (no)
37
+ * @param {{ yes?: string, always?: string }} [reach] what "yes" and "always" grant at this question (default once / session)
38
+ */
39
+ function decisionOf(answer, reach = {}) {
40
+ const scope = (s) => (SCOPES.includes(s) ? s : 'once');
41
+ if (answer === 'yes') return { decision: 'allow', scope: scope(reach.yes) };
42
+ if (answer === 'always') return { decision: 'allow', scope: scope(reach.always || 'session') };
43
+ // "Without the sandbox" covers this one command; the contract has no value for the sandbox itself.
44
+ if (answer === 'unrestricted') return { decision: 'allow', scope: 'once' };
45
+ return { decision: 'deny', scope: 'once' };
46
+ }
47
+
48
+ class ApprovalLog {
49
+ constructor({ transport = null, retryDelaysMs = RETRY_DELAYS_MS, limit = MAX_QUEUED, now = () => new Date(), uuid = randomUUID, debug = () => {} } = {}) {
50
+ this.transport = transport;
51
+ this.retryDelaysMs = retryDelaysMs;
52
+ this.limit = limit;
53
+ this.now = now;
54
+ this.uuid = uuid;
55
+ this.debug = debug;
56
+ this.queue = []; // not yet delivered: { payload, call, permission, attempts }
57
+ this.seen = new Set(); // one decision per call and permission
58
+ this.undelivered = new Set(); // calls whose FIRST decision was given up
59
+ this.inFlight = null; // the pending delivery
60
+ this.timer = null;
61
+ this.dropped = 0;
62
+ this.generation = 0; // clear() makes an older delivery's outcome irrelevant
63
+ this.outcomes = {}; // recorded, conflict, unknown_call, forbidden, invalid, unsupported, gave_up, unaddressable, not_expressible, superseded
64
+ }
65
+
66
+ /** Connect (or replace) the way events reach the backend; queued events are then delivered. */
67
+ setTransport(transport) {
68
+ this.transport = transport;
69
+ this.pump();
70
+ }
71
+
72
+ count(what) {
73
+ this.outcomes[what] = (this.outcomes[what] || 0) + 1;
74
+ }
75
+
76
+ /**
77
+ * Record a person's answer.
78
+ * @param {object} i
79
+ * @param {{ conversation: object, call: { position: number, tool: string, byIndex: boolean, seq?: () => (number|null) } }} i.ref
80
+ * position: from 0 among the calls of the reply; byIndex: that position means the same call to the server; seq: the
81
+ * sequence number the server announced for the call, if it did
82
+ * @returns {object|null} the payload, or null when nothing can be reported (no run, no safe way to name the call, or a
83
+ * decision about this call and permission was already made)
84
+ */
85
+ record({ ref, answer, cancelled = false, permission = 'tool', reach }) {
86
+ // (A command the user started themselves, such as /verify, belongs to no reply.)
87
+ if (!ref || !ref.conversation || !ref.conversation.chatId || !ref.call) return null;
88
+ const { conversation, call } = ref;
89
+ const tool = String(call.tool);
90
+ const runId = conversation.requestRunId;
91
+ const callKey = JSON.stringify([conversation.chatId, runId || conversation.clientMessageId, call.position]);
92
+ const key = `${callKey}:${permission}`;
93
+ if (this.seen.has(key)) return null;
94
+ this.seen.add(key);
95
+ if (this.seen.size > MAX_REMEMBERED) this.seen.delete(this.seen.values().next().value);
96
+
97
+ const callSeq = call.seq ? call.seq() : null;
98
+ const hasSeq = Number.isSafeInteger(callSeq) && callSeq >= 0;
99
+ // Reporting a decision against the wrong call would be worse than not reporting it.
100
+ if (!runId || !TOOL_RE.test(tool) || (!hasSeq && !call.byIndex)) {
101
+ this.count('unaddressable');
102
+ this.debug(`approval not reported: ${!runId ? 'the server gave no run id' : 'the call cannot be identified safely'} (${permission}, call ${call.position})`);
103
+ return null;
104
+ }
105
+ const { decision, scope } = decisionOf(cancelled ? 'no' : answer, reach);
106
+ // Refusing local networking does not refuse the call (the command still runs, without it), and the contract can only
107
+ // describe the call: sent, this "deny" could be recorded as the decision about a command that ran.
108
+ if (permission === 'local_network' && decision === 'deny') {
109
+ this.count('not_expressible');
110
+ this.debug('approval not reported: the contract cannot express a refusal of local networking alone');
111
+ return null;
112
+ }
113
+ const payload = Object.freeze({
114
+ clientEventId: this.uuid(),
115
+ chatId: String(conversation.chatId),
116
+ requestRunId: String(runId),
117
+ ...(hasSeq ? { callSeq } : { callIndex: call.position }),
118
+ tool,
119
+ decision,
120
+ scope,
121
+ decidedAt: this.now().toISOString(),
122
+ });
123
+ this.queue.push({ payload, call: callKey, permission, attempts: 0 });
124
+ while (this.queue.length > this.limit) {
125
+ // (never the one being sent right now)
126
+ const [gone] = this.queue.splice(this.inFlight ? 1 : 0, 1);
127
+ this.giveUp(gone, 'the queue is full');
128
+ }
129
+ this.pump();
130
+ return payload;
131
+ }
132
+
133
+ /** Events still waiting to be delivered. */
134
+ pending() {
135
+ return this.queue.map((q) => q.payload);
136
+ }
137
+
138
+ /** Forget everything undelivered (the account changed). */
139
+ clear() {
140
+ this.generation++;
141
+ this.queue = [];
142
+ this.inFlight = null;
143
+ clearTimeout(this.timer);
144
+ this.timer = null;
145
+ }
146
+
147
+ giveUp(item, why) {
148
+ this.dropped++;
149
+ if (item.permission === 'tool') this.undelivered.add(item.call);
150
+ this.count('gave_up');
151
+ this.debug(`approval report given up: ${why}`);
152
+ }
153
+
154
+ /** Deliver what is queued, in the background. Never throws, never keeps the process alive. */
155
+ pump() {
156
+ if (!this.transport || this.inFlight || this.timer || !this.queue.length) return;
157
+ // (deferred: the caller, an approval, continues first)
158
+ this.inFlight = new Promise((resolve) => setImmediate(resolve)).then(() => this.deliver(this.generation));
159
+ }
160
+
161
+ async deliver(generation) {
162
+ if (generation !== this.generation) return;
163
+ const item = this.queue[0];
164
+ let wait = null;
165
+ // The server keeps the first decision it gets about a call. A second one (local networking, after the command) must
166
+ // not arrive in place of a first that never did.
167
+ if (item.permission !== 'tool' && this.undelivered.has(item.call)) {
168
+ this.queue.shift();
169
+ this.count('superseded');
170
+ } else {
171
+ try {
172
+ await this.transport.send(item.payload);
173
+ if (generation !== this.generation) return;
174
+ this.queue.shift();
175
+ this.count('recorded');
176
+ } catch (err) {
177
+ if (generation !== this.generation) return;
178
+ if (err && err.permanent) {
179
+ this.queue.shift();
180
+ this.dropped++;
181
+ this.count(err.reason || 'invalid');
182
+ if (item.permission === 'tool' && err.reason !== 'conflict') this.undelivered.add(item.call);
183
+ this.debug(`approval report refused (${err.reason || 'final'}) for ${item.payload.tool}: not retried`);
184
+ } else if (item.attempts >= this.retryDelaysMs.length) {
185
+ this.queue.shift();
186
+ this.giveUp(item, `${item.attempts + 1} attempts failed (${err && err.message})`);
187
+ } else {
188
+ wait = this.retryDelaysMs[item.attempts++];
189
+ this.debug(`approval report not delivered (${err && err.message}); retrying in ${wait} ms`);
190
+ }
191
+ }
192
+ }
193
+ this.inFlight = null;
194
+ if (wait === null) return this.pump();
195
+ this.timer = setTimeout(() => {
196
+ this.timer = null;
197
+ this.pump();
198
+ }, wait);
199
+ this.timer.unref();
200
+ }
201
+
202
+ /** Wait (briefly, before the CLI exits) for what is being delivered. Does not wait for retries. */
203
+ async flush(timeoutMs = 1_500) {
204
+ let timer;
205
+ const limit = new Promise((resolve) => (timer = setTimeout(() => resolve('late'), timeoutMs)));
206
+ try {
207
+ while (this.inFlight && (await Promise.race([this.inFlight, limit])) !== 'late');
208
+ } finally {
209
+ clearTimeout(timer);
210
+ }
211
+ return this.queue.length === 0;
212
+ }
213
+ }
214
+
215
+ module.exports = { ApprovalLog, decisionOf, SCOPES, RETRY_DELAYS_MS, MAX_QUEUED };
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * lib/approval-transport.js
5
+ * -----------------------------------------------------------------------------
6
+ * How an approval event reaches the backend (contract draft of 2026-11-27):
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
+ * A server without the feature never acknowledges the event and answers 404 to the request. After that, nothing more is
15
+ * sent for that chat by this process (the server still records rejections from the tool results, as before).
16
+ */
17
+
18
+ const api = require('./api');
19
+ const { AuthError } = require('./errors');
20
+
21
+ /**
22
+ * OFF until the backend's final (v2) approval contract is available: nothing is sent. Decisions are still recorded in
23
+ * memory, and rejections still reach the server in the tool results. There is deliberately no setting that turns it on.
24
+ */
25
+ const APPROVAL_REPORTING_ENABLED = false;
26
+ const ACK_TIMEOUT_MS = 5_000;
27
+ const REQUEST_TIMEOUT_MS = 10_000;
28
+ /** The contract's errors: each is the server's final answer about this event. */
29
+ const FINAL_ERRORS = Object.freeze(['unknown_call', 'conflict', 'forbidden', 'invalid']);
30
+
31
+ const final = (reason) => Object.assign(new Error(`approval refused: ${reason}`), { permanent: true, reason });
32
+
33
+ /** @returns {{ stepSeq: number|null }|null} null: not an answer in the contract's form. Throws for { ok: false }. */
34
+ function readAnswer(body) {
35
+ if (!body || typeof body !== 'object') return null;
36
+ if (body.ok === true) return { stepSeq: Number.isSafeInteger(body.stepSeq) ? body.stepSeq : null };
37
+ if (body.ok !== false) return null;
38
+ if (FINAL_ERRORS.includes(body.error)) throw final(body.error);
39
+ throw new Error('the server answered with an unknown error'); // retried, a bounded number of times
40
+ }
41
+
42
+ /** The answer inside an error response, if it is the contract's. */
43
+ function bodyOf(err) {
44
+ try {
45
+ const json = JSON.parse(err.body);
46
+ return json && typeof json === 'object' && json.ok === false ? json : null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ class ApprovalTransport {
53
+ /**
54
+ * @param {object} session the chat session: its current token and realtime connection are used
55
+ * @param {{ ackTimeoutMs?: number, requestTimeoutMs?: number }} [opts] (tests use short timeouts)
56
+ */
57
+ constructor(session, { ackTimeoutMs = ACK_TIMEOUT_MS, requestTimeoutMs = REQUEST_TIMEOUT_MS } = {}) {
58
+ this.session = session;
59
+ this.ackTimeoutMs = ackTimeoutMs;
60
+ this.requestTimeoutMs = requestTimeoutMs;
61
+ this.unsupported = new Set(); // chat ids for which the server has no approval route
62
+ }
63
+
64
+ async send(payload) {
65
+ if (this.unsupported.has(payload.chatId)) throw final('unsupported');
66
+ const realtime = this.session.realtime;
67
+ if (realtime && realtime.isLive(payload.chatId)) {
68
+ const ack = await realtime.emitWithAck('chat:approval', payload, this.ackTimeoutMs);
69
+ const answer = readAnswer(ack);
70
+ if (answer) return answer;
71
+ }
72
+ return this.post(payload);
73
+ }
74
+
75
+ async post(payload) {
76
+ if (!this.session.token) throw final('forbidden');
77
+ let data;
78
+ try {
79
+ data = await api.reportApproval(this.session.token, payload.chatId, payload, { timeoutMs: this.requestTimeoutMs });
80
+ } catch (err) {
81
+ const refusal = err.body ? bodyOf(err) : null;
82
+ if (refusal) return readAnswer(refusal);
83
+ if (err instanceof AuthError || err.status === 403) throw final('forbidden');
84
+ if ([404, 405, 501].includes(err.status)) {
85
+ this.unsupported.add(payload.chatId);
86
+ throw final('unsupported');
87
+ }
88
+ if (err.status === 400 || err.status === 422) throw final('invalid');
89
+ throw err; // the connection, a timeout, 408, 429 or a server error: retried
90
+ }
91
+ const answer = readAnswer(data);
92
+ if (!answer) throw new Error('the server sent no acknowledgement');
93
+ return answer;
94
+ }
95
+ }
96
+
97
+ module.exports = { ApprovalTransport, readAnswer, FINAL_ERRORS, ACK_TIMEOUT_MS, APPROVAL_REPORTING_ENABLED };
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "profile": "beta",
3
- "version": "1.0.5",
4
- "builtAt": "2026-11-26T17:23:41.482Z"
3
+ "version": "1.0.7",
4
+ "builtAt": "2026-11-27T00:07:42.976Z"
5
5
  }
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; // (the tests of the kept implementation switch it on)
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
- if (!(await confirm('Continue in a new chat with this summary?', { default: false }))) {
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
  }
@@ -1141,7 +1145,7 @@ async function autoCommand(session, args = []) {
1141
1145
  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
1146
  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
1147
  ui.hint(' Esc stops a running command or reply.');
1144
- ui.hint(' Commands written as Markdown code blocks still ask.');
1148
+ ui.hint(' Files written as Markdown code blocks still ask. Commands in code blocks are only shown, never run.');
1145
1149
  let ok = false;
1146
1150
  try {
1147
1151
  ok = await askYesNo('Turn on autonomous mode?', { default: false });
@@ -1468,9 +1472,11 @@ function maybeDelivered(err) {
1468
1472
  * same clientMessageId is never stored twice. That guarantee is not verified
1469
1473
  * (see docs/api-versioning.md, question 1), so it is not assumed.
1470
1474
  */
1471
- async function sendWithRetry(session, request, signal) {
1475
+ async function sendWithRetry(session, request, signal, onId = null) {
1476
+ const clientMessageId = randomUUID();
1477
+ if (onId) onId(clientMessageId);
1472
1478
  const payload = {
1473
- clientMessageId: randomUUID(),
1479
+ clientMessageId,
1474
1480
  branchId: session.branchId,
1475
1481
  ...request.payload, // text, webSearch and, under the CLI computer contract, toolsMode / options (lib/contract.js)
1476
1482
  };
@@ -1713,6 +1719,8 @@ async function runTurn(session, text, { plain = false, transcript, stream = fals
1713
1719
  let result = null;
1714
1720
  let requestRunId = null;
1715
1721
  let activeRun = null;
1722
+ let clientMessageId = null;
1723
+ let acceptedRunId = null; // of any accepted message, also one answered at once
1716
1724
  let sent = false;
1717
1725
  let message = null;
1718
1726
  // While a hidden tool block streams, show what it is ("Writing src/app.js…").
@@ -1798,7 +1806,8 @@ async function runTurn(session, text, { plain = false, transcript, stream = fals
1798
1806
  plain: noTools,
1799
1807
  implemented: TOOLS.map((t) => t.name),
1800
1808
  });
1801
- const accepted = await sendWithRetry(session, request, controller.signal);
1809
+ const accepted = await sendWithRetry(session, request, controller.signal, (id) => (clientMessageId = id));
1810
+ acceptedRunId = accepted.requestRunId || null;
1802
1811
  if (request.v1) noteContractAck(session, accepted);
1803
1812
  sent = true;
1804
1813
  session.stats.sent += text.length;
@@ -1918,7 +1927,9 @@ async function runTurn(session, text, { plain = false, transcript, stream = fals
1918
1927
  if (!plain && (started || error || interrupted)) console.log();
1919
1928
  // A cut-off reply may still hold complete tool calls; agentTurn decides.
1920
1929
  const incomplete = Boolean(result && result.status === 'failed' && result.kind === 'incomplete' && streamed);
1921
- return { ok: !error && !interrupted, sent, text: streamed, message, error, incomplete, interrupted: Boolean(interrupted) };
1930
+ // The identifiers of this exchange: what the calls of the reply (and the decisions about them) belong to.
1931
+ const ids = { chatId: session.chatId, branchId: session.branchId || null, requestRunId: acceptedRunId, clientMessageId, assistantMessageId: (message && message.id) || null };
1932
+ return { ok: !error && !interrupted, sent, text: streamed, message, error, incomplete, interrupted: Boolean(interrupted), ids };
1922
1933
  }
1923
1934
 
1924
1935
  /**
@@ -2099,7 +2110,16 @@ async function agentTurn(session, userText, { plain = false, send = runTurn, now
2099
2110
  return finish({ ...res, ok: true }, { stopped: budgetStop.reason });
2100
2111
  }
2101
2112
 
2102
- const results = await session.tools.runAll(calls);
2113
+ const approvals = session.tools.approvals;
2114
+ if (session.approvalReporting && approvals && !approvals.transport) approvals.setTransport(new ApprovalTransport(session));
2115
+ const runId = res.ids && res.ids.requestRunId;
2116
+ session.tools.replyContext = res.ids ? { ...res.ids, toolCallSteps: () => (runId && session.realtime ? session.realtime.toolCallSteps(runId) : []) } : null;
2117
+ let results;
2118
+ try {
2119
+ results = await session.tools.runAll(calls);
2120
+ } finally {
2121
+ session.tools.replyContext = null;
2122
+ }
2103
2123
 
2104
2124
  // A headless run needed an approval nobody can give: it stops here, says what and why (never guesses, never waits).
2105
2125
  if (session.tools.approvalBlocked) {
@@ -2529,6 +2549,17 @@ async function startChat(opts = {}) {
2529
2549
  }
2530
2550
 
2531
2551
  // ---- Interactive REPL (always starts, logged in or not) ----
2552
+ // Updates (interactive terminals only). Before anything else is shown or typed, a newer release is installed and the
2553
+ // command starts again in it. Later in the session the same object only looks and reports between turns.
2554
+ const { Session: UpdateSession } = require('./update');
2555
+ const updates = new UpdateSession();
2556
+ const restart = require('./update-restart');
2557
+ const installed = await updates.launch({ restarted: restart.restarted() });
2558
+ if (installed) {
2559
+ session.close();
2560
+ await restart.handoff(installed.version); // never returns
2561
+ }
2562
+
2532
2563
  let expired = false;
2533
2564
  let warning = null;
2534
2565
  if (session.loggedIn) {
@@ -2547,7 +2578,8 @@ async function startChat(opts = {}) {
2547
2578
  }
2548
2579
  }
2549
2580
 
2550
- if (interactive) await showWelcome(session);
2581
+ // Right after an update restart the screen is kept, so what was installed stays readable above the banner.
2582
+ if (interactive) await showWelcome(session, { keepScreen: restart.restarted() });
2551
2583
  if (warning) ui.warn(`${warning}\n`);
2552
2584
  if (interactive) showCompat();
2553
2585
  if (expired) ui.warn(`Your session has expired. ${theme.dim('Type /login to sign in again.')}\n`);
@@ -2589,10 +2621,8 @@ async function startChat(opts = {}) {
2589
2621
  // The prompt says when autonomous mode is on, so it is never on unnoticed.
2590
2622
  const promptFor = () => `${autoMode(session) ? `${theme.warn('auto')} ` : ''}${theme.userPrompt('>')} `;
2591
2623
 
2592
- // Looks for a new version in the background (interactive terminals only). It speaks only between turns, and files
2593
- // are replaced only after the conversation has ended.
2594
- const { Session: UpdateSession } = require('./update');
2595
- const updates = new UpdateSession();
2624
+ // Anything newer that appears from now on is downloaded in the background, announced between turns, and installed
2625
+ // only after the conversation has ended: nothing of it is lost.
2596
2626
  updates.tick();
2597
2627
 
2598
2628
  // The REPL: prompt -> answer -> prompt, until /exit, Ctrl+D or Ctrl+C twice.
@@ -2632,6 +2662,7 @@ async function startChat(opts = {}) {
2632
2662
  if (bg.length && interactive) ui.hint(`Stopping ${bg.length} background process${bg.length === 1 ? '' : 'es'}…`);
2633
2663
  if (bg.length) await session.tools.processes.stopAll();
2634
2664
  if (interactive) ui.hint('Goodbye!');
2665
+ if (session.tools) await session.tools.approvals.flush(); // a decision just made may still be on its way (bounded)
2635
2666
  session.close();
2636
2667
  await updates.finish(); // the last thing this process does: it may replace its own files
2637
2668
  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 (draft)
55
56
  },
56
57
  };
57
58
 
@@ -66,11 +66,17 @@ function networkHint(command, { background = false } = {}) {
66
66
  return m ? `it looks like it needs the network (“${m[0].replace(/\s+/g, ' ').slice(0, 40)}”), which autonomous mode keeps off unless you allow it` : null;
67
67
  }
68
68
 
69
+ /** Commands that probably open or reach a local server (macOS: a person is asked to allow local networking). A hint only. */
70
+ const LOCAL_HINT_RE = /\blocalhost\b|127\.0\.0\.1|::1\b|\b(?:npm|pnpm|yarn)\s+(?:start|test|t\b|run\b)|\bnode\s+(?!--check\b|-v\b|--version\b|-p\b)\S+|\b(?:jest|vitest|mocha|ava|pytest|nodemon|uvicorn|gunicorn|hypercorn|flask|http\.server|vite|next\s+(?:dev|start)|serve|manage\.py)\b/;
71
+
72
+ const wantsLocalNetwork = (command, { background = false } = {}) => background || LOCAL_HINT_RE.test(String(command));
73
+
69
74
  /** One line for the screen: what the sandbox will allow this command. */
70
75
  function describe(sb) {
71
76
  const e = sb.effective;
72
- const parts = [`workspace ${e.writeWorkspace ? (e.unlink ? 'writable' : 'writable, no deletes') : 'read-only'}`, e.network ? 'network on' : 'network off', 'credentials hidden', 'nothing outside the project changes'];
77
+ const network = e.network ? 'network on' : e.local ? (sb.backend === 'bubblewrap' ? 'external network off, localhost inside the sandbox' : 'external network off, this computer allowed') : 'network off';
78
+ const parts = [`workspace ${e.writeWorkspace ? (e.unlink ? 'writable' : 'writable, no deletes') : 'read-only'}`, network, 'credentials hidden', 'nothing outside the project changes'];
73
79
  return `sandbox (${sb.backend}): ${parts.join(' · ')}`;
74
80
  }
75
81
 
76
- module.exports = { NETWORK_HINT_RE, grantsFor, modeOf, networkHint, describe, shellNetworkEnabled };
82
+ module.exports = { NETWORK_HINT_RE, LOCAL_HINT_RE, grantsFor, modeOf, networkHint, wantsLocalNetwork, describe, shellNetworkEnabled };