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 CHANGED
@@ -1,7 +1,83 @@
1
+ import { CredentialBinding, CredentialSource, IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
1
2
  import { z } from "zod";
2
- import { IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
3
3
  import { Memory, ResourceRef } from "@alineo-labs/memory";
4
4
 
5
+ //#region src/permissions.d.ts
6
+ /**
7
+ * Human-in-the-loop tool-call policy — the host-side half.
8
+ *
9
+ * `AgentSpec.permissions` (a mode string or a full policy) is normalized here into a
10
+ * `NormalizedPermissionPolicy`, written into the sandbox at `/etc/alineo-pi.json`, and read
11
+ * by the bundled Pi gate extension (`adapters/pi-permission-gate.js`), which re-implements
12
+ * the tiny matcher below inline (same duplication tradeoff `pi-bridge.js` already makes —
13
+ * the gate can't import from a published package it runs beside via jiti). Keep the two
14
+ * matchers in sync; `test/permissions.test.ts` covers this one.
15
+ */
16
+ /**
17
+ * Shorthand for the common cases:
18
+ * - `"auto"` — never ask (the default; identical to not setting `permissions` at all)
19
+ * - `"ask"` — ask before every tool call
20
+ * - `"readonly"` — auto-allow the read-only tools (`read`/`grep`/`find`/`ls`), ask before
21
+ * `write`/`edit`/`bash`/`powershell`. Pi has no network tool — an agent reaches the
22
+ * network through `bash`, so `"readonly"` gates that by gating `bash`, not as a category.
23
+ */
24
+ type PermissionMode = "auto" | "ask" | "readonly";
25
+ /**
26
+ * What happens when a rule (or the policy default) matches a tool call:
27
+ * - `allow` — run it, no prompt
28
+ * - `ask` — pause, surface a `permission_request`, wait for a human decision
29
+ * - `deny` — refuse, with a reason the model reads and can adjust to
30
+ * - `rate_limit` — allow up to `limit.count` matching calls per `limit.windowMs`, then deny
31
+ * - `classify` — best-effort read-vs-write triage of the call (today: `bash`/`powershell`
32
+ * only, splitting on `&&`/`||`/`;`/`|`/newline and checking each sub-command against a
33
+ * built-in safe-reader list). All sub-commands look read-only → `allow`; anything
34
+ * unrecognised or a redirect/`sudo`/`rm` → falls through to `ask`. For any other tool,
35
+ * `classify` is treated as `ask`.
36
+ */
37
+ type PermissionAction = "allow" | "ask" | "deny" | "rate_limit" | "classify";
38
+ interface PermissionRule {
39
+ /** Tool name or glob (`*` = any run of chars, `?` = one), e.g. `"bash"`, `"write"`, `"*"`. */
40
+ tool: string;
41
+ /**
42
+ * Glob matched against a tool-specific target string, extracted from Pi's typed
43
+ * `event.input` — the command for `bash`, the path for `read`/`write`/`edit`, the query
44
+ * for `grep`. Anchored: `"git *"` matches `"git status"` but not `"x && git status"` —
45
+ * use `"*git*"` for a substring match. Omit to match any call to `tool`.
46
+ */
47
+ pattern?: string;
48
+ action: PermissionAction;
49
+ /** `rate_limit` only: the ceiling and rolling window. */
50
+ limit?: {
51
+ count: number;
52
+ windowMs: number;
53
+ };
54
+ }
55
+ interface PermissionPolicy {
56
+ /** Action when no rule matches. Default `"ask"`. */
57
+ default?: PermissionAction;
58
+ /** Evaluated in order; the **last** matching rule wins (opencode semantics). */
59
+ rules?: PermissionRule[];
60
+ /**
61
+ * Tools the agent may never call. The gate strips these from the model's tool list at
62
+ * session start (via Pi's `setActiveTools`) so the model never attempts them, and also
63
+ * keeps an unconditional `deny` as a backstop for any tool registered after startup
64
+ * (SDK / MCP tools).
65
+ */
66
+ disabledTools?: string[];
67
+ /**
68
+ * If set, the ONLY tools the model may see — the gate calls Pi's `setActiveTools` with
69
+ * this list at session start. `"readonly"` mode expands to this (the read-only tools).
70
+ * Distinct from `disabledTools` (a denylist); this is an allowlist for the toolset.
71
+ */
72
+ restrictToTools?: string[];
73
+ }
74
+ /**
75
+ * Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
76
+ * recognised pure reader with no output redirection; `false` = something needs a human.
77
+ * Mirrored verbatim in `adapters/pi-permission-gate.js`.
78
+ */
79
+ declare function isReadOnlyBashCommand(command: string): boolean;
80
+ //#endregion
5
81
  //#region src/schema.d.ts
6
82
  /**
7
83
  * Opt-in alternative to a plain `AgentSpec.env` string value — instead of interpolating
@@ -18,17 +94,29 @@ interface CredentialEnvBinding {
18
94
  host: string;
19
95
  /** Narrows the binding to requests whose path starts with this prefix. */
20
96
  pathPrefix?: string;
21
- /** How the credential reaches the request. */
97
+ /**
98
+ * How the credential reaches the request. `header` adds `name: <value>`. `substitution`
99
+ * replaces every literal `placeholder` in the listed request surfaces with the value — the
100
+ * request must already contain `placeholder` verbatim (put it in a base URL, say). Mirrors
101
+ * `@alineo-labs/core`'s `CredentialInjection`; `packages/agent/test/schema.test.ts` is the
102
+ * drift check.
103
+ */
22
104
  injection: {
23
105
  type: "header";
24
106
  name: string;
25
107
  } | {
26
- type: "query";
27
- param: string;
28
- } | {
29
- type: "path";
30
- segment: string;
108
+ type: "substitution";
109
+ placeholder: string;
110
+ in: Array<"path" | "query" | "header" | "body">;
31
111
  };
112
+ /**
113
+ * `"hold"` gates outbound egress to `host` behind a human decision: the agent's sandbox
114
+ * starts with `host` denied at the egress sidecar, the first request to it pauses and
115
+ * raises an approval request, and the host is allowed only once someone approves. Requires
116
+ * an `onEgressRequest` handler on `Alineo.load()`. Omit for the default (the host is
117
+ * reachable as soon as the credential is bound).
118
+ */
119
+ approval?: "hold";
32
120
  }
33
121
  /**
34
122
  * A single named setup step run inside the sandbox after Pi CLI install,
@@ -167,6 +255,16 @@ interface AgentSpec {
167
255
  * regardless of what the ledger ends up calling the forked sandbox.
168
256
  */
169
257
  resourceId?: string;
258
+ /**
259
+ * Human-in-the-loop tool-call policy, enforced by a bundled Pi extension that runs on
260
+ * every tool call before it executes. Either a mode shorthand (`"auto"` — the default,
261
+ * never ask; `"ask"` — ask before every call; `"readonly"` — auto-allow reads, ask before
262
+ * writes/exec) or a full `PermissionPolicy` with ordered per-tool / per-pattern rules
263
+ * (last match wins). When set to anything other than `"auto"`, a `permission_request`
264
+ * event is emitted on the agent stream for each gated call; resolve it with
265
+ * `agent.resolvePermission(requestId, decision)`.
266
+ */
267
+ permissions?: PermissionMode | PermissionPolicy;
170
268
  }
171
269
  /**
172
270
  * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
@@ -186,6 +284,11 @@ declare function validateAgentSpec(data: unknown): AgentSpec;
186
284
  * - `extension_ui` — a Pi extension requested UI interaction; dialog requests are
187
285
  * auto-cancelled by the bridge so Pi never stalls, but the event is forwarded so
188
286
  * callers can observe what was requested
287
+ * - `permission_request` — the permission gate paused a tool call for human approval
288
+ * (only when `AgentSpec.permissions` is set to something other than `"auto"`); resolve
289
+ * it with `agent.resolvePermission(requestId, decision)`
290
+ * - `permission_resolved` — a `permission_request` was answered (by a caller, a batched
291
+ * "always"/"reject" decision, or the timeout)
189
292
  * - `auto_retry_start` — Pi is about to retry after a transient error (429, 5xx)
190
293
  * - `auto_retry_end` — Pi's retry sequence completed (success or exhausted)
191
294
  * - `agent_start` — Pi began processing the prompt
@@ -226,6 +329,16 @@ type AgentEvent = {
226
329
  params: unknown;
227
330
  isDialog: boolean;
228
331
  requestId?: string;
332
+ } | {
333
+ type: "permission_request"; /** Pass to `agent.resolvePermission()`. */
334
+ requestId: string; /** The tool Pi is about to run, e.g. `"bash"`. */
335
+ tool: string; /** Tool-specific target: the command for `bash`, the path for file tools. */
336
+ target: string; /** Human-readable one-line summary for a prompt. */
337
+ title: string;
338
+ } | {
339
+ type: "permission_resolved";
340
+ requestId: string;
341
+ decision: PermissionDecision;
229
342
  } | {
230
343
  type: "auto_retry_start";
231
344
  attempt: number;
@@ -286,6 +399,38 @@ type AgentEvent = {
286
399
  event: string;
287
400
  error: string;
288
401
  };
402
+ /**
403
+ * A human's answer to a `permission_request`, passed to `agent.resolvePermission()`.
404
+ * - `once` — allow this one call
405
+ * - `always` — allow this call and auto-allow every other still-pending request for the
406
+ * same tool (opencode's batch-clear); does not persist past the session
407
+ * - `reject` — block the call; `feedback` (if given) becomes the reason the model reads,
408
+ * and every other still-pending request for the same tool is rejected too
409
+ */
410
+ type PermissionDecision = {
411
+ kind: "once";
412
+ } | {
413
+ kind: "always";
414
+ } | {
415
+ kind: "reject";
416
+ feedback?: string;
417
+ };
418
+ /** The payload of a `permission_request`, as handed to a `prompt()` `onPermission` handler. */
419
+ interface PermissionRequest {
420
+ requestId: string;
421
+ tool: string;
422
+ target: string;
423
+ title: string;
424
+ }
425
+ /** One entry from `agent.listPendingPermissions()` — a tool call paused awaiting a decision. */
426
+ interface PendingPermission {
427
+ requestId: string;
428
+ tool: string;
429
+ target: string;
430
+ title: string;
431
+ /** Unix ms when the gate raised this request. */
432
+ since: number;
433
+ }
289
434
  /**
290
435
  * Async iterable of structured agent events. Returned by `Alineo.prompt()` and `Alineo.bash()`.
291
436
  *
@@ -448,6 +593,10 @@ declare class PiAdapter {
448
593
  bash(command: string): AgentStream;
449
594
  steer(message: string): Promise<void>;
450
595
  abort(): Promise<void>;
596
+ /** Resolve a pending `permission_request` (see `AgentEvent`'s `permission_request`). */
597
+ resolvePermission(requestId: string, decision: PermissionDecision): Promise<void>;
598
+ /** Tool calls currently paused awaiting a human decision. */
599
+ listPendingPermissions(): Promise<PendingPermission[]>;
451
600
  followUp(message: string): Promise<void>;
452
601
  newSession(): Promise<void>;
453
602
  setThinkingLevel(level: ThinkingLevel): Promise<void>;
@@ -525,6 +674,102 @@ declare class AgentSnapshotStore {
525
674
  list(): Promise<AgentSnapshotRecord[]>;
526
675
  }
527
676
  //#endregion
677
+ //#region src/agent/egress-approval.d.ts
678
+ /**
679
+ * Human-in-the-loop gate for a sandboxed agent's outbound network access.
680
+ *
681
+ * Credential env bindings marked `approval: "hold"` in `AgentSpec.env` start with their host
682
+ * *denied* at the egress sidecar (the sandbox is `defaultAction: "allow"` with an explicit
683
+ * `deny` rule per held host, so everything else — including the agent's own model traffic —
684
+ * keeps working) and their credential **not registered in the vault at all** (the vault
685
+ * refuses a binding whose host isn't allowed).
686
+ *
687
+ * The sidecar POSTs a fire-and-forget webhook when the sandbox is denied a DNS query. This
688
+ * gate listens for that, calls the caller's handler, and on approval:
689
+ * 1. flips the sidecar rule to `allow` for that host (`sb.egress.patch`), then
690
+ * 2. registers the held credential(s) for it (`sb.credentials.set`) — so the credential
691
+ * literally does not exist inside the sandbox until a human approves.
692
+ *
693
+ * `allow-once` reverses both at the end of the turn; `allow-always` leaves them in place.
694
+ * Enforcement is entirely out-of-process — a compromised in-sandbox agent cannot skip it.
695
+ *
696
+ * The listener binds `0.0.0.0` on an ephemeral port and is torn down with the agent.
697
+ */
698
+ type EgressDecision = "allow-once" | "allow-always" | "deny";
699
+ /** One egress attempt awaiting a decision. */
700
+ interface EgressRequest {
701
+ /** The hostname the agent's sandbox tried to reach. */
702
+ host: string;
703
+ /** Unix ms when the sidecar reported the denial. */
704
+ since: number;
705
+ }
706
+ type EgressRequestHandler = (req: EgressRequest) => EgressDecision | Promise<EgressDecision>;
707
+ /** A credential whose registration is gated behind egress approval for its host. */
708
+ interface HeldCredential {
709
+ name: string;
710
+ value: string;
711
+ binding: CredentialBinding;
712
+ source?: CredentialSource;
713
+ }
714
+ interface EgressApprovalGateOptions {
715
+ /**
716
+ * Credentials whose host starts denied. The gate allows the host and registers these on
717
+ * approval. (Non-credential held hosts can be passed as `{ name, value: "", binding }` with
718
+ * an empty value — the gate then only manages the egress rule.)
719
+ */
720
+ heldCredentials: HeldCredential[];
721
+ handler: EgressRequestHandler;
722
+ /**
723
+ * Address the sandbox's egress sidecar can reach this host process at. Defaults to the
724
+ * Docker default-bridge gateway (`172.17.0.1`), which an `alineo init` server's sidecars
725
+ * can reach. Override for other topologies via `ALINEO_EGRESS_APPROVAL_HOST`.
726
+ */
727
+ webhookHost?: string;
728
+ }
729
+ declare class EgressApprovalGate {
730
+ private server;
731
+ private port;
732
+ private sandbox;
733
+ private readonly handler;
734
+ private readonly webhookHost;
735
+ /** host → the held credentials bound to it. */
736
+ private readonly byHost;
737
+ /** Hosts still gated — dropped once permanently opened by `allow-always`. */
738
+ private readonly held;
739
+ /** host → last time we raised a request for it (dedup; the webhook fires per DNS query). */
740
+ private readonly seen;
741
+ /** Hosts with a decision currently in flight. */
742
+ private readonly inFlight;
743
+ /** Hosts approved `allow-once` — reversed on `endTurn()`. */
744
+ private readonly onceApproved;
745
+ constructor(opts: EgressApprovalGateOptions);
746
+ /** Attach the sandbox whose egress this gate manages. Called once its handle exists. */
747
+ bind(sandbox: SandboxHandle): void;
748
+ private sb;
749
+ /** Start the listener. Idempotent. */
750
+ start(): Promise<void>;
751
+ /** Stop the listener. */
752
+ stop(): Promise<void>;
753
+ /** The `OPENSANDBOX_EGRESS_DENY_WEBHOOK` value to put in the sandbox's env. */
754
+ get webhookUrl(): string;
755
+ /** Egress requests currently awaiting a decision. */
756
+ pending(): EgressRequest[];
757
+ /**
758
+ * Reverse every `allow-once` approval — remove its credential(s) and re-deny the host.
759
+ * Call when an agent turn ends so a one-shot grant does not silently persist.
760
+ */
761
+ endTurn(): Promise<void>;
762
+ private onDenied;
763
+ }
764
+ //#endregion
765
+ //#region src/agent/session-control.d.ts
766
+ /**
767
+ * Called for each `permission_request` on a `prompt()`/`bash()` stream when passed as
768
+ * `opts.onPermission`. Return the decision; the SDK resolves the request for you. The
769
+ * `permission_request` / `permission_resolved` events still flow through the stream.
770
+ */
771
+ type PermissionHandler = (req: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
772
+ //#endregion
528
773
  //#region src/agent/agent.d.ts
529
774
  /**
530
775
  * A live AI coding agent running inside an OpenSandbox container.
@@ -609,7 +854,15 @@ declare class Alineo {
609
854
  * `.memory` methods instead if this agent's resourceId/teamId aren't the identity you want.
610
855
  */
611
856
  get resourceRef(): ResourceRef;
857
+ /**
858
+ * Present when the spec has `approval: "hold"` credential bindings — the out-of-process
859
+ * gate that holds the sandbox's egress to those hosts until `onEgressRequest` approves.
860
+ * Stopped by `close()`.
861
+ */
862
+ readonly egressGate?: EgressApprovalGate;
612
863
  private constructor();
864
+ /** Egress requests currently awaiting a decision (see `AgentSpec.env` `approval: "hold"`). */
865
+ pendingEgressRequests(): EgressRequest[];
613
866
  /**
614
867
  * Validate `spec` and return a fully initialised `Alineo`.
615
868
  *
@@ -642,6 +895,13 @@ declare class Alineo {
642
895
  maxAgents?: number;
643
896
  runId?: string; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
644
897
  memory?: Memory;
898
+ /**
899
+ * Required when the spec has `approval: "hold"` credential bindings — decides each
900
+ * first outbound request to a held host: return `"allow-once"` (reverts at turn end),
901
+ * `"allow-always"` (permanent for this agent's life), or `"deny"`. Enforcement is
902
+ * out-of-process at the egress sidecar; a compromised agent cannot skip it.
903
+ */
904
+ onEgressRequest?: EgressRequestHandler;
645
905
  }): Promise<Alineo>;
646
906
  /**
647
907
  * Reconnect to a previously-created agent whose host process has exited.
@@ -763,6 +1023,12 @@ declare class Alineo {
763
1023
  prompt(message: string, opts?: {
764
1024
  streamingBehavior?: "steer" | "followUp";
765
1025
  inactivityTimeoutMs?: number;
1026
+ /**
1027
+ * Auto-resolve each `permission_request` on this stream with the handler's decision,
1028
+ * instead of the caller wiring `resolvePermission()` by hand. The
1029
+ * `permission_request` / `permission_resolved` events still flow through the stream.
1030
+ */
1031
+ onPermission?: PermissionHandler;
766
1032
  }): AgentStream;
767
1033
  /**
768
1034
  * Run a shell command inside Pi's working context. Not incrementally
@@ -774,6 +1040,26 @@ declare class Alineo {
774
1040
  steer(message: string): Promise<void>;
775
1041
  /** Abort Pi's current operation. */
776
1042
  abort(): Promise<void>;
1043
+ /**
1044
+ * Resolve a pending `permission_request` from the agent stream — emitted for each gated
1045
+ * tool call when `AgentSpec.permissions` is set to something other than `"auto"`.
1046
+ *
1047
+ * @example
1048
+ * ```ts
1049
+ * for await (const ev of agent.prompt("Refactor auth")) {
1050
+ * if (ev.type === "permission_request") {
1051
+ * await agent.resolvePermission(ev.requestId, { kind: "once" });
1052
+ * }
1053
+ * }
1054
+ * ```
1055
+ */
1056
+ resolvePermission(requestId: string, decision: PermissionDecision): Promise<void>;
1057
+ /**
1058
+ * Tool calls currently paused awaiting a human decision — useful after reconnecting to a
1059
+ * session to discover approvals still outstanding. Each entry is resolvable with
1060
+ * `resolvePermission(entry.requestId, …)`.
1061
+ */
1062
+ listPendingPermissions(): Promise<PendingPermission[]>;
777
1063
  /** Queue a message to be sent to Pi after it finishes its current task. */
778
1064
  followUp(message: string): Promise<void>;
779
1065
  /** Start a fresh Pi session, clearing all prior context. */
@@ -909,4 +1195,4 @@ declare class AgentSpecValidationError extends WorkflowError {
909
1195
  constructor(message: string, issues: readonly Pick<z.core.$ZodIssue, "path" | "message" | "code">[]);
910
1196
  }
911
1197
  //#endregion
912
- export { type AgentEvent, type AgentSnapshotRecord, AgentSnapshotStore, type AgentSpec, AgentSpecValidationError, type AgentStream, Alineo, type CompactResult, type PiMessage, type PiModel, type PiSessionState, type PiSlashCommand, type PromptStream, PromptTimeoutError, type SessionStats, type SetupStep, type ThinkingLevel, computeSetupHash, snapshotsPath, textOnly, validateAgentSpec };
1198
+ export { type AgentEvent, type AgentSnapshotRecord, AgentSnapshotStore, type AgentSpec, AgentSpecValidationError, type AgentStream, Alineo, type CompactResult, EgressApprovalGate, type EgressApprovalGateOptions, type EgressDecision, type EgressRequest, type EgressRequestHandler, type HeldCredential, type PendingPermission, type PermissionAction, type PermissionDecision, type PermissionHandler, type PermissionMode, type PermissionPolicy, type PermissionRequest, type PermissionRule, type PiMessage, type PiModel, type PiSessionState, type PiSlashCommand, type PromptStream, PromptTimeoutError, type SessionStats, type SetupStep, type ThinkingLevel, computeSetupHash, isReadOnlyBashCommand, snapshotsPath, textOnly, validateAgentSpec };