@aexhq/sdk 0.58.0 → 0.59.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/session.js CHANGED
@@ -1,10 +1,9 @@
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;
@@ -20,21 +19,109 @@ export class Sessions {
20
19
  if (this.#closed)
21
20
  return;
22
21
  this.#closed = true;
23
- for (const environment of this.#customerEnvironmentInstances.values())
24
- environment.close();
22
+ for (const hand of this.#customerEnvironmentInstances.values())
23
+ hand.close();
25
24
  this.#customerEnvironmentInstances.clear();
26
25
  this.#customerEnvironments.clear();
27
26
  }
28
27
  async create(options, request = {}) {
29
28
  if (this.#closed)
30
29
  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);
30
+ if (options.model?.component === undefined) {
31
+ throw new TypeError("sessions.create requires an imported Model component");
32
+ }
33
+ if (options.agentloop === undefined) {
34
+ throw new TypeError("sessions.create requires an imported Agentloop component");
35
+ }
36
+ const model = options.model.component;
37
+ const agentloop = options.agentloop;
38
+ const tools = [...(options.tools ?? [])];
39
+ const componentTools = tools.filter(isComponentTool);
40
+ const callbackTools = tools.filter((tool) => !isComponentTool(tool));
41
+ const environments = Object.entries(options.environments ?? {});
42
+ if (environments.some(([, environment]) => !isEnvironmentComponent(environment))) {
43
+ throw new TypeError("component sessions accept only precompiled Environment component values");
44
+ }
45
+ const environmentComponents = environments.map(([name, environment]) => {
46
+ if (!isEnvironmentComponent(environment)) {
47
+ throw new TypeError(`Environment ${JSON.stringify(name)} is not a component`);
48
+ }
49
+ return [name, environment];
50
+ });
51
+ const applicationEnvironments = environmentComponents.filter(([, environment]) => isApplicationEnvironment(environment));
52
+ if (callbackTools.length > 0 && applicationEnvironments.length !== 1) {
53
+ throw new TypeError("application callback Tools require exactly one app() Environment");
54
+ }
55
+ const callbacks = await compileCallbacks(callbackTools);
56
+ const allComponentTools = [...componentTools, ...callbacks.components];
57
+ const toolDefinitions = allComponentTools.map(componentToolDefinition);
58
+ const names = new Set();
59
+ for (const definition of toolDefinitions) {
60
+ if (names.has(definition.name)) {
61
+ throw new TypeError(`Tool ${JSON.stringify(definition.name)} was selected twice`);
62
+ }
63
+ names.add(definition.name);
64
+ }
65
+ const callbackEnvironment = applicationEnvironments[0];
66
+ if (callbackEnvironment !== undefined) {
67
+ await this.#ensureCustomerEnvironment(applicationEnvironmentId(callbackEnvironment[1]), callbacks.registrations, request.signal);
68
+ }
69
+ const prepared = await prepareComponents([
70
+ model,
71
+ agentloop,
72
+ ...allComponentTools,
73
+ ...environmentComponents.map(([, environment]) => environment),
74
+ ]);
75
+ const modelBinding = prepared.bindings[0];
76
+ const agentloopBinding = prepared.bindings[1];
77
+ if (modelBinding === undefined || agentloopBinding === undefined) {
78
+ throw new TypeError("component session bindings are incomplete");
79
+ }
80
+ const toolBindings = prepared.bindings.slice(2, 2 + allComponentTools.length);
81
+ const environmentBindings = prepared.bindings.slice(2 + allComponentTools.length);
82
+ const toolItems = allComponentTools.map((tool, index) => {
83
+ const binding = toolBindings[index];
84
+ if (binding === undefined)
85
+ throw new TypeError("Tool component binding is missing");
86
+ const definition = toolDefinitions[index];
87
+ if (definition === undefined)
88
+ throw new TypeError("Tool component definition is missing");
89
+ const needsEnvironment = binding.grants.includes("environment");
90
+ const isCallback = index >= componentTools.length;
91
+ if (needsEnvironment && !isCallback && environmentComponents.length !== 1) {
92
+ throw new TypeError("a Tool with the environment grant requires exactly one declared Environment");
93
+ }
94
+ const environmentName = isCallback
95
+ ? callbackEnvironment?.[0]
96
+ : environmentComponents[0]?.[0];
97
+ return {
98
+ definition,
99
+ executor: {
100
+ kind: "component",
101
+ component_digest: binding.component_digest,
102
+ world: binding.world,
103
+ config: binding.config,
104
+ grants: binding.grants,
105
+ ...(needsEnvironment ? { environment: environmentName } : {}),
106
+ },
107
+ };
108
+ });
109
+ const environmentConfig = Object.fromEntries(environmentComponents.map(([name], index) => {
110
+ const binding = environmentBindings[index];
111
+ if (binding === undefined) {
112
+ throw new TypeError(`Environment component binding ${JSON.stringify(name)} is missing`);
113
+ }
114
+ return [name, {
115
+ component_digest: binding.component_digest,
116
+ world: binding.world,
117
+ config: binding.config,
118
+ }];
119
+ }));
36
120
  const body = {
37
121
  model: {
122
+ component_digest: modelBinding.component_digest,
123
+ world: modelBinding.world,
124
+ config: modelBinding.config,
38
125
  provider: options.model.provider,
39
126
  name: options.model.name,
40
127
  api_key: options.model.apiKey,
@@ -42,37 +129,24 @@ export class Sessions {
42
129
  ...(options.model.maxOutputTokens === undefined
43
130
  ? {}
44
131
  : { max_output_tokens: options.model.maxOutputTokens }),
45
- ...(options.model.contextWindowTokens === undefined
46
- ? {}
47
- : { context_window_tokens: options.model.contextWindowTokens }),
48
132
  },
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
133
  agentloop: {
57
- source_bundle_sha256: options.loop.sha256,
58
- toolchain: options.loop.toolchain,
59
- bundle_base64: encodeBase64(new TextEncoder().encode(options.loop.source)),
134
+ component_digest: agentloopBinding.component_digest,
135
+ world: agentloopBinding.world,
136
+ config: agentloopBinding.config,
60
137
  },
138
+ component_artifacts: prepared.artifacts,
139
+ tools: { items: toolItems },
140
+ ...(environmentComponents.length === 0 ? {} : { environments: environmentConfig }),
61
141
  ...(options.secrets === undefined ? {} : { secrets: options.secrets }),
62
142
  ...(options.metadata === undefined ? {} : { metadata: options.metadata }),
63
- ...(options.network === undefined
143
+ ...(options.retainUntil === undefined
64
144
  ? {}
65
- : { network: options.network }),
145
+ : { retain_until: normalizeTimestamp(options.retainUntil, "retainUntil") }),
146
+ ...(options.network === undefined ? {} : { network: options.network }),
66
147
  ...(options.providerRecoveryRetries === undefined
67
148
  ? {}
68
149
  : { provider_recovery_retries: options.providerRecoveryRetries }),
69
- ...(compiledTools.callbackClientId === undefined
70
- ? {}
71
- : {
72
- client: {
73
- id: compiledTools.callbackClientId,
74
- },
75
- }),
76
150
  ...(options.children === undefined
77
151
  ? {}
78
152
  : {
@@ -95,7 +169,7 @@ export class Sessions {
95
169
  signal: request.signal,
96
170
  retry: true,
97
171
  });
98
- return new Session(this.#transport, data, compiledTools.environmentNames);
172
+ return new Session(this.#transport, data);
99
173
  }
100
174
  async get(id, options = {}) {
101
175
  const data = await this.#transport.json("GET", `/v1/sessions/${encodeURIComponent(id)}`, { signal: options.signal });
@@ -168,11 +242,47 @@ export class Sessions {
168
242
  await waitWithSignal(starting, signal);
169
243
  return;
170
244
  }
171
- const environment = await waitWithSignal(existing, signal);
245
+ const hand = await waitWithSignal(existing, signal);
172
246
  if (this.#closed)
173
247
  throw new SessionError("Aex client is closed");
174
- await waitWithSignal(environment.register(registrations), signal);
248
+ await waitWithSignal(hand.register(registrations), signal);
249
+ }
250
+ }
251
+ function isApplicationEnvironment(value) {
252
+ const config = value.config;
253
+ return config !== null && typeof config === "object" && !Array.isArray(config) &&
254
+ config.driver === "customer";
255
+ }
256
+ function applicationEnvironmentId(value) {
257
+ const config = value.config;
258
+ const id = config.configuration?.registration;
259
+ if (typeof id !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/u.test(id)) {
260
+ throw new TypeError("app() Environment registration is invalid");
175
261
  }
262
+ return id;
263
+ }
264
+ function isComponentTool(value) {
265
+ return value !== null
266
+ && typeof value === "object"
267
+ && value.kind === "brain.component"
268
+ && value.extension === "tool";
269
+ }
270
+ function isEnvironmentComponent(value) {
271
+ return value !== null
272
+ && typeof value === "object"
273
+ && value.kind === "brain.component"
274
+ && value.extension === "environment";
275
+ }
276
+ function componentToolDefinition(value) {
277
+ const config = value.config;
278
+ if (config === null || typeof config !== "object" || Array.isArray(config)) {
279
+ throw new TypeError("Tool component config must be an object containing definition");
280
+ }
281
+ const definition = config.definition;
282
+ if (definition === null || typeof definition !== "object" || Array.isArray(definition)) {
283
+ throw new TypeError("Tool component config.definition is required");
284
+ }
285
+ return definition;
176
286
  }
177
287
  function waitWithSignal(promise, signal) {
178
288
  if (signal === undefined)
@@ -192,32 +302,16 @@ function waitWithSignal(promise, signal) {
192
302
  export class Session {
193
303
  #transport;
194
304
  #data;
305
+ sandbox;
195
306
  storage;
196
307
  children;
197
- #environmentNames;
198
- #environmentHandles = new Map();
199
- constructor(transport, data, environmentNames = new Map()) {
308
+ constructor(transport, data) {
200
309
  this.#transport = transport;
201
310
  this.#data = data;
202
- this.#environmentNames = environmentNames;
203
- this.storage = new SessionStorage(transport, data.id, environmentNames);
311
+ this.sandbox = new SessionSandbox(transport, data.id);
312
+ this.storage = new SessionStorage(transport, data.id);
204
313
  this.children = new SessionChildren(transport, data.id);
205
314
  }
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
315
  get id() {
222
316
  return this.#data.id;
223
317
  }
@@ -250,6 +344,9 @@ export class Session {
250
344
  get updatedAt() {
251
345
  return this.#data.updated_at;
252
346
  }
347
+ get retainUntil() {
348
+ return this.#data.retain_until;
349
+ }
253
350
  get metadata() {
254
351
  return this.#data.metadata;
255
352
  }
@@ -351,6 +448,25 @@ export class Session {
351
448
  this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/cancel`, { signal: options.signal, retry: true });
352
449
  return this;
353
450
  }
451
+ async suspend(options = {}) {
452
+ this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/suspend`, { signal: options.signal, retry: true });
453
+ return this;
454
+ }
455
+ async resume(options = {}) {
456
+ this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/resume`, { signal: options.signal, retry: true });
457
+ return this;
458
+ }
459
+ async setRetention(value, options = {}) {
460
+ this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/retention`, {
461
+ body: {
462
+ retain_until: normalizeTimestamp(value, "retainUntil"),
463
+ allow_shorten: options.allowShorten ?? false,
464
+ },
465
+ signal: options.signal,
466
+ retry: true,
467
+ });
468
+ return this;
469
+ }
354
470
  async end(options = {}) {
355
471
  this.#data = await this.#transport.json("POST", `/v1/sessions/${encodeURIComponent(this.id)}/end`, { signal: options.signal, retry: true });
356
472
  return this;
@@ -369,6 +485,12 @@ export class Session {
369
485
  function isOutputOptions(options) {
370
486
  return "output" in options;
371
487
  }
488
+ function normalizeTimestamp(value, field) {
489
+ const parsed = value instanceof Date ? value : new Date(value);
490
+ if (!Number.isFinite(parsed.getTime()))
491
+ throw new TypeError(`${field} must be a valid timestamp`);
492
+ return parsed.toISOString();
493
+ }
372
494
  async function compileOutputSchema(schema, retries) {
373
495
  let jsonSchema;
374
496
  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 {};