alineo 0.2.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 +388 -6
- package/dist/index.mjs +723 -24
- package/dist/pi-bridge.js +249 -16
- package/dist/pi-permission-gate.js +337 -0
- package/package.json +4 -3
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 = {
|
|
@@ -80,6 +81,15 @@ var AgentSpecValidationError = class extends WorkflowError {
|
|
|
80
81
|
};
|
|
81
82
|
//#endregion
|
|
82
83
|
//#region src/schema.ts
|
|
84
|
+
/** Renders an arbitrary invalid field value for an error message without risking "[object Object]". */
|
|
85
|
+
function describeValue(value) {
|
|
86
|
+
if (typeof value === "string") return value;
|
|
87
|
+
try {
|
|
88
|
+
const json = JSON.stringify(value);
|
|
89
|
+
if (json !== void 0) return json;
|
|
90
|
+
} catch {}
|
|
91
|
+
return typeof value === "object" && value !== null ? Object.prototype.toString.call(value) : String(value);
|
|
92
|
+
}
|
|
83
93
|
/**
|
|
84
94
|
* Runtime schema for `SetupStep`/`AgentSpec` above. Kept as a separate Zod schema rather than
|
|
85
95
|
* generating the interfaces from it (`z.infer<>`) so the hand-written interfaces above can carry
|
|
@@ -88,11 +98,57 @@ var AgentSpecValidationError = class extends WorkflowError {
|
|
|
88
98
|
* If you add/change/remove a field on `AgentSpec`/`SetupStep`, update the matching schema field
|
|
89
99
|
* here too — `packages/agent/test/schema.test.ts` is the drift check.
|
|
90
100
|
*/
|
|
101
|
+
const CredentialEnvBindingSchema = z$1.object({
|
|
102
|
+
credential: z$1.string({ error: "Each credential env binding must have a 'credential' string" }),
|
|
103
|
+
host: z$1.string({ error: "Each credential env binding must have a 'host' string" }),
|
|
104
|
+
pathPrefix: z$1.string().optional(),
|
|
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()
|
|
119
|
+
}).loose();
|
|
91
120
|
const SetupStepSchema = z$1.object({
|
|
92
121
|
name: z$1.string({ error: "Each setup step must have a 'name' string" }),
|
|
93
122
|
run: z$1.string({ error: "Each setup step must have a 'run' string" }),
|
|
94
123
|
cwd: z$1.string().optional()
|
|
95
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]);
|
|
96
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();
|
|
97
153
|
const AgentSpecSchema = z$1.object({
|
|
98
154
|
$schema: z$1.string().optional(),
|
|
@@ -101,12 +157,12 @@ const AgentSpecSchema = z$1.object({
|
|
|
101
157
|
description: z$1.string().optional(),
|
|
102
158
|
author: z$1.string().optional(),
|
|
103
159
|
categories: z$1.array(z$1.string()).optional(),
|
|
104
|
-
cli: z$1.literal("pi", { error: (issue) => issue.input === void 0 ? "Agent spec must have a 'cli' field. Supported values: pi" : `Unsupported CLI: '${
|
|
160
|
+
cli: z$1.literal("pi", { error: (issue) => issue.input === void 0 ? "Agent spec must have a 'cli' field. Supported values: pi" : `Unsupported CLI: '${describeValue(issue.input)}'. Supported values: pi` }),
|
|
105
161
|
cliVersion: z$1.string().optional(),
|
|
106
162
|
provider: z$1.string().optional(),
|
|
107
163
|
model: z$1.string().optional(),
|
|
108
164
|
packages: z$1.array(z$1.string()).optional(),
|
|
109
|
-
env: z$1.record(z$1.string(), z$1.string()).optional(),
|
|
165
|
+
env: z$1.record(z$1.string(), z$1.union([z$1.string(), CredentialEnvBindingSchema])).optional(),
|
|
110
166
|
resources: z$1.object({
|
|
111
167
|
cpu: z$1.string(),
|
|
112
168
|
memory: z$1.string(),
|
|
@@ -116,7 +172,10 @@ const AgentSpecSchema = z$1.object({
|
|
|
116
172
|
registryDependencies: z$1.array(z$1.string()).optional(),
|
|
117
173
|
setup: z$1.array(SetupStepSchema).optional(),
|
|
118
174
|
spawnDepth: nonNegativeIntSpecField("spawnDepth"),
|
|
119
|
-
maxAgents: nonNegativeIntSpecField("maxAgents")
|
|
175
|
+
maxAgents: nonNegativeIntSpecField("maxAgents"),
|
|
176
|
+
teamId: z$1.string().optional(),
|
|
177
|
+
resourceId: z$1.string().optional(),
|
|
178
|
+
permissions: PermissionsSchema.optional()
|
|
120
179
|
}).loose();
|
|
121
180
|
/**
|
|
122
181
|
* Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
|
|
@@ -133,16 +192,233 @@ function validateAgentSpec(data) {
|
|
|
133
192
|
return result.data;
|
|
134
193
|
}
|
|
135
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
|
|
136
367
|
//#region src/adapters/pi.ts
|
|
137
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");
|
|
138
370
|
function toShellExports(env) {
|
|
139
371
|
return Object.entries(env).map(([k, v]) => `export ${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`).join("\n") + "\n";
|
|
140
372
|
}
|
|
373
|
+
/**
|
|
374
|
+
* Resolves plain string entries of `AgentSpec.env`, interpolating `${VAR}` from `process.env`.
|
|
375
|
+
* Credential-bound entries (`{ credential, host, injection }`) are deliberately skipped here —
|
|
376
|
+
* see `extractCredentialBindings()` — they never become a container env var at all.
|
|
377
|
+
*/
|
|
141
378
|
function resolveEnv(env) {
|
|
142
379
|
const result = {};
|
|
143
|
-
for (const [key, value] of Object.entries(env))
|
|
380
|
+
for (const [key, value] of Object.entries(env)) {
|
|
381
|
+
if (typeof value !== "string") continue;
|
|
382
|
+
result[key] = value.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] ?? "");
|
|
383
|
+
}
|
|
144
384
|
return result;
|
|
145
385
|
}
|
|
386
|
+
/** Matches a `credential` value that is *only* a single `${VAR}` reference, nothing else. */
|
|
387
|
+
const SOLE_ENV_REF = /^\$\{([^}]+)\}$/;
|
|
388
|
+
/**
|
|
389
|
+
* Pulls the credential-bound entries out of `AgentSpec.env` — the opt-in alternative to plain
|
|
390
|
+
* env-var interpolation (see `AgentSpec.env`'s docs). Each entry's `credential` value is
|
|
391
|
+
* interpolated the same way `resolveEnv()` interpolates plain strings; the resolved value is
|
|
392
|
+
* only ever handed to `sb.credentials.set()`, never written into the container's environment.
|
|
393
|
+
*
|
|
394
|
+
* Also derives a `CredentialSource` for each: `credential: "${VAR}"` (the whole value, nothing
|
|
395
|
+
* else around it) becomes `{ type: "env", varName: "VAR" }`, letting `fork()`/`resume()`
|
|
396
|
+
* re-resolve it automatically later without needing a callback. Anything else — a literal
|
|
397
|
+
* value, or `${VAR}` embedded in a larger string — becomes `{ type: "external" }`, since it
|
|
398
|
+
* isn't reliably re-derivable the same way twice.
|
|
399
|
+
*/
|
|
400
|
+
function extractCredentialBindings(env) {
|
|
401
|
+
const out = [];
|
|
402
|
+
for (const [key, value] of Object.entries(env)) {
|
|
403
|
+
if (typeof value === "string") continue;
|
|
404
|
+
const soleRef = value.credential.match(SOLE_ENV_REF);
|
|
405
|
+
out.push({
|
|
406
|
+
name: key,
|
|
407
|
+
value: value.credential.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] ?? ""),
|
|
408
|
+
binding: {
|
|
409
|
+
host: value.host,
|
|
410
|
+
pathPrefix: value.pathPrefix,
|
|
411
|
+
injection: value.injection
|
|
412
|
+
},
|
|
413
|
+
source: soleRef ? {
|
|
414
|
+
type: "env",
|
|
415
|
+
varName: soleRef[1]
|
|
416
|
+
} : { type: "external" },
|
|
417
|
+
...value.approval ? { approval: value.approval } : {}
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
return out;
|
|
421
|
+
}
|
|
146
422
|
/** Inverse of `toShellExports` — parses `/etc/alineo-env`'s content back into a plain object. */
|
|
147
423
|
function parseShellExports(content) {
|
|
148
424
|
const result = {};
|
|
@@ -209,9 +485,12 @@ var PiAdapter = class {
|
|
|
209
485
|
if (spec.provider) piConfig.provider = spec.provider;
|
|
210
486
|
if (spec.model) piConfig.model = spec.model;
|
|
211
487
|
if (opts?.resume) piConfig.resume = true;
|
|
488
|
+
const permissions = normalizePermissions(spec.permissions);
|
|
489
|
+
if (permissions) piConfig.permissions = permissions;
|
|
212
490
|
await sb.writeFile("/etc/alineo-pi.json", JSON.stringify(piConfig));
|
|
213
491
|
await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
|
|
214
492
|
await sb.writeFile("/alineo-bridge.js", BRIDGE_SCRIPT);
|
|
493
|
+
if (permissions) await sb.writeFile("/alineo-permission-gate.js", PERMISSION_GATE_SCRIPT);
|
|
215
494
|
}
|
|
216
495
|
/**
|
|
217
496
|
* Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the
|
|
@@ -266,6 +545,17 @@ var PiAdapter = class {
|
|
|
266
545
|
async abort() {
|
|
267
546
|
await rpcPost(this.bridgeUrl, "/abort");
|
|
268
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
|
+
}
|
|
269
559
|
async followUp(message) {
|
|
270
560
|
await rpcPost(this.bridgeUrl, "/follow-up", { message });
|
|
271
561
|
}
|
|
@@ -403,13 +693,25 @@ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeo
|
|
|
403
693
|
const decoder = new TextDecoder();
|
|
404
694
|
let buf = "";
|
|
405
695
|
let lastEventAt = Date.now();
|
|
696
|
+
const pendingPermissions = /* @__PURE__ */ new Set();
|
|
406
697
|
let reachedNaturalEnd = false;
|
|
407
698
|
try {
|
|
408
699
|
while (true) {
|
|
700
|
+
const awaitingHuman = pendingPermissions.size > 0;
|
|
409
701
|
const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
|
|
410
|
-
if (remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
411
|
-
const result = await Promise.race([reader.read(), new Promise((resolve) =>
|
|
412
|
-
|
|
702
|
+
if (!awaitingHuman && remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
703
|
+
const result = await Promise.race([reader.read(), new Promise((resolve) => {
|
|
704
|
+
setTimeout(() => {
|
|
705
|
+
resolve("timeout");
|
|
706
|
+
}, awaitingHuman ? inactivityTimeoutMs : Math.max(remainingMs, 1));
|
|
707
|
+
})]);
|
|
708
|
+
if (result === "timeout") {
|
|
709
|
+
if (pendingPermissions.size > 0) {
|
|
710
|
+
lastEventAt = Date.now();
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
714
|
+
}
|
|
413
715
|
const { done, value } = result;
|
|
414
716
|
if (done) {
|
|
415
717
|
reachedNaturalEnd = true;
|
|
@@ -417,13 +719,15 @@ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeo
|
|
|
417
719
|
}
|
|
418
720
|
buf += decoder.decode(value, { stream: true });
|
|
419
721
|
const lines = buf.split("\n");
|
|
420
|
-
buf = lines.pop();
|
|
722
|
+
buf = lines.pop() ?? "";
|
|
421
723
|
for (const line of lines) {
|
|
422
724
|
if (!line.startsWith("data: ")) continue;
|
|
423
725
|
const payload = line.slice(6).trim();
|
|
424
726
|
if (payload === "[DONE]") return;
|
|
425
727
|
const raw = JSON.parse(payload);
|
|
426
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);
|
|
427
731
|
lastEventAt = Date.now();
|
|
428
732
|
yield raw;
|
|
429
733
|
}
|
|
@@ -495,6 +799,19 @@ var AgentSnapshotStore = class {
|
|
|
495
799
|
};
|
|
496
800
|
//#endregion
|
|
497
801
|
//#region src/agent/validation.ts
|
|
802
|
+
/**
|
|
803
|
+
* The durable resource identity for a spawned child, frozen from the child spec BEFORE
|
|
804
|
+
* `Alineo.spawn()` overwrites its `.name` to the forked sandbox's auto-generated ledger name
|
|
805
|
+
* (`fork-<parent>-<id>`) — see `AgentSpec.resourceId`'s own doc comment for why `child.name`
|
|
806
|
+
* can't be read for this after the fork completes. Extracted as its own function (mirroring
|
|
807
|
+
* `resolveParentSpawnDepth`/`resolveParentMaxAgents` below) so this one line of resolution
|
|
808
|
+
* logic — easy to get backwards, hard to notice if so, since both `spawnChild()`'s
|
|
809
|
+
* `self.sandbox.fork()` call and its returned `AgentConstructorArgs.spec.resourceId` must
|
|
810
|
+
* agree on the exact same value — is independently unit-testable.
|
|
811
|
+
*/
|
|
812
|
+
function resolveChildResourceId(childSpec) {
|
|
813
|
+
return childSpec.resourceId ?? childSpec.name;
|
|
814
|
+
}
|
|
498
815
|
function assertValidSpawnDepth(value, context) {
|
|
499
816
|
if (!Number.isInteger(value) || value < 0) throw new Error(`${context}: spawnDepth must be a non-negative integer (got ${value})`);
|
|
500
817
|
}
|
|
@@ -528,6 +845,156 @@ function resolveParentMaxAgents(envValue, override) {
|
|
|
528
845
|
return raw;
|
|
529
846
|
}
|
|
530
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
|
|
531
998
|
//#region src/agent/factory.ts
|
|
532
999
|
function elapsed(t) {
|
|
533
1000
|
return `${Date.now() - t}ms`;
|
|
@@ -557,6 +1024,32 @@ async function loadAgent(specInput, opts) {
|
|
|
557
1024
|
...config.defaults.resources,
|
|
558
1025
|
...spec.resources ?? {}
|
|
559
1026
|
};
|
|
1027
|
+
const credentialBindings = extractCredentialBindings(spec.env ?? {});
|
|
1028
|
+
const needsCredentialProxy = credentialBindings.length > 0;
|
|
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 ? {
|
|
1033
|
+
defaultAction: "allow",
|
|
1034
|
+
egress: heldHosts.map((target) => ({
|
|
1035
|
+
action: "deny",
|
|
1036
|
+
target
|
|
1037
|
+
}))
|
|
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
|
+
}
|
|
560
1053
|
const client = new Sandbox({
|
|
561
1054
|
baseUrl: config.serverUrl,
|
|
562
1055
|
apiKey: config.apiKey,
|
|
@@ -573,7 +1066,13 @@ async function loadAgent(specInput, opts) {
|
|
|
573
1066
|
if (record) try {
|
|
574
1067
|
console.log(`[agent] restoring from snapshot...`);
|
|
575
1068
|
const t1 = Date.now();
|
|
576
|
-
sb = await client.restoreSnapshot(record.snapshotId, spec.name, resources, runId
|
|
1069
|
+
sb = await client.restoreSnapshot(record.snapshotId, spec.name, resources, runId, {
|
|
1070
|
+
networkPolicy,
|
|
1071
|
+
...egressEnv.OPENSANDBOX_EGRESS_DENY_WEBHOOK ? { env: egressEnv } : {},
|
|
1072
|
+
credentialProxy: needsCredentialProxy,
|
|
1073
|
+
resourceId: spec.resourceId ?? spec.name,
|
|
1074
|
+
teamId: spec.teamId
|
|
1075
|
+
});
|
|
577
1076
|
console.log(`[agent] snapshot ready ${elapsed(t1)} (${sb.sandboxId})`);
|
|
578
1077
|
fromSnapshot = true;
|
|
579
1078
|
} catch (err) {
|
|
@@ -589,8 +1088,15 @@ async function loadAgent(specInput, opts) {
|
|
|
589
1088
|
image: "node:22",
|
|
590
1089
|
resources,
|
|
591
1090
|
name: spec.name,
|
|
592
|
-
env:
|
|
593
|
-
|
|
1091
|
+
env: {
|
|
1092
|
+
...resolvedEnv,
|
|
1093
|
+
...egressEnv
|
|
1094
|
+
},
|
|
1095
|
+
runId,
|
|
1096
|
+
networkPolicy,
|
|
1097
|
+
credentialProxy: needsCredentialProxy,
|
|
1098
|
+
resourceId: spec.resourceId ?? spec.name,
|
|
1099
|
+
teamId: spec.teamId
|
|
594
1100
|
});
|
|
595
1101
|
console.log(`[agent] sandbox ready ${elapsed(t1)} (${sb.sandboxId})`);
|
|
596
1102
|
console.log(`[agent] installing Pi CLI...`);
|
|
@@ -615,6 +1121,12 @@ async function loadAgent(specInput, opts) {
|
|
|
615
1121
|
});
|
|
616
1122
|
console.log(`[agent] checkpoint done ${elapsed(t3)}`);
|
|
617
1123
|
}
|
|
1124
|
+
if (!sb) throw new Error("internal error: sandbox was neither restored nor created");
|
|
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
|
+
}
|
|
618
1130
|
resolvedEnv.ALINEO_SANDBOX_ID = sb.sandboxId;
|
|
619
1131
|
await adapter.configure(sb, spec, resolvedEnv);
|
|
620
1132
|
console.log(`[agent] starting bridge...`);
|
|
@@ -629,7 +1141,8 @@ async function loadAgent(specInput, opts) {
|
|
|
629
1141
|
env: resolvedEnv,
|
|
630
1142
|
adapter,
|
|
631
1143
|
fromSnapshot,
|
|
632
|
-
runId
|
|
1144
|
+
runId,
|
|
1145
|
+
egressGate
|
|
633
1146
|
};
|
|
634
1147
|
}
|
|
635
1148
|
/**
|
|
@@ -666,7 +1179,11 @@ async function resumeAgent(sandboxId, opts) {
|
|
|
666
1179
|
resolvedEnv.ALINEO_RUN_ID = runId;
|
|
667
1180
|
console.log(`[agent] reconnecting to ${sandboxId}...`);
|
|
668
1181
|
const t1 = Date.now();
|
|
669
|
-
const sb = await client.connect(sandboxId, spec.name, {
|
|
1182
|
+
const sb = await client.connect(sandboxId, spec.name, {
|
|
1183
|
+
runId,
|
|
1184
|
+
resourceId: spec.resourceId ?? spec.name,
|
|
1185
|
+
teamId: spec.teamId
|
|
1186
|
+
});
|
|
670
1187
|
console.log(`[agent] connected ${elapsed(t1)}`);
|
|
671
1188
|
await sb.exec("pkill -f 'node /alineo-bridge.js' 2>/dev/null; sleep 0.1; true", { strict: false });
|
|
672
1189
|
const adapter = new PiAdapter();
|
|
@@ -677,6 +1194,7 @@ async function resumeAgent(sandboxId, opts) {
|
|
|
677
1194
|
await adapter.startBridge(sb);
|
|
678
1195
|
await adapter.waitReady();
|
|
679
1196
|
console.log(`[agent] bridge ready ${elapsed(t2)}`);
|
|
1197
|
+
await reconcileDroppedPermissions(opts.adapter, sb, spec.name, sandboxId);
|
|
680
1198
|
console.log(`[agent] total ${elapsed(t0)}`);
|
|
681
1199
|
return {
|
|
682
1200
|
sandbox: sb,
|
|
@@ -687,6 +1205,25 @@ async function resumeAgent(sandboxId, opts) {
|
|
|
687
1205
|
runId
|
|
688
1206
|
};
|
|
689
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
|
+
}
|
|
690
1227
|
/**
|
|
691
1228
|
* Connect to an already-running sandbox WITHOUT touching its Pi bridge. See
|
|
692
1229
|
* `Alineo.attach()` for the public-facing docs.
|
|
@@ -735,10 +1272,18 @@ async function spawnChild(self, childSpecPath, opts = {}) {
|
|
|
735
1272
|
if (parentMax !== void 0) childEnv.ALINEO_MAX_AGENTS = String(parentMax - 1);
|
|
736
1273
|
const runId = process.env.ALINEO_RUN_ID ?? crypto.randomUUID();
|
|
737
1274
|
childEnv.ALINEO_RUN_ID = runId;
|
|
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.`);
|
|
1277
|
+
const childResourceId = resolveChildResourceId(childSpec);
|
|
738
1278
|
console.log(`[agent] forking sandbox for spawn (${childSpec.name})...`);
|
|
739
1279
|
const t0 = Date.now();
|
|
740
|
-
const forkedSb = await self.sandbox.fork(childSpec.name, runId
|
|
1280
|
+
const forkedSb = await self.sandbox.fork(childSpec.name, runId, {
|
|
1281
|
+
credentialProxy: childCredentialBindings.length > 0,
|
|
1282
|
+
resourceId: childResourceId,
|
|
1283
|
+
teamId: childSpec.teamId
|
|
1284
|
+
});
|
|
741
1285
|
console.log(`[agent] fork ready ${elapsed(t0)} (${forkedSb.sandboxId})`);
|
|
1286
|
+
for (const { name, value, binding, source } of childCredentialBindings) await forkedSb.credentials.set(name, value, binding, source);
|
|
742
1287
|
const adapter = new PiAdapter();
|
|
743
1288
|
childEnv.ALINEO_SANDBOX_ID = forkedSb.sandboxId;
|
|
744
1289
|
await adapter.configure(forkedSb, childSpec, childEnv);
|
|
@@ -751,7 +1296,8 @@ async function spawnChild(self, childSpecPath, opts = {}) {
|
|
|
751
1296
|
sandbox: forkedSb,
|
|
752
1297
|
spec: {
|
|
753
1298
|
...childSpec,
|
|
754
|
-
name: forkedSb.name
|
|
1299
|
+
name: forkedSb.name,
|
|
1300
|
+
resourceId: childResourceId
|
|
755
1301
|
},
|
|
756
1302
|
env: childEnv,
|
|
757
1303
|
adapter,
|
|
@@ -759,11 +1305,68 @@ async function spawnChild(self, childSpecPath, opts = {}) {
|
|
|
759
1305
|
runId
|
|
760
1306
|
};
|
|
761
1307
|
}
|
|
1308
|
+
/**
|
|
1309
|
+
* Seed a just-constructed spawn child's memory from its parent — the memory-layer
|
|
1310
|
+
* counterpart to `spawnChild()`'s sandbox-level fork above. Called from `Alineo.spawn()`
|
|
1311
|
+
* after the child is constructed (not from `spawnChild()` itself, which runs before the
|
|
1312
|
+
* child exists and so has no `child.resourceRef` to fork into yet).
|
|
1313
|
+
*
|
|
1314
|
+
* A no-op when `parentMemory` is `undefined` — most agents don't have `.memory` configured.
|
|
1315
|
+
* Otherwise forks an independent snapshot copy the child can mutate on its own, not a live
|
|
1316
|
+
* share of the parent's scope (`child.resourceRef` already names a different resource — the
|
|
1317
|
+
* child spec's own name — so this seeds that scope rather than overwriting the parent's).
|
|
1318
|
+
*
|
|
1319
|
+
* The sandbox fork has already succeeded by the time this runs (`child.sandbox` is live) —
|
|
1320
|
+
* if the memory-layer fork throws, close the child sandbox before rethrowing rather than
|
|
1321
|
+
* leaving it orphaned with nothing left to close it.
|
|
1322
|
+
*/
|
|
1323
|
+
async function forkChildMemory(parentMemory, parentRef, child) {
|
|
1324
|
+
if (!parentMemory) return;
|
|
1325
|
+
try {
|
|
1326
|
+
await parentMemory.fork(parentRef, child.resourceRef.resourceId);
|
|
1327
|
+
} catch (err) {
|
|
1328
|
+
await child.close().catch(() => {});
|
|
1329
|
+
throw err;
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
762
1332
|
//#endregion
|
|
763
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
|
+
}
|
|
764
1367
|
/** Send a prompt to Pi and stream the response. Pi manages its own session context. */
|
|
765
1368
|
function prompt(a, message, opts) {
|
|
766
|
-
return a.adapter.prompt(message, opts);
|
|
1369
|
+
return instrument(a, a.adapter.prompt(message, opts), opts?.onPermission);
|
|
767
1370
|
}
|
|
768
1371
|
/**
|
|
769
1372
|
* Run a shell command inside Pi's working context. Not incrementally
|
|
@@ -771,7 +1374,11 @@ function prompt(a, message, opts) {
|
|
|
771
1374
|
* arrives as a single `text` event once the command completes.
|
|
772
1375
|
*/
|
|
773
1376
|
function bash(a, command) {
|
|
774
|
-
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();
|
|
775
1382
|
}
|
|
776
1383
|
/** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
|
|
777
1384
|
async function steer(a, message) {
|
|
@@ -781,6 +1388,13 @@ async function steer(a, message) {
|
|
|
781
1388
|
async function abort(a) {
|
|
782
1389
|
return a.adapter.abort();
|
|
783
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
|
+
}
|
|
784
1398
|
/** Queue a message to be sent to Pi after it finishes its current task. */
|
|
785
1399
|
async function followUp(a, message) {
|
|
786
1400
|
return a.adapter.followUp(message);
|
|
@@ -934,6 +1548,7 @@ async function setEnv(a, vars) {
|
|
|
934
1548
|
/** Delete the sandbox container and release all resources. Always call in a `finally` block. */
|
|
935
1549
|
async function close(a) {
|
|
936
1550
|
a.adapter.disposeConnections();
|
|
1551
|
+
await a.egressGate?.stop().catch(() => {});
|
|
937
1552
|
await a.sandbox.close();
|
|
938
1553
|
}
|
|
939
1554
|
//#endregion
|
|
@@ -988,14 +1603,65 @@ var Alineo = class Alineo {
|
|
|
988
1603
|
* transitively, `alineo fork`) always inherits its parent's `runId`.
|
|
989
1604
|
*/
|
|
990
1605
|
runId;
|
|
991
|
-
|
|
1606
|
+
/**
|
|
1607
|
+
* Optional provider-agnostic memory (`@alineo-labs/memory`), wired in via `opts.memory` on
|
|
1608
|
+
* `load()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
|
|
1609
|
+
* constructs a `Memory` on your own behalf, matching this package's "own the pipeline,
|
|
1610
|
+
* don't assume a backend" design. `spawn()` carries the parent's `memory` (if any) onto the
|
|
1611
|
+
* child automatically, the same way it force-computes spawn-depth rather than reading it
|
|
1612
|
+
* back off the child's own spec.
|
|
1613
|
+
*/
|
|
1614
|
+
memory;
|
|
1615
|
+
/**
|
|
1616
|
+
* Durable team identity for `.resourceRef` — see `AgentSpec.teamId`. `undefined` unless the
|
|
1617
|
+
* spec this agent was loaded from set it.
|
|
1618
|
+
*/
|
|
1619
|
+
teamId;
|
|
1620
|
+
/**
|
|
1621
|
+
* Durable resource identity for `.resourceRef` — see `AgentSpec.resourceId`. Deliberately
|
|
1622
|
+
* separate from `.name`: for a spawned child specifically, `.name` gets overwritten to the
|
|
1623
|
+
* forked sandbox's auto-generated ledger name (`fork-<parent>-<id>`), which is NOT what
|
|
1624
|
+
* memory should be scoped by — see `AgentSpec.resourceId`'s own doc comment for why.
|
|
1625
|
+
*/
|
|
1626
|
+
resourceId;
|
|
1627
|
+
/**
|
|
1628
|
+
* Convenience `ResourceRef` scoping `.memory` calls to this agent. `resourceId`/`teamId`
|
|
1629
|
+
* come from `AgentSpec.resourceId`/`AgentSpec.teamId` (`resourceId` defaulting to this
|
|
1630
|
+
* agent's `name` when unset) — `load()`/`resume()`/`spawn()` also thread both into the
|
|
1631
|
+
* ledger (see each field's own doc comment) so this getter and the agent's own episodic
|
|
1632
|
+
* history stay consistent, including across a spawned child whose `.name` differs from its
|
|
1633
|
+
* memory identity.
|
|
1634
|
+
*
|
|
1635
|
+
* Only meaningful once `.memory` is set; pass a different `ResourceRef` explicitly to
|
|
1636
|
+
* `.memory` methods instead if this agent's resourceId/teamId aren't the identity you want.
|
|
1637
|
+
*/
|
|
1638
|
+
get resourceRef() {
|
|
1639
|
+
return {
|
|
1640
|
+
resourceId: this.resourceId,
|
|
1641
|
+
teamId: this.teamId
|
|
1642
|
+
};
|
|
1643
|
+
}
|
|
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) {
|
|
992
1651
|
this.sandbox = sandbox;
|
|
993
1652
|
this.sandboxId = sandbox.sandboxId;
|
|
994
1653
|
this.name = spec.name;
|
|
1654
|
+
this.teamId = spec.teamId;
|
|
1655
|
+
this.resourceId = spec.resourceId ?? spec.name;
|
|
995
1656
|
this.adapter = adapter;
|
|
996
1657
|
this.env = env;
|
|
997
1658
|
this.fromSnapshot = fromSnapshot;
|
|
998
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() ?? [];
|
|
999
1665
|
}
|
|
1000
1666
|
/**
|
|
1001
1667
|
* Validate `spec` and return a fully initialised `Alineo`.
|
|
@@ -1024,7 +1690,9 @@ var Alineo = class Alineo {
|
|
|
1024
1690
|
*/
|
|
1025
1691
|
static async load(spec, opts) {
|
|
1026
1692
|
const r = await loadAgent(spec, opts);
|
|
1027
|
-
|
|
1693
|
+
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId, r.egressGate);
|
|
1694
|
+
agent.memory = opts.memory;
|
|
1695
|
+
return agent;
|
|
1028
1696
|
}
|
|
1029
1697
|
/**
|
|
1030
1698
|
* Reconnect to a previously-created agent whose host process has exited.
|
|
@@ -1060,7 +1728,9 @@ var Alineo = class Alineo {
|
|
|
1060
1728
|
*/
|
|
1061
1729
|
static async resume(sandboxId, opts) {
|
|
1062
1730
|
const r = await resumeAgent(sandboxId, opts);
|
|
1063
|
-
|
|
1731
|
+
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
|
|
1732
|
+
agent.memory = opts.memory;
|
|
1733
|
+
return agent;
|
|
1064
1734
|
}
|
|
1065
1735
|
/**
|
|
1066
1736
|
* Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
|
|
@@ -1094,7 +1764,9 @@ var Alineo = class Alineo {
|
|
|
1094
1764
|
*/
|
|
1095
1765
|
static async attach(sandboxId, opts) {
|
|
1096
1766
|
const r = await attachAgent(sandboxId, opts);
|
|
1097
|
-
|
|
1767
|
+
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
|
|
1768
|
+
agent.memory = opts.memory;
|
|
1769
|
+
return agent;
|
|
1098
1770
|
}
|
|
1099
1771
|
/**
|
|
1100
1772
|
* Fork this agent's live sandbox — filesystem, installed packages, checked-out
|
|
@@ -1131,7 +1803,10 @@ var Alineo = class Alineo {
|
|
|
1131
1803
|
*/
|
|
1132
1804
|
async spawn(childSpecPath, opts = {}) {
|
|
1133
1805
|
const r = await spawnChild(this, childSpecPath, opts);
|
|
1134
|
-
|
|
1806
|
+
const child = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
|
|
1807
|
+
child.memory = this.memory;
|
|
1808
|
+
await forkChildMemory(this.memory, this.resourceRef, child);
|
|
1809
|
+
return child;
|
|
1135
1810
|
}
|
|
1136
1811
|
/** Send a prompt to Pi and stream the response. Pi manages its own session context. */
|
|
1137
1812
|
prompt(message, opts) {
|
|
@@ -1153,6 +1828,30 @@ var Alineo = class Alineo {
|
|
|
1153
1828
|
async abort() {
|
|
1154
1829
|
return abort(this);
|
|
1155
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
|
+
}
|
|
1156
1855
|
/** Queue a message to be sent to Pi after it finishes its current task. */
|
|
1157
1856
|
async followUp(message) {
|
|
1158
1857
|
return followUp(this, message);
|
|
@@ -1304,4 +2003,4 @@ async function* textOnly(stream) {
|
|
|
1304
2003
|
for await (const ev of stream) if (ev.type === "text") yield ev.text;
|
|
1305
2004
|
}
|
|
1306
2005
|
//#endregion
|
|
1307
|
-
export { AgentSnapshotStore, AgentSpecValidationError, Alineo, PromptTimeoutError, computeSetupHash, snapshotsPath, textOnly, validateAgentSpec };
|
|
2006
|
+
export { AgentSnapshotStore, AgentSpecValidationError, Alineo, EgressApprovalGate, PromptTimeoutError, computeSetupHash, isReadOnlyBashCommand, snapshotsPath, textOnly, validateAgentSpec };
|