alineo 0.2.0 → 0.3.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,35 @@
1
1
  import { z } from "zod";
2
2
  import { IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
3
+ import { Memory, ResourceRef } from "@alineo-labs/memory";
3
4
 
4
5
  //#region src/schema.d.ts
6
+ /**
7
+ * Opt-in alternative to a plain `AgentSpec.env` string value — instead of interpolating
8
+ * straight into the container's environment, `credential` is registered with the sandbox's
9
+ * `CredentialBroker` via `sb.credentials.set()` and injected transparently into outbound
10
+ * requests to `host`. The sandbox process never sees the resolved value at all. Requires the
11
+ * agent's sandbox to be created with `credentialProxy: true` — `Alineo.load()`/`.resume()`/
12
+ * `.spawn()` set this automatically whenever `env` contains at least one binding like this.
13
+ */
14
+ interface CredentialEnvBinding {
15
+ /** Host env var reference to resolve the real value from, e.g. `"${OPENAI_API_KEY}"`. */
16
+ credential: string;
17
+ /** FQDN or wildcard domain this credential is injected for. */
18
+ host: string;
19
+ /** Narrows the binding to requests whose path starts with this prefix. */
20
+ pathPrefix?: string;
21
+ /** How the credential reaches the request. */
22
+ injection: {
23
+ type: "header";
24
+ name: string;
25
+ } | {
26
+ type: "query";
27
+ param: string;
28
+ } | {
29
+ type: "path";
30
+ segment: string;
31
+ };
32
+ }
5
33
  /**
6
34
  * A single named setup step run inside the sandbox after Pi CLI install,
7
35
  * before the snapshot is taken. The step is a bash shell command.
@@ -62,8 +90,12 @@ interface AgentSpec {
62
90
  /**
63
91
  * Environment variables available inside the sandbox.
64
92
  * Values may reference host env vars: `{ GEMINI_API_KEY: "${GEMINI_API_KEY}" }`.
93
+ *
94
+ * A value can instead be a `CredentialEnvBinding` to opt that one key out of plain env-var
95
+ * interpolation entirely — the key never becomes a container env var; its value is injected
96
+ * transparently into matching outbound requests instead. See `CredentialEnvBinding`.
65
97
  */
66
- env?: Record<string, string>;
98
+ env?: Record<string, string | CredentialEnvBinding>;
67
99
  /**
68
100
  * CPU/memory/GPU resource limits for the sandbox container.
69
101
  * Falls back to defaults in `alineo.config.json` if omitted.
@@ -107,6 +139,34 @@ interface AgentSpec {
107
139
  * coordinate this budget with each other.
108
140
  */
109
141
  maxAgents?: number;
142
+ /**
143
+ * Durable team identity for this agent's `.resourceRef` — see `@alineo-labs/memory`'s
144
+ * `ResourceRef.teamId`. Unset by default (unlike `resourceId`, which always gets
145
+ * `spec.name` as its own default) — most agents aren't tied to a team-scoped memory.
146
+ * `Alineo.load()`/`.resume()` also thread this into `SandboxOptions.teamId`/
147
+ * `RestoreSnapshotOptions.teamId` so it stays consistent with the ledger, not just
148
+ * `.resourceRef` — otherwise a team-scoped agent's own episodic history would be
149
+ * unreachable through its own `resourceRef`, since `episodicRecall()` enforces `teamId`
150
+ * strictly. `Alineo.spawn()` passes `SandboxHandle.fork()`'s `resourceId`/`teamId` override
151
+ * (see its own doc comment) so a spawned child's ledger record matches its
152
+ * `.resourceRef` too, rather than silently inheriting the parent's.
153
+ */
154
+ teamId?: string;
155
+ /**
156
+ * Durable resource identity for this agent's `.resourceRef` — see `@alineo-labs/memory`'s
157
+ * `ResourceRef.resourceId`. Defaults to `spec.name` when unset, same as the implicit
158
+ * behavior before this field existed.
159
+ *
160
+ * Exists as its own field, separate from `name`, specifically for `Alineo.spawn()`: a
161
+ * spawned child's `.name` is overwritten to the forked sandbox's auto-generated ledger name
162
+ * (`fork-<parent>-<id>`, used for `alineo agents` display and future fork labeling) — not
163
+ * `childSpec.name`. Without a separate `resourceId` field, a spawned child's memory scope
164
+ * would silently become that auto-generated name instead of the identity the spec author
165
+ * actually declared. `Alineo.spawn()` freezes this to `childSpec.resourceId ?? childSpec.name`
166
+ * before the rename happens, so a spawned child's memory scope is stable and predictable
167
+ * regardless of what the ledger ends up calling the forked sandbox.
168
+ */
169
+ resourceId?: string;
110
170
  }
111
171
  /**
112
172
  * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
@@ -516,6 +576,39 @@ declare class Alineo {
516
576
  * transitively, `alineo fork`) always inherits its parent's `runId`.
517
577
  */
518
578
  readonly runId: string;
579
+ /**
580
+ * Optional provider-agnostic memory (`@alineo-labs/memory`), wired in via `opts.memory` on
581
+ * `load()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
582
+ * constructs a `Memory` on your own behalf, matching this package's "own the pipeline,
583
+ * don't assume a backend" design. `spawn()` carries the parent's `memory` (if any) onto the
584
+ * child automatically, the same way it force-computes spawn-depth rather than reading it
585
+ * back off the child's own spec.
586
+ */
587
+ memory?: Memory;
588
+ /**
589
+ * Durable team identity for `.resourceRef` — see `AgentSpec.teamId`. `undefined` unless the
590
+ * spec this agent was loaded from set it.
591
+ */
592
+ readonly teamId: string | undefined;
593
+ /**
594
+ * Durable resource identity for `.resourceRef` — see `AgentSpec.resourceId`. Deliberately
595
+ * separate from `.name`: for a spawned child specifically, `.name` gets overwritten to the
596
+ * forked sandbox's auto-generated ledger name (`fork-<parent>-<id>`), which is NOT what
597
+ * memory should be scoped by — see `AgentSpec.resourceId`'s own doc comment for why.
598
+ */
599
+ readonly resourceId: string;
600
+ /**
601
+ * Convenience `ResourceRef` scoping `.memory` calls to this agent. `resourceId`/`teamId`
602
+ * come from `AgentSpec.resourceId`/`AgentSpec.teamId` (`resourceId` defaulting to this
603
+ * agent's `name` when unset) — `load()`/`resume()`/`spawn()` also thread both into the
604
+ * ledger (see each field's own doc comment) so this getter and the agent's own episodic
605
+ * history stay consistent, including across a spawned child whose `.name` differs from its
606
+ * memory identity.
607
+ *
608
+ * Only meaningful once `.memory` is set; pass a different `ResourceRef` explicitly to
609
+ * `.memory` methods instead if this agent's resourceId/teamId aren't the identity you want.
610
+ */
611
+ get resourceRef(): ResourceRef;
519
612
  private constructor();
520
613
  /**
521
614
  * Validate `spec` and return a fully initialised `Alineo`.
@@ -547,7 +640,8 @@ declare class Alineo {
547
640
  rebuild?: boolean;
548
641
  spawnDepth?: number;
549
642
  maxAgents?: number;
550
- runId?: string;
643
+ runId?: string; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
644
+ memory?: Memory;
551
645
  }): Promise<Alineo>;
552
646
  /**
553
647
  * Reconnect to a previously-created agent whose host process has exited.
@@ -585,7 +679,8 @@ declare class Alineo {
585
679
  adapter: IStorageAdapter;
586
680
  spec?: AgentSpec | Record<string, unknown>;
587
681
  specPath?: string;
588
- runId?: string;
682
+ runId?: string; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
683
+ memory?: Memory;
589
684
  }): Promise<Alineo>;
590
685
  /**
591
686
  * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
@@ -624,7 +719,8 @@ declare class Alineo {
624
719
  cpu: string;
625
720
  memory: string;
626
721
  gpu?: string;
627
- };
722
+ }; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
723
+ memory?: Memory;
628
724
  }): Promise<Alineo>;
629
725
  /**
630
726
  * Fork this agent's live sandbox — filesystem, installed packages, checked-out
package/dist/index.mjs CHANGED
@@ -80,6 +80,15 @@ var AgentSpecValidationError = class extends WorkflowError {
80
80
  };
81
81
  //#endregion
82
82
  //#region src/schema.ts
83
+ /** Renders an arbitrary invalid field value for an error message without risking "[object Object]". */
84
+ function describeValue(value) {
85
+ if (typeof value === "string") return value;
86
+ try {
87
+ const json = JSON.stringify(value);
88
+ if (json !== void 0) return json;
89
+ } catch {}
90
+ return typeof value === "object" && value !== null ? Object.prototype.toString.call(value) : String(value);
91
+ }
83
92
  /**
84
93
  * Runtime schema for `SetupStep`/`AgentSpec` above. Kept as a separate Zod schema rather than
85
94
  * generating the interfaces from it (`z.infer<>`) so the hand-written interfaces above can carry
@@ -88,6 +97,25 @@ var AgentSpecValidationError = class extends WorkflowError {
88
97
  * If you add/change/remove a field on `AgentSpec`/`SetupStep`, update the matching schema field
89
98
  * here too — `packages/agent/test/schema.test.ts` is the drift check.
90
99
  */
100
+ const CredentialEnvBindingSchema = z$1.object({
101
+ credential: z$1.string({ error: "Each credential env binding must have a 'credential' string" }),
102
+ host: z$1.string({ error: "Each credential env binding must have a 'host' string" }),
103
+ 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
+ ])
118
+ }).loose();
91
119
  const SetupStepSchema = z$1.object({
92
120
  name: z$1.string({ error: "Each setup step must have a 'name' string" }),
93
121
  run: z$1.string({ error: "Each setup step must have a 'run' string" }),
@@ -101,12 +129,12 @@ const AgentSpecSchema = z$1.object({
101
129
  description: z$1.string().optional(),
102
130
  author: z$1.string().optional(),
103
131
  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: '${String(issue.input)}'. Supported values: pi` }),
132
+ 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
133
  cliVersion: z$1.string().optional(),
106
134
  provider: z$1.string().optional(),
107
135
  model: z$1.string().optional(),
108
136
  packages: z$1.array(z$1.string()).optional(),
109
- env: z$1.record(z$1.string(), z$1.string()).optional(),
137
+ env: z$1.record(z$1.string(), z$1.union([z$1.string(), CredentialEnvBindingSchema])).optional(),
110
138
  resources: z$1.object({
111
139
  cpu: z$1.string(),
112
140
  memory: z$1.string(),
@@ -116,7 +144,9 @@ const AgentSpecSchema = z$1.object({
116
144
  registryDependencies: z$1.array(z$1.string()).optional(),
117
145
  setup: z$1.array(SetupStepSchema).optional(),
118
146
  spawnDepth: nonNegativeIntSpecField("spawnDepth"),
119
- maxAgents: nonNegativeIntSpecField("maxAgents")
147
+ maxAgents: nonNegativeIntSpecField("maxAgents"),
148
+ teamId: z$1.string().optional(),
149
+ resourceId: z$1.string().optional()
120
150
  }).loose();
121
151
  /**
122
152
  * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
@@ -138,11 +168,54 @@ const BRIDGE_SCRIPT = readFileSync(fileURLToPath(new URL("./pi-bridge.js", impor
138
168
  function toShellExports(env) {
139
169
  return Object.entries(env).map(([k, v]) => `export ${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`).join("\n") + "\n";
140
170
  }
171
+ /**
172
+ * Resolves plain string entries of `AgentSpec.env`, interpolating `${VAR}` from `process.env`.
173
+ * Credential-bound entries (`{ credential, host, injection }`) are deliberately skipped here —
174
+ * see `extractCredentialBindings()` — they never become a container env var at all.
175
+ */
141
176
  function resolveEnv(env) {
142
177
  const result = {};
143
- for (const [key, value] of Object.entries(env)) result[key] = value.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] ?? "");
178
+ for (const [key, value] of Object.entries(env)) {
179
+ if (typeof value !== "string") continue;
180
+ result[key] = value.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] ?? "");
181
+ }
144
182
  return result;
145
183
  }
184
+ /** Matches a `credential` value that is *only* a single `${VAR}` reference, nothing else. */
185
+ const SOLE_ENV_REF = /^\$\{([^}]+)\}$/;
186
+ /**
187
+ * Pulls the credential-bound entries out of `AgentSpec.env` — the opt-in alternative to plain
188
+ * env-var interpolation (see `AgentSpec.env`'s docs). Each entry's `credential` value is
189
+ * interpolated the same way `resolveEnv()` interpolates plain strings; the resolved value is
190
+ * only ever handed to `sb.credentials.set()`, never written into the container's environment.
191
+ *
192
+ * Also derives a `CredentialSource` for each: `credential: "${VAR}"` (the whole value, nothing
193
+ * else around it) becomes `{ type: "env", varName: "VAR" }`, letting `fork()`/`resume()`
194
+ * re-resolve it automatically later without needing a callback. Anything else — a literal
195
+ * value, or `${VAR}` embedded in a larger string — becomes `{ type: "external" }`, since it
196
+ * isn't reliably re-derivable the same way twice.
197
+ */
198
+ function extractCredentialBindings(env) {
199
+ const out = [];
200
+ for (const [key, value] of Object.entries(env)) {
201
+ if (typeof value === "string") continue;
202
+ const soleRef = value.credential.match(SOLE_ENV_REF);
203
+ out.push({
204
+ name: key,
205
+ value: value.credential.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] ?? ""),
206
+ binding: {
207
+ host: value.host,
208
+ pathPrefix: value.pathPrefix,
209
+ injection: value.injection
210
+ },
211
+ source: soleRef ? {
212
+ type: "env",
213
+ varName: soleRef[1]
214
+ } : { type: "external" }
215
+ });
216
+ }
217
+ return out;
218
+ }
146
219
  /** Inverse of `toShellExports` — parses `/etc/alineo-env`'s content back into a plain object. */
147
220
  function parseShellExports(content) {
148
221
  const result = {};
@@ -408,7 +481,11 @@ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeo
408
481
  while (true) {
409
482
  const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
410
483
  if (remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
411
- const result = await Promise.race([reader.read(), new Promise((resolve) => setTimeout(() => resolve("timeout"), remainingMs))]);
484
+ const result = await Promise.race([reader.read(), new Promise((resolve) => {
485
+ setTimeout(() => {
486
+ resolve("timeout");
487
+ }, remainingMs);
488
+ })]);
412
489
  if (result === "timeout") throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
413
490
  const { done, value } = result;
414
491
  if (done) {
@@ -417,7 +494,7 @@ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeo
417
494
  }
418
495
  buf += decoder.decode(value, { stream: true });
419
496
  const lines = buf.split("\n");
420
- buf = lines.pop();
497
+ buf = lines.pop() ?? "";
421
498
  for (const line of lines) {
422
499
  if (!line.startsWith("data: ")) continue;
423
500
  const payload = line.slice(6).trim();
@@ -495,6 +572,19 @@ var AgentSnapshotStore = class {
495
572
  };
496
573
  //#endregion
497
574
  //#region src/agent/validation.ts
575
+ /**
576
+ * The durable resource identity for a spawned child, frozen from the child spec BEFORE
577
+ * `Alineo.spawn()` overwrites its `.name` to the forked sandbox's auto-generated ledger name
578
+ * (`fork-<parent>-<id>`) — see `AgentSpec.resourceId`'s own doc comment for why `child.name`
579
+ * can't be read for this after the fork completes. Extracted as its own function (mirroring
580
+ * `resolveParentSpawnDepth`/`resolveParentMaxAgents` below) so this one line of resolution
581
+ * logic — easy to get backwards, hard to notice if so, since both `spawnChild()`'s
582
+ * `self.sandbox.fork()` call and its returned `AgentConstructorArgs.spec.resourceId` must
583
+ * agree on the exact same value — is independently unit-testable.
584
+ */
585
+ function resolveChildResourceId(childSpec) {
586
+ return childSpec.resourceId ?? childSpec.name;
587
+ }
498
588
  function assertValidSpawnDepth(value, context) {
499
589
  if (!Number.isInteger(value) || value < 0) throw new Error(`${context}: spawnDepth must be a non-negative integer (got ${value})`);
500
590
  }
@@ -557,6 +647,12 @@ async function loadAgent(specInput, opts) {
557
647
  ...config.defaults.resources,
558
648
  ...spec.resources ?? {}
559
649
  };
650
+ const credentialBindings = extractCredentialBindings(spec.env ?? {});
651
+ const needsCredentialProxy = credentialBindings.length > 0;
652
+ const networkPolicy = needsCredentialProxy ? {
653
+ defaultAction: "allow",
654
+ egress: []
655
+ } : void 0;
560
656
  const client = new Sandbox({
561
657
  baseUrl: config.serverUrl,
562
658
  apiKey: config.apiKey,
@@ -573,7 +669,12 @@ async function loadAgent(specInput, opts) {
573
669
  if (record) try {
574
670
  console.log(`[agent] restoring from snapshot...`);
575
671
  const t1 = Date.now();
576
- sb = await client.restoreSnapshot(record.snapshotId, spec.name, resources, runId);
672
+ sb = await client.restoreSnapshot(record.snapshotId, spec.name, resources, runId, {
673
+ networkPolicy,
674
+ credentialProxy: needsCredentialProxy,
675
+ resourceId: spec.resourceId ?? spec.name,
676
+ teamId: spec.teamId
677
+ });
577
678
  console.log(`[agent] snapshot ready ${elapsed(t1)} (${sb.sandboxId})`);
578
679
  fromSnapshot = true;
579
680
  } catch (err) {
@@ -590,7 +691,11 @@ async function loadAgent(specInput, opts) {
590
691
  resources,
591
692
  name: spec.name,
592
693
  env: resolvedEnv,
593
- runId
694
+ runId,
695
+ networkPolicy,
696
+ credentialProxy: needsCredentialProxy,
697
+ resourceId: spec.resourceId ?? spec.name,
698
+ teamId: spec.teamId
594
699
  });
595
700
  console.log(`[agent] sandbox ready ${elapsed(t1)} (${sb.sandboxId})`);
596
701
  console.log(`[agent] installing Pi CLI...`);
@@ -615,6 +720,8 @@ async function loadAgent(specInput, opts) {
615
720
  });
616
721
  console.log(`[agent] checkpoint done ${elapsed(t3)}`);
617
722
  }
723
+ 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);
618
725
  resolvedEnv.ALINEO_SANDBOX_ID = sb.sandboxId;
619
726
  await adapter.configure(sb, spec, resolvedEnv);
620
727
  console.log(`[agent] starting bridge...`);
@@ -666,7 +773,11 @@ async function resumeAgent(sandboxId, opts) {
666
773
  resolvedEnv.ALINEO_RUN_ID = runId;
667
774
  console.log(`[agent] reconnecting to ${sandboxId}...`);
668
775
  const t1 = Date.now();
669
- const sb = await client.connect(sandboxId, spec.name, { runId });
776
+ const sb = await client.connect(sandboxId, spec.name, {
777
+ runId,
778
+ resourceId: spec.resourceId ?? spec.name,
779
+ teamId: spec.teamId
780
+ });
670
781
  console.log(`[agent] connected ${elapsed(t1)}`);
671
782
  await sb.exec("pkill -f 'node /alineo-bridge.js' 2>/dev/null; sleep 0.1; true", { strict: false });
672
783
  const adapter = new PiAdapter();
@@ -735,10 +846,17 @@ async function spawnChild(self, childSpecPath, opts = {}) {
735
846
  if (parentMax !== void 0) childEnv.ALINEO_MAX_AGENTS = String(parentMax - 1);
736
847
  const runId = process.env.ALINEO_RUN_ID ?? crypto.randomUUID();
737
848
  childEnv.ALINEO_RUN_ID = runId;
849
+ const childCredentialBindings = extractCredentialBindings(childSpec.env ?? {});
850
+ const childResourceId = resolveChildResourceId(childSpec);
738
851
  console.log(`[agent] forking sandbox for spawn (${childSpec.name})...`);
739
852
  const t0 = Date.now();
740
- const forkedSb = await self.sandbox.fork(childSpec.name, runId);
853
+ const forkedSb = await self.sandbox.fork(childSpec.name, runId, {
854
+ credentialProxy: childCredentialBindings.length > 0,
855
+ resourceId: childResourceId,
856
+ teamId: childSpec.teamId
857
+ });
741
858
  console.log(`[agent] fork ready ${elapsed(t0)} (${forkedSb.sandboxId})`);
859
+ for (const { name, value, binding, source } of childCredentialBindings) await forkedSb.credentials.set(name, value, binding, source);
742
860
  const adapter = new PiAdapter();
743
861
  childEnv.ALINEO_SANDBOX_ID = forkedSb.sandboxId;
744
862
  await adapter.configure(forkedSb, childSpec, childEnv);
@@ -751,7 +869,8 @@ async function spawnChild(self, childSpecPath, opts = {}) {
751
869
  sandbox: forkedSb,
752
870
  spec: {
753
871
  ...childSpec,
754
- name: forkedSb.name
872
+ name: forkedSb.name,
873
+ resourceId: childResourceId
755
874
  },
756
875
  env: childEnv,
757
876
  adapter,
@@ -759,6 +878,30 @@ async function spawnChild(self, childSpecPath, opts = {}) {
759
878
  runId
760
879
  };
761
880
  }
881
+ /**
882
+ * Seed a just-constructed spawn child's memory from its parent — the memory-layer
883
+ * counterpart to `spawnChild()`'s sandbox-level fork above. Called from `Alineo.spawn()`
884
+ * after the child is constructed (not from `spawnChild()` itself, which runs before the
885
+ * child exists and so has no `child.resourceRef` to fork into yet).
886
+ *
887
+ * A no-op when `parentMemory` is `undefined` — most agents don't have `.memory` configured.
888
+ * Otherwise forks an independent snapshot copy the child can mutate on its own, not a live
889
+ * share of the parent's scope (`child.resourceRef` already names a different resource — the
890
+ * child spec's own name — so this seeds that scope rather than overwriting the parent's).
891
+ *
892
+ * The sandbox fork has already succeeded by the time this runs (`child.sandbox` is live) —
893
+ * if the memory-layer fork throws, close the child sandbox before rethrowing rather than
894
+ * leaving it orphaned with nothing left to close it.
895
+ */
896
+ async function forkChildMemory(parentMemory, parentRef, child) {
897
+ if (!parentMemory) return;
898
+ try {
899
+ await parentMemory.fork(parentRef, child.resourceRef.resourceId);
900
+ } catch (err) {
901
+ await child.close().catch(() => {});
902
+ throw err;
903
+ }
904
+ }
762
905
  //#endregion
763
906
  //#region src/agent/session-control.ts
764
907
  /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
@@ -988,10 +1131,50 @@ var Alineo = class Alineo {
988
1131
  * transitively, `alineo fork`) always inherits its parent's `runId`.
989
1132
  */
990
1133
  runId;
1134
+ /**
1135
+ * Optional provider-agnostic memory (`@alineo-labs/memory`), wired in via `opts.memory` on
1136
+ * `load()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
1137
+ * constructs a `Memory` on your own behalf, matching this package's "own the pipeline,
1138
+ * don't assume a backend" design. `spawn()` carries the parent's `memory` (if any) onto the
1139
+ * child automatically, the same way it force-computes spawn-depth rather than reading it
1140
+ * back off the child's own spec.
1141
+ */
1142
+ memory;
1143
+ /**
1144
+ * Durable team identity for `.resourceRef` — see `AgentSpec.teamId`. `undefined` unless the
1145
+ * spec this agent was loaded from set it.
1146
+ */
1147
+ teamId;
1148
+ /**
1149
+ * Durable resource identity for `.resourceRef` — see `AgentSpec.resourceId`. Deliberately
1150
+ * separate from `.name`: for a spawned child specifically, `.name` gets overwritten to the
1151
+ * forked sandbox's auto-generated ledger name (`fork-<parent>-<id>`), which is NOT what
1152
+ * memory should be scoped by — see `AgentSpec.resourceId`'s own doc comment for why.
1153
+ */
1154
+ resourceId;
1155
+ /**
1156
+ * Convenience `ResourceRef` scoping `.memory` calls to this agent. `resourceId`/`teamId`
1157
+ * come from `AgentSpec.resourceId`/`AgentSpec.teamId` (`resourceId` defaulting to this
1158
+ * agent's `name` when unset) — `load()`/`resume()`/`spawn()` also thread both into the
1159
+ * ledger (see each field's own doc comment) so this getter and the agent's own episodic
1160
+ * history stay consistent, including across a spawned child whose `.name` differs from its
1161
+ * memory identity.
1162
+ *
1163
+ * Only meaningful once `.memory` is set; pass a different `ResourceRef` explicitly to
1164
+ * `.memory` methods instead if this agent's resourceId/teamId aren't the identity you want.
1165
+ */
1166
+ get resourceRef() {
1167
+ return {
1168
+ resourceId: this.resourceId,
1169
+ teamId: this.teamId
1170
+ };
1171
+ }
991
1172
  constructor(sandbox, spec, env, adapter, fromSnapshot, runId) {
992
1173
  this.sandbox = sandbox;
993
1174
  this.sandboxId = sandbox.sandboxId;
994
1175
  this.name = spec.name;
1176
+ this.teamId = spec.teamId;
1177
+ this.resourceId = spec.resourceId ?? spec.name;
995
1178
  this.adapter = adapter;
996
1179
  this.env = env;
997
1180
  this.fromSnapshot = fromSnapshot;
@@ -1024,7 +1207,9 @@ var Alineo = class Alineo {
1024
1207
  */
1025
1208
  static async load(spec, opts) {
1026
1209
  const r = await loadAgent(spec, opts);
1027
- return new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1210
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1211
+ agent.memory = opts.memory;
1212
+ return agent;
1028
1213
  }
1029
1214
  /**
1030
1215
  * Reconnect to a previously-created agent whose host process has exited.
@@ -1060,7 +1245,9 @@ var Alineo = class Alineo {
1060
1245
  */
1061
1246
  static async resume(sandboxId, opts) {
1062
1247
  const r = await resumeAgent(sandboxId, opts);
1063
- return new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1248
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1249
+ agent.memory = opts.memory;
1250
+ return agent;
1064
1251
  }
1065
1252
  /**
1066
1253
  * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
@@ -1094,7 +1281,9 @@ var Alineo = class Alineo {
1094
1281
  */
1095
1282
  static async attach(sandboxId, opts) {
1096
1283
  const r = await attachAgent(sandboxId, opts);
1097
- return new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1284
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1285
+ agent.memory = opts.memory;
1286
+ return agent;
1098
1287
  }
1099
1288
  /**
1100
1289
  * Fork this agent's live sandbox — filesystem, installed packages, checked-out
@@ -1131,7 +1320,10 @@ var Alineo = class Alineo {
1131
1320
  */
1132
1321
  async spawn(childSpecPath, opts = {}) {
1133
1322
  const r = await spawnChild(this, childSpecPath, opts);
1134
- return new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1323
+ const child = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1324
+ child.memory = this.memory;
1325
+ await forkChildMemory(this.memory, this.resourceRef, child);
1326
+ return child;
1135
1327
  }
1136
1328
  /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
1137
1329
  prompt(message, opts) {
package/dist/pi-bridge.js CHANGED
@@ -29,7 +29,7 @@ function buildPiArgs() {
29
29
  if (cfg.model) args.push("--model", cfg.model);
30
30
  if (cfg.resume) args.push("--continue");
31
31
  }
32
- } catch (e) {}
32
+ } catch {}
33
33
  return args;
34
34
  }
35
35
 
@@ -53,7 +53,7 @@ function startHeartbeat(res) {
53
53
  return setInterval(function () {
54
54
  try {
55
55
  res.write(": ping\n\n");
56
- } catch (e) {}
56
+ } catch {}
57
57
  }, 3000);
58
58
  }
59
59
  function stopHeartbeat(iv) {
@@ -82,7 +82,7 @@ function cleanupPendingCmds(reason) {
82
82
  try {
83
83
  p.res.write("data: " + JSON.stringify({ error: reason }) + "\n\n");
84
84
  p.res.end();
85
- } catch (e) {}
85
+ } catch {}
86
86
  } else {
87
87
  respond(p.res, 500, { ok: false, error: reason });
88
88
  }
@@ -103,12 +103,12 @@ function startPi() {
103
103
  if (state.rl) {
104
104
  try {
105
105
  state.rl.close();
106
- } catch (e) {}
106
+ } catch {}
107
107
  }
108
108
  if (state.proc) {
109
109
  try {
110
110
  state.proc.kill("SIGTERM");
111
- } catch (e) {}
111
+ } catch {}
112
112
  }
113
113
  state.proc = null;
114
114
  state.rl = null;
@@ -180,7 +180,7 @@ function handleLine(line) {
180
180
  var ev;
181
181
  try {
182
182
  ev = JSON.parse(line);
183
- } catch (e) {
183
+ } catch {
184
184
  return;
185
185
  }
186
186
 
@@ -222,11 +222,11 @@ function handleLine(line) {
222
222
  if (output)
223
223
  try {
224
224
  pending.res.write("data: " + JSON.stringify({ type: "text", text: output }) + "\n\n");
225
- } catch (e) {}
225
+ } catch {}
226
226
  try {
227
227
  pending.res.write("data: [DONE]\n\n");
228
228
  pending.res.end();
229
- } catch (e) {}
229
+ } catch {}
230
230
  } else if (ev.success) {
231
231
  respond(pending.res, 200, { ok: true, data: ev.data || null });
232
232
  } else {
@@ -515,7 +515,7 @@ function respond(res, status, body) {
515
515
  try {
516
516
  res.writeHead(status, { "Content-Type": "application/json" });
517
517
  res.end(JSON.stringify(body));
518
- } catch (e) {}
518
+ } catch {}
519
519
  }
520
520
 
521
521
  // --- HTTP server ---
@@ -565,7 +565,7 @@ http
565
565
  var data = {};
566
566
  try {
567
567
  if (body) data = JSON.parse(body);
568
- } catch (e) {
568
+ } catch {
569
569
  res.writeHead(400);
570
570
  res.end("bad json");
571
571
  return;
@@ -597,7 +597,7 @@ http
597
597
  try {
598
598
  res.write("data: " + JSON.stringify({ error: "bash timeout" }) + "\n\n");
599
599
  res.end();
600
- } catch (e) {}
600
+ } catch {}
601
601
  }
602
602
  }, 30000);
603
603
  res.writeHead(200, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alineo",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -28,8 +28,9 @@
28
28
  "test": "bun test"
29
29
  },
30
30
  "dependencies": {
31
- "@alineo-labs/core": "0.2.0",
32
- "@alineo-labs/sandbox": "0.2.0",
31
+ "@alineo-labs/core": "0.3.0",
32
+ "@alineo-labs/memory": "0.2.0",
33
+ "@alineo-labs/sandbox": "0.3.0",
33
34
  "zod": "^4.4.3"
34
35
  },
35
36
  "devDependencies": {