korveniq 1.0.7 → 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 +12 -0
- package/lib/approval-report.js +38 -49
- package/lib/approval-transport.js +30 -12
- package/lib/build-profile.json +2 -2
- package/lib/chat.js +5 -2
- package/lib/endpoints.js +1 -1
- package/lib/mac-notify.js +121 -0
- package/lib/notifier.js +18 -16
- package/lib/realtime.js +11 -10
- package/lib/tool-parser.js +10 -0
- package/lib/tools.js +12 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -510,6 +510,18 @@ The text is always one of the fixed sentences above: never your prompt, the
|
|
|
510
510
|
reply, a command, a path or a token. Scripts and CI (no terminal) never get
|
|
511
511
|
notifications unless `KORVENIQ_NOTIFICATIONS=1`.
|
|
512
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
|
+
|
|
513
525
|
```bash
|
|
514
526
|
/notifications status # settings, and how (or why not) they are shown here
|
|
515
527
|
/notifications test # send one now
|
package/lib/approval-report.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* lib/approval-report.js
|
|
5
5
|
* -----------------------------------------------------------------------------
|
|
6
6
|
* What a person decided when a tool call asked for permission, as the events of the backend's approval contract
|
|
7
|
-
* (
|
|
7
|
+
* (v2; docs/approval-reporting.md), and the queue that delivers them. How they travel is a "transport"
|
|
8
8
|
* (lib/approval-transport.js):
|
|
9
9
|
*
|
|
10
10
|
* { send(payload) -> Promise<{ stepSeq }> } rejects with error.permanent = true (and error.reason) when the server's
|
|
@@ -15,7 +15,9 @@
|
|
|
15
15
|
* not a person's decision and makes none. It says what was decided, never whether the tool then ran or succeeded: that
|
|
16
16
|
* stays in the tool result, which is unchanged.
|
|
17
17
|
*
|
|
18
|
-
*
|
|
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.
|
|
19
21
|
*
|
|
20
22
|
* Delivery never delays or blocks a tool: it runs in the background, one event at a time, in the order the decisions were
|
|
21
23
|
* made, with a bounded number of retries that reuse the event's clientEventId. The queue is held in memory, is limited,
|
|
@@ -24,11 +26,14 @@
|
|
|
24
26
|
|
|
25
27
|
const { randomUUID } = require('crypto');
|
|
26
28
|
|
|
27
|
-
/**
|
|
29
|
+
/** The server remembers a clientEventId for the whole life of the chat, so a retry is never recorded twice. */
|
|
28
30
|
const RETRY_DELAYS_MS = Object.freeze([1_000, 5_000, 30_000, 120_000, 600_000]);
|
|
29
31
|
const MAX_QUEUED = 200;
|
|
30
32
|
const MAX_REMEMBERED = 5_000;
|
|
31
|
-
const SCOPES = Object.freeze(['once', 'new_files_in_project', 'session'
|
|
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']);
|
|
32
37
|
const TOOL_RE = /^[A-Za-z_][\w.-]{0,63}$/;
|
|
33
38
|
|
|
34
39
|
/**
|
|
@@ -53,14 +58,13 @@ class ApprovalLog {
|
|
|
53
58
|
this.now = now;
|
|
54
59
|
this.uuid = uuid;
|
|
55
60
|
this.debug = debug;
|
|
56
|
-
this.queue = []; // not yet delivered: { payload,
|
|
57
|
-
this.seen = new Set(); // one decision per call and
|
|
58
|
-
this.undelivered = new Set(); // calls whose FIRST decision was given up
|
|
61
|
+
this.queue = []; // not yet delivered: { payload, attempts }
|
|
62
|
+
this.seen = new Set(); // one decision per call and kind
|
|
59
63
|
this.inFlight = null; // the pending delivery
|
|
60
64
|
this.timer = null;
|
|
61
65
|
this.dropped = 0;
|
|
62
66
|
this.generation = 0; // clear() makes an older delivery's outcome irrelevant
|
|
63
|
-
this.outcomes = {}; // recorded, conflict, unknown_call, forbidden, invalid, unsupported, gave_up, unaddressable
|
|
67
|
+
this.outcomes = {}; // recorded, conflict, unknown_call, forbidden, invalid, unsupported, gave_up, unaddressable
|
|
64
68
|
}
|
|
65
69
|
|
|
66
70
|
/** Connect (or replace) the way events reach the backend; queued events are then delivered. */
|
|
@@ -80,7 +84,7 @@ class ApprovalLog {
|
|
|
80
84
|
* position: from 0 among the calls of the reply; byIndex: that position means the same call to the server; seq: the
|
|
81
85
|
* sequence number the server announced for the call, if it did
|
|
82
86
|
* @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
|
|
87
|
+
* decision of this kind about this call was already made)
|
|
84
88
|
*/
|
|
85
89
|
record({ ref, answer, cancelled = false, permission = 'tool', reach }) {
|
|
86
90
|
// (A command the user started themselves, such as /verify, belongs to no reply.)
|
|
@@ -88,8 +92,8 @@ class ApprovalLog {
|
|
|
88
92
|
const { conversation, call } = ref;
|
|
89
93
|
const tool = String(call.tool);
|
|
90
94
|
const runId = conversation.requestRunId;
|
|
91
|
-
const
|
|
92
|
-
const key =
|
|
95
|
+
const kind = NETWORK_PERMISSIONS.includes(permission) ? 'network' : 'action';
|
|
96
|
+
const key = JSON.stringify([conversation.chatId, runId || conversation.clientMessageId, call.position, kind]);
|
|
93
97
|
if (this.seen.has(key)) return null;
|
|
94
98
|
this.seen.add(key);
|
|
95
99
|
if (this.seen.size > MAX_REMEMBERED) this.seen.delete(this.seen.values().next().value);
|
|
@@ -99,32 +103,26 @@ class ApprovalLog {
|
|
|
99
103
|
// Reporting a decision against the wrong call would be worse than not reporting it.
|
|
100
104
|
if (!runId || !TOOL_RE.test(tool) || (!hasSeq && !call.byIndex)) {
|
|
101
105
|
this.count('unaddressable');
|
|
102
|
-
this.debug(`approval not reported: ${!runId ? 'the server gave no run id' : 'the call cannot be identified safely'} (${
|
|
106
|
+
this.debug(`approval not reported: ${!runId ? 'the server gave no run id' : 'the call cannot be identified safely'} (${kind}, call ${call.position})`);
|
|
103
107
|
return null;
|
|
104
108
|
}
|
|
105
109
|
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
110
|
const payload = Object.freeze({
|
|
114
111
|
clientEventId: this.uuid(),
|
|
115
112
|
chatId: String(conversation.chatId),
|
|
116
113
|
requestRunId: String(runId),
|
|
117
114
|
...(hasSeq ? { callSeq } : { callIndex: call.position }),
|
|
118
115
|
tool,
|
|
116
|
+
kind,
|
|
119
117
|
decision,
|
|
120
118
|
scope,
|
|
121
119
|
decidedAt: this.now().toISOString(),
|
|
122
120
|
});
|
|
123
|
-
this.queue.push({ payload,
|
|
121
|
+
this.queue.push({ payload, attempts: 0 });
|
|
124
122
|
while (this.queue.length > this.limit) {
|
|
125
123
|
// (never the one being sent right now)
|
|
126
|
-
|
|
127
|
-
this.giveUp(
|
|
124
|
+
this.queue.splice(this.inFlight ? 1 : 0, 1);
|
|
125
|
+
this.giveUp('the queue is full');
|
|
128
126
|
}
|
|
129
127
|
this.pump();
|
|
130
128
|
return payload;
|
|
@@ -144,9 +142,8 @@ class ApprovalLog {
|
|
|
144
142
|
this.timer = null;
|
|
145
143
|
}
|
|
146
144
|
|
|
147
|
-
giveUp(
|
|
145
|
+
giveUp(why) {
|
|
148
146
|
this.dropped++;
|
|
149
|
-
if (item.permission === 'tool') this.undelivered.add(item.call);
|
|
150
147
|
this.count('gave_up');
|
|
151
148
|
this.debug(`approval report given up: ${why}`);
|
|
152
149
|
}
|
|
@@ -162,32 +159,24 @@ class ApprovalLog {
|
|
|
162
159
|
if (generation !== this.generation) return;
|
|
163
160
|
const item = this.queue[0];
|
|
164
161
|
let wait = null;
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
162
|
+
try {
|
|
163
|
+
await this.transport.send(item.payload);
|
|
164
|
+
if (generation !== this.generation) return;
|
|
168
165
|
this.queue.shift();
|
|
169
|
-
this.count('
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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) {
|
|
174
175
|
this.queue.shift();
|
|
175
|
-
this.
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
|
|
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
|
-
}
|
|
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`);
|
|
191
180
|
}
|
|
192
181
|
}
|
|
193
182
|
this.inFlight = null;
|
|
@@ -212,4 +201,4 @@ class ApprovalLog {
|
|
|
212
201
|
}
|
|
213
202
|
}
|
|
214
203
|
|
|
215
|
-
module.exports = { ApprovalLog, decisionOf, SCOPES, RETRY_DELAYS_MS, MAX_QUEUED };
|
|
204
|
+
module.exports = { ApprovalLog, decisionOf, SCOPES, KINDS, RETRY_DELAYS_MS, MAX_QUEUED };
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* lib/approval-transport.js
|
|
5
5
|
* -----------------------------------------------------------------------------
|
|
6
|
-
* How an approval event reaches the backend (contract
|
|
6
|
+
* How an approval event reaches the backend (approval contract v2):
|
|
7
7
|
*
|
|
8
8
|
* 1. Socket.IO, on the connection that carries the chat, once subscribed: emit('chat:approval', payload, ack)
|
|
9
9
|
* 2. otherwise, or without an acknowledgement: POST /api/v1/chat/{chatId}/approvals (bearer token), same payload
|
|
@@ -11,20 +11,22 @@
|
|
|
11
11
|
* Both answer { ok: true, stepSeq } or { ok: false, error }. Both attempts carry the same clientEventId, so the server
|
|
12
12
|
* records the decision once even if it received both.
|
|
13
13
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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.
|
|
16
17
|
*/
|
|
17
18
|
|
|
18
19
|
const api = require('./api');
|
|
19
20
|
const { AuthError } = require('./errors');
|
|
20
21
|
|
|
21
|
-
/**
|
|
22
|
-
|
|
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;
|
|
22
|
+
/** The backend's approval contract v2 is deployed. There is no setting that changes this. */
|
|
23
|
+
const APPROVAL_REPORTING_ENABLED = true;
|
|
26
24
|
const ACK_TIMEOUT_MS = 5_000;
|
|
27
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' });
|
|
28
30
|
/** The contract's errors: each is the server's final answer about this event. */
|
|
29
31
|
const FINAL_ERRORS = Object.freeze(['unknown_call', 'conflict', 'forbidden', 'invalid']);
|
|
30
32
|
|
|
@@ -54,17 +56,33 @@ class ApprovalTransport {
|
|
|
54
56
|
* @param {object} session the chat session: its current token and realtime connection are used
|
|
55
57
|
* @param {{ ackTimeoutMs?: number, requestTimeoutMs?: number }} [opts] (tests use short timeouts)
|
|
56
58
|
*/
|
|
57
|
-
constructor(session, { ackTimeoutMs = ACK_TIMEOUT_MS, requestTimeoutMs = REQUEST_TIMEOUT_MS } = {}) {
|
|
59
|
+
constructor(session, { ackTimeoutMs = ACK_TIMEOUT_MS, requestTimeoutMs = REQUEST_TIMEOUT_MS, socketLimit = SOCKET_LIMIT, socketWindowMs = SOCKET_WINDOW_MS } = {}) {
|
|
58
60
|
this.session = session;
|
|
59
61
|
this.ackTimeoutMs = ackTimeoutMs;
|
|
60
62
|
this.requestTimeoutMs = requestTimeoutMs;
|
|
61
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
|
+
}
|
|
62
77
|
}
|
|
63
78
|
|
|
64
79
|
async send(payload) {
|
|
65
80
|
if (this.unsupported.has(payload.chatId)) throw final('unsupported');
|
|
66
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)
|
|
67
84
|
if (realtime && realtime.isLive(payload.chatId)) {
|
|
85
|
+
this.emitted.push(Date.now());
|
|
68
86
|
const ack = await realtime.emitWithAck('chat:approval', payload, this.ackTimeoutMs);
|
|
69
87
|
const answer = readAnswer(ack);
|
|
70
88
|
if (answer) return answer;
|
|
@@ -80,12 +98,12 @@ class ApprovalTransport {
|
|
|
80
98
|
} catch (err) {
|
|
81
99
|
const refusal = err.body ? bodyOf(err) : null;
|
|
82
100
|
if (refusal) return readAnswer(refusal);
|
|
83
|
-
if (err instanceof AuthError
|
|
84
|
-
if ([
|
|
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) {
|
|
85
104
|
this.unsupported.add(payload.chatId);
|
|
86
105
|
throw final('unsupported');
|
|
87
106
|
}
|
|
88
|
-
if (err.status === 400 || err.status === 422) throw final('invalid');
|
|
89
107
|
throw err; // the connection, a timeout, 408, 429 or a server error: retried
|
|
90
108
|
}
|
|
91
109
|
const answer = readAnswer(data);
|
package/lib/build-profile.json
CHANGED
package/lib/chat.js
CHANGED
|
@@ -123,7 +123,7 @@ class ChatSession {
|
|
|
123
123
|
this.declinedInstructions = null; // "file:hash" of instructions the user said no to this session
|
|
124
124
|
this.realtime = null;
|
|
125
125
|
this.socketWarned = false;
|
|
126
|
-
this.approvalReporting = APPROVAL_REPORTING_ENABLED; // (
|
|
126
|
+
this.approvalReporting = APPROVAL_REPORTING_ENABLED; // (tests may change it)
|
|
127
127
|
this.setToken(token);
|
|
128
128
|
}
|
|
129
129
|
|
|
@@ -998,7 +998,10 @@ function notificationsCommand(args = []) {
|
|
|
998
998
|
if (arg === 'test') {
|
|
999
999
|
const s = mgr.status();
|
|
1000
1000
|
if (!s.available) ui.warn(`Cannot show notifications: ${s.unavailableReason}.\n`);
|
|
1001
|
-
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
|
+
}
|
|
1002
1005
|
else ui.warn('The notification could not be sent.\n');
|
|
1003
1006
|
return;
|
|
1004
1007
|
}
|
package/lib/endpoints.js
CHANGED
|
@@ -52,7 +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
|
+
chatApprovals: 'POST /api/v1/chat/{chatId}/approvals', // the REST fallback of the approval contract
|
|
56
56
|
},
|
|
57
57
|
};
|
|
58
58
|
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* lib/mac-notify.js: show one macOS notification. Run by lib/notifier.js as its own short process:
|
|
5
|
+
*
|
|
6
|
+
* node lib/mac-notify.js <title> <body>
|
|
7
|
+
*
|
|
8
|
+
* `osascript -e 'display notification …'` posts as Script Editor. On a Mac that never allowed Script Editor to notify,
|
|
9
|
+
* macOS cannot ask for that permission on its behalf: the notification is accepted (exit 0) and never shown. So the
|
|
10
|
+
* notification is posted by a small applet of our own, "Korveniq AI", which macOS can ask about once and lists in
|
|
11
|
+
* System Settings > Notifications. It is built on this Mac with the system's own tools (osacompile, plutil, codesign),
|
|
12
|
+
* in the Korveniq settings folder, without sudo or downloads, with the Korveniq orb as its icon. If it cannot be built
|
|
13
|
+
* or opened, osascript is used.
|
|
14
|
+
*
|
|
15
|
+
* Title and body are only ever arguments, never script text.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
const cp = require('child_process');
|
|
21
|
+
|
|
22
|
+
const BUNDLE_ID = 'com.korveniq.cli.notifier';
|
|
23
|
+
const APP_FILE = 'Korveniq AI.app';
|
|
24
|
+
/** Raise when the applet changes: it is then built again. (A rebuilt applet may have to be allowed again.) */
|
|
25
|
+
const APPLET_VERSION = '2';
|
|
26
|
+
const MARK = '--korveniq-notify';
|
|
27
|
+
const ORB_ICON = path.join(__dirname, '..', 'assets', 'korveniq-orb.png');
|
|
28
|
+
const LSREGISTER = '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister';
|
|
29
|
+
|
|
30
|
+
// (opened any other way, for example by clicking a notification, it has no mark and does nothing)
|
|
31
|
+
const APPLET = `ObjC.import('Foundation');
|
|
32
|
+
function run() {
|
|
33
|
+
const args = ObjC.deepUnwrap($.NSProcessInfo.processInfo.arguments);
|
|
34
|
+
const at = args.indexOf('${MARK}');
|
|
35
|
+
if (at === -1) return;
|
|
36
|
+
const app = Application.currentApplication();
|
|
37
|
+
app.includeStandardAdditions = true;
|
|
38
|
+
app.displayNotification(args[at + 2], { withTitle: args[at + 1] });
|
|
39
|
+
delay(1);
|
|
40
|
+
}
|
|
41
|
+
`;
|
|
42
|
+
|
|
43
|
+
const exec = (command, args) => cp.execFileSync(command, args, { stdio: 'ignore', timeout: 4000 });
|
|
44
|
+
|
|
45
|
+
const versionFile = (app) => path.join(app, 'Contents', 'Resources', 'korveniq-version');
|
|
46
|
+
|
|
47
|
+
function installed(app) {
|
|
48
|
+
try {
|
|
49
|
+
return fs.readFileSync(versionFile(app), 'utf8') === APPLET_VERSION;
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Give the applet the Korveniq orb. Without it the notifications still work, so a failure here is ignored. */
|
|
56
|
+
function setIcon(app, run) {
|
|
57
|
+
try {
|
|
58
|
+
run('/usr/bin/sips', ['-s', 'format', 'icns', ORB_ICON, '--out', path.join(app, 'Contents', 'Resources', 'applet.icns')]);
|
|
59
|
+
} catch {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
// (newer macOS versions of osacompile add an asset catalogue, which would be preferred over the .icns file)
|
|
63
|
+
try {
|
|
64
|
+
run('/usr/bin/plutil', ['-remove', 'CFBundleIconName', path.join(app, 'Contents', 'Info.plist')]);
|
|
65
|
+
fs.rmSync(path.join(app, 'Contents', 'Resources', 'Assets.car'), { force: true });
|
|
66
|
+
} catch {
|
|
67
|
+
/* there is none */
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The applet in `dir`, built first if it is missing or old. Throws when it cannot be built. */
|
|
72
|
+
function ensureApplet(dir, run = exec) {
|
|
73
|
+
const app = path.join(dir, APP_FILE);
|
|
74
|
+
if (installed(app)) return app;
|
|
75
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
76
|
+
const stage = fs.mkdtempSync(path.join(dir, '.build-'));
|
|
77
|
+
try {
|
|
78
|
+
const source = path.join(stage, 'notify.js');
|
|
79
|
+
const built = path.join(stage, APP_FILE);
|
|
80
|
+
fs.writeFileSync(source, APPLET);
|
|
81
|
+
run('/usr/bin/osacompile', ['-l', 'JavaScript', '-o', built, source]);
|
|
82
|
+
const plist = path.join(built, 'Contents', 'Info.plist');
|
|
83
|
+
run('/usr/bin/plutil', ['-replace', 'CFBundleIdentifier', '-string', BUNDLE_ID, plist]);
|
|
84
|
+
run('/usr/bin/plutil', ['-replace', 'LSUIElement', '-bool', 'true', plist]); // no Dock icon
|
|
85
|
+
setIcon(built, run);
|
|
86
|
+
fs.writeFileSync(versionFile(built), APPLET_VERSION);
|
|
87
|
+
run('/usr/bin/codesign', ['--force', '--sign', '-', built]); // (the changes above broke the signature)
|
|
88
|
+
fs.rmSync(app, { recursive: true, force: true });
|
|
89
|
+
try {
|
|
90
|
+
fs.renameSync(built, app);
|
|
91
|
+
} catch (err) {
|
|
92
|
+
if (!installed(app)) throw err; // (another process built it first)
|
|
93
|
+
}
|
|
94
|
+
run(LSREGISTER, ['-f', app]);
|
|
95
|
+
return app;
|
|
96
|
+
} finally {
|
|
97
|
+
fs.rmSync(stage, { recursive: true, force: true });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** @returns {'applet'|'osascript'} how it was posted. Throws when neither way works. */
|
|
102
|
+
function deliver(title, body, { dir = path.join(require('./config').CONFIG_DIR, 'notifier'), run = exec } = {}) {
|
|
103
|
+
try {
|
|
104
|
+
run('/usr/bin/open', ['-n', '-g', ensureApplet(dir, run), '--args', MARK, title, body]);
|
|
105
|
+
return 'applet';
|
|
106
|
+
} catch (err) {
|
|
107
|
+
if (err.code === 'ETIMEDOUT') throw err; // it may still appear: posting it a second way could show it twice
|
|
108
|
+
run('/usr/bin/osascript', ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', title, body]);
|
|
109
|
+
return 'osascript';
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = { deliver, ensureApplet, BUNDLE_ID, APPLET };
|
|
114
|
+
|
|
115
|
+
if (require.main === module) {
|
|
116
|
+
try {
|
|
117
|
+
deliver(process.argv[2] || '', process.argv[3] || '');
|
|
118
|
+
} catch {
|
|
119
|
+
process.exitCode = 1; // the notifier then switches itself off for this session
|
|
120
|
+
}
|
|
121
|
+
}
|
package/lib/notifier.js
CHANGED
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
* org.freedesktop.Notifications.Notify on the session bus.
|
|
10
10
|
* Needs a desktop session (DBUS_SESSION_BUS_ADDRESS, DISPLAY or
|
|
11
11
|
* WAYLAND_DISPLAY); over plain SSH there is none.
|
|
12
|
-
* macOS osascript "display notification"
|
|
13
|
-
* Windows PowerShell + Windows.UI.Notifications toast
|
|
12
|
+
* macOS our own "Korveniq AI" applet (lib/mac-notify.js), else osascript "display notification"
|
|
13
|
+
* Windows PowerShell + Windows.UI.Notifications toast, as "Korveniq AI" with the orb (registered for this user
|
|
14
|
+
* under HKCU, no administrator rights; as PowerShell if that cannot be written)
|
|
14
15
|
*
|
|
15
16
|
* Safety:
|
|
16
17
|
* - The backend is found by scanning PATH (no process is started for that).
|
|
@@ -32,11 +33,13 @@ const { spawn } = require('child_process');
|
|
|
32
33
|
const { HIDDEN_CHARS_RE } = require('./sanitize');
|
|
33
34
|
|
|
34
35
|
const NOTIFY_TIMEOUT_MS = 5000;
|
|
36
|
+
const MAC_TIMEOUT_MS = 15_000; // the first notification also builds the applet
|
|
35
37
|
// The Korveniq orb (from the web app), shipped in the package. A theme icon
|
|
36
38
|
// name is the fallback if the file is missing.
|
|
37
39
|
const ORB_ICON = path.join(__dirname, '..', 'assets', 'korveniq-orb.png');
|
|
38
40
|
const icon = () => (fs.existsSync(ORB_ICON) ? ORB_ICON : 'dialog-information');
|
|
39
41
|
const APP_NAME = 'Korveniq AI';
|
|
42
|
+
const WINDOWS_APP_ID = 'Korveniq.CLI';
|
|
40
43
|
const MAX_TITLE = 80;
|
|
41
44
|
const MAX_BODY = 240;
|
|
42
45
|
|
|
@@ -90,17 +93,12 @@ function detectBackend(platform = process.platform, env = process.env) {
|
|
|
90
93
|
if (env.KORVENIQ_NOTIFY_BACKEND === 'none') return null;
|
|
91
94
|
|
|
92
95
|
if (platform === 'darwin') {
|
|
93
|
-
|
|
94
|
-
if (!osa) return null;
|
|
96
|
+
if (!which('osascript')) return null;
|
|
95
97
|
return {
|
|
96
|
-
name: '
|
|
97
|
-
command:
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
'-e', 'display notification (item 2 of argv) with title (item 1 of argv)',
|
|
101
|
-
'-e', 'end run',
|
|
102
|
-
title, body,
|
|
103
|
-
],
|
|
98
|
+
name: 'macos',
|
|
99
|
+
command: process.execPath,
|
|
100
|
+
timeoutMs: MAC_TIMEOUT_MS,
|
|
101
|
+
args: (title, body) => [path.join(__dirname, 'mac-notify.js'), title, body],
|
|
104
102
|
};
|
|
105
103
|
}
|
|
106
104
|
|
|
@@ -115,16 +113,20 @@ function detectBackend(platform = process.platform, env = process.env) {
|
|
|
115
113
|
'[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null',
|
|
116
114
|
'$t = [Security.SecurityElement]::Escape($env:KQ_NOTIFY_TITLE)',
|
|
117
115
|
'$b = [Security.SecurityElement]::Escape($env:KQ_NOTIFY_BODY)',
|
|
116
|
+
'$i = ""',
|
|
117
|
+
'if ($env:KQ_NOTIFY_ICON) { $i = "<image placement=`"appLogoOverride`" src=`"" + [Security.SecurityElement]::Escape($env:KQ_NOTIFY_ICON) + "`"/>" }',
|
|
118
118
|
'$xml = New-Object Windows.Data.Xml.Dom.XmlDocument',
|
|
119
|
-
'$xml.LoadXml("<toast><visual><binding template=`"ToastGeneric`"><text>$t</text><text>$b</text
|
|
120
|
-
|
|
119
|
+
'$xml.LoadXml("<toast><visual><binding template=`"ToastGeneric`"><text>$t</text><text>$b</text>$i</binding></visual></toast>")',
|
|
120
|
+
// The name and icon shown above a toast belong to its application id: ours, registered for this user only.
|
|
121
|
+
`$app = "${WINDOWS_APP_ID}"`,
|
|
122
|
+
`try { $k = "HKCU:\\Software\\Classes\\AppUserModelId\\${WINDOWS_APP_ID}"; if (-not (Test-Path $k)) { New-Item -Path $k -Force | Out-Null }; New-ItemProperty -Path $k -Name DisplayName -Value "${APP_NAME}" -PropertyType String -Force | Out-Null; if ($env:KQ_NOTIFY_ICON) { New-ItemProperty -Path $k -Name IconUri -Value $env:KQ_NOTIFY_ICON -PropertyType String -Force | Out-Null } } catch { $app = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe" }`,
|
|
121
123
|
'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app).Show([Windows.UI.Notifications.ToastNotification]::new($xml))',
|
|
122
124
|
].join('; ');
|
|
123
125
|
return {
|
|
124
126
|
name: 'powershell',
|
|
125
127
|
command: ps,
|
|
126
128
|
args: () => ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script],
|
|
127
|
-
env: (title, body) => ({ KQ_NOTIFY_TITLE: title, KQ_NOTIFY_BODY: body }),
|
|
129
|
+
env: (title, body) => ({ KQ_NOTIFY_TITLE: title, KQ_NOTIFY_BODY: body, KQ_NOTIFY_ICON: fs.existsSync(ORB_ICON) ? ORB_ICON : '' }),
|
|
128
130
|
};
|
|
129
131
|
}
|
|
130
132
|
|
|
@@ -217,7 +219,7 @@ class Notifier {
|
|
|
217
219
|
} catch {
|
|
218
220
|
/* gone */
|
|
219
221
|
}
|
|
220
|
-
}, NOTIFY_TIMEOUT_MS);
|
|
222
|
+
}, this.backend.timeoutMs || NOTIFY_TIMEOUT_MS);
|
|
221
223
|
timer.unref();
|
|
222
224
|
child.on('error', (err) => this.fail(err.message));
|
|
223
225
|
child.on('exit', (code) => {
|
package/lib/realtime.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* reconnect, because the server forgets subscriptions when a socket drops.
|
|
12
12
|
* - Routes chat:thinking / chat:delta / chat:completed / chat:failed to the
|
|
13
13
|
* watcher registered for that requestRunId.
|
|
14
|
-
* - Remembers the
|
|
14
|
+
* - Remembers the steps announced by chat:step, by sequence number, and sends events that are
|
|
15
15
|
* acknowledged (chat:approval).
|
|
16
16
|
*
|
|
17
17
|
* Events can arrive before POST /messages has returned the requestRunId, so
|
|
@@ -49,7 +49,7 @@ class Realtime {
|
|
|
49
49
|
this.bufferedCount = 0;
|
|
50
50
|
this.finished = new Set(); // runs whose watcher has stopped
|
|
51
51
|
this.subscription = null; // { socketId, chatId, promise }: one subscribe per connection and chat
|
|
52
|
-
this.steps = new Map(); // requestRunId -> Map(seq ->
|
|
52
|
+
this.steps = new Map(); // requestRunId -> Map(seq -> { type, tool, status })
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
get connected() {
|
|
@@ -177,16 +177,14 @@ class Realtime {
|
|
|
177
177
|
}
|
|
178
178
|
|
|
179
179
|
/**
|
|
180
|
-
* Keep what identifies a
|
|
181
|
-
*
|
|
182
|
-
* else is ignored.
|
|
180
|
+
* Keep what identifies a step from a chat:step event, { requestRunId, step: { seq, type, tool, status, … } }. A step
|
|
181
|
+
* that arrives again with the same seq replaces the one kept.
|
|
183
182
|
*/
|
|
184
183
|
_noteStep(payload) {
|
|
185
184
|
if (!payload || typeof payload !== 'object') return;
|
|
186
|
-
const
|
|
187
|
-
const run = payload.requestRunId ?? step.requestRunId;
|
|
185
|
+
const { requestRunId: run, step } = payload;
|
|
188
186
|
if ((typeof run !== 'string' && typeof run !== 'number') || run === '') return;
|
|
189
|
-
if (step
|
|
187
|
+
if (!step || typeof step !== 'object' || !Number.isSafeInteger(step.seq) || typeof step.type !== 'string') return;
|
|
190
188
|
const runId = String(run);
|
|
191
189
|
let steps = this.steps.get(runId);
|
|
192
190
|
if (!steps) {
|
|
@@ -194,12 +192,15 @@ class Realtime {
|
|
|
194
192
|
this.steps.set(runId, steps);
|
|
195
193
|
if (this.steps.size > MAX_STEP_RUNS) this.steps.delete(this.steps.keys().next().value);
|
|
196
194
|
}
|
|
197
|
-
if (steps.size < MAX_STEPS_PER_RUN) steps.set(step.seq, step.tool);
|
|
195
|
+
if (steps.has(step.seq) || steps.size < MAX_STEPS_PER_RUN) steps.set(step.seq, { type: step.type, tool: step.tool, status: step.status });
|
|
198
196
|
}
|
|
199
197
|
|
|
200
198
|
/** The tool_call steps announced for a run, in order: [{ seq, tool }]. */
|
|
201
199
|
toolCallSteps(requestRunId) {
|
|
202
|
-
return [...(this.steps.get(String(requestRunId)) || [])]
|
|
200
|
+
return [...(this.steps.get(String(requestRunId)) || [])]
|
|
201
|
+
.filter(([, s]) => s.type === 'tool_call' && typeof s.tool === 'string')
|
|
202
|
+
.map(([seq, s]) => ({ seq, tool: s.tool }))
|
|
203
|
+
.sort((a, b) => a.seq - b.seq);
|
|
203
204
|
}
|
|
204
205
|
|
|
205
206
|
/** Emit an event and wait for its acknowledgement; null if there is none in time (or no connection). */
|
package/lib/tool-parser.js
CHANGED
|
@@ -328,6 +328,7 @@ function findRegions(text) {
|
|
|
328
328
|
let lastBlockEnd = -1; // a block may directly follow another one on the same line
|
|
329
329
|
let orphanBudget = ORPHAN_SCAN_BUDGET;
|
|
330
330
|
const lineOf = protocol.lineTracker(text);
|
|
331
|
+
let uncountedAt = Infinity;
|
|
331
332
|
for (;;) {
|
|
332
333
|
while (fi < fences.length && fences[fi].start < cursor) fi++;
|
|
333
334
|
const fence = fences[fi] || null;
|
|
@@ -340,6 +341,9 @@ function findRegions(text) {
|
|
|
340
341
|
if (!cand || cand.index >= limit) break;
|
|
341
342
|
pos = cand.index + 1;
|
|
342
343
|
const open = protocol.readOpenTag(text, cand.index);
|
|
344
|
+
if (!open && uncountedAt === Infinity && text.startsWith('<tool_call>', cand.index) && protocol.isStructuralAt(text, lineOf(cand.index), cand.index)) {
|
|
345
|
+
uncountedAt = cand.index; // a block of its own line that is not read as a call (its body is not JSON)
|
|
346
|
+
}
|
|
343
347
|
if (!open || open === 'wait') continue;
|
|
344
348
|
const structural =
|
|
345
349
|
protocol.isStructuralAt(text, lineOf(cand.index), cand.index) ||
|
|
@@ -407,6 +411,8 @@ function findRegions(text) {
|
|
|
407
411
|
}
|
|
408
412
|
break;
|
|
409
413
|
}
|
|
414
|
+
// The server may count that block as a call: the position of whatever follows it is not certain.
|
|
415
|
+
for (const r of regions) if (r.start > uncountedAt) r.positionUnclear = true;
|
|
410
416
|
return regions;
|
|
411
417
|
}
|
|
412
418
|
|
|
@@ -450,7 +456,9 @@ function extractToolCalls({ text = '', message = null, nonces = null, markerHint
|
|
|
450
456
|
text = text.replace(/\r\n/g, '\n'); // CRLF would break line-based fence detection
|
|
451
457
|
|
|
452
458
|
const calls = [];
|
|
459
|
+
let unclearFrom = -1; // the first call whose position in the reply the server may count differently
|
|
453
460
|
for (const r of findRegions(text)) {
|
|
461
|
+
if (r.positionUnclear && unclearFrom === -1) unclearFrom = calls.length;
|
|
454
462
|
if (calls.length >= MAX_CALLS_PER_REPLY) {
|
|
455
463
|
calls.push({ name: null, error: `Too many tool calls in one reply (the limit is ${MAX_CALLS_PER_REPLY}). The rest were not run; send them in the next reply.` });
|
|
456
464
|
break;
|
|
@@ -522,6 +530,8 @@ function extractToolCalls({ text = '', message = null, nonces = null, markerHint
|
|
|
522
530
|
});
|
|
523
531
|
}
|
|
524
532
|
}
|
|
533
|
+
// (not enumerable: it is about reporting approvals, not part of the call)
|
|
534
|
+
if (unclearFrom !== -1) for (const c of calls.slice(unclearFrom)) Object.defineProperty(c, 'positionUnclear', { value: true });
|
|
525
535
|
return calls;
|
|
526
536
|
}
|
|
527
537
|
|
package/lib/tools.js
CHANGED
|
@@ -1202,7 +1202,7 @@ class ToolRunner {
|
|
|
1202
1202
|
* In autonomous mode the answer is 'yes' without asking, except for a call
|
|
1203
1203
|
* guessed from a Markdown code block (`fallback`), which still asks.
|
|
1204
1204
|
*/
|
|
1205
|
-
async approve(question, { allowAlways = false, fallback = false, alwaysHint = 'yes to all new files in this project', risk = null, allowUnrestricted = false, permission = 'tool', reach = undefined } = {}) {
|
|
1205
|
+
async approve(question, { allowAlways = false, fallback = false, alwaysHint = 'yes to all new files in this project', risk = null, allowUnrestricted = false, permission = 'tool', reach = undefined, alsoNetwork = false } = {}) {
|
|
1206
1206
|
if (this.headless) return this.headlessApprove({ fallback, risk });
|
|
1207
1207
|
if (!this.interactive) {
|
|
1208
1208
|
resultLine('Refused: approval needs an interactive terminal.', theme.warn);
|
|
@@ -1225,6 +1225,10 @@ class ToolRunner {
|
|
|
1225
1225
|
const ref = this.approvalRef;
|
|
1226
1226
|
const decided = (answer, cancelled = false) => {
|
|
1227
1227
|
this.approvals.record({ ref, answer, cancelled, permission, reach });
|
|
1228
|
+
// A yes that also lets this command use the network is reported as its own network decision.
|
|
1229
|
+
if (alsoNetwork && !cancelled && (answer === 'yes' || answer === 'always')) {
|
|
1230
|
+
this.approvals.record({ ref, answer, permission: 'command_network', reach: { yes: 'once', always: 'session' } });
|
|
1231
|
+
}
|
|
1228
1232
|
return answer;
|
|
1229
1233
|
};
|
|
1230
1234
|
try {
|
|
@@ -1312,9 +1316,10 @@ class ToolRunner {
|
|
|
1312
1316
|
const results = [];
|
|
1313
1317
|
let rejected = false;
|
|
1314
1318
|
let previous = null; // the call before this one, for repeated read-only calls
|
|
1315
|
-
// The position of a call identifies it to the server
|
|
1316
|
-
//
|
|
1317
|
-
|
|
1319
|
+
// The position of a call identifies it to the server. A malformed or unreadable block keeps its own position there too.
|
|
1320
|
+
// How a misplaced block, a Markdown code block or a block that is not read as a call is counted is not specified, so
|
|
1321
|
+
// positions from one of those on are not used.
|
|
1322
|
+
const unclear = calls.findIndex((c) => c.misplaced || c.fallback || c.positionUnclear);
|
|
1318
1323
|
for (const [position, call] of calls.entries()) {
|
|
1319
1324
|
const key = !call.error && !call.fallback && REPEATABLE_TOOLS.has(call.name) ? `${call.name}:${canonicalJson(call.args)}` : null;
|
|
1320
1325
|
if (key && previous === key) {
|
|
@@ -1627,7 +1632,9 @@ class ToolRunner {
|
|
|
1627
1632
|
risk,
|
|
1628
1633
|
allowAlways: mode === 'auto' && Boolean(netHint),
|
|
1629
1634
|
alwaysHint: 'network on for the rest of autonomous mode',
|
|
1630
|
-
|
|
1635
|
+
// "yes" to a command that was asked about for its network use, and "network on for the rest of autonomous mode"
|
|
1636
|
+
alsoNetwork: mode === 'auto' && Boolean(netHint),
|
|
1637
|
+
reach: { always: 'once' },
|
|
1631
1638
|
allowUnrestricted: mode !== 'headless' && det.available && profile.allowUnsandboxed,
|
|
1632
1639
|
});
|
|
1633
1640
|
if (answer === 'no') {
|