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/index.mjs
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { Sandbox } from "@alineo-labs/sandbox";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
+
import { LedgerEvent, WorkflowError } from "@alineo-labs/core";
|
|
3
4
|
import { existsSync } from "fs";
|
|
4
5
|
import * as z$1 from "zod";
|
|
5
|
-
import { WorkflowError } from "@alineo-labs/core";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
8
8
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
9
9
|
import { dirname } from "node:path";
|
|
10
|
+
import { createServer } from "node:http";
|
|
10
11
|
//#region src/config.ts
|
|
11
12
|
const CONFIG_FILE = "alineo.config.json";
|
|
12
13
|
const DEFAULT_CONFIG = {
|
|
@@ -101,26 +102,53 @@ const CredentialEnvBindingSchema = z$1.object({
|
|
|
101
102
|
credential: z$1.string({ error: "Each credential env binding must have a 'credential' string" }),
|
|
102
103
|
host: z$1.string({ error: "Each credential env binding must have a 'host' string" }),
|
|
103
104
|
pathPrefix: z$1.string().optional(),
|
|
104
|
-
injection: z$1.union([
|
|
105
|
-
z$1.
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
z$1.
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
105
|
+
injection: z$1.union([z$1.object({
|
|
106
|
+
type: z$1.literal("header"),
|
|
107
|
+
name: z$1.string()
|
|
108
|
+
}), z$1.object({
|
|
109
|
+
type: z$1.literal("substitution"),
|
|
110
|
+
placeholder: z$1.string(),
|
|
111
|
+
in: z$1.array(z$1.enum([
|
|
112
|
+
"path",
|
|
113
|
+
"query",
|
|
114
|
+
"header",
|
|
115
|
+
"body"
|
|
116
|
+
])).min(1)
|
|
117
|
+
})]),
|
|
118
|
+
approval: z$1.literal("hold").optional()
|
|
118
119
|
}).loose();
|
|
119
120
|
const SetupStepSchema = z$1.object({
|
|
120
121
|
name: z$1.string({ error: "Each setup step must have a 'name' string" }),
|
|
121
122
|
run: z$1.string({ error: "Each setup step must have a 'run' string" }),
|
|
122
123
|
cwd: z$1.string().optional()
|
|
123
124
|
}).loose();
|
|
125
|
+
const PermissionActionSchema = z$1.enum([
|
|
126
|
+
"allow",
|
|
127
|
+
"ask",
|
|
128
|
+
"deny",
|
|
129
|
+
"rate_limit",
|
|
130
|
+
"classify"
|
|
131
|
+
]);
|
|
132
|
+
const PermissionRuleSchema = z$1.object({
|
|
133
|
+
tool: z$1.string({ error: "Each permission rule must have a 'tool' string" }),
|
|
134
|
+
pattern: z$1.string().optional(),
|
|
135
|
+
action: PermissionActionSchema,
|
|
136
|
+
limit: z$1.object({
|
|
137
|
+
count: z$1.number().int().positive(),
|
|
138
|
+
windowMs: z$1.number().int().positive()
|
|
139
|
+
}).optional()
|
|
140
|
+
}).loose();
|
|
141
|
+
const PermissionPolicySchema = z$1.object({
|
|
142
|
+
default: PermissionActionSchema.optional(),
|
|
143
|
+
rules: z$1.array(PermissionRuleSchema).optional(),
|
|
144
|
+
disabledTools: z$1.array(z$1.string()).optional(),
|
|
145
|
+
restrictToTools: z$1.array(z$1.string()).optional()
|
|
146
|
+
}).loose();
|
|
147
|
+
const PermissionsSchema = z$1.union([z$1.enum([
|
|
148
|
+
"auto",
|
|
149
|
+
"ask",
|
|
150
|
+
"readonly"
|
|
151
|
+
]), PermissionPolicySchema]);
|
|
124
152
|
const nonNegativeIntSpecField = (fieldName) => z$1.number({ error: `Agent spec '${fieldName}' must be a non-negative integer if set` }).int(`Agent spec '${fieldName}' must be a non-negative integer if set`).nonnegative(`Agent spec '${fieldName}' must be a non-negative integer if set`).optional();
|
|
125
153
|
const AgentSpecSchema = z$1.object({
|
|
126
154
|
$schema: z$1.string().optional(),
|
|
@@ -146,7 +174,8 @@ const AgentSpecSchema = z$1.object({
|
|
|
146
174
|
spawnDepth: nonNegativeIntSpecField("spawnDepth"),
|
|
147
175
|
maxAgents: nonNegativeIntSpecField("maxAgents"),
|
|
148
176
|
teamId: z$1.string().optional(),
|
|
149
|
-
resourceId: z$1.string().optional()
|
|
177
|
+
resourceId: z$1.string().optional(),
|
|
178
|
+
permissions: PermissionsSchema.optional()
|
|
150
179
|
}).loose();
|
|
151
180
|
/**
|
|
152
181
|
* Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
|
|
@@ -163,8 +192,181 @@ function validateAgentSpec(data) {
|
|
|
163
192
|
return result.data;
|
|
164
193
|
}
|
|
165
194
|
//#endregion
|
|
195
|
+
//#region src/permissions.ts
|
|
196
|
+
/** Read-only built-in tools — auto-allowed (and the entire toolset) under `"readonly"`. */
|
|
197
|
+
const READ_ONLY_TOOLS = [
|
|
198
|
+
"read",
|
|
199
|
+
"grep",
|
|
200
|
+
"find",
|
|
201
|
+
"ls"
|
|
202
|
+
];
|
|
203
|
+
/**
|
|
204
|
+
* First tokens that make a shell command a pure reader — used by the `"classify"` action
|
|
205
|
+
* and by the `bash` rule `"readonly"` installs. Deliberately conservative: an unrecognised
|
|
206
|
+
* command falls through to `ask`, never to `allow`.
|
|
207
|
+
*/
|
|
208
|
+
const SAFE_BASH_COMMANDS = [
|
|
209
|
+
"ls",
|
|
210
|
+
"cat",
|
|
211
|
+
"head",
|
|
212
|
+
"tail",
|
|
213
|
+
"grep",
|
|
214
|
+
"rg",
|
|
215
|
+
"egrep",
|
|
216
|
+
"fgrep",
|
|
217
|
+
"zgrep",
|
|
218
|
+
"find",
|
|
219
|
+
"pwd",
|
|
220
|
+
"whoami",
|
|
221
|
+
"id",
|
|
222
|
+
"env",
|
|
223
|
+
"printenv",
|
|
224
|
+
"echo",
|
|
225
|
+
"printf",
|
|
226
|
+
"which",
|
|
227
|
+
"type",
|
|
228
|
+
"file",
|
|
229
|
+
"stat",
|
|
230
|
+
"wc",
|
|
231
|
+
"date",
|
|
232
|
+
"uname",
|
|
233
|
+
"hostname",
|
|
234
|
+
"df",
|
|
235
|
+
"du",
|
|
236
|
+
"tree",
|
|
237
|
+
"basename",
|
|
238
|
+
"dirname",
|
|
239
|
+
"realpath",
|
|
240
|
+
"readlink",
|
|
241
|
+
"true",
|
|
242
|
+
"false",
|
|
243
|
+
"cmp",
|
|
244
|
+
"diff",
|
|
245
|
+
"column",
|
|
246
|
+
"nl",
|
|
247
|
+
"less",
|
|
248
|
+
"more",
|
|
249
|
+
"tac",
|
|
250
|
+
"hexdump",
|
|
251
|
+
"xxd",
|
|
252
|
+
"od",
|
|
253
|
+
"strings",
|
|
254
|
+
"sha1sum",
|
|
255
|
+
"sha256sum",
|
|
256
|
+
"md5sum",
|
|
257
|
+
"cksum"
|
|
258
|
+
];
|
|
259
|
+
/** `git <sub>` combinations that only read. */
|
|
260
|
+
const SAFE_GIT_SUBCOMMANDS = [
|
|
261
|
+
"status",
|
|
262
|
+
"log",
|
|
263
|
+
"diff",
|
|
264
|
+
"show",
|
|
265
|
+
"branch",
|
|
266
|
+
"remote",
|
|
267
|
+
"rev-parse",
|
|
268
|
+
"describe",
|
|
269
|
+
"blame",
|
|
270
|
+
"tag",
|
|
271
|
+
"config",
|
|
272
|
+
"ls-files",
|
|
273
|
+
"ls-tree",
|
|
274
|
+
"shortlog",
|
|
275
|
+
"reflog",
|
|
276
|
+
"cat-file",
|
|
277
|
+
"for-each-ref",
|
|
278
|
+
"whatchanged",
|
|
279
|
+
"rev-list",
|
|
280
|
+
"name-rev",
|
|
281
|
+
"symbolic-ref",
|
|
282
|
+
"count-objects"
|
|
283
|
+
];
|
|
284
|
+
function expandMode(mode) {
|
|
285
|
+
switch (mode) {
|
|
286
|
+
case "auto": return;
|
|
287
|
+
case "ask": return {
|
|
288
|
+
default: "ask",
|
|
289
|
+
rules: [],
|
|
290
|
+
disabledTools: [],
|
|
291
|
+
restrictToTools: []
|
|
292
|
+
};
|
|
293
|
+
case "readonly": return {
|
|
294
|
+
default: "ask",
|
|
295
|
+
rules: [...READ_ONLY_TOOLS.map((tool) => ({
|
|
296
|
+
tool,
|
|
297
|
+
action: "allow"
|
|
298
|
+
})), {
|
|
299
|
+
tool: "bash",
|
|
300
|
+
action: "classify"
|
|
301
|
+
}],
|
|
302
|
+
disabledTools: [],
|
|
303
|
+
restrictToTools: [...READ_ONLY_TOOLS]
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Turn `AgentSpec.permissions` into the normalized policy the gate consumes, or `undefined`
|
|
309
|
+
* when no gate is needed (unset, or `"auto"`).
|
|
310
|
+
*/
|
|
311
|
+
function normalizePermissions(input) {
|
|
312
|
+
if (input === void 0) return void 0;
|
|
313
|
+
if (typeof input === "string") return expandMode(input);
|
|
314
|
+
return {
|
|
315
|
+
default: input.default ?? "ask",
|
|
316
|
+
rules: input.rules ?? [],
|
|
317
|
+
disabledTools: input.disabledTools ?? [],
|
|
318
|
+
restrictToTools: input.restrictToTools ?? []
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
const WRAPPER_COMMANDS = /* @__PURE__ */ new Set([
|
|
322
|
+
"env",
|
|
323
|
+
"command",
|
|
324
|
+
"nice",
|
|
325
|
+
"stdbuf",
|
|
326
|
+
"time"
|
|
327
|
+
]);
|
|
328
|
+
/**
|
|
329
|
+
* True if `seg` contains a file output redirection (`> file`, `>> file`). A `>` immediately
|
|
330
|
+
* followed by `&` (`2>&1`, `>&2`), preceded by a digit (`2>`, stderr), or preceded by `&`
|
|
331
|
+
* is a file-descriptor op, not a file write. Linear scan — no regex (ReDoS-safe).
|
|
332
|
+
*/
|
|
333
|
+
function hasOutputRedirect(seg) {
|
|
334
|
+
for (let i = 0; i < seg.length; i++) {
|
|
335
|
+
if (seg[i] !== ">") continue;
|
|
336
|
+
const next = seg[i + 1];
|
|
337
|
+
const prev = seg[i - 1];
|
|
338
|
+
if (next === "&" || prev === "&" || prev >= "0" && prev <= "9") continue;
|
|
339
|
+
return true;
|
|
340
|
+
}
|
|
341
|
+
return false;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
|
|
345
|
+
* recognised pure reader with no output redirection; `false` = something needs a human.
|
|
346
|
+
* Mirrored verbatim in `adapters/pi-permission-gate.js`.
|
|
347
|
+
*/
|
|
348
|
+
function isReadOnlyBashCommand(command) {
|
|
349
|
+
const segments = command.split(/&&|\|\||[;\n|]/).map((s) => s.trim()).filter(Boolean);
|
|
350
|
+
if (segments.length === 0) return false;
|
|
351
|
+
return segments.every((seg) => {
|
|
352
|
+
if (hasOutputRedirect(seg)) return false;
|
|
353
|
+
let tokens = seg.split(/\s+/).filter(Boolean);
|
|
354
|
+
while (tokens.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) tokens = tokens.slice(1);
|
|
355
|
+
while (tokens.length > 1 && WRAPPER_COMMANDS.has(tokens[0])) tokens = tokens.slice(1);
|
|
356
|
+
if (tokens[0] === "timeout" && tokens.length > 2) tokens = tokens.slice(2);
|
|
357
|
+
const first = tokens[0] ?? "";
|
|
358
|
+
const slash = first.lastIndexOf("/");
|
|
359
|
+
const cmd = slash === -1 ? first : first.slice(slash + 1);
|
|
360
|
+
if (!cmd) return false;
|
|
361
|
+
if (SAFE_BASH_COMMANDS.includes(cmd)) return true;
|
|
362
|
+
if (cmd === "git" && SAFE_GIT_SUBCOMMANDS.includes(tokens[1] ?? "")) return true;
|
|
363
|
+
return false;
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
166
367
|
//#region src/adapters/pi.ts
|
|
167
368
|
const BRIDGE_SCRIPT = readFileSync(fileURLToPath(new URL("./pi-bridge.js", import.meta.url)), "utf8");
|
|
369
|
+
const PERMISSION_GATE_SCRIPT = readFileSync(fileURLToPath(new URL("./pi-permission-gate.js", import.meta.url)), "utf8");
|
|
168
370
|
function toShellExports(env) {
|
|
169
371
|
return Object.entries(env).map(([k, v]) => `export ${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`).join("\n") + "\n";
|
|
170
372
|
}
|
|
@@ -211,7 +413,8 @@ function extractCredentialBindings(env) {
|
|
|
211
413
|
source: soleRef ? {
|
|
212
414
|
type: "env",
|
|
213
415
|
varName: soleRef[1]
|
|
214
|
-
} : { type: "external" }
|
|
416
|
+
} : { type: "external" },
|
|
417
|
+
...value.approval ? { approval: value.approval } : {}
|
|
215
418
|
});
|
|
216
419
|
}
|
|
217
420
|
return out;
|
|
@@ -282,9 +485,12 @@ var PiAdapter = class {
|
|
|
282
485
|
if (spec.provider) piConfig.provider = spec.provider;
|
|
283
486
|
if (spec.model) piConfig.model = spec.model;
|
|
284
487
|
if (opts?.resume) piConfig.resume = true;
|
|
488
|
+
const permissions = normalizePermissions(spec.permissions);
|
|
489
|
+
if (permissions) piConfig.permissions = permissions;
|
|
285
490
|
await sb.writeFile("/etc/alineo-pi.json", JSON.stringify(piConfig));
|
|
286
491
|
await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
|
|
287
492
|
await sb.writeFile("/alineo-bridge.js", BRIDGE_SCRIPT);
|
|
493
|
+
if (permissions) await sb.writeFile("/alineo-permission-gate.js", PERMISSION_GATE_SCRIPT);
|
|
288
494
|
}
|
|
289
495
|
/**
|
|
290
496
|
* Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the
|
|
@@ -339,6 +545,17 @@ var PiAdapter = class {
|
|
|
339
545
|
async abort() {
|
|
340
546
|
await rpcPost(this.bridgeUrl, "/abort");
|
|
341
547
|
}
|
|
548
|
+
/** Resolve a pending `permission_request` (see `AgentEvent`'s `permission_request`). */
|
|
549
|
+
async resolvePermission(requestId, decision) {
|
|
550
|
+
await rpcPost(this.bridgeUrl, "/permission-response", {
|
|
551
|
+
requestId,
|
|
552
|
+
decision
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
/** Tool calls currently paused awaiting a human decision. */
|
|
556
|
+
async listPendingPermissions() {
|
|
557
|
+
return (await rpcGet(this.bridgeUrl, "/pending-permissions")).pending;
|
|
558
|
+
}
|
|
342
559
|
async followUp(message) {
|
|
343
560
|
await rpcPost(this.bridgeUrl, "/follow-up", { message });
|
|
344
561
|
}
|
|
@@ -476,17 +693,25 @@ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeo
|
|
|
476
693
|
const decoder = new TextDecoder();
|
|
477
694
|
let buf = "";
|
|
478
695
|
let lastEventAt = Date.now();
|
|
696
|
+
const pendingPermissions = /* @__PURE__ */ new Set();
|
|
479
697
|
let reachedNaturalEnd = false;
|
|
480
698
|
try {
|
|
481
699
|
while (true) {
|
|
700
|
+
const awaitingHuman = pendingPermissions.size > 0;
|
|
482
701
|
const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
|
|
483
|
-
if (remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
702
|
+
if (!awaitingHuman && remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
484
703
|
const result = await Promise.race([reader.read(), new Promise((resolve) => {
|
|
485
704
|
setTimeout(() => {
|
|
486
705
|
resolve("timeout");
|
|
487
|
-
}, remainingMs);
|
|
706
|
+
}, awaitingHuman ? inactivityTimeoutMs : Math.max(remainingMs, 1));
|
|
488
707
|
})]);
|
|
489
|
-
if (result === "timeout")
|
|
708
|
+
if (result === "timeout") {
|
|
709
|
+
if (pendingPermissions.size > 0) {
|
|
710
|
+
lastEventAt = Date.now();
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
714
|
+
}
|
|
490
715
|
const { done, value } = result;
|
|
491
716
|
if (done) {
|
|
492
717
|
reachedNaturalEnd = true;
|
|
@@ -501,6 +726,8 @@ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeo
|
|
|
501
726
|
if (payload === "[DONE]") return;
|
|
502
727
|
const raw = JSON.parse(payload);
|
|
503
728
|
if (raw.error) throw new Error(`Bridge error: ${raw.error}`);
|
|
729
|
+
if (raw.type === "permission_request") pendingPermissions.add(raw.requestId);
|
|
730
|
+
else if (raw.type === "permission_resolved") pendingPermissions.delete(raw.requestId);
|
|
504
731
|
lastEventAt = Date.now();
|
|
505
732
|
yield raw;
|
|
506
733
|
}
|
|
@@ -618,6 +845,156 @@ function resolveParentMaxAgents(envValue, override) {
|
|
|
618
845
|
return raw;
|
|
619
846
|
}
|
|
620
847
|
//#endregion
|
|
848
|
+
//#region src/agent/egress-approval.ts
|
|
849
|
+
const DEDUP_TTL_MS = 3e4;
|
|
850
|
+
var EgressApprovalGate = class {
|
|
851
|
+
server;
|
|
852
|
+
port = 0;
|
|
853
|
+
sandbox;
|
|
854
|
+
handler;
|
|
855
|
+
webhookHost;
|
|
856
|
+
/** host → the held credentials bound to it. */
|
|
857
|
+
byHost = /* @__PURE__ */ new Map();
|
|
858
|
+
/** Hosts still gated — dropped once permanently opened by `allow-always`. */
|
|
859
|
+
held = /* @__PURE__ */ new Set();
|
|
860
|
+
/** host → last time we raised a request for it (dedup; the webhook fires per DNS query). */
|
|
861
|
+
seen = /* @__PURE__ */ new Map();
|
|
862
|
+
/** Hosts with a decision currently in flight. */
|
|
863
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
864
|
+
/** Hosts approved `allow-once` — reversed on `endTurn()`. */
|
|
865
|
+
onceApproved = /* @__PURE__ */ new Set();
|
|
866
|
+
constructor(opts) {
|
|
867
|
+
this.handler = opts.handler;
|
|
868
|
+
this.webhookHost = opts.webhookHost ?? process.env.ALINEO_EGRESS_APPROVAL_HOST ?? "172.17.0.1";
|
|
869
|
+
for (const held of opts.heldCredentials) {
|
|
870
|
+
const host = normalizeHost(held.binding.host);
|
|
871
|
+
this.held.add(host);
|
|
872
|
+
const list = this.byHost.get(host);
|
|
873
|
+
if (list) list.push(held);
|
|
874
|
+
else this.byHost.set(host, [held]);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
/** Attach the sandbox whose egress this gate manages. Called once its handle exists. */
|
|
878
|
+
bind(sandbox) {
|
|
879
|
+
this.sandbox = sandbox;
|
|
880
|
+
}
|
|
881
|
+
sb() {
|
|
882
|
+
if (!this.sandbox) throw new Error("EgressApprovalGate.bind() has not been called");
|
|
883
|
+
return this.sandbox;
|
|
884
|
+
}
|
|
885
|
+
/** Start the listener. Idempotent. */
|
|
886
|
+
async start() {
|
|
887
|
+
if (this.server) return;
|
|
888
|
+
const server = createServer((req, res) => {
|
|
889
|
+
if (req.method !== "POST" || (req.url ?? "").split("?")[0] !== "/egress-deny") {
|
|
890
|
+
res.writeHead(404).end();
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
let raw = "";
|
|
894
|
+
req.on("data", (c) => raw += c);
|
|
895
|
+
req.on("end", () => {
|
|
896
|
+
res.writeHead(200).end("ok");
|
|
897
|
+
let body = null;
|
|
898
|
+
try {
|
|
899
|
+
body = JSON.parse(raw);
|
|
900
|
+
} catch {
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
const host = body?.hostname ? normalizeHost(body.hostname) : void 0;
|
|
904
|
+
if (host) this.onDenied(host);
|
|
905
|
+
});
|
|
906
|
+
});
|
|
907
|
+
await new Promise((resolve, reject) => {
|
|
908
|
+
server.once("error", reject);
|
|
909
|
+
server.listen(0, "0.0.0.0", () => {
|
|
910
|
+
const addr = server.address();
|
|
911
|
+
this.port = typeof addr === "object" && addr ? addr.port : 0;
|
|
912
|
+
resolve();
|
|
913
|
+
});
|
|
914
|
+
});
|
|
915
|
+
server.unref();
|
|
916
|
+
this.server = server;
|
|
917
|
+
}
|
|
918
|
+
/** Stop the listener. */
|
|
919
|
+
async stop() {
|
|
920
|
+
const server = this.server;
|
|
921
|
+
this.server = void 0;
|
|
922
|
+
if (!server) return;
|
|
923
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
924
|
+
}
|
|
925
|
+
/** The `OPENSANDBOX_EGRESS_DENY_WEBHOOK` value to put in the sandbox's env. */
|
|
926
|
+
get webhookUrl() {
|
|
927
|
+
if (!this.server) throw new Error("EgressApprovalGate.start() has not been called");
|
|
928
|
+
return `http://${this.webhookHost}:${this.port}/egress-deny`;
|
|
929
|
+
}
|
|
930
|
+
/** Egress requests currently awaiting a decision. */
|
|
931
|
+
pending() {
|
|
932
|
+
return [...this.inFlight].map((host) => ({
|
|
933
|
+
host,
|
|
934
|
+
since: this.seen.get(host) ?? Date.now()
|
|
935
|
+
}));
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Reverse every `allow-once` approval — remove its credential(s) and re-deny the host.
|
|
939
|
+
* Call when an agent turn ends so a one-shot grant does not silently persist.
|
|
940
|
+
*/
|
|
941
|
+
async endTurn() {
|
|
942
|
+
const toRevert = [...this.onceApproved].filter((h) => this.held.has(h));
|
|
943
|
+
this.onceApproved.clear();
|
|
944
|
+
for (const host of toRevert) {
|
|
945
|
+
for (const held of this.byHost.get(host) ?? []) if (held.value !== "") await this.sb().credentials.remove(held.name).catch(() => {});
|
|
946
|
+
await this.sb().egress.patch([{
|
|
947
|
+
action: "deny",
|
|
948
|
+
target: host
|
|
949
|
+
}]);
|
|
950
|
+
this.seen.delete(host);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
async onDenied(host) {
|
|
954
|
+
if (!this.held.has(host)) return;
|
|
955
|
+
const now = Date.now();
|
|
956
|
+
const last = this.seen.get(host);
|
|
957
|
+
if (last !== void 0 && now - last < DEDUP_TTL_MS) return;
|
|
958
|
+
if (this.inFlight.has(host)) return;
|
|
959
|
+
this.seen.set(host, now);
|
|
960
|
+
this.inFlight.add(host);
|
|
961
|
+
this.sb().emit(LedgerEvent.PermissionRequested, -1, {
|
|
962
|
+
requestId: `egress:${host}`,
|
|
963
|
+
tool: "network",
|
|
964
|
+
target: host
|
|
965
|
+
});
|
|
966
|
+
let decision = "deny";
|
|
967
|
+
try {
|
|
968
|
+
decision = await this.handler({
|
|
969
|
+
host,
|
|
970
|
+
since: now
|
|
971
|
+
});
|
|
972
|
+
} catch {
|
|
973
|
+
decision = "deny";
|
|
974
|
+
}
|
|
975
|
+
try {
|
|
976
|
+
if (decision === "allow-once" || decision === "allow-always") {
|
|
977
|
+
await this.sb().egress.patch([{
|
|
978
|
+
action: "allow",
|
|
979
|
+
target: host
|
|
980
|
+
}]);
|
|
981
|
+
for (const held of this.byHost.get(host) ?? []) if (held.value !== "") await this.sb().credentials.set(held.name, held.value, held.binding, held.source);
|
|
982
|
+
if (decision === "allow-once") this.onceApproved.add(host);
|
|
983
|
+
else this.held.delete(host);
|
|
984
|
+
}
|
|
985
|
+
} finally {
|
|
986
|
+
this.inFlight.delete(host);
|
|
987
|
+
this.sb().emit(LedgerEvent.PermissionResolved, -1, {
|
|
988
|
+
requestId: `egress:${host}`,
|
|
989
|
+
decision: { kind: decision }
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
function normalizeHost(host) {
|
|
995
|
+
return host.trim().replace(/\.$/, "").toLowerCase();
|
|
996
|
+
}
|
|
997
|
+
//#endregion
|
|
621
998
|
//#region src/agent/factory.ts
|
|
622
999
|
function elapsed(t) {
|
|
623
1000
|
return `${Date.now() - t}ms`;
|
|
@@ -649,10 +1026,30 @@ async function loadAgent(specInput, opts) {
|
|
|
649
1026
|
};
|
|
650
1027
|
const credentialBindings = extractCredentialBindings(spec.env ?? {});
|
|
651
1028
|
const needsCredentialProxy = credentialBindings.length > 0;
|
|
652
|
-
const
|
|
1029
|
+
const heldCredentials = credentialBindings.filter((b) => b.approval === "hold");
|
|
1030
|
+
const heldHosts = [...new Set(heldCredentials.map((b) => b.binding.host.trim().replace(/\.$/, "").toLowerCase()))];
|
|
1031
|
+
if (heldCredentials.length > 0 && !opts.onEgressRequest) throw new Error(`AgentSpec.env has ${heldCredentials.length} credential binding(s) with approval: "hold" (${heldHosts.join(", ")}) but Alineo.load() was called without an onEgressRequest handler.`);
|
|
1032
|
+
const networkPolicy = needsCredentialProxy || heldHosts.length > 0 ? {
|
|
653
1033
|
defaultAction: "allow",
|
|
654
|
-
egress:
|
|
1034
|
+
egress: heldHosts.map((target) => ({
|
|
1035
|
+
action: "deny",
|
|
1036
|
+
target
|
|
1037
|
+
}))
|
|
655
1038
|
} : void 0;
|
|
1039
|
+
const egressGate = heldCredentials.length > 0 && opts.onEgressRequest ? new EgressApprovalGate({
|
|
1040
|
+
heldCredentials: heldCredentials.map((b) => ({
|
|
1041
|
+
name: b.name,
|
|
1042
|
+
value: b.value,
|
|
1043
|
+
binding: b.binding,
|
|
1044
|
+
source: b.source
|
|
1045
|
+
})),
|
|
1046
|
+
handler: opts.onEgressRequest
|
|
1047
|
+
}) : void 0;
|
|
1048
|
+
const egressEnv = {};
|
|
1049
|
+
if (egressGate) {
|
|
1050
|
+
await egressGate.start();
|
|
1051
|
+
egressEnv.OPENSANDBOX_EGRESS_DENY_WEBHOOK = egressGate.webhookUrl;
|
|
1052
|
+
}
|
|
656
1053
|
const client = new Sandbox({
|
|
657
1054
|
baseUrl: config.serverUrl,
|
|
658
1055
|
apiKey: config.apiKey,
|
|
@@ -671,6 +1068,7 @@ async function loadAgent(specInput, opts) {
|
|
|
671
1068
|
const t1 = Date.now();
|
|
672
1069
|
sb = await client.restoreSnapshot(record.snapshotId, spec.name, resources, runId, {
|
|
673
1070
|
networkPolicy,
|
|
1071
|
+
...egressEnv.OPENSANDBOX_EGRESS_DENY_WEBHOOK ? { env: egressEnv } : {},
|
|
674
1072
|
credentialProxy: needsCredentialProxy,
|
|
675
1073
|
resourceId: spec.resourceId ?? spec.name,
|
|
676
1074
|
teamId: spec.teamId
|
|
@@ -690,7 +1088,10 @@ async function loadAgent(specInput, opts) {
|
|
|
690
1088
|
image: "node:22",
|
|
691
1089
|
resources,
|
|
692
1090
|
name: spec.name,
|
|
693
|
-
env:
|
|
1091
|
+
env: {
|
|
1092
|
+
...resolvedEnv,
|
|
1093
|
+
...egressEnv
|
|
1094
|
+
},
|
|
694
1095
|
runId,
|
|
695
1096
|
networkPolicy,
|
|
696
1097
|
credentialProxy: needsCredentialProxy,
|
|
@@ -721,7 +1122,11 @@ async function loadAgent(specInput, opts) {
|
|
|
721
1122
|
console.log(`[agent] checkpoint done ${elapsed(t3)}`);
|
|
722
1123
|
}
|
|
723
1124
|
if (!sb) throw new Error("internal error: sandbox was neither restored nor created");
|
|
724
|
-
|
|
1125
|
+
egressGate?.bind(sb);
|
|
1126
|
+
for (const cb of credentialBindings) {
|
|
1127
|
+
if (cb.approval === "hold") continue;
|
|
1128
|
+
await sb.credentials.set(cb.name, cb.value, cb.binding, cb.source);
|
|
1129
|
+
}
|
|
725
1130
|
resolvedEnv.ALINEO_SANDBOX_ID = sb.sandboxId;
|
|
726
1131
|
await adapter.configure(sb, spec, resolvedEnv);
|
|
727
1132
|
console.log(`[agent] starting bridge...`);
|
|
@@ -736,7 +1141,8 @@ async function loadAgent(specInput, opts) {
|
|
|
736
1141
|
env: resolvedEnv,
|
|
737
1142
|
adapter,
|
|
738
1143
|
fromSnapshot,
|
|
739
|
-
runId
|
|
1144
|
+
runId,
|
|
1145
|
+
egressGate
|
|
740
1146
|
};
|
|
741
1147
|
}
|
|
742
1148
|
/**
|
|
@@ -788,6 +1194,7 @@ async function resumeAgent(sandboxId, opts) {
|
|
|
788
1194
|
await adapter.startBridge(sb);
|
|
789
1195
|
await adapter.waitReady();
|
|
790
1196
|
console.log(`[agent] bridge ready ${elapsed(t2)}`);
|
|
1197
|
+
await reconcileDroppedPermissions(opts.adapter, sb, spec.name, sandboxId);
|
|
791
1198
|
console.log(`[agent] total ${elapsed(t0)}`);
|
|
792
1199
|
return {
|
|
793
1200
|
sandbox: sb,
|
|
@@ -798,6 +1205,25 @@ async function resumeAgent(sandboxId, opts) {
|
|
|
798
1205
|
runId
|
|
799
1206
|
};
|
|
800
1207
|
}
|
|
1208
|
+
async function reconcileDroppedPermissions(adapter, sb, name, sandboxId) {
|
|
1209
|
+
try {
|
|
1210
|
+
const events = await adapter.readAll(name, sandboxId);
|
|
1211
|
+
const resolved = /* @__PURE__ */ new Set();
|
|
1212
|
+
for (const e of events) if (e.event === LedgerEvent.PermissionResolved) {
|
|
1213
|
+
const rid = e.payload?.requestId;
|
|
1214
|
+
if (rid) resolved.add(rid);
|
|
1215
|
+
}
|
|
1216
|
+
for (const e of events) {
|
|
1217
|
+
if (e.event !== LedgerEvent.PermissionRequested) continue;
|
|
1218
|
+
const rid = e.payload?.requestId;
|
|
1219
|
+
if (rid && !resolved.has(rid)) await sb.emit(LedgerEvent.PermissionResolved, -1, {
|
|
1220
|
+
requestId: rid,
|
|
1221
|
+
decision: { kind: "reject" },
|
|
1222
|
+
note: "session resumed — pending approval dropped"
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
} catch {}
|
|
1226
|
+
}
|
|
801
1227
|
/**
|
|
802
1228
|
* Connect to an already-running sandbox WITHOUT touching its Pi bridge. See
|
|
803
1229
|
* `Alineo.attach()` for the public-facing docs.
|
|
@@ -847,6 +1273,7 @@ async function spawnChild(self, childSpecPath, opts = {}) {
|
|
|
847
1273
|
const runId = process.env.ALINEO_RUN_ID ?? crypto.randomUUID();
|
|
848
1274
|
childEnv.ALINEO_RUN_ID = runId;
|
|
849
1275
|
const childCredentialBindings = extractCredentialBindings(childSpec.env ?? {});
|
|
1276
|
+
if (childCredentialBindings.some((b) => b.approval === "hold")) throw new Error(`Spawned agent "${childSpec.name}" has a credential binding with approval: "hold" — egress approval gating is not supported for spawned agents yet (no handler is wired on the spawn path). Remove approval: "hold" from the child spec.`);
|
|
850
1277
|
const childResourceId = resolveChildResourceId(childSpec);
|
|
851
1278
|
console.log(`[agent] forking sandbox for spawn (${childSpec.name})...`);
|
|
852
1279
|
const t0 = Date.now();
|
|
@@ -904,9 +1331,42 @@ async function forkChildMemory(parentMemory, parentRef, child) {
|
|
|
904
1331
|
}
|
|
905
1332
|
//#endregion
|
|
906
1333
|
//#region src/agent/session-control.ts
|
|
1334
|
+
/**
|
|
1335
|
+
* Wrap a raw adapter stream so that every permission event is mirrored to the ledger
|
|
1336
|
+
* (`PermissionRequested` / `PermissionResolved`) and, when `onPermission` is given, each
|
|
1337
|
+
* request is auto-resolved with the handler's decision.
|
|
1338
|
+
*/
|
|
1339
|
+
async function* instrument(a, stream, onPermission) {
|
|
1340
|
+
try {
|
|
1341
|
+
for await (const ev of stream) {
|
|
1342
|
+
if (ev.type === "permission_request") {
|
|
1343
|
+
a.sandbox.emit(LedgerEvent.PermissionRequested, -1, {
|
|
1344
|
+
requestId: ev.requestId,
|
|
1345
|
+
tool: ev.tool,
|
|
1346
|
+
target: ev.target
|
|
1347
|
+
});
|
|
1348
|
+
if (onPermission) {
|
|
1349
|
+
const req = {
|
|
1350
|
+
requestId: ev.requestId,
|
|
1351
|
+
tool: ev.tool,
|
|
1352
|
+
target: ev.target,
|
|
1353
|
+
title: ev.title
|
|
1354
|
+
};
|
|
1355
|
+
Promise.resolve(onPermission(req)).then((decision) => a.adapter.resolvePermission(ev.requestId, decision)).catch(() => {});
|
|
1356
|
+
}
|
|
1357
|
+
} else if (ev.type === "permission_resolved") a.sandbox.emit(LedgerEvent.PermissionResolved, -1, {
|
|
1358
|
+
requestId: ev.requestId,
|
|
1359
|
+
decision: ev.decision
|
|
1360
|
+
});
|
|
1361
|
+
yield ev;
|
|
1362
|
+
}
|
|
1363
|
+
} finally {
|
|
1364
|
+
await a.egressGate?.endTurn().catch(() => {});
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
907
1367
|
/** Send a prompt to Pi and stream the response. Pi manages its own session context. */
|
|
908
1368
|
function prompt(a, message, opts) {
|
|
909
|
-
return a.adapter.prompt(message, opts);
|
|
1369
|
+
return instrument(a, a.adapter.prompt(message, opts), opts?.onPermission);
|
|
910
1370
|
}
|
|
911
1371
|
/**
|
|
912
1372
|
* Run a shell command inside Pi's working context. Not incrementally
|
|
@@ -914,7 +1374,11 @@ function prompt(a, message, opts) {
|
|
|
914
1374
|
* arrives as a single `text` event once the command completes.
|
|
915
1375
|
*/
|
|
916
1376
|
function bash(a, command) {
|
|
917
|
-
return a.adapter.bash(command);
|
|
1377
|
+
return instrument(a, a.adapter.bash(command));
|
|
1378
|
+
}
|
|
1379
|
+
/** Snapshot of tool calls currently paused awaiting a human decision. */
|
|
1380
|
+
async function listPendingPermissions(a) {
|
|
1381
|
+
return a.adapter.listPendingPermissions();
|
|
918
1382
|
}
|
|
919
1383
|
/** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
|
|
920
1384
|
async function steer(a, message) {
|
|
@@ -924,6 +1388,13 @@ async function steer(a, message) {
|
|
|
924
1388
|
async function abort(a) {
|
|
925
1389
|
return a.adapter.abort();
|
|
926
1390
|
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Resolve a pending `permission_request` emitted by the permission gate. `decision` is
|
|
1393
|
+
* `{ kind: "once" }`, `{ kind: "always" }`, or `{ kind: "reject", feedback? }`.
|
|
1394
|
+
*/
|
|
1395
|
+
async function resolvePermission(a, requestId, decision) {
|
|
1396
|
+
return a.adapter.resolvePermission(requestId, decision);
|
|
1397
|
+
}
|
|
927
1398
|
/** Queue a message to be sent to Pi after it finishes its current task. */
|
|
928
1399
|
async function followUp(a, message) {
|
|
929
1400
|
return a.adapter.followUp(message);
|
|
@@ -1077,6 +1548,7 @@ async function setEnv(a, vars) {
|
|
|
1077
1548
|
/** Delete the sandbox container and release all resources. Always call in a `finally` block. */
|
|
1078
1549
|
async function close(a) {
|
|
1079
1550
|
a.adapter.disposeConnections();
|
|
1551
|
+
await a.egressGate?.stop().catch(() => {});
|
|
1080
1552
|
await a.sandbox.close();
|
|
1081
1553
|
}
|
|
1082
1554
|
//#endregion
|
|
@@ -1169,7 +1641,13 @@ var Alineo = class Alineo {
|
|
|
1169
1641
|
teamId: this.teamId
|
|
1170
1642
|
};
|
|
1171
1643
|
}
|
|
1172
|
-
|
|
1644
|
+
/**
|
|
1645
|
+
* Present when the spec has `approval: "hold"` credential bindings — the out-of-process
|
|
1646
|
+
* gate that holds the sandbox's egress to those hosts until `onEgressRequest` approves.
|
|
1647
|
+
* Stopped by `close()`.
|
|
1648
|
+
*/
|
|
1649
|
+
egressGate;
|
|
1650
|
+
constructor(sandbox, spec, env, adapter, fromSnapshot, runId, egressGate) {
|
|
1173
1651
|
this.sandbox = sandbox;
|
|
1174
1652
|
this.sandboxId = sandbox.sandboxId;
|
|
1175
1653
|
this.name = spec.name;
|
|
@@ -1179,6 +1657,11 @@ var Alineo = class Alineo {
|
|
|
1179
1657
|
this.env = env;
|
|
1180
1658
|
this.fromSnapshot = fromSnapshot;
|
|
1181
1659
|
this.runId = runId;
|
|
1660
|
+
this.egressGate = egressGate;
|
|
1661
|
+
}
|
|
1662
|
+
/** Egress requests currently awaiting a decision (see `AgentSpec.env` `approval: "hold"`). */
|
|
1663
|
+
pendingEgressRequests() {
|
|
1664
|
+
return this.egressGate?.pending() ?? [];
|
|
1182
1665
|
}
|
|
1183
1666
|
/**
|
|
1184
1667
|
* Validate `spec` and return a fully initialised `Alineo`.
|
|
@@ -1207,7 +1690,7 @@ var Alineo = class Alineo {
|
|
|
1207
1690
|
*/
|
|
1208
1691
|
static async load(spec, opts) {
|
|
1209
1692
|
const r = await loadAgent(spec, opts);
|
|
1210
|
-
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
|
|
1693
|
+
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId, r.egressGate);
|
|
1211
1694
|
agent.memory = opts.memory;
|
|
1212
1695
|
return agent;
|
|
1213
1696
|
}
|
|
@@ -1345,6 +1828,30 @@ var Alineo = class Alineo {
|
|
|
1345
1828
|
async abort() {
|
|
1346
1829
|
return abort(this);
|
|
1347
1830
|
}
|
|
1831
|
+
/**
|
|
1832
|
+
* Resolve a pending `permission_request` from the agent stream — emitted for each gated
|
|
1833
|
+
* tool call when `AgentSpec.permissions` is set to something other than `"auto"`.
|
|
1834
|
+
*
|
|
1835
|
+
* @example
|
|
1836
|
+
* ```ts
|
|
1837
|
+
* for await (const ev of agent.prompt("Refactor auth")) {
|
|
1838
|
+
* if (ev.type === "permission_request") {
|
|
1839
|
+
* await agent.resolvePermission(ev.requestId, { kind: "once" });
|
|
1840
|
+
* }
|
|
1841
|
+
* }
|
|
1842
|
+
* ```
|
|
1843
|
+
*/
|
|
1844
|
+
async resolvePermission(requestId, decision) {
|
|
1845
|
+
return resolvePermission(this, requestId, decision);
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Tool calls currently paused awaiting a human decision — useful after reconnecting to a
|
|
1849
|
+
* session to discover approvals still outstanding. Each entry is resolvable with
|
|
1850
|
+
* `resolvePermission(entry.requestId, …)`.
|
|
1851
|
+
*/
|
|
1852
|
+
async listPendingPermissions() {
|
|
1853
|
+
return listPendingPermissions(this);
|
|
1854
|
+
}
|
|
1348
1855
|
/** Queue a message to be sent to Pi after it finishes its current task. */
|
|
1349
1856
|
async followUp(message) {
|
|
1350
1857
|
return followUp(this, message);
|
|
@@ -1496,4 +2003,4 @@ async function* textOnly(stream) {
|
|
|
1496
2003
|
for await (const ev of stream) if (ev.type === "text") yield ev.text;
|
|
1497
2004
|
}
|
|
1498
2005
|
//#endregion
|
|
1499
|
-
export { AgentSnapshotStore, AgentSpecValidationError, Alineo, PromptTimeoutError, computeSetupHash, snapshotsPath, textOnly, validateAgentSpec };
|
|
2006
|
+
export { AgentSnapshotStore, AgentSpecValidationError, Alineo, EgressApprovalGate, PromptTimeoutError, computeSetupHash, isReadOnlyBashCommand, snapshotsPath, textOnly, validateAgentSpec };
|