alineo 0.3.0 → 0.4.0
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/dist/index.d.mts +294 -8
- package/dist/index.mjs +537 -30
- package/dist/pi-bridge.js +238 -5
- package/dist/pi-permission-gate.js +337 -0
- package/package.json +4 -4
package/dist/pi-bridge.js
CHANGED
|
@@ -4,9 +4,12 @@ var createInterface = require("readline").createInterface;
|
|
|
4
4
|
var http = require("http");
|
|
5
5
|
var fs = require("fs");
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
var
|
|
7
|
+
// Paths/port are fixed in the sandbox; the env overrides exist only so the bridge can be
|
|
8
|
+
// driven against a stub `pi` in unit tests (test/pi-bridge.test.ts).
|
|
9
|
+
var PORT = Number(process.env.ALINEO_BRIDGE_PORT) || 3001;
|
|
10
|
+
var ENV_FILE = process.env.ALINEO_ENV_FILE || "/etc/alineo-env";
|
|
11
|
+
var PI_CONFIG_FILE = process.env.ALINEO_PI_CONFIG || "/etc/alineo-pi.json";
|
|
12
|
+
var PI_BIN = process.env.ALINEO_PI_BIN || "pi";
|
|
10
13
|
|
|
11
14
|
// Re-read /etc/alineo-env into process.env on each Pi (re)start so setEnv() changes take effect.
|
|
12
15
|
function loadEnv() {
|
|
@@ -19,7 +22,12 @@ function loadEnv() {
|
|
|
19
22
|
}
|
|
20
23
|
|
|
21
24
|
// Build the pi CLI args from /etc/alineo-pi.json (model/provider config, written by the host).
|
|
22
|
-
// Supports: provider, model, resume (--continue to resume the most recent session)
|
|
25
|
+
// Supports: provider, model, resume (--continue to resume the most recent session),
|
|
26
|
+
// permissions (loads the alineo permission-gate extension by explicit path).
|
|
27
|
+
// `POLICY_ACTIVE` gates the permission-request routing below and is set here, before Pi
|
|
28
|
+
// is ever spawned, so there is no window where Pi could emit a gate dialog first.
|
|
29
|
+
var POLICY_ACTIVE = false;
|
|
30
|
+
var PERMISSION_GATE_PATH = process.env.ALINEO_PERMISSION_GATE_PATH || "/alineo-permission-gate.js";
|
|
23
31
|
function buildPiArgs() {
|
|
24
32
|
var args = ["--mode", "rpc", "--approve"];
|
|
25
33
|
try {
|
|
@@ -28,6 +36,10 @@ function buildPiArgs() {
|
|
|
28
36
|
if (cfg.provider) args.push("--provider", cfg.provider);
|
|
29
37
|
if (cfg.model) args.push("--model", cfg.model);
|
|
30
38
|
if (cfg.resume) args.push("--continue");
|
|
39
|
+
if (cfg.permissions && fs.existsSync(PERMISSION_GATE_PATH)) {
|
|
40
|
+
POLICY_ACTIVE = true;
|
|
41
|
+
args.push("-e", PERMISSION_GATE_PATH);
|
|
42
|
+
}
|
|
31
43
|
}
|
|
32
44
|
} catch {}
|
|
33
45
|
return args;
|
|
@@ -70,8 +82,100 @@ var state = {
|
|
|
70
82
|
queue: [], // pending items: { message, streamingBehavior?, res, text, t0 }
|
|
71
83
|
gen: 0, // incremented on every (re)start; guards against stale async callbacks
|
|
72
84
|
pendingCmds: {}, // id → { res, timer, bash? } — commands waiting for Pi's response ack
|
|
85
|
+
pendingPermissions: {}, // pi extension_ui_request id → { tool, target, title, timer }
|
|
86
|
+
permissionChannel: null, // { res } — long-lived SSE sink for permission_request when no prompt is active
|
|
73
87
|
};
|
|
74
88
|
|
|
89
|
+
// Permission-gate dialogs whose title starts with this marker are held + routed to the host
|
|
90
|
+
// instead of auto-cancelled. Must match adapters/pi-permission-gate.js's MARKER.
|
|
91
|
+
var PERM_MARKER = "ALINEO_PERM ";
|
|
92
|
+
var PERMISSION_TIMEOUT_MS = 300000; // 5 min, matches Cline's desktop auto-deny
|
|
93
|
+
|
|
94
|
+
// Push a permission event to every live SSE sink: the active prompt stream (so a caller
|
|
95
|
+
// iterating prompt() sees it inline) AND the dedicated /permission-stream channel (so an
|
|
96
|
+
// attached operator sees it even between / across prompts). Both may be present.
|
|
97
|
+
function emitPermission(obj) {
|
|
98
|
+
var line = "data: " + JSON.stringify(obj) + "\n\n";
|
|
99
|
+
var sinks = [state.active, state.permissionChannel];
|
|
100
|
+
for (var i = 0; i < sinks.length; i++) {
|
|
101
|
+
if (sinks[i] && sinks[i].res) {
|
|
102
|
+
try {
|
|
103
|
+
sinks[i].res.write(line);
|
|
104
|
+
} catch {}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Answer a held Pi extension_ui_request. `value` is a JSON string the gate parses;
|
|
110
|
+
// omit it (pass null) to send { cancelled: true } instead.
|
|
111
|
+
function answerPermission(id, value) {
|
|
112
|
+
if (value === null) rpc({ type: "extension_ui_response", id: id, cancelled: true });
|
|
113
|
+
else rpc({ type: "extension_ui_response", id: id, value: value });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Auto-resolve every OTHER pending permission for the same tool — opencode's "one decision
|
|
117
|
+
// clears the batch" for an "always" (allow) or "reject" (deny) verdict.
|
|
118
|
+
function resolveMatchingPending(exceptId, tool, verdict) {
|
|
119
|
+
Object.keys(state.pendingPermissions).forEach(function (pid) {
|
|
120
|
+
if (pid === exceptId) return;
|
|
121
|
+
var p = state.pendingPermissions[pid];
|
|
122
|
+
if (p.tool !== tool) return;
|
|
123
|
+
clearTimeout(p.timer);
|
|
124
|
+
delete state.pendingPermissions[pid];
|
|
125
|
+
answerPermission(
|
|
126
|
+
pid,
|
|
127
|
+
verdict === "allow"
|
|
128
|
+
? JSON.stringify({ verdict: "allow", scope: "once" })
|
|
129
|
+
: JSON.stringify({ verdict: "reject" }),
|
|
130
|
+
);
|
|
131
|
+
emitPermission({
|
|
132
|
+
type: "permission_resolved",
|
|
133
|
+
requestId: pid,
|
|
134
|
+
decision: verdict === "allow" ? { kind: "once" } : { kind: "reject" },
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Time a held permission request out: answer the gate as cancelled + tell the host.
|
|
140
|
+
function expirePermission(pid) {
|
|
141
|
+
if (!state.pendingPermissions[pid]) return;
|
|
142
|
+
delete state.pendingPermissions[pid];
|
|
143
|
+
answerPermission(pid, null);
|
|
144
|
+
emitPermission({ type: "permission_resolved", requestId: pid, decision: { kind: "reject" } });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// While a caller is attached to /permission-stream a human is present, so the auto-deny
|
|
148
|
+
// timeout is suspended; it's re-armed (fresh full window) when they disconnect.
|
|
149
|
+
function suspendPermissionTimers() {
|
|
150
|
+
Object.keys(state.pendingPermissions).forEach(function (pid) {
|
|
151
|
+
var p = state.pendingPermissions[pid];
|
|
152
|
+
if (p.timer) {
|
|
153
|
+
clearTimeout(p.timer);
|
|
154
|
+
p.timer = null;
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
function resumePermissionTimers() {
|
|
159
|
+
Object.keys(state.pendingPermissions).forEach(function (pid) {
|
|
160
|
+
var p = state.pendingPermissions[pid];
|
|
161
|
+
if (!p.timer) {
|
|
162
|
+
p.timer = setTimeout(function () {
|
|
163
|
+
expirePermission(pid);
|
|
164
|
+
}, PERMISSION_TIMEOUT_MS);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Fail every held permission request (pi restart, abort, exit).
|
|
170
|
+
function cancelPendingPermissions() {
|
|
171
|
+
Object.keys(state.pendingPermissions).forEach(function (pid) {
|
|
172
|
+
var p = state.pendingPermissions[pid];
|
|
173
|
+
clearTimeout(p.timer);
|
|
174
|
+
answerPermission(pid, null);
|
|
175
|
+
});
|
|
176
|
+
state.pendingPermissions = {};
|
|
177
|
+
}
|
|
178
|
+
|
|
75
179
|
// Fail all in-flight pendingCmds cleanly, handling bash (SSE) vs regular (JSON) responses.
|
|
76
180
|
function cleanupPendingCmds(reason) {
|
|
77
181
|
Object.keys(state.pendingCmds).forEach(function (id) {
|
|
@@ -99,6 +203,7 @@ function startPi() {
|
|
|
99
203
|
state.active = null;
|
|
100
204
|
}
|
|
101
205
|
cleanupPendingCmds("pi restarted");
|
|
206
|
+
cancelPendingPermissions();
|
|
102
207
|
|
|
103
208
|
if (state.rl) {
|
|
104
209
|
try {
|
|
@@ -120,7 +225,7 @@ function startPi() {
|
|
|
120
225
|
var gen = ++state.gen;
|
|
121
226
|
log("pi start gen=" + gen + ": " + args.join(" "));
|
|
122
227
|
|
|
123
|
-
var proc = spawn(
|
|
228
|
+
var proc = spawn(PI_BIN, args, {
|
|
124
229
|
stdio: ["pipe", "pipe", "pipe"],
|
|
125
230
|
env: Object.assign({}, process.env),
|
|
126
231
|
});
|
|
@@ -141,6 +246,7 @@ function startPi() {
|
|
|
141
246
|
state.proc = null;
|
|
142
247
|
state.ready = false;
|
|
143
248
|
cleanupPendingCmds("pi exited");
|
|
249
|
+
cancelPendingPermissions();
|
|
144
250
|
if (state.active) {
|
|
145
251
|
stopHeartbeat(state.active.heartbeat);
|
|
146
252
|
state.active.res.write("data: " + JSON.stringify({ error: "pi exited" }) + "\n\n");
|
|
@@ -285,6 +391,43 @@ function handleLine(line) {
|
|
|
285
391
|
// We auto-cancel them immediately so Pi never stalls — even when there is no active prompt.
|
|
286
392
|
// Fire-and-forget methods need no response; we just forward them.
|
|
287
393
|
if (ev.type === "extension_ui_request") {
|
|
394
|
+
// alineo permission-gate dialog: title is `ALINEO_PERM {json}`. Hold it open, route it
|
|
395
|
+
// to the host as a permission_request, and wait for POST /permission-response.
|
|
396
|
+
if (
|
|
397
|
+
POLICY_ACTIVE &&
|
|
398
|
+
ev.method === "select" &&
|
|
399
|
+
ev.id &&
|
|
400
|
+
typeof ev.title === "string" &&
|
|
401
|
+
ev.title.indexOf(PERM_MARKER) === 0
|
|
402
|
+
) {
|
|
403
|
+
var meta = {};
|
|
404
|
+
try {
|
|
405
|
+
meta = JSON.parse(ev.title.slice(PERM_MARKER.length));
|
|
406
|
+
} catch {}
|
|
407
|
+
var entry = {
|
|
408
|
+
tool: meta.tool || "unknown",
|
|
409
|
+
target: meta.target || "",
|
|
410
|
+
title: meta.title || "Approve tool call",
|
|
411
|
+
since: Date.now(),
|
|
412
|
+
timer: null,
|
|
413
|
+
};
|
|
414
|
+
// No auto-deny clock while a human is watching the permission stream.
|
|
415
|
+
if (!state.permissionChannel) {
|
|
416
|
+
entry.timer = setTimeout(function () {
|
|
417
|
+
expirePermission(ev.id);
|
|
418
|
+
}, PERMISSION_TIMEOUT_MS);
|
|
419
|
+
}
|
|
420
|
+
state.pendingPermissions[ev.id] = entry;
|
|
421
|
+
emitPermission({
|
|
422
|
+
type: "permission_request",
|
|
423
|
+
requestId: ev.id,
|
|
424
|
+
tool: entry.tool,
|
|
425
|
+
target: entry.target,
|
|
426
|
+
title: entry.title,
|
|
427
|
+
});
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
|
|
288
431
|
var DIALOG_METHODS = ["select", "confirm", "input", "editor"];
|
|
289
432
|
var isDialog = DIALOG_METHODS.indexOf(ev.method) !== -1;
|
|
290
433
|
var uiParams = {};
|
|
@@ -534,6 +677,63 @@ http
|
|
|
534
677
|
res.end(logBuf.join("\n"));
|
|
535
678
|
return;
|
|
536
679
|
}
|
|
680
|
+
if (req.url === "/permission-stream") {
|
|
681
|
+
// Long-lived SSE sink so permission_request events surface even when no prompt()
|
|
682
|
+
// stream is open. One at a time — a new subscriber replaces the old.
|
|
683
|
+
if (state.permissionChannel) {
|
|
684
|
+
try {
|
|
685
|
+
state.permissionChannel.res.end();
|
|
686
|
+
} catch {}
|
|
687
|
+
}
|
|
688
|
+
res.writeHead(200, {
|
|
689
|
+
"Content-Type": "text/event-stream",
|
|
690
|
+
"Cache-Control": "no-cache",
|
|
691
|
+
Connection: "keep-alive",
|
|
692
|
+
});
|
|
693
|
+
var pHeartbeat = startHeartbeat(res);
|
|
694
|
+
state.permissionChannel = { res: res };
|
|
695
|
+
// A reconnecting operator needs to see what's still outstanding, and the auto-deny
|
|
696
|
+
// clock pauses while they're attached.
|
|
697
|
+
suspendPermissionTimers();
|
|
698
|
+
Object.keys(state.pendingPermissions).forEach(function (pid) {
|
|
699
|
+
var p = state.pendingPermissions[pid];
|
|
700
|
+
try {
|
|
701
|
+
res.write(
|
|
702
|
+
"data: " +
|
|
703
|
+
JSON.stringify({
|
|
704
|
+
type: "permission_request",
|
|
705
|
+
requestId: pid,
|
|
706
|
+
tool: p.tool,
|
|
707
|
+
target: p.target,
|
|
708
|
+
title: p.title,
|
|
709
|
+
}) +
|
|
710
|
+
"\n\n",
|
|
711
|
+
);
|
|
712
|
+
} catch {}
|
|
713
|
+
});
|
|
714
|
+
req.on("close", function () {
|
|
715
|
+
stopHeartbeat(pHeartbeat);
|
|
716
|
+
if (state.permissionChannel && state.permissionChannel.res === res) {
|
|
717
|
+
state.permissionChannel = null;
|
|
718
|
+
resumePermissionTimers();
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
if (req.url === "/pending-permissions") {
|
|
724
|
+
var pending = Object.keys(state.pendingPermissions).map(function (pid) {
|
|
725
|
+
var p = state.pendingPermissions[pid];
|
|
726
|
+
return {
|
|
727
|
+
requestId: pid,
|
|
728
|
+
tool: p.tool,
|
|
729
|
+
target: p.target,
|
|
730
|
+
title: p.title,
|
|
731
|
+
since: p.since || 0,
|
|
732
|
+
};
|
|
733
|
+
});
|
|
734
|
+
respond(res, 200, { ok: true, data: { pending: pending } });
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
537
737
|
if (req.url === "/messages") {
|
|
538
738
|
rpcWithAck({ id: "gm" + Date.now(), type: "get_messages" }, res);
|
|
539
739
|
return;
|
|
@@ -617,6 +817,9 @@ http
|
|
|
617
817
|
|
|
618
818
|
case "/abort":
|
|
619
819
|
// End the active SSE stream immediately, drain the queue, then wait for Pi's ack.
|
|
820
|
+
// A held permission request would leave Pi's tool_call hook awaiting forever —
|
|
821
|
+
// reject each so the abort can actually unwind.
|
|
822
|
+
cancelPendingPermissions();
|
|
620
823
|
state.queue.length = 0;
|
|
621
824
|
if (state.active) {
|
|
622
825
|
stopHeartbeat(state.active.heartbeat);
|
|
@@ -631,6 +834,36 @@ http
|
|
|
631
834
|
rpcWithAck({ id: "s" + Date.now(), type: "steer", message: data.message || "" }, res);
|
|
632
835
|
return;
|
|
633
836
|
|
|
837
|
+
case "/permission-response": {
|
|
838
|
+
var pp = state.pendingPermissions[data.requestId];
|
|
839
|
+
if (!pp) {
|
|
840
|
+
respond(res, 404, { ok: false, error: "no such pending permission" });
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
clearTimeout(pp.timer);
|
|
844
|
+
delete state.pendingPermissions[data.requestId];
|
|
845
|
+
var decision = data.decision || {};
|
|
846
|
+
if (decision.kind === "once") {
|
|
847
|
+
answerPermission(data.requestId, JSON.stringify({ verdict: "allow", scope: "once" }));
|
|
848
|
+
} else if (decision.kind === "always") {
|
|
849
|
+
answerPermission(data.requestId, JSON.stringify({ verdict: "allow", scope: "always" }));
|
|
850
|
+
resolveMatchingPending(data.requestId, pp.tool, "allow");
|
|
851
|
+
} else {
|
|
852
|
+
answerPermission(
|
|
853
|
+
data.requestId,
|
|
854
|
+
JSON.stringify({ verdict: "reject", feedback: decision.feedback || "" }),
|
|
855
|
+
);
|
|
856
|
+
resolveMatchingPending(data.requestId, pp.tool, "reject");
|
|
857
|
+
}
|
|
858
|
+
emitPermission({
|
|
859
|
+
type: "permission_resolved",
|
|
860
|
+
requestId: data.requestId,
|
|
861
|
+
decision: decision,
|
|
862
|
+
});
|
|
863
|
+
respond(res, 200, { ok: true });
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
|
|
634
867
|
case "/follow-up":
|
|
635
868
|
rpcWithAck(
|
|
636
869
|
{ id: "fu" + Date.now(), type: "follow_up", message: data.message || "" },
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* alineo permission gate — a Pi extension loaded via `-e /alineo-permission-gate.js` when
|
|
3
|
+
* `AgentSpec.permissions` is set to anything other than "auto".
|
|
4
|
+
*
|
|
5
|
+
* It reads the normalized policy from /etc/alineo-pi.json (written by
|
|
6
|
+
* `packages/agent/src/adapters/pi.ts`'s `configure()`), and:
|
|
7
|
+
* - on `session_start`, applies `restrictToTools` / `disabledTools` via Pi's
|
|
8
|
+
* `setActiveTools` so the model never sees a tool it may not use;
|
|
9
|
+
* - on every `tool_call`, decides allow / deny / rate-limit / classify / ask. An "ask"
|
|
10
|
+
* call blocks on `ctx.ui.select()` with a marker-prefixed title that `pi-bridge.js`
|
|
11
|
+
* recognizes, holds open, and forwards to the host as a `permission_request` — resolved
|
|
12
|
+
* by a matching POST to `/permission-response`.
|
|
13
|
+
*
|
|
14
|
+
* The matcher here mirrors `packages/agent/src/permissions.ts` (kept in sync by hand — a
|
|
15
|
+
* jiti-loaded extension can't import from the published `alineo` package it sits beside;
|
|
16
|
+
* same tradeoff pi-bridge.js already makes). `test/permissions.test.ts` covers the TS copy;
|
|
17
|
+
* `test/pi-permission-gate.test.ts` covers this one.
|
|
18
|
+
*/
|
|
19
|
+
import { readFileSync } from "node:fs";
|
|
20
|
+
|
|
21
|
+
const CONFIG_FILE = process.env.ALINEO_PI_CONFIG || "/etc/alineo-pi.json";
|
|
22
|
+
/** Title prefix pi-bridge.js keys on to route a select() dialog to the host instead of auto-cancelling. */
|
|
23
|
+
const MARKER = "ALINEO_PERM ";
|
|
24
|
+
|
|
25
|
+
/** Mirror of `permissions.ts` SAFE_BASH_COMMANDS. */
|
|
26
|
+
const SAFE_BASH_COMMANDS = new Set([
|
|
27
|
+
"ls",
|
|
28
|
+
"cat",
|
|
29
|
+
"head",
|
|
30
|
+
"tail",
|
|
31
|
+
"grep",
|
|
32
|
+
"rg",
|
|
33
|
+
"egrep",
|
|
34
|
+
"fgrep",
|
|
35
|
+
"zgrep",
|
|
36
|
+
"find",
|
|
37
|
+
"pwd",
|
|
38
|
+
"whoami",
|
|
39
|
+
"id",
|
|
40
|
+
"env",
|
|
41
|
+
"printenv",
|
|
42
|
+
"echo",
|
|
43
|
+
"printf",
|
|
44
|
+
"which",
|
|
45
|
+
"type",
|
|
46
|
+
"file",
|
|
47
|
+
"stat",
|
|
48
|
+
"wc",
|
|
49
|
+
"date",
|
|
50
|
+
"uname",
|
|
51
|
+
"hostname",
|
|
52
|
+
"df",
|
|
53
|
+
"du",
|
|
54
|
+
"tree",
|
|
55
|
+
"basename",
|
|
56
|
+
"dirname",
|
|
57
|
+
"realpath",
|
|
58
|
+
"readlink",
|
|
59
|
+
"true",
|
|
60
|
+
"false",
|
|
61
|
+
"cmp",
|
|
62
|
+
"diff",
|
|
63
|
+
"column",
|
|
64
|
+
"nl",
|
|
65
|
+
"less",
|
|
66
|
+
"more",
|
|
67
|
+
"tac",
|
|
68
|
+
"hexdump",
|
|
69
|
+
"xxd",
|
|
70
|
+
"od",
|
|
71
|
+
"strings",
|
|
72
|
+
"sha1sum",
|
|
73
|
+
"sha256sum",
|
|
74
|
+
"md5sum",
|
|
75
|
+
"cksum",
|
|
76
|
+
]);
|
|
77
|
+
const SAFE_GIT_SUBCOMMANDS = new Set([
|
|
78
|
+
"status",
|
|
79
|
+
"log",
|
|
80
|
+
"diff",
|
|
81
|
+
"show",
|
|
82
|
+
"branch",
|
|
83
|
+
"remote",
|
|
84
|
+
"rev-parse",
|
|
85
|
+
"describe",
|
|
86
|
+
"blame",
|
|
87
|
+
"tag",
|
|
88
|
+
"config",
|
|
89
|
+
"ls-files",
|
|
90
|
+
"ls-tree",
|
|
91
|
+
"shortlog",
|
|
92
|
+
"reflog",
|
|
93
|
+
"cat-file",
|
|
94
|
+
"for-each-ref",
|
|
95
|
+
"whatchanged",
|
|
96
|
+
"rev-list",
|
|
97
|
+
"name-rev",
|
|
98
|
+
"symbolic-ref",
|
|
99
|
+
"count-objects",
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
/** @returns {{default: string, rules: Array, disabledTools: string[], restrictToTools: string[]} | null} */
|
|
103
|
+
function loadPolicy() {
|
|
104
|
+
try {
|
|
105
|
+
const cfg = JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
|
|
106
|
+
const p = cfg && cfg.permissions;
|
|
107
|
+
if (!p || typeof p !== "object") return null;
|
|
108
|
+
return {
|
|
109
|
+
default: p.default || "ask",
|
|
110
|
+
rules: Array.isArray(p.rules) ? p.rules : [],
|
|
111
|
+
disabledTools: Array.isArray(p.disabledTools) ? p.disabledTools : [],
|
|
112
|
+
restrictToTools: Array.isArray(p.restrictToTools) ? p.restrictToTools : [],
|
|
113
|
+
};
|
|
114
|
+
} catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const WRAPPER_COMMANDS = new Set(["env", "command", "nice", "stdbuf", "time"]);
|
|
120
|
+
|
|
121
|
+
// Linear scan for a file output redirection — no regex (ReDoS-safe). A `>` next to `&`
|
|
122
|
+
// (`2>&1`, `>&2`), preceded by a digit (`2>`), or preceded by `&` is an fd op, not a write.
|
|
123
|
+
function hasOutputRedirect(seg) {
|
|
124
|
+
for (let i = 0; i < seg.length; i++) {
|
|
125
|
+
if (seg[i] !== ">") continue;
|
|
126
|
+
const next = seg[i + 1];
|
|
127
|
+
const prev = seg[i - 1];
|
|
128
|
+
if (next === "&" || prev === "&" || (prev >= "0" && prev <= "9")) continue;
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Mirror of `permissions.ts` isReadOnlyBashCommand. */
|
|
135
|
+
function isReadOnlyBashCommand(command) {
|
|
136
|
+
const segments = String(command)
|
|
137
|
+
.split(/&&|\|\||[;\n|]/)
|
|
138
|
+
.map((s) => s.trim())
|
|
139
|
+
.filter(Boolean);
|
|
140
|
+
if (segments.length === 0) return false;
|
|
141
|
+
return segments.every((seg) => {
|
|
142
|
+
if (hasOutputRedirect(seg)) return false;
|
|
143
|
+
let tokens = seg.split(/\s+/).filter(Boolean);
|
|
144
|
+
while (tokens.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) {
|
|
145
|
+
tokens = tokens.slice(1);
|
|
146
|
+
}
|
|
147
|
+
while (tokens.length > 1 && WRAPPER_COMMANDS.has(tokens[0])) tokens = tokens.slice(1);
|
|
148
|
+
if (tokens[0] === "timeout" && tokens.length > 2) tokens = tokens.slice(2);
|
|
149
|
+
const first = tokens[0] || "";
|
|
150
|
+
const slash = first.lastIndexOf("/");
|
|
151
|
+
const cmd = slash === -1 ? first : first.slice(slash + 1);
|
|
152
|
+
if (!cmd) return false;
|
|
153
|
+
if (SAFE_BASH_COMMANDS.has(cmd)) return true;
|
|
154
|
+
if (cmd === "git" && SAFE_GIT_SUBCOMMANDS.has(tokens[1] || "")) return true;
|
|
155
|
+
return false;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Tool-specific target string, pulled from Pi's typed `event.input`. */
|
|
160
|
+
function targetOf(toolName, input) {
|
|
161
|
+
if (!input || typeof input !== "object") return "";
|
|
162
|
+
switch (toolName) {
|
|
163
|
+
case "bash":
|
|
164
|
+
case "powershell":
|
|
165
|
+
return String(input.command ?? "");
|
|
166
|
+
case "read":
|
|
167
|
+
case "write":
|
|
168
|
+
case "edit":
|
|
169
|
+
case "ls":
|
|
170
|
+
return String(input.path ?? "");
|
|
171
|
+
case "grep":
|
|
172
|
+
return String(input.pattern ?? input.query ?? "");
|
|
173
|
+
case "find":
|
|
174
|
+
return String(input.pattern ?? input.name ?? "");
|
|
175
|
+
default:
|
|
176
|
+
try {
|
|
177
|
+
return JSON.stringify(input);
|
|
178
|
+
} catch {
|
|
179
|
+
return "";
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function globToRegExp(glob) {
|
|
185
|
+
const body = String(glob)
|
|
186
|
+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
187
|
+
.replace(/\*/g, ".*")
|
|
188
|
+
.replace(/\?/g, ".");
|
|
189
|
+
return new RegExp(`^${body}$`, "s");
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function ruleMatches(rule, toolName, target) {
|
|
193
|
+
if (!globToRegExp(rule.tool).test(toolName)) return false;
|
|
194
|
+
if (
|
|
195
|
+
rule.pattern !== undefined &&
|
|
196
|
+
rule.pattern !== null &&
|
|
197
|
+
!globToRegExp(rule.pattern).test(target)
|
|
198
|
+
) {
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function evaluate(policy, toolName, target) {
|
|
205
|
+
if (policy.disabledTools.indexOf(toolName) !== -1) return { action: "deny" };
|
|
206
|
+
let match;
|
|
207
|
+
for (const rule of policy.rules) {
|
|
208
|
+
if (ruleMatches(rule, toolName, target)) match = rule;
|
|
209
|
+
}
|
|
210
|
+
let action = match ? match.action : policy.default;
|
|
211
|
+
if (action === "classify") {
|
|
212
|
+
action = toolName === "bash" && isReadOnlyBashCommand(target) ? "allow" : "ask";
|
|
213
|
+
}
|
|
214
|
+
return { action, rule: match };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Rolling-window rate limiter, keyed per rule. */
|
|
218
|
+
const rateHits = new Map();
|
|
219
|
+
function underLimit(rule, key) {
|
|
220
|
+
if (!rule || !rule.limit) return true;
|
|
221
|
+
const now = Date.now();
|
|
222
|
+
const windowStart = now - rule.limit.windowMs;
|
|
223
|
+
const hits = (rateHits.get(key) || []).filter((t) => t >= windowStart);
|
|
224
|
+
if (hits.length >= rule.limit.count) {
|
|
225
|
+
rateHits.set(key, hits);
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
hits.push(now);
|
|
229
|
+
rateHits.set(key, hits);
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Apply `restrictToTools` (allowlist) then `disabledTools` (denylist) to the model's
|
|
235
|
+
* visible toolset. Best-effort: `setActiveTools` may not exist on older Pi — the
|
|
236
|
+
* `tool_call` deny backstop still covers `disabledTools` in that case.
|
|
237
|
+
*/
|
|
238
|
+
function applyToolset(pi, policy) {
|
|
239
|
+
if (typeof pi.setActiveTools !== "function" || typeof pi.getActiveTools !== "function") {
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
let active = pi.getActiveTools();
|
|
243
|
+
if (!Array.isArray(active)) return;
|
|
244
|
+
if (policy.restrictToTools.length > 0) {
|
|
245
|
+
active = active.filter((t) => policy.restrictToTools.indexOf(t) !== -1);
|
|
246
|
+
}
|
|
247
|
+
if (policy.disabledTools.length > 0) {
|
|
248
|
+
active = active.filter((t) => policy.disabledTools.indexOf(t) === -1);
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
pi.setActiveTools(active);
|
|
252
|
+
} catch {}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export default function (pi) {
|
|
256
|
+
const policy = loadPolicy();
|
|
257
|
+
if (!policy) return; // shouldn't happen — the extension is only loaded when a policy exists
|
|
258
|
+
|
|
259
|
+
// Action methods (setActiveTools) can't be called during extension load — only from a
|
|
260
|
+
// lifecycle hook once the runtime is up. Re-applying is idempotent (getActiveTools()
|
|
261
|
+
// returns the already-filtered set), so run it on session start and before every turn
|
|
262
|
+
// in case Pi re-registers tools.
|
|
263
|
+
if (policy.restrictToTools.length > 0 || policy.disabledTools.length > 0) {
|
|
264
|
+
const apply = () => {
|
|
265
|
+
applyToolset(pi, policy);
|
|
266
|
+
};
|
|
267
|
+
pi.on("session_start", apply);
|
|
268
|
+
pi.on("before_agent_start", apply);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Session-scoped "always allow" memory, keyed tool + target. */
|
|
272
|
+
const alwaysAllow = new Set();
|
|
273
|
+
|
|
274
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
275
|
+
const toolName = event.toolName;
|
|
276
|
+
const target = targetOf(toolName, event.input);
|
|
277
|
+
const key = `${toolName} ${target}`;
|
|
278
|
+
|
|
279
|
+
if (alwaysAllow.has(key)) return undefined;
|
|
280
|
+
|
|
281
|
+
const { action, rule } = evaluate(policy, toolName, target);
|
|
282
|
+
|
|
283
|
+
if (action === "allow") return undefined;
|
|
284
|
+
if (action === "deny") {
|
|
285
|
+
return {
|
|
286
|
+
block: true,
|
|
287
|
+
reason: `The operator's policy denies this tool call: ${toolName} ${target}`.trim(),
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
if (action === "rate_limit") {
|
|
291
|
+
return underLimit(rule, key)
|
|
292
|
+
? undefined
|
|
293
|
+
: {
|
|
294
|
+
block: true,
|
|
295
|
+
reason: `Rate limit reached for ${toolName}. Wait before trying this again, or take a different approach.`,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// action === "ask"
|
|
300
|
+
if (!ctx.hasUI) {
|
|
301
|
+
return {
|
|
302
|
+
block: true,
|
|
303
|
+
reason: "This tool call needs operator approval, but no UI is attached.",
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const title =
|
|
308
|
+
MARKER + JSON.stringify({ tool: toolName, target, title: `Run ${toolName}: ${target}` });
|
|
309
|
+
let raw;
|
|
310
|
+
try {
|
|
311
|
+
raw = await ctx.ui.select(title, ["decide"]);
|
|
312
|
+
} catch {
|
|
313
|
+
raw = undefined;
|
|
314
|
+
}
|
|
315
|
+
if (raw === undefined || raw === null) {
|
|
316
|
+
return { block: true, reason: "Approval request was cancelled or timed out." };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
let decision;
|
|
320
|
+
try {
|
|
321
|
+
decision = JSON.parse(raw);
|
|
322
|
+
} catch {
|
|
323
|
+
decision = { verdict: "reject" };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (decision.verdict === "allow") {
|
|
327
|
+
if (decision.scope === "always") alwaysAllow.add(key);
|
|
328
|
+
return undefined;
|
|
329
|
+
}
|
|
330
|
+
return {
|
|
331
|
+
block: true,
|
|
332
|
+
reason: decision.feedback
|
|
333
|
+
? `The operator declined this and said: ${decision.feedback}`
|
|
334
|
+
: "The operator declined this tool call.",
|
|
335
|
+
};
|
|
336
|
+
});
|
|
337
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "alineo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -28,9 +28,9 @@
|
|
|
28
28
|
"test": "bun test"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@alineo-labs/core": "0.
|
|
32
|
-
"@alineo-labs/memory": "0.2.
|
|
33
|
-
"@alineo-labs/sandbox": "0.
|
|
31
|
+
"@alineo-labs/core": "0.4.0",
|
|
32
|
+
"@alineo-labs/memory": "0.2.1",
|
|
33
|
+
"@alineo-labs/sandbox": "0.4.0",
|
|
34
34
|
"zod": "^4.4.3"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|