alineo 0.3.0 → 0.5.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.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.object({
106
- type: z$1.literal("header"),
107
- name: z$1.string()
108
- }),
109
- z$1.object({
110
- type: z$1.literal("query"),
111
- param: z$1.string()
112
- }),
113
- z$1.object({
114
- type: z$1.literal("path"),
115
- segment: z$1.string()
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
@@ -303,6 +509,20 @@ var PiAdapter = class {
303
509
  const { url } = await sb.proxy(3001);
304
510
  this._bridgeUrl = url;
305
511
  }
512
+ /**
513
+ * Rebind to a bridge that's already running (as opposed to `startBridge()`, which execs a
514
+ * fresh `node /alineo-bridge.js`). `sb.proxy(port)` is a pure URL lookup against the
515
+ * sandbox's control plane — it starts nothing — so this has zero effect on the sandbox
516
+ * itself: no killed process, no dropped in-flight turn, no reset Pi conversation state.
517
+ *
518
+ * Call `waitReady()` afterwards to confirm the bridge is actually still there before relying
519
+ * on it — the container can be alive while the bridge process inside it isn't (e.g. it
520
+ * crashed independently), and this method alone can't tell the difference.
521
+ */
522
+ async reattachBridge(sb) {
523
+ const { url } = await sb.proxy(3001);
524
+ this._bridgeUrl = url;
525
+ }
306
526
  async waitReady(timeoutMs = 3e4) {
307
527
  const deadline = Date.now() + timeoutMs;
308
528
  while (Date.now() < deadline) {
@@ -339,6 +559,17 @@ var PiAdapter = class {
339
559
  async abort() {
340
560
  await rpcPost(this.bridgeUrl, "/abort");
341
561
  }
562
+ /** Resolve a pending `permission_request` (see `AgentEvent`'s `permission_request`). */
563
+ async resolvePermission(requestId, decision) {
564
+ await rpcPost(this.bridgeUrl, "/permission-response", {
565
+ requestId,
566
+ decision
567
+ });
568
+ }
569
+ /** Tool calls currently paused awaiting a human decision. */
570
+ async listPendingPermissions() {
571
+ return (await rpcGet(this.bridgeUrl, "/pending-permissions")).pending;
572
+ }
342
573
  async followUp(message) {
343
574
  await rpcPost(this.bridgeUrl, "/follow-up", { message });
344
575
  }
@@ -476,17 +707,25 @@ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeo
476
707
  const decoder = new TextDecoder();
477
708
  let buf = "";
478
709
  let lastEventAt = Date.now();
710
+ const pendingPermissions = /* @__PURE__ */ new Set();
479
711
  let reachedNaturalEnd = false;
480
712
  try {
481
713
  while (true) {
714
+ const awaitingHuman = pendingPermissions.size > 0;
482
715
  const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
483
- if (remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
716
+ if (!awaitingHuman && remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
484
717
  const result = await Promise.race([reader.read(), new Promise((resolve) => {
485
718
  setTimeout(() => {
486
719
  resolve("timeout");
487
- }, remainingMs);
720
+ }, awaitingHuman ? inactivityTimeoutMs : Math.max(remainingMs, 1));
488
721
  })]);
489
- if (result === "timeout") throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
722
+ if (result === "timeout") {
723
+ if (pendingPermissions.size > 0) {
724
+ lastEventAt = Date.now();
725
+ continue;
726
+ }
727
+ throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
728
+ }
490
729
  const { done, value } = result;
491
730
  if (done) {
492
731
  reachedNaturalEnd = true;
@@ -501,6 +740,8 @@ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeo
501
740
  if (payload === "[DONE]") return;
502
741
  const raw = JSON.parse(payload);
503
742
  if (raw.error) throw new Error(`Bridge error: ${raw.error}`);
743
+ if (raw.type === "permission_request") pendingPermissions.add(raw.requestId);
744
+ else if (raw.type === "permission_resolved") pendingPermissions.delete(raw.requestId);
504
745
  lastEventAt = Date.now();
505
746
  yield raw;
506
747
  }
@@ -618,6 +859,156 @@ function resolveParentMaxAgents(envValue, override) {
618
859
  return raw;
619
860
  }
620
861
  //#endregion
862
+ //#region src/agent/egress-approval.ts
863
+ const DEDUP_TTL_MS = 3e4;
864
+ var EgressApprovalGate = class {
865
+ server;
866
+ port = 0;
867
+ sandbox;
868
+ handler;
869
+ webhookHost;
870
+ /** host → the held credentials bound to it. */
871
+ byHost = /* @__PURE__ */ new Map();
872
+ /** Hosts still gated — dropped once permanently opened by `allow-always`. */
873
+ held = /* @__PURE__ */ new Set();
874
+ /** host → last time we raised a request for it (dedup; the webhook fires per DNS query). */
875
+ seen = /* @__PURE__ */ new Map();
876
+ /** Hosts with a decision currently in flight. */
877
+ inFlight = /* @__PURE__ */ new Set();
878
+ /** Hosts approved `allow-once` — reversed on `endTurn()`. */
879
+ onceApproved = /* @__PURE__ */ new Set();
880
+ constructor(opts) {
881
+ this.handler = opts.handler;
882
+ this.webhookHost = opts.webhookHost ?? process.env.ALINEO_EGRESS_APPROVAL_HOST ?? "172.17.0.1";
883
+ for (const held of opts.heldCredentials) {
884
+ const host = normalizeHost(held.binding.host);
885
+ this.held.add(host);
886
+ const list = this.byHost.get(host);
887
+ if (list) list.push(held);
888
+ else this.byHost.set(host, [held]);
889
+ }
890
+ }
891
+ /** Attach the sandbox whose egress this gate manages. Called once its handle exists. */
892
+ bind(sandbox) {
893
+ this.sandbox = sandbox;
894
+ }
895
+ sb() {
896
+ if (!this.sandbox) throw new Error("EgressApprovalGate.bind() has not been called");
897
+ return this.sandbox;
898
+ }
899
+ /** Start the listener. Idempotent. */
900
+ async start() {
901
+ if (this.server) return;
902
+ const server = createServer((req, res) => {
903
+ if (req.method !== "POST" || (req.url ?? "").split("?")[0] !== "/egress-deny") {
904
+ res.writeHead(404).end();
905
+ return;
906
+ }
907
+ let raw = "";
908
+ req.on("data", (c) => raw += c);
909
+ req.on("end", () => {
910
+ res.writeHead(200).end("ok");
911
+ let body = null;
912
+ try {
913
+ body = JSON.parse(raw);
914
+ } catch {
915
+ return;
916
+ }
917
+ const host = body?.hostname ? normalizeHost(body.hostname) : void 0;
918
+ if (host) this.onDenied(host);
919
+ });
920
+ });
921
+ await new Promise((resolve, reject) => {
922
+ server.once("error", reject);
923
+ server.listen(0, "0.0.0.0", () => {
924
+ const addr = server.address();
925
+ this.port = typeof addr === "object" && addr ? addr.port : 0;
926
+ resolve();
927
+ });
928
+ });
929
+ server.unref();
930
+ this.server = server;
931
+ }
932
+ /** Stop the listener. */
933
+ async stop() {
934
+ const server = this.server;
935
+ this.server = void 0;
936
+ if (!server) return;
937
+ await new Promise((resolve) => server.close(() => resolve()));
938
+ }
939
+ /** The `OPENSANDBOX_EGRESS_DENY_WEBHOOK` value to put in the sandbox's env. */
940
+ get webhookUrl() {
941
+ if (!this.server) throw new Error("EgressApprovalGate.start() has not been called");
942
+ return `http://${this.webhookHost}:${this.port}/egress-deny`;
943
+ }
944
+ /** Egress requests currently awaiting a decision. */
945
+ pending() {
946
+ return [...this.inFlight].map((host) => ({
947
+ host,
948
+ since: this.seen.get(host) ?? Date.now()
949
+ }));
950
+ }
951
+ /**
952
+ * Reverse every `allow-once` approval — remove its credential(s) and re-deny the host.
953
+ * Call when an agent turn ends so a one-shot grant does not silently persist.
954
+ */
955
+ async endTurn() {
956
+ const toRevert = [...this.onceApproved].filter((h) => this.held.has(h));
957
+ this.onceApproved.clear();
958
+ for (const host of toRevert) {
959
+ for (const held of this.byHost.get(host) ?? []) if (held.value !== "") await this.sb().credentials.remove(held.name).catch(() => {});
960
+ await this.sb().egress.patch([{
961
+ action: "deny",
962
+ target: host
963
+ }]);
964
+ this.seen.delete(host);
965
+ }
966
+ }
967
+ async onDenied(host) {
968
+ if (!this.held.has(host)) return;
969
+ const now = Date.now();
970
+ const last = this.seen.get(host);
971
+ if (last !== void 0 && now - last < DEDUP_TTL_MS) return;
972
+ if (this.inFlight.has(host)) return;
973
+ this.seen.set(host, now);
974
+ this.inFlight.add(host);
975
+ this.sb().emit(LedgerEvent.PermissionRequested, -1, {
976
+ requestId: `egress:${host}`,
977
+ tool: "network",
978
+ target: host
979
+ });
980
+ let decision = "deny";
981
+ try {
982
+ decision = await this.handler({
983
+ host,
984
+ since: now
985
+ });
986
+ } catch {
987
+ decision = "deny";
988
+ }
989
+ try {
990
+ if (decision === "allow-once" || decision === "allow-always") {
991
+ await this.sb().egress.patch([{
992
+ action: "allow",
993
+ target: host
994
+ }]);
995
+ for (const held of this.byHost.get(host) ?? []) if (held.value !== "") await this.sb().credentials.set(held.name, held.value, held.binding, held.source);
996
+ if (decision === "allow-once") this.onceApproved.add(host);
997
+ else this.held.delete(host);
998
+ }
999
+ } finally {
1000
+ this.inFlight.delete(host);
1001
+ this.sb().emit(LedgerEvent.PermissionResolved, -1, {
1002
+ requestId: `egress:${host}`,
1003
+ decision: { kind: decision }
1004
+ });
1005
+ }
1006
+ }
1007
+ };
1008
+ function normalizeHost(host) {
1009
+ return host.trim().replace(/\.$/, "").toLowerCase();
1010
+ }
1011
+ //#endregion
621
1012
  //#region src/agent/factory.ts
622
1013
  function elapsed(t) {
623
1014
  return `${Date.now() - t}ms`;
@@ -649,10 +1040,30 @@ async function loadAgent(specInput, opts) {
649
1040
  };
650
1041
  const credentialBindings = extractCredentialBindings(spec.env ?? {});
651
1042
  const needsCredentialProxy = credentialBindings.length > 0;
652
- const networkPolicy = needsCredentialProxy ? {
1043
+ const heldCredentials = credentialBindings.filter((b) => b.approval === "hold");
1044
+ const heldHosts = [...new Set(heldCredentials.map((b) => b.binding.host.trim().replace(/\.$/, "").toLowerCase()))];
1045
+ 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.`);
1046
+ const networkPolicy = needsCredentialProxy || heldHosts.length > 0 ? {
653
1047
  defaultAction: "allow",
654
- egress: []
1048
+ egress: heldHosts.map((target) => ({
1049
+ action: "deny",
1050
+ target
1051
+ }))
655
1052
  } : void 0;
1053
+ const egressGate = heldCredentials.length > 0 && opts.onEgressRequest ? new EgressApprovalGate({
1054
+ heldCredentials: heldCredentials.map((b) => ({
1055
+ name: b.name,
1056
+ value: b.value,
1057
+ binding: b.binding,
1058
+ source: b.source
1059
+ })),
1060
+ handler: opts.onEgressRequest
1061
+ }) : void 0;
1062
+ const egressEnv = {};
1063
+ if (egressGate) {
1064
+ await egressGate.start();
1065
+ egressEnv.OPENSANDBOX_EGRESS_DENY_WEBHOOK = egressGate.webhookUrl;
1066
+ }
656
1067
  const client = new Sandbox({
657
1068
  baseUrl: config.serverUrl,
658
1069
  apiKey: config.apiKey,
@@ -671,6 +1082,7 @@ async function loadAgent(specInput, opts) {
671
1082
  const t1 = Date.now();
672
1083
  sb = await client.restoreSnapshot(record.snapshotId, spec.name, resources, runId, {
673
1084
  networkPolicy,
1085
+ ...egressEnv.OPENSANDBOX_EGRESS_DENY_WEBHOOK ? { env: egressEnv } : {},
674
1086
  credentialProxy: needsCredentialProxy,
675
1087
  resourceId: spec.resourceId ?? spec.name,
676
1088
  teamId: spec.teamId
@@ -690,7 +1102,10 @@ async function loadAgent(specInput, opts) {
690
1102
  image: "node:22",
691
1103
  resources,
692
1104
  name: spec.name,
693
- env: resolvedEnv,
1105
+ env: {
1106
+ ...resolvedEnv,
1107
+ ...egressEnv
1108
+ },
694
1109
  runId,
695
1110
  networkPolicy,
696
1111
  credentialProxy: needsCredentialProxy,
@@ -721,7 +1136,11 @@ async function loadAgent(specInput, opts) {
721
1136
  console.log(`[agent] checkpoint done ${elapsed(t3)}`);
722
1137
  }
723
1138
  if (!sb) throw new Error("internal error: sandbox was neither restored nor created");
724
- for (const { name, value, binding, source } of credentialBindings) await sb.credentials.set(name, value, binding, source);
1139
+ egressGate?.bind(sb);
1140
+ for (const cb of credentialBindings) {
1141
+ if (cb.approval === "hold") continue;
1142
+ await sb.credentials.set(cb.name, cb.value, cb.binding, cb.source);
1143
+ }
725
1144
  resolvedEnv.ALINEO_SANDBOX_ID = sb.sandboxId;
726
1145
  await adapter.configure(sb, spec, resolvedEnv);
727
1146
  console.log(`[agent] starting bridge...`);
@@ -736,7 +1155,8 @@ async function loadAgent(specInput, opts) {
736
1155
  env: resolvedEnv,
737
1156
  adapter,
738
1157
  fromSnapshot,
739
- runId
1158
+ runId,
1159
+ egressGate
740
1160
  };
741
1161
  }
742
1162
  /**
@@ -775,6 +1195,7 @@ async function resumeAgent(sandboxId, opts) {
775
1195
  const t1 = Date.now();
776
1196
  const sb = await client.connect(sandboxId, spec.name, {
777
1197
  runId,
1198
+ resources: spec.resources ?? config.defaults.resources,
778
1199
  resourceId: spec.resourceId ?? spec.name,
779
1200
  teamId: spec.teamId
780
1201
  });
@@ -788,6 +1209,85 @@ async function resumeAgent(sandboxId, opts) {
788
1209
  await adapter.startBridge(sb);
789
1210
  await adapter.waitReady();
790
1211
  console.log(`[agent] bridge ready ${elapsed(t2)}`);
1212
+ await reconcileDroppedPermissions(opts.adapter, sb, spec.name, sandboxId);
1213
+ console.log(`[agent] total ${elapsed(t0)}`);
1214
+ return {
1215
+ sandbox: sb,
1216
+ spec,
1217
+ env: resolvedEnv,
1218
+ adapter,
1219
+ fromSnapshot: false,
1220
+ runId
1221
+ };
1222
+ }
1223
+ async function reconcileDroppedPermissions(adapter, sb, name, sandboxId) {
1224
+ try {
1225
+ const events = await adapter.readAll(name, sandboxId);
1226
+ const resolved = /* @__PURE__ */ new Set();
1227
+ for (const e of events) if (e.event === LedgerEvent.PermissionResolved) {
1228
+ const rid = e.payload?.requestId;
1229
+ if (rid) resolved.add(rid);
1230
+ }
1231
+ for (const e of events) {
1232
+ if (e.event !== LedgerEvent.PermissionRequested) continue;
1233
+ const rid = e.payload?.requestId;
1234
+ if (rid && !resolved.has(rid)) await sb.emit(LedgerEvent.PermissionResolved, -1, {
1235
+ requestId: rid,
1236
+ decision: { kind: "reject" },
1237
+ note: "session resumed — pending approval dropped"
1238
+ });
1239
+ }
1240
+ } catch {}
1241
+ }
1242
+ /**
1243
+ * Reconnect to a previously-created agent WITHOUT restarting its bridge. See
1244
+ * `Alineo.reattach()` for the public-facing docs. Structurally `resumeAgent()` minus its two
1245
+ * destructive steps (the `pkill` and the fresh `startBridge()`) — everything else (spec
1246
+ * resolution, env, `client.connect()`) is identical.
1247
+ */
1248
+ async function reattachAgent(sandboxId, opts) {
1249
+ const t0 = Date.now();
1250
+ const config = await readProjectConfig();
1251
+ const client = new Sandbox({
1252
+ baseUrl: config.serverUrl,
1253
+ apiKey: config.apiKey,
1254
+ adapter: opts.adapter,
1255
+ useServerProxy: config.useServerProxy
1256
+ });
1257
+ let spec;
1258
+ if (opts.spec) spec = validateAgentSpec(opts.spec);
1259
+ else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
1260
+ else {
1261
+ const session = (await client.sandboxes.list()).find((s) => s.sandboxId === sandboxId);
1262
+ if (!session) throw new Error(`No ledger record for sandbox ${sandboxId} — pass opts.spec or opts.specPath explicitly`);
1263
+ spec = validateAgentSpec(await Bun.file(`./agents/${session.name}.json`).json());
1264
+ }
1265
+ const resolvedEnv = resolveEnv(spec.env ?? {});
1266
+ if (spec.maxAgents !== void 0) {
1267
+ assertValidMaxAgents(spec.maxAgents, "Alineo.reattach()");
1268
+ resolvedEnv.ALINEO_MAX_AGENTS = String(spec.maxAgents);
1269
+ }
1270
+ if (spec.spawnDepth !== void 0) {
1271
+ assertValidSpawnDepth(spec.spawnDepth, "Alineo.reattach()");
1272
+ resolvedEnv.ALINEO_SPAWN_DEPTH = String(spec.spawnDepth);
1273
+ }
1274
+ const runId = opts.runId ?? crypto.randomUUID();
1275
+ resolvedEnv.ALINEO_RUN_ID = runId;
1276
+ resolvedEnv.ALINEO_SANDBOX_ID = sandboxId;
1277
+ console.log(`[agent] reattaching to ${sandboxId}...`);
1278
+ const t1 = Date.now();
1279
+ const sb = await client.connect(sandboxId, spec.name, {
1280
+ runId,
1281
+ resourceId: spec.resourceId ?? spec.name,
1282
+ teamId: spec.teamId,
1283
+ resources: spec.resources ?? config.defaults.resources
1284
+ });
1285
+ console.log(`[agent] connected ${elapsed(t1)}`);
1286
+ const adapter = new PiAdapter();
1287
+ await adapter.reattachBridge(sb);
1288
+ const t2 = Date.now();
1289
+ await adapter.waitReady(5e3);
1290
+ console.log(`[agent] bridge reattached ${elapsed(t2)}`);
791
1291
  console.log(`[agent] total ${elapsed(t0)}`);
792
1292
  return {
793
1293
  sandbox: sb,
@@ -847,6 +1347,7 @@ async function spawnChild(self, childSpecPath, opts = {}) {
847
1347
  const runId = process.env.ALINEO_RUN_ID ?? crypto.randomUUID();
848
1348
  childEnv.ALINEO_RUN_ID = runId;
849
1349
  const childCredentialBindings = extractCredentialBindings(childSpec.env ?? {});
1350
+ 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
1351
  const childResourceId = resolveChildResourceId(childSpec);
851
1352
  console.log(`[agent] forking sandbox for spawn (${childSpec.name})...`);
852
1353
  const t0 = Date.now();
@@ -904,9 +1405,42 @@ async function forkChildMemory(parentMemory, parentRef, child) {
904
1405
  }
905
1406
  //#endregion
906
1407
  //#region src/agent/session-control.ts
1408
+ /**
1409
+ * Wrap a raw adapter stream so that every permission event is mirrored to the ledger
1410
+ * (`PermissionRequested` / `PermissionResolved`) and, when `onPermission` is given, each
1411
+ * request is auto-resolved with the handler's decision.
1412
+ */
1413
+ async function* instrument(a, stream, onPermission) {
1414
+ try {
1415
+ for await (const ev of stream) {
1416
+ if (ev.type === "permission_request") {
1417
+ a.sandbox.emit(LedgerEvent.PermissionRequested, -1, {
1418
+ requestId: ev.requestId,
1419
+ tool: ev.tool,
1420
+ target: ev.target
1421
+ });
1422
+ if (onPermission) {
1423
+ const req = {
1424
+ requestId: ev.requestId,
1425
+ tool: ev.tool,
1426
+ target: ev.target,
1427
+ title: ev.title
1428
+ };
1429
+ Promise.resolve(onPermission(req)).then((decision) => a.adapter.resolvePermission(ev.requestId, decision)).catch(() => {});
1430
+ }
1431
+ } else if (ev.type === "permission_resolved") a.sandbox.emit(LedgerEvent.PermissionResolved, -1, {
1432
+ requestId: ev.requestId,
1433
+ decision: ev.decision
1434
+ });
1435
+ yield ev;
1436
+ }
1437
+ } finally {
1438
+ await a.egressGate?.endTurn().catch(() => {});
1439
+ }
1440
+ }
907
1441
  /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
908
1442
  function prompt(a, message, opts) {
909
- return a.adapter.prompt(message, opts);
1443
+ return instrument(a, a.adapter.prompt(message, opts), opts?.onPermission);
910
1444
  }
911
1445
  /**
912
1446
  * Run a shell command inside Pi's working context. Not incrementally
@@ -914,7 +1448,11 @@ function prompt(a, message, opts) {
914
1448
  * arrives as a single `text` event once the command completes.
915
1449
  */
916
1450
  function bash(a, command) {
917
- return a.adapter.bash(command);
1451
+ return instrument(a, a.adapter.bash(command));
1452
+ }
1453
+ /** Snapshot of tool calls currently paused awaiting a human decision. */
1454
+ async function listPendingPermissions(a) {
1455
+ return a.adapter.listPendingPermissions();
918
1456
  }
919
1457
  /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
920
1458
  async function steer(a, message) {
@@ -924,6 +1462,13 @@ async function steer(a, message) {
924
1462
  async function abort(a) {
925
1463
  return a.adapter.abort();
926
1464
  }
1465
+ /**
1466
+ * Resolve a pending `permission_request` emitted by the permission gate. `decision` is
1467
+ * `{ kind: "once" }`, `{ kind: "always" }`, or `{ kind: "reject", feedback? }`.
1468
+ */
1469
+ async function resolvePermission(a, requestId, decision) {
1470
+ return a.adapter.resolvePermission(requestId, decision);
1471
+ }
927
1472
  /** Queue a message to be sent to Pi after it finishes its current task. */
928
1473
  async function followUp(a, message) {
929
1474
  return a.adapter.followUp(message);
@@ -1077,6 +1622,7 @@ async function setEnv(a, vars) {
1077
1622
  /** Delete the sandbox container and release all resources. Always call in a `finally` block. */
1078
1623
  async function close(a) {
1079
1624
  a.adapter.disposeConnections();
1625
+ await a.egressGate?.stop().catch(() => {});
1080
1626
  await a.sandbox.close();
1081
1627
  }
1082
1628
  //#endregion
@@ -1169,7 +1715,13 @@ var Alineo = class Alineo {
1169
1715
  teamId: this.teamId
1170
1716
  };
1171
1717
  }
1172
- constructor(sandbox, spec, env, adapter, fromSnapshot, runId) {
1718
+ /**
1719
+ * Present when the spec has `approval: "hold"` credential bindings — the out-of-process
1720
+ * gate that holds the sandbox's egress to those hosts until `onEgressRequest` approves.
1721
+ * Stopped by `close()`.
1722
+ */
1723
+ egressGate;
1724
+ constructor(sandbox, spec, env, adapter, fromSnapshot, runId, egressGate) {
1173
1725
  this.sandbox = sandbox;
1174
1726
  this.sandboxId = sandbox.sandboxId;
1175
1727
  this.name = spec.name;
@@ -1179,6 +1731,11 @@ var Alineo = class Alineo {
1179
1731
  this.env = env;
1180
1732
  this.fromSnapshot = fromSnapshot;
1181
1733
  this.runId = runId;
1734
+ this.egressGate = egressGate;
1735
+ }
1736
+ /** Egress requests currently awaiting a decision (see `AgentSpec.env` `approval: "hold"`). */
1737
+ pendingEgressRequests() {
1738
+ return this.egressGate?.pending() ?? [];
1182
1739
  }
1183
1740
  /**
1184
1741
  * Validate `spec` and return a fully initialised `Alineo`.
@@ -1207,7 +1764,7 @@ var Alineo = class Alineo {
1207
1764
  */
1208
1765
  static async load(spec, opts) {
1209
1766
  const r = await loadAgent(spec, opts);
1210
- const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1767
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId, r.egressGate);
1211
1768
  agent.memory = opts.memory;
1212
1769
  return agent;
1213
1770
  }
@@ -1218,6 +1775,12 @@ var Alineo = class Alineo {
1218
1775
  * are already present — only the bridge process needs to be restarted.
1219
1776
  * Pi is started with `--continue` so it resumes the most recent session.
1220
1777
  *
1778
+ * **Kills and restarts the bridge process** — anything mid-flight when the previous host
1779
+ * process exited (a streaming turn, a tool call parked on a human decision) is dropped.
1780
+ * If the bridge might still be alive and you'd rather preserve that, try `Alineo.reattach()`
1781
+ * first and fall back to this only if it fails (e.g. the whole sandbox — not just this
1782
+ * process — actually restarted).
1783
+ *
1221
1784
  * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
1222
1785
  * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
1223
1786
  * `load()`. Takes precedence over `opts.specPath` if both are set.
@@ -1250,6 +1813,41 @@ var Alineo = class Alineo {
1250
1813
  return agent;
1251
1814
  }
1252
1815
  /**
1816
+ * Reconnect to a previously-created agent WITHOUT restarting its bridge — the crash-only
1817
+ * counterpart to `resume()`. Use this when the caller's own process exited or restarted
1818
+ * (e.g. a control-plane daemon coming back up) but has good reason to believe the sandbox,
1819
+ * and the bridge process inside it, never stopped: nothing here kills or re-execs anything.
1820
+ * `sb.proxy()` is a pure URL lookup, so the only network activity is re-deriving the proxy
1821
+ * URL and one health-check request.
1822
+ *
1823
+ * The returned `Alineo` is fully functional — `.prompt()`/`.bash()` work exactly as they
1824
+ * would have on the original handle, continuing the same Pi conversation, because it's
1825
+ * still the same process.
1826
+ *
1827
+ * **Fails fast (5s) if the bridge doesn't answer** — the container can be `Running` while
1828
+ * the bridge process inside it has independently died, and this can't distinguish that from
1829
+ * a slow-to-respond-but-fine bridge on its own. On failure, fall back to `Alineo.resume()`.
1830
+ *
1831
+ * @param sandboxId The sandbox ID returned by the original `Alineo.load()`/`.spawn()`.
1832
+ * @param opts.spec / opts.specPath Same three-way fallback as `resume()` — see its docs.
1833
+ *
1834
+ * @example
1835
+ * ```ts
1836
+ * let agent: Alineo;
1837
+ * try {
1838
+ * agent = await Alineo.reattach(savedSandboxId, { adapter });
1839
+ * } catch {
1840
+ * agent = await Alineo.resume(savedSandboxId, { adapter }); // bridge really is gone
1841
+ * }
1842
+ * ```
1843
+ */
1844
+ static async reattach(sandboxId, opts) {
1845
+ const r = await reattachAgent(sandboxId, opts);
1846
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1847
+ agent.memory = opts.memory;
1848
+ return agent;
1849
+ }
1850
+ /**
1253
1851
  * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
1254
1852
  * `resume()`, which kills and restarts the bridge process. Use this when you only
1255
1853
  * need `.spawn()`/`.sandbox`, not `.prompt()`/`.bash()`.
@@ -1345,6 +1943,30 @@ var Alineo = class Alineo {
1345
1943
  async abort() {
1346
1944
  return abort(this);
1347
1945
  }
1946
+ /**
1947
+ * Resolve a pending `permission_request` from the agent stream — emitted for each gated
1948
+ * tool call when `AgentSpec.permissions` is set to something other than `"auto"`.
1949
+ *
1950
+ * @example
1951
+ * ```ts
1952
+ * for await (const ev of agent.prompt("Refactor auth")) {
1953
+ * if (ev.type === "permission_request") {
1954
+ * await agent.resolvePermission(ev.requestId, { kind: "once" });
1955
+ * }
1956
+ * }
1957
+ * ```
1958
+ */
1959
+ async resolvePermission(requestId, decision) {
1960
+ return resolvePermission(this, requestId, decision);
1961
+ }
1962
+ /**
1963
+ * Tool calls currently paused awaiting a human decision — useful after reconnecting to a
1964
+ * session to discover approvals still outstanding. Each entry is resolvable with
1965
+ * `resolvePermission(entry.requestId, …)`.
1966
+ */
1967
+ async listPendingPermissions() {
1968
+ return listPendingPermissions(this);
1969
+ }
1348
1970
  /** Queue a message to be sent to Pi after it finishes its current task. */
1349
1971
  async followUp(message) {
1350
1972
  return followUp(this, message);
@@ -1496,4 +2118,4 @@ async function* textOnly(stream) {
1496
2118
  for await (const ev of stream) if (ev.type === "text") yield ev.text;
1497
2119
  }
1498
2120
  //#endregion
1499
- export { AgentSnapshotStore, AgentSpecValidationError, Alineo, PromptTimeoutError, computeSetupHash, snapshotsPath, textOnly, validateAgentSpec };
2121
+ export { AgentSnapshotStore, AgentSpecValidationError, Alineo, EgressApprovalGate, PromptTimeoutError, computeSetupHash, isReadOnlyBashCommand, snapshotsPath, textOnly, validateAgentSpec };