@aexhq/sdk 0.58.0 → 0.59.1

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/session.js CHANGED
@@ -1,15 +1,15 @@
1
- import { CustomerEnvironment } from "@aexhq/session-protocol";
2
- import { inspectEnvironment } from "@aexhq/environment";
1
+ import { CustomerEnvironment, prepareComponents, } from "@aexhq/brain";
3
2
  import * as z from "zod";
4
3
  import { AbortError, OutputRefusalError, OutputSchemaError, OutputValidationError, SessionError, abortError, errorFromApi, } from "./errors.js";
5
4
  import { canonicalize, jcsSha256, randomIdempotencyKey } from "./json.js";
6
- import { compileTools } from "./tools.js";
7
- import { encodeBase64, SessionChildren, SessionStorage } from "./resources.js";
5
+ import { compileCallbacks } from "./tools.js";
6
+ import { SessionChildren, SessionSandbox, SessionStorage } from "./resources.js";
8
7
  export class Sessions {
9
8
  #transport;
10
9
  #webSocketFactory;
11
10
  #customerEnvironments = new Map();
12
11
  #customerEnvironmentInstances = new Map();
12
+ #customerEnvironmentReadinessWaiters = new Map();
13
13
  #closed = false;
14
14
  constructor(transport, webSocketFactory) {
15
15
  this.#transport = transport;
@@ -20,21 +20,109 @@ export class Sessions {
20
20
  if (this.#closed)
21
21
  return;
22
22
  this.#closed = true;
23
- for (const environment of this.#customerEnvironmentInstances.values())
24
- environment.close();
23
+ for (const hand of this.#customerEnvironmentInstances.values())
24
+ hand.close();
25
25
  this.#customerEnvironmentInstances.clear();
26
26
  this.#customerEnvironments.clear();
27
27
  }
28
28
  async create(options, request = {}) {
29
29
  if (this.#closed)
30
30
  throw new SessionError("Aex client is closed");
31
- if (options.loop === undefined)
32
- throw new TypeError("sessions.create requires an imported loop");
33
- const compiledTools = await compileTools(options.tools, options.environments, options.secrets);
34
- await Promise.all(compiledTools.layers.map((layer) => this.#transport.ensureArtifactLayer(layer.checksum, layer.media_type, layer.content, request.signal)));
35
- await this.#ensureCustomerEnvironment(compiledTools.callbackClientId, compiledTools.clientRegistrations, request.signal);
31
+ if (options.model?.component === undefined) {
32
+ throw new TypeError("sessions.create requires an imported Model component");
33
+ }
34
+ if (options.agentloop === undefined) {
35
+ throw new TypeError("sessions.create requires an imported Agentloop component");
36
+ }
37
+ const model = options.model.component;
38
+ const agentloop = options.agentloop;
39
+ const tools = [...(options.tools ?? [])];
40
+ const componentTools = tools.filter(isComponentTool);
41
+ const callbackTools = tools.filter((tool) => !isComponentTool(tool));
42
+ const environments = Object.entries(options.environments ?? {});
43
+ if (environments.some(([, environment]) => !isEnvironmentComponent(environment))) {
44
+ throw new TypeError("component sessions accept only precompiled Environment component values");
45
+ }
46
+ const environmentComponents = environments.map(([name, environment]) => {
47
+ if (!isEnvironmentComponent(environment)) {
48
+ throw new TypeError(`Environment ${JSON.stringify(name)} is not a component`);
49
+ }
50
+ return [name, environment];
51
+ });
52
+ const applicationEnvironments = environmentComponents.filter(([, environment]) => isApplicationEnvironment(environment));
53
+ if (callbackTools.length > 0 && applicationEnvironments.length !== 1) {
54
+ throw new TypeError("application callback Tools require exactly one app() Environment");
55
+ }
56
+ const callbacks = await compileCallbacks(callbackTools);
57
+ const allComponentTools = [...componentTools, ...callbacks.components];
58
+ const toolDefinitions = allComponentTools.map(componentToolDefinition);
59
+ const names = new Set();
60
+ for (const definition of toolDefinitions) {
61
+ if (names.has(definition.name)) {
62
+ throw new TypeError(`Tool ${JSON.stringify(definition.name)} was selected twice`);
63
+ }
64
+ names.add(definition.name);
65
+ }
66
+ const callbackEnvironment = applicationEnvironments[0];
67
+ if (callbackEnvironment !== undefined) {
68
+ await this.#ensureCustomerEnvironment(applicationEnvironmentId(callbackEnvironment[1]), callbacks.registrations, request.signal);
69
+ }
70
+ const prepared = await prepareComponents([
71
+ model,
72
+ agentloop,
73
+ ...allComponentTools,
74
+ ...environmentComponents.map(([, environment]) => environment),
75
+ ]);
76
+ const modelBinding = prepared.bindings[0];
77
+ const agentloopBinding = prepared.bindings[1];
78
+ if (modelBinding === undefined || agentloopBinding === undefined) {
79
+ throw new TypeError("component session bindings are incomplete");
80
+ }
81
+ const toolBindings = prepared.bindings.slice(2, 2 + allComponentTools.length);
82
+ const environmentBindings = prepared.bindings.slice(2 + allComponentTools.length);
83
+ const toolItems = allComponentTools.map((tool, index) => {
84
+ const binding = toolBindings[index];
85
+ if (binding === undefined)
86
+ throw new TypeError("Tool component binding is missing");
87
+ const definition = toolDefinitions[index];
88
+ if (definition === undefined)
89
+ throw new TypeError("Tool component definition is missing");
90
+ const needsEnvironment = binding.grants.includes("environment");
91
+ const isCallback = index >= componentTools.length;
92
+ if (needsEnvironment && !isCallback && environmentComponents.length !== 1) {
93
+ throw new TypeError("a Tool with the environment grant requires exactly one declared Environment");
94
+ }
95
+ const environmentName = isCallback
96
+ ? callbackEnvironment?.[0]
97
+ : environmentComponents[0]?.[0];
98
+ return {
99
+ definition,
100
+ executor: {
101
+ kind: "component",
102
+ component_digest: binding.component_digest,
103
+ world: binding.world,
104
+ config: binding.config,
105
+ grants: binding.grants,
106
+ ...(needsEnvironment ? { environment: environmentName } : {}),
107
+ },
108
+ };
109
+ });
110
+ const environmentConfig = Object.fromEntries(environmentComponents.map(([name], index) => {
111
+ const binding = environmentBindings[index];
112
+ if (binding === undefined) {
113
+ throw new TypeError(`Environment component binding ${JSON.stringify(name)} is missing`);
114
+ }
115
+ return [name, {
116
+ component_digest: binding.component_digest,
117
+ world: binding.world,
118
+ config: binding.config,
119
+ }];
120
+ }));
36
121
  const body = {
37
122
  model: {
123
+ component_digest: modelBinding.component_digest,
124
+ world: modelBinding.world,
125
+ config: modelBinding.config,
38
126
  provider: options.model.provider,
39
127
  name: options.model.name,
40
128
  api_key: options.model.apiKey,
@@ -42,37 +130,24 @@ export class Sessions {
42
130
  ...(options.model.maxOutputTokens === undefined
43
131
  ? {}
44
132
  : { max_output_tokens: options.model.maxOutputTokens }),
45
- ...(options.model.contextWindowTokens === undefined
46
- ? {}
47
- : { context_window_tokens: options.model.contextWindowTokens }),
48
133
  },
49
- tools: {
50
- items: compiledTools.items,
51
- },
52
- ...(Object.keys(compiledTools.environments).length === 0
53
- ? {}
54
- : { environments: compiledTools.environments }),
55
- ...(compiledTools.bundles.length === 0 ? {} : { tool_bundles: compiledTools.bundles }),
56
134
  agentloop: {
57
- source_bundle_sha256: options.loop.sha256,
58
- toolchain: options.loop.toolchain,
59
- bundle_base64: encodeBase64(new TextEncoder().encode(options.loop.source)),
135
+ component_digest: agentloopBinding.component_digest,
136
+ world: agentloopBinding.world,
137
+ config: agentloopBinding.config,
60
138
  },
139
+ component_artifacts: prepared.artifacts,
140
+ tools: { items: toolItems },
141
+ ...(environmentComponents.length === 0 ? {} : { environments: environmentConfig }),
61
142
  ...(options.secrets === undefined ? {} : { secrets: options.secrets }),
62
143
  ...(options.metadata === undefined ? {} : { metadata: options.metadata }),
63
- ...(options.network === undefined
144
+ ...(options.retainUntil === undefined
64
145
  ? {}
65
- : { network: options.network }),
146
+ : { retain_until: normalizeTimestamp(options.retainUntil, "retainUntil") }),
147
+ ...(options.network === undefined ? {} : { network: options.network }),
66
148
  ...(options.providerRecoveryRetries === undefined
67
149
  ? {}
68
150
  : { provider_recovery_retries: options.providerRecoveryRetries }),
69
- ...(compiledTools.callbackClientId === undefined
70
- ? {}
71
- : {
72
- client: {
73
- id: compiledTools.callbackClientId,
74
- },
75
- }),
76
151
  ...(options.children === undefined
77
152
  ? {}
78
153
  : {
@@ -95,7 +170,7 @@ export class Sessions {
95
170
  signal: request.signal,
96
171
  retry: true,
97
172
  });
98
- return new Session(this.#transport, data, compiledTools.environmentNames);
173
+ return new Session(this.#transport, data);
99
174
  }
100
175
  async get(id, options = {}) {
101
176
  const data = await this.#transport.json("GET", `/v1/sessions/${encodeURIComponent(id)}`, { signal: options.signal });
@@ -163,16 +238,78 @@ export class Sessions {
163
238
  }
164
239
  }
165
240
  });
166
- // The request may stop waiting, but the process-scoped runner remains reconnectable for
167
- // later sessions. Its grant/reconnect lifetime must never inherit one create signal.
168
- await waitWithSignal(starting, signal);
241
+ await this.#waitForCustomerEnvironmentReadiness(clientId, starting, signal);
169
242
  return;
170
243
  }
171
- const environment = await waitWithSignal(existing, signal);
244
+ const hand = await this.#waitForCustomerEnvironmentReadiness(clientId, existing, signal);
172
245
  if (this.#closed)
173
246
  throw new SessionError("Aex client is closed");
174
- await waitWithSignal(environment.register(registrations), signal);
247
+ await waitWithSignal(hand.register(registrations), signal);
175
248
  }
249
+ async #waitForCustomerEnvironmentReadiness(clientId, starting, signal) {
250
+ this.#customerEnvironmentReadinessWaiters.set(clientId, (this.#customerEnvironmentReadinessWaiters.get(clientId) ?? 0) + 1);
251
+ let settled = false;
252
+ void starting.then(() => { settled = true; }, () => { settled = true; });
253
+ try {
254
+ return await waitWithSignal(starting, signal);
255
+ }
256
+ catch (error) {
257
+ if (signal?.aborted && !settled
258
+ && this.#customerEnvironmentReadinessWaiters.get(clientId) === 1
259
+ && this.#customerEnvironments.get(clientId) === starting) {
260
+ const partial = this.#customerEnvironmentInstances.get(clientId);
261
+ partial?.close();
262
+ this.#customerEnvironments.delete(clientId);
263
+ if (this.#customerEnvironmentInstances.get(clientId) === partial) {
264
+ this.#customerEnvironmentInstances.delete(clientId);
265
+ }
266
+ }
267
+ throw error;
268
+ }
269
+ finally {
270
+ const waiters = this.#customerEnvironmentReadinessWaiters.get(clientId) ?? 1;
271
+ if (waiters <= 1)
272
+ this.#customerEnvironmentReadinessWaiters.delete(clientId);
273
+ else
274
+ this.#customerEnvironmentReadinessWaiters.set(clientId, waiters - 1);
275
+ }
276
+ }
277
+ }
278
+ function isApplicationEnvironment(value) {
279
+ const config = value.config;
280
+ return config !== null && typeof config === "object" && !Array.isArray(config) &&
281
+ config.driver === "customer";
282
+ }
283
+ function applicationEnvironmentId(value) {
284
+ const config = value.config;
285
+ const id = config.configuration?.registration;
286
+ if (typeof id !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/u.test(id)) {
287
+ throw new TypeError("app() Environment registration is invalid");
288
+ }
289
+ return id;
290
+ }
291
+ function isComponentTool(value) {
292
+ return value !== null
293
+ && typeof value === "object"
294
+ && value.kind === "brain.component"
295
+ && value.extension === "tool";
296
+ }
297
+ function isEnvironmentComponent(value) {
298
+ return value !== null
299
+ && typeof value === "object"
300
+ && value.kind === "brain.component"
301
+ && value.extension === "environment";
302
+ }
303
+ function componentToolDefinition(value) {
304
+ const config = value.config;
305
+ if (config === null || typeof config !== "object" || Array.isArray(config)) {
306
+ throw new TypeError("Tool component config must be an object containing definition");
307
+ }
308
+ const definition = config.definition;
309
+ if (definition === null || typeof definition !== "object" || Array.isArray(definition)) {
310
+ throw new TypeError("Tool component config.definition is required");
311
+ }
312
+ return definition;
176
313
  }
177
314
  function waitWithSignal(promise, signal) {
178
315
  if (signal === undefined)
@@ -192,32 +329,16 @@ function waitWithSignal(promise, signal) {
192
329
  export class Session {
193
330
  #transport;
194
331
  #data;
332
+ sandbox;
195
333
  storage;
196
334
  children;
197
- #environmentNames;
198
- #environmentHandles = new Map();
199
- constructor(transport, data, environmentNames = new Map()) {
335
+ constructor(transport, data) {
200
336
  this.#transport = transport;
201
337
  this.#data = data;
202
- this.#environmentNames = environmentNames;
203
- this.storage = new SessionStorage(transport, data.id, environmentNames);
338
+ this.sandbox = new SessionSandbox(transport, data.id);
339
+ this.storage = new SessionStorage(transport, data.id);
204
340
  this.children = new SessionChildren(transport, data.id);
205
341
  }
206
- environment(environment) {
207
- const name = this.#environmentNames.get(environment);
208
- if (name === undefined)
209
- throw new TypeError("EnvironmentRef does not belong to this Session");
210
- const existing = this.#environmentHandles.get(environment);
211
- if (existing !== undefined)
212
- return existing;
213
- const handle = inspectEnvironment(environment).createHandle({
214
- sessionId: this.id,
215
- environment: name,
216
- request: async (method, path, body) => await this.#transport.json(method, path, body === undefined ? {} : { body }),
217
- });
218
- this.#environmentHandles.set(environment, handle);
219
- return handle;
220
- }
221
342
  get id() {
222
343
  return this.#data.id;
223
344
  }
@@ -250,6 +371,9 @@ export class Session {
250
371
  get updatedAt() {
251
372
  return this.#data.updated_at;
252
373
  }
374
+ get retainUntil() {
375
+ return this.#data.retain_until;
376
+ }
253
377
  get metadata() {
254
378
  return this.#data.metadata;
255
379
  }
@@ -351,6 +475,25 @@ export class Session {
351
475
  this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/cancel`, { signal: options.signal, retry: true });
352
476
  return this;
353
477
  }
478
+ async suspend(options = {}) {
479
+ this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/suspend`, { signal: options.signal, retry: true });
480
+ return this;
481
+ }
482
+ async resume(options = {}) {
483
+ this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/resume`, { signal: options.signal, retry: true });
484
+ return this;
485
+ }
486
+ async setRetention(value, options = {}) {
487
+ this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/retention`, {
488
+ body: {
489
+ retain_until: normalizeTimestamp(value, "retainUntil"),
490
+ allow_shorten: options.allowShorten ?? false,
491
+ },
492
+ signal: options.signal,
493
+ retry: true,
494
+ });
495
+ return this;
496
+ }
354
497
  async end(options = {}) {
355
498
  this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/end`, { signal: options.signal, retry: true });
356
499
  return this;
@@ -369,6 +512,12 @@ export class Session {
369
512
  function isOutputOptions(options) {
370
513
  return "output" in options;
371
514
  }
515
+ function normalizeTimestamp(value, field) {
516
+ const parsed = value instanceof Date ? value : new Date(value);
517
+ if (!Number.isFinite(parsed.getTime()))
518
+ throw new TypeError(`${field} must be a valid timestamp`);
519
+ return parsed.toISOString();
520
+ }
372
521
  async function compileOutputSchema(schema, retries) {
373
522
  let jsonSchema;
374
523
  try {
package/dist/tools.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { type ComputerProfile, type EnvironmentRef } from "@aexhq/environment";
1
+ import type { ComponentExtension } from "@aexhq/brain";
2
+ import type { ToolDefinition } from "@aexhq/brain/session";
2
3
  import * as z from "zod";
3
4
  export type JsonSchema = Record<string, unknown>;
4
5
  export interface ToolContext {
@@ -6,37 +7,8 @@ export interface ToolContext {
6
7
  readonly operationId: string;
7
8
  readonly sessionId: string;
8
9
  readonly deadlineMs: number;
9
- readonly workspace?: string;
10
10
  }
11
11
  export type ToolHandler<Input extends z.ZodType, Output = unknown> = (input: z.output<Input>, context: ToolContext) => Output | Promise<Output>;
12
- export type ToolSetupHandler = () => void | Promise<void>;
13
- export interface ToolRequirements {
14
- readonly env?: readonly string[];
15
- readonly workspace?: boolean;
16
- readonly processes?: boolean;
17
- readonly network?: readonly {
18
- readonly host: string;
19
- readonly port: number;
20
- }[];
21
- readonly streaming?: boolean;
22
- readonly recovery?: "retained" | "connection" | "replay-safe";
23
- }
24
- export interface PreparedArtifact {
25
- readonly digest: string;
26
- readonly target: ComputerProfile["platform"];
27
- readonly bytes: number;
28
- readonly execute: string;
29
- readonly setup?: string;
30
- readonly layers: readonly PreparedArtifactLayer[];
31
- }
32
- export interface PreparedArtifactLayer {
33
- readonly digest: string;
34
- readonly bytes: number;
35
- readonly mediaType: "application/javascript+esm" | "application/x-xz";
36
- readonly mountPath: string;
37
- readonly unpack: "file" | "tar.xz";
38
- readonly source: URL;
39
- }
40
12
  export interface ToolContract {
41
13
  readonly name: string;
42
14
  readonly description?: string;
@@ -50,29 +22,14 @@ export interface Tool<Input extends z.ZodType = z.ZodType, Output = unknown> {
50
22
  readonly description?: string;
51
23
  readonly input: Input;
52
24
  readonly output?: z.ZodType;
53
- readonly requirements: ToolRequirements;
54
25
  readonly handler: ToolHandler<Input, Output>;
55
- readonly setupHandler?: ToolSetupHandler;
56
- readonly artifact?: PreparedArtifact;
57
26
  describe(description: string): Tool<Input, Output>;
58
27
  named(name: string): Tool<Input, Output>;
59
28
  returns<Schema extends z.ZodType>(schema: Schema): Tool<Input, z.output<Schema>>;
60
- needs(requirements: ToolRequirements): Tool<Input, Output>;
61
- setup(handler: ToolSetupHandler): Tool<Input, Output>;
62
- bind<Environment extends EnvironmentRef>(environment: Environment): BoundTool<Environment, Input, Output>;
63
- }
64
- export interface BoundTool<Environment extends EnvironmentRef = EnvironmentRef, Input extends z.ZodType = z.ZodType, Output = unknown> {
65
- readonly kind: "aex.bound-tool";
66
- readonly tool: Tool<Input, Output>;
67
- readonly environment: Environment;
68
29
  }
69
30
  declare const EMPTY_INPUT: z.ZodObject<{}, z.core.$strip>;
70
31
  export declare function tool<Output>(handler: ToolHandler<typeof EMPTY_INPUT, Output>): Tool<typeof EMPTY_INPUT, Output>;
71
32
  export declare function tool<Input extends z.ZodType, Output>(input: Input, handler: ToolHandler<Input, Output>): Tool<Input, Output>;
72
- export declare function withPreparedArtifact<Input extends z.ZodType, Output>(value: Tool<Input, Output>, artifact: PreparedArtifact): Tool<Input, Output>;
73
- export type EnvironmentMap = Record<string, EnvironmentRef>;
74
- export type EnvironmentValue<Environments extends EnvironmentMap> = Environments[keyof Environments];
75
- export type ToolSelection<Environment extends EnvironmentRef = EnvironmentRef> = Tool | BoundTool<Environment>;
76
33
  export interface ClientRegistration {
77
34
  readonly registration: string;
78
35
  readonly name: string;
@@ -81,20 +38,11 @@ export interface ClientRegistration {
81
38
  readonly output?: z.ZodType;
82
39
  readonly handler: ToolHandler<z.ZodType>;
83
40
  }
84
- export interface CompiledTools {
85
- readonly items: readonly unknown[];
86
- readonly bundles: readonly unknown[];
87
- readonly layers: readonly CompiledArtifactLayer[];
88
- readonly clientRegistrations: readonly ClientRegistration[];
89
- readonly environments: Readonly<Record<string, unknown>>;
90
- readonly environmentNames: ReadonlyMap<EnvironmentRef, string>;
91
- readonly callbackClientId?: string;
92
- }
93
- export interface CompiledArtifactLayer {
94
- readonly checksum: string;
95
- readonly bytes: number;
96
- readonly media_type: string;
97
- readonly content: Uint8Array;
41
+ export interface CompiledCallbacks {
42
+ readonly components: readonly ComponentExtension<"tool", Readonly<Record<string, unknown>> & {
43
+ readonly definition: ToolDefinition;
44
+ }>[];
45
+ readonly registrations: readonly ClientRegistration[];
98
46
  }
99
- export declare function compileTools(selections: readonly ToolSelection[] | undefined, declared: EnvironmentMap | undefined, secrets?: Readonly<Record<string, string>>): Promise<CompiledTools>;
47
+ export declare function compileCallbacks(selections: readonly Tool[]): Promise<CompiledCallbacks>;
100
48
  export {};