nexustrade 0.1.0 → 0.2.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/AGENTS.md CHANGED
@@ -217,6 +217,33 @@ Always parameterize with `?` rather than interpolating into the SQL string.
217
217
  Stream parts with `downloadLakeQueryPart` instead of materializing large results.
218
218
  </details>
219
219
 
220
+ <details>
221
+ <summary><b>Run an agent</b></summary>
222
+
223
+ Agents are the one job kind that is NOT fire-and-poll. Three states —
224
+ `pending_plan_approval`, `pending_action_approval`, `awaiting_user_input` — are
225
+ ones the run cannot leave on its own, so the caller is the approver.
226
+
227
+ ```ts
228
+ const run = await nt.createAgent("Find momentum names in the S&P 500", {
229
+ idempotencyKey: "momentum-scan-v1",
230
+ });
231
+
232
+ for await (const event of run) {
233
+ console.log(event.text);
234
+ if (event.needsApproval) await run.approve(); // or run.reject()
235
+ else if (event.needsInput) await run.say("focus on semis");
236
+ }
237
+ ```
238
+
239
+ Iterating waits. If you never answer a blocked run, iteration throws
240
+ `agent_awaiting_input` rather than spinning silently — the run keeps going
241
+ server-side, so reattach with `nt.attachAgent(run.id)`.
242
+
243
+ Approving can place orders, so it needs the `trade` scope; everything else
244
+ needs `write`. Agent runs are unavailable to `run_compute` sandbox code.
245
+ </details>
246
+
220
247
  ## Errors
221
248
 
222
249
  All failures throw `NexusTradeApiError` with a stable `.status`, `.code`, and
@@ -240,7 +267,6 @@ Not in this SDK. Do not attempt to reach them through it:
240
267
 
241
268
  - **Screener** — MCP only.
242
269
  - **Live trading and order placement** — deliberately excluded.
243
- - **Agent runs** — the NexusTrade agent API is not exposed here yet.
244
270
 
245
271
  ## Verifying your work
246
272
 
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ /**
3
+ * Agent runs as an async iterator.
4
+ *
5
+ * Every other NexusTrade job is fire-and-poll: submit, wait, read a terminal
6
+ * result. Agents are not, because three of their states —
7
+ * `pending_plan_approval`, `pending_action_approval` and `awaiting_user_input`
8
+ * — are ones the run cannot leave on its own. A caller that only polled would
9
+ * start a run that stalls forever waiting for an approval nobody is present to
10
+ * give, and bill for the wait.
11
+ *
12
+ * So the caller *is* the approver:
13
+ *
14
+ * ```ts
15
+ * const run = await nt.createAgent("Find momentum names in the S&P 500", {
16
+ * idempotencyKey: "momentum-scan-v1",
17
+ * });
18
+ * for await (const event of run) {
19
+ * console.log(event.text);
20
+ * if (event.needsApproval) await run.approve();
21
+ * }
22
+ * ```
23
+ *
24
+ * Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.AgentRun = void 0;
28
+ const client_ts_1 = require("./client.js");
29
+ const DEFAULT_EVENT_LIMIT = 50;
30
+ function sleep(seconds) {
31
+ return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
32
+ }
33
+ /** A live agent run. Iterate it; answer it when it asks. */
34
+ class AgentRun {
35
+ id;
36
+ status;
37
+ terminal = false;
38
+ /** Every event yielded so far, in order. */
39
+ events = [];
40
+ /**
41
+ * Pacing, public and mutable to mirror the Python dataclass fields. Tests
42
+ * collapse the backoff through these; callers can widen the timeout on a run
43
+ * they expect to sit blocked for a while.
44
+ */
45
+ timeoutSeconds;
46
+ pollIntervalSeconds;
47
+ maxPollIntervalSeconds;
48
+ eventLimit;
49
+ #transport;
50
+ #cursor = null;
51
+ #seen = new Map();
52
+ constructor(id, transport, status = "initializing", options = {}) {
53
+ this.id = id;
54
+ this.status = status;
55
+ this.#transport = transport;
56
+ this.timeoutSeconds =
57
+ options.timeoutSeconds ?? client_ts_1.DEFAULT_POLL_TIMEOUT_SECONDS;
58
+ this.pollIntervalSeconds =
59
+ options.pollIntervalSeconds ?? client_ts_1.DEFAULT_POLL_INTERVAL_SECONDS;
60
+ this.maxPollIntervalSeconds =
61
+ options.maxPollIntervalSeconds ?? client_ts_1.MAX_POLL_INTERVAL_SECONDS;
62
+ this.eventLimit = options.eventLimit ?? DEFAULT_EVENT_LIMIT;
63
+ }
64
+ /** Resume a run already in flight from a known cursor. */
65
+ setCursor(cursor) {
66
+ this.#cursor = cursor;
67
+ }
68
+ /**
69
+ * Yield events until the run is terminal.
70
+ *
71
+ * Waits between polls on the same deterministic backoff the operation waiter
72
+ * uses. When the run reaches a state only the caller can clear, the blocking
73
+ * event is yielded and iteration then waits for the state to move — the
74
+ * caller is expected to answer from inside the loop body.
75
+ */
76
+ async *[Symbol.asyncIterator]() {
77
+ let interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
78
+ let deadline = Date.now() + this.timeoutSeconds * 1000;
79
+ let blockedStatus = null;
80
+ for (;;) {
81
+ const page = await this.#fetch();
82
+ const fresh = this.#absorb(page);
83
+ for (const event of fresh)
84
+ yield event;
85
+ if (this.terminal)
86
+ return;
87
+ if (fresh.length > 0) {
88
+ // Progress resets both the backoff and the stall deadline: a run that is
89
+ // still talking is not stuck, however long it runs.
90
+ interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
91
+ deadline = Date.now() + this.timeoutSeconds * 1000;
92
+ }
93
+ const waitingOnCaller = Boolean(page.pendingApproval) || Boolean(page.needsInput);
94
+ if (waitingOnCaller) {
95
+ if (blockedStatus === null) {
96
+ blockedStatus = this.status;
97
+ }
98
+ else if (this.status !== blockedStatus) {
99
+ // The caller answered; resume at full speed.
100
+ blockedStatus = null;
101
+ interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
102
+ deadline = Date.now() + this.timeoutSeconds * 1000;
103
+ }
104
+ }
105
+ else {
106
+ blockedStatus = null;
107
+ }
108
+ const remaining = (deadline - Date.now()) / 1000;
109
+ if (remaining <= 0) {
110
+ throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, waitingOnCaller ? "agent_awaiting_input" : "agent_timeout", `Agent ${this.id} was still '${this.status}' after ` +
111
+ `${this.timeoutSeconds}s. It is still running — answer ` +
112
+ "it, or attach again with the same id.");
113
+ }
114
+ if (interval > 0)
115
+ await sleep(Math.min(interval, remaining));
116
+ interval = Math.min(interval * client_ts_1.POLL_BACKOFF_FACTOR, this.maxPollIntervalSeconds);
117
+ }
118
+ }
119
+ async #fetch() {
120
+ const query = new URLSearchParams({
121
+ limit: String(this.eventLimit),
122
+ });
123
+ if (this.#cursor)
124
+ query.set("cursor", this.#cursor);
125
+ return this.#transport.request("GET", `agents/${encodeURIComponent(this.id)}/events?${query.toString()}`);
126
+ }
127
+ /**
128
+ * Fold a page into run state, dropping anything already delivered.
129
+ *
130
+ * The server re-sends rather than risk skipping, so the same id can arrive
131
+ * twice. Deduping here is what turns that guarantee into an exactly-once
132
+ * stream for the caller.
133
+ */
134
+ #absorb(page) {
135
+ if (typeof page.status === "string")
136
+ this.status = page.status;
137
+ this.terminal = Boolean(page.terminal);
138
+ if (typeof page.nextCursor === "string" && page.nextCursor) {
139
+ this.#cursor = page.nextCursor;
140
+ }
141
+ const approval = page.pendingApproval;
142
+ const approvalKind = approval && typeof approval === "object" && !Array.isArray(approval)
143
+ ? String(approval.kind ?? "")
144
+ : null;
145
+ const needsInput = Boolean(page.needsInput);
146
+ const raw = page.events;
147
+ if (!Array.isArray(raw))
148
+ return [];
149
+ const fresh = [];
150
+ raw.forEach((item, index) => {
151
+ if (!item || typeof item !== "object" || Array.isArray(item))
152
+ return;
153
+ const record = item;
154
+ const id = String(record.id ?? "");
155
+ const digest = String(record.digest ?? "");
156
+ if (!id)
157
+ return;
158
+ const previous = this.#seen.get(id);
159
+ if (previous === digest)
160
+ return; // already delivered, unchanged
161
+ this.#seen.set(id, digest);
162
+ const isLast = index === raw.length - 1;
163
+ const event = {
164
+ id,
165
+ digest,
166
+ role: String(record.role ?? "Assistant"),
167
+ text: String(record.text ?? ""),
168
+ data: record.data,
169
+ // Only the final event of a page can be the one the run is blocked on —
170
+ // the state applies to the tail, not the history.
171
+ needsApproval: Boolean(approvalKind) && isLast,
172
+ approvalKind: isLast && approvalKind ? approvalKind : null,
173
+ needsInput: needsInput && isLast,
174
+ supersedes: previous !== undefined,
175
+ };
176
+ fresh.push(event);
177
+ this.events.push(event);
178
+ });
179
+ return fresh;
180
+ }
181
+ /** Approve a pending plan or action. Needs the `trade` scope. */
182
+ approve() {
183
+ return this.#post("approve");
184
+ }
185
+ /** Reject a pending plan or action. */
186
+ reject() {
187
+ return this.#post("reject");
188
+ }
189
+ /** Stop the run. */
190
+ stop() {
191
+ return this.#post("stop");
192
+ }
193
+ /** Append a user message — a follow-up or a course correction. */
194
+ say(content) {
195
+ return this.#post("messages", { content });
196
+ }
197
+ async #post(action, body = {}) {
198
+ const response = await this.#transport.request("POST", `agents/${encodeURIComponent(this.id)}/${action}`, {
199
+ body,
200
+ idempotencyKey: `${this.id}:${action}:${this.events.length}`,
201
+ });
202
+ const agent = response.agent;
203
+ if (agent && typeof agent === "object" && !Array.isArray(agent)) {
204
+ const status = agent.status;
205
+ if (typeof status === "string")
206
+ this.status = status;
207
+ }
208
+ return this.status;
209
+ }
210
+ }
211
+ exports.AgentRun = AgentRun;
@@ -7,9 +7,10 @@
7
7
  * or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = void 0;
10
+ exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = exports.POLL_BACKOFF_FACTOR = exports.MAX_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_TIMEOUT_SECONDS = exports.NO_HTTP_STATUS = void 0;
11
11
  exports.waitForOperation = waitForOperation;
12
12
  exports.createPortfolio = createPortfolio;
13
+ const agent_ts_1 = require("./agent.js");
13
14
  const env_ts_1 = require("./env.js");
14
15
  /** Boundary adapter: builder output is JSON by construction. */
15
16
  function asJsonObject(value) {
@@ -23,16 +24,16 @@ const MAX_REDIRECTS = 5;
23
24
  // `status` for errors no HTTP status describes: the request never reached the
24
25
  // API, or it returned 2xx with an envelope the client could not use. Reporting
25
26
  // a literal 200 there would misattribute a 201 response.
26
- const NO_HTTP_STATUS = 0;
27
+ exports.NO_HTTP_STATUS = 0;
27
28
  // Polling defaults. Every NexusTrade job — backtest, optimization,
28
29
  // walk-forward, and any future operation kind — reports through the same
29
30
  // envelope, so one poller serves all of them. Kept in lockstep with the Python
30
31
  // SDK by checkSdkClientParity.ts; the backoff is deterministic (no jitter) so
31
32
  // both languages issue the identical request sequence.
32
- const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
33
- const DEFAULT_POLL_INTERVAL_SECONDS = 2;
34
- const MAX_POLL_INTERVAL_SECONDS = 15;
35
- const POLL_BACKOFF_FACTOR = 1.5;
33
+ exports.DEFAULT_POLL_TIMEOUT_SECONDS = 900;
34
+ exports.DEFAULT_POLL_INTERVAL_SECONDS = 2;
35
+ exports.MAX_POLL_INTERVAL_SECONDS = 15;
36
+ exports.POLL_BACKOFF_FACTOR = 1.5;
36
37
  const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
37
38
  class NexusTradeApiError extends Error {
38
39
  status;
@@ -197,7 +198,7 @@ class HttpTransport {
197
198
  }
198
199
  catch (error) {
199
200
  const reason = error instanceof Error ? error.message : String(error);
200
- throw new NexusTradeApiError(NO_HTTP_STATUS, "transport_error", reason);
201
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "transport_error", reason);
201
202
  }
202
203
  if (response.status >= 300 && response.status < 400) {
203
204
  const location = response.headers.get("location");
@@ -286,7 +287,7 @@ function operationFailure(operation, operationId, status) {
286
287
  if (error.message)
287
288
  message = String(error.message);
288
289
  }
289
- return new NexusTradeApiError(NO_HTTP_STATUS, code, message);
290
+ return new NexusTradeApiError(exports.NO_HTTP_STATUS, code, message);
290
291
  }
291
292
  /**
292
293
  * Poll `fetch(operationId)` until the operation reaches a terminal state.
@@ -301,9 +302,9 @@ function operationFailure(operation, operationId, status) {
301
302
  * them would report an infrastructure outage as a still-running job.
302
303
  */
303
304
  async function waitForOperation(fetch, operationId, options = {}) {
304
- const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_POLL_TIMEOUT_SECONDS;
305
- const pollIntervalSeconds = options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS;
306
- const maxPollIntervalSeconds = options.maxPollIntervalSeconds ?? MAX_POLL_INTERVAL_SECONDS;
305
+ const timeoutSeconds = options.timeoutSeconds ?? exports.DEFAULT_POLL_TIMEOUT_SECONDS;
306
+ const pollIntervalSeconds = options.pollIntervalSeconds ?? exports.DEFAULT_POLL_INTERVAL_SECONDS;
307
+ const maxPollIntervalSeconds = options.maxPollIntervalSeconds ?? exports.MAX_POLL_INTERVAL_SECONDS;
307
308
  const raiseOnFailure = options.raiseOnFailure ?? true;
308
309
  if (!(timeoutSeconds > 0)) {
309
310
  throw new Error("timeoutSeconds must be positive.");
@@ -324,7 +325,7 @@ async function waitForOperation(fetch, operationId, options = {}) {
324
325
  }
325
326
  const remainingMs = deadline - Date.now();
326
327
  if (remainingMs <= 0) {
327
- throw new NexusTradeApiError(NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
328
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
328
329
  `${timeoutSeconds}s. It is still running — poll again with the ` +
329
330
  "same id rather than resubmitting.");
330
331
  }
@@ -332,7 +333,7 @@ async function waitForOperation(fetch, operationId, options = {}) {
332
333
  const delayMs = Math.min(interval * 1000, remainingMs);
333
334
  await new Promise((resolve) => setTimeout(resolve, delayMs));
334
335
  }
335
- interval = Math.min(interval * POLL_BACKOFF_FACTOR, maxPollIntervalSeconds);
336
+ interval = Math.min(interval * exports.POLL_BACKOFF_FACTOR, maxPollIntervalSeconds);
336
337
  }
337
338
  }
338
339
  class NexusTradeClient {
@@ -342,9 +343,10 @@ class NexusTradeClient {
342
343
  this.transport = options.transport;
343
344
  return;
344
345
  }
345
- // Read the file once, so a two-variable lookup does not walk the tree
346
- // twice and cannot see two different files mid-resolution.
347
- const dotenv = (0, env_ts_1.loadDotenvValues)();
346
+ // Lazy and memoized: the tree is walked at most once, and not at all when
347
+ // the environment already answers — which is always true inside
348
+ // run_compute, where the platform injects both variables.
349
+ const dotenv = new env_ts_1.LazyDotenv();
348
350
  const apiKey = options.apiKey ?? (0, env_ts_1.environmentValue)("NEXUSTRADE_API_KEY", dotenv);
349
351
  const baseUrl = options.baseUrl ?? (0, env_ts_1.environmentValue)("NEXUSTRADE_API_BASE_URL", dotenv);
350
352
  if (!apiKey || !baseUrl) {
@@ -368,7 +370,7 @@ class NexusTradeClient {
368
370
  });
369
371
  const result = response.portfolio;
370
372
  if (!isJsonObject(result)) {
371
- throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
373
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
372
374
  }
373
375
  return result;
374
376
  }
@@ -381,7 +383,7 @@ class NexusTradeClient {
381
383
  const operations = response.operations;
382
384
  if (!Array.isArray(operations) ||
383
385
  !operations.every((operation) => isJsonObject(operation))) {
384
- throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Backtest response is missing operations.");
386
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Backtest response is missing operations.");
385
387
  }
386
388
  return operations;
387
389
  }
@@ -389,10 +391,53 @@ class NexusTradeClient {
389
391
  async createBacktest(backtest, options) {
390
392
  const operations = await this.createBacktests([backtest], options);
391
393
  if (operations.length !== 1) {
392
- throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Single backtest response returned the wrong operation count.");
394
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Single backtest response returned the wrong operation count.");
393
395
  }
394
396
  return operations[0];
395
397
  }
398
+ /**
399
+ * Start an agent run and return an iterable handle.
400
+ *
401
+ * Unlike the other job kinds this is not fire-and-poll: iterate the run to
402
+ * receive its events, and answer it when it asks. See `AgentRun`.
403
+ */
404
+ async createAgent(prompt, options) {
405
+ const body = { prompt };
406
+ if (options.maxIterations !== undefined) {
407
+ body.maxIterations = options.maxIterations;
408
+ }
409
+ const response = await this.transport.request("POST", "agents", {
410
+ body,
411
+ idempotencyKey: options.idempotencyKey,
412
+ });
413
+ const agent = response.agent;
414
+ if (!isJsonObject(agent) || !agent.id) {
415
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Agent response is missing agent.");
416
+ }
417
+ return new agent_ts_1.AgentRun(String(agent.id), this.transport, typeof agent.status === "string" ? agent.status : "initializing");
418
+ }
419
+ /**
420
+ * Reattach to a run already in flight.
421
+ *
422
+ * The run lives server-side and bills whether or not anyone is listening, so
423
+ * a dropped connection must not orphan it. Omit `cursor` to replay from the
424
+ * beginning; events are durable, so replay is exact.
425
+ */
426
+ async attachAgent(agentId, options = {}) {
427
+ const agent = await this.getAgent(agentId);
428
+ const run = new agent_ts_1.AgentRun(typeof agent.id === "string" ? agent.id : agentId, this.transport, typeof agent.status === "string" ? agent.status : "initializing");
429
+ run.terminal = Boolean(agent.terminal);
430
+ run.setCursor(options.cursor ?? null);
431
+ return run;
432
+ }
433
+ async getAgent(agentId) {
434
+ const response = await this.transport.request("GET", `agents/${encodeURIComponent(agentId)}`);
435
+ const agent = response.agent;
436
+ if (!isJsonObject(agent)) {
437
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Agent response is missing agent.");
438
+ }
439
+ return agent;
440
+ }
396
441
  async getBacktest(backtestId) {
397
442
  const response = await this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}`);
398
443
  return operationOf(response);
@@ -431,7 +476,7 @@ class NexusTradeClient {
431
476
  const response = await this.transport.request("GET", "lake/catalog");
432
477
  const tables = response.tables;
433
478
  if (!Array.isArray(tables) || !tables.every((t) => isJsonObject(t))) {
434
- throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Lake catalog response is missing tables.");
479
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Lake catalog response is missing tables.");
435
480
  }
436
481
  return tables;
437
482
  }
@@ -440,14 +485,14 @@ class NexusTradeClient {
440
485
  const response = await this.transport.request("GET", `lake/catalog/lake/${encodePathSegment(name)}`);
441
486
  const described = response.table;
442
487
  if (!isJsonObject(described)) {
443
- throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Lake describe response is missing table.");
488
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Lake describe response is missing table.");
444
489
  }
445
490
  return described;
446
491
  }
447
492
  /** Download one Parquet part, optionally a byte range of it. */
448
493
  async downloadLakeQueryPart(queryId, part, options = {}) {
449
494
  if (!supportsBinary(this.transport)) {
450
- throw new NexusTradeApiError(NO_HTTP_STATUS, "unsupported_transport", "Lake part download requires a transport implementing requestBytes.");
495
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsupported_transport", "Lake part download requires a transport implementing requestBytes.");
451
496
  }
452
497
  return this.transport.requestBytes("GET", `lake/queries/${encodePathSegment(queryId)}/parts/${Math.trunc(part)}`, options);
453
498
  }
@@ -514,7 +559,7 @@ function backtestInput(item) {
514
559
  function operationOf(response) {
515
560
  const operation = response.operation;
516
561
  if (!isJsonObject(operation)) {
517
- throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Response is missing operation.");
562
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Response is missing operation.");
518
563
  }
519
564
  return operation;
520
565
  }
package/dist/cjs/env.js CHANGED
@@ -24,6 +24,7 @@
24
24
  * this package supports Node 18 — so the walk and parse live here.
25
25
  */
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.LazyDotenv = void 0;
27
28
  exports.dotenvDisabled = dotenvDisabled;
28
29
  exports.parseDotenv = parseDotenv;
29
30
  exports.findDotenv = findDotenv;
@@ -147,12 +148,37 @@ function loadDotenvValues(start) {
147
148
  return {};
148
149
  }
149
150
  }
151
+ /**
152
+ * Reads the `.env` at most once, and only if something actually needs it.
153
+ *
154
+ * The file walk is skipped entirely when the environment already answers —
155
+ * which is always the case inside `run_compute`, where the platform injects the
156
+ * variables. Constructing a client should not stat up to 32 directories to
157
+ * discover a file it was never going to consult.
158
+ */
159
+ class LazyDotenv {
160
+ #values = null;
161
+ #start;
162
+ constructor(start) {
163
+ this.#start = start;
164
+ }
165
+ get(name) {
166
+ if (this.#values === null)
167
+ this.#values = loadDotenvValues(this.#start);
168
+ return this.#values[name];
169
+ }
170
+ /** True once the file has actually been read. Used by tests. */
171
+ get loaded() {
172
+ return this.#values !== null;
173
+ }
174
+ }
175
+ exports.LazyDotenv = LazyDotenv;
150
176
  /** `process.env` first, then `.env`. Blank is treated as absent. */
151
177
  function environmentValue(name, dotenv) {
152
178
  const live = process.env[name];
153
179
  if (live && live.trim())
154
180
  return live;
155
- const values = dotenv ?? loadDotenvValues();
156
- const fallback = values[name];
181
+ const source = dotenv ?? new LazyDotenv();
182
+ const fallback = source instanceof LazyDotenv ? source.get(name) : source[name];
157
183
  return fallback && fallback.trim() ? fallback : undefined;
158
184
  }
package/dist/cjs/index.js CHANGED
@@ -14,7 +14,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.waitForOperation = exports.createPortfolio = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = void 0;
17
+ exports.waitForOperation = exports.createPortfolio = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = exports.AgentRun = void 0;
18
+ var agent_js_1 = require("./agent.js");
19
+ Object.defineProperty(exports, "AgentRun", { enumerable: true, get: function () { return agent_js_1.AgentRun; } });
18
20
  var client_js_1 = require("./client.js");
19
21
  Object.defineProperty(exports, "HttpTransport", { enumerable: true, get: function () { return client_js_1.HttpTransport; } });
20
22
  Object.defineProperty(exports, "NexusTradeApiError", { enumerable: true, get: function () { return client_js_1.NexusTradeApiError; } });
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Agent runs as an async iterator.
3
+ *
4
+ * Every other NexusTrade job is fire-and-poll: submit, wait, read a terminal
5
+ * result. Agents are not, because three of their states —
6
+ * `pending_plan_approval`, `pending_action_approval` and `awaiting_user_input`
7
+ * — are ones the run cannot leave on its own. A caller that only polled would
8
+ * start a run that stalls forever waiting for an approval nobody is present to
9
+ * give, and bill for the wait.
10
+ *
11
+ * So the caller *is* the approver:
12
+ *
13
+ * ```ts
14
+ * const run = await nt.createAgent("Find momentum names in the S&P 500", {
15
+ * idempotencyKey: "momentum-scan-v1",
16
+ * });
17
+ * for await (const event of run) {
18
+ * console.log(event.text);
19
+ * if (event.needsApproval) await run.approve();
20
+ * }
21
+ * ```
22
+ *
23
+ * Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
24
+ */
25
+ import { type Transport } from "./client.ts";
26
+ export interface AgentEvent {
27
+ id: string;
28
+ digest: string;
29
+ role: string;
30
+ text: string;
31
+ data?: unknown;
32
+ /** The run is blocked until `approve()` or `reject()` is called. */
33
+ needsApproval: boolean;
34
+ /** "plan" or "action" when `needsApproval`; otherwise null. */
35
+ approvalKind: string | null;
36
+ /** The run is blocked until `say(...)` is called. */
37
+ needsInput: boolean;
38
+ /** This event replaces an earlier one with the same `id`. */
39
+ supersedes: boolean;
40
+ }
41
+ export interface AgentRunOptions {
42
+ timeoutSeconds?: number;
43
+ pollIntervalSeconds?: number;
44
+ maxPollIntervalSeconds?: number;
45
+ eventLimit?: number;
46
+ }
47
+ /** A live agent run. Iterate it; answer it when it asks. */
48
+ export declare class AgentRun {
49
+ #private;
50
+ readonly id: string;
51
+ status: string;
52
+ terminal: boolean;
53
+ /** Every event yielded so far, in order. */
54
+ readonly events: AgentEvent[];
55
+ /**
56
+ * Pacing, public and mutable to mirror the Python dataclass fields. Tests
57
+ * collapse the backoff through these; callers can widen the timeout on a run
58
+ * they expect to sit blocked for a while.
59
+ */
60
+ timeoutSeconds: number;
61
+ pollIntervalSeconds: number;
62
+ maxPollIntervalSeconds: number;
63
+ eventLimit: number;
64
+ constructor(id: string, transport: Transport, status?: string, options?: AgentRunOptions);
65
+ /** Resume a run already in flight from a known cursor. */
66
+ setCursor(cursor: string | null): void;
67
+ /**
68
+ * Yield events until the run is terminal.
69
+ *
70
+ * Waits between polls on the same deterministic backoff the operation waiter
71
+ * uses. When the run reaches a state only the caller can clear, the blocking
72
+ * event is yielded and iteration then waits for the state to move — the
73
+ * caller is expected to answer from inside the loop body.
74
+ */
75
+ [Symbol.asyncIterator](): AsyncIterator<AgentEvent>;
76
+ /** Approve a pending plan or action. Needs the `trade` scope. */
77
+ approve(): Promise<string>;
78
+ /** Reject a pending plan or action. */
79
+ reject(): Promise<string>;
80
+ /** Stop the run. */
81
+ stop(): Promise<string>;
82
+ /** Append a user message — a follow-up or a course correction. */
83
+ say(content: string): Promise<string>;
84
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Agent runs as an async iterator.
3
+ *
4
+ * Every other NexusTrade job is fire-and-poll: submit, wait, read a terminal
5
+ * result. Agents are not, because three of their states —
6
+ * `pending_plan_approval`, `pending_action_approval` and `awaiting_user_input`
7
+ * — are ones the run cannot leave on its own. A caller that only polled would
8
+ * start a run that stalls forever waiting for an approval nobody is present to
9
+ * give, and bill for the wait.
10
+ *
11
+ * So the caller *is* the approver:
12
+ *
13
+ * ```ts
14
+ * const run = await nt.createAgent("Find momentum names in the S&P 500", {
15
+ * idempotencyKey: "momentum-scan-v1",
16
+ * });
17
+ * for await (const event of run) {
18
+ * console.log(event.text);
19
+ * if (event.needsApproval) await run.approve();
20
+ * }
21
+ * ```
22
+ *
23
+ * Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
24
+ */
25
+ import { DEFAULT_POLL_INTERVAL_SECONDS, DEFAULT_POLL_TIMEOUT_SECONDS, MAX_POLL_INTERVAL_SECONDS, NO_HTTP_STATUS, NexusTradeApiError, POLL_BACKOFF_FACTOR, } from "./client.js";
26
+ const DEFAULT_EVENT_LIMIT = 50;
27
+ function sleep(seconds) {
28
+ return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
29
+ }
30
+ /** A live agent run. Iterate it; answer it when it asks. */
31
+ export class AgentRun {
32
+ id;
33
+ status;
34
+ terminal = false;
35
+ /** Every event yielded so far, in order. */
36
+ events = [];
37
+ /**
38
+ * Pacing, public and mutable to mirror the Python dataclass fields. Tests
39
+ * collapse the backoff through these; callers can widen the timeout on a run
40
+ * they expect to sit blocked for a while.
41
+ */
42
+ timeoutSeconds;
43
+ pollIntervalSeconds;
44
+ maxPollIntervalSeconds;
45
+ eventLimit;
46
+ #transport;
47
+ #cursor = null;
48
+ #seen = new Map();
49
+ constructor(id, transport, status = "initializing", options = {}) {
50
+ this.id = id;
51
+ this.status = status;
52
+ this.#transport = transport;
53
+ this.timeoutSeconds =
54
+ options.timeoutSeconds ?? DEFAULT_POLL_TIMEOUT_SECONDS;
55
+ this.pollIntervalSeconds =
56
+ options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS;
57
+ this.maxPollIntervalSeconds =
58
+ options.maxPollIntervalSeconds ?? MAX_POLL_INTERVAL_SECONDS;
59
+ this.eventLimit = options.eventLimit ?? DEFAULT_EVENT_LIMIT;
60
+ }
61
+ /** Resume a run already in flight from a known cursor. */
62
+ setCursor(cursor) {
63
+ this.#cursor = cursor;
64
+ }
65
+ /**
66
+ * Yield events until the run is terminal.
67
+ *
68
+ * Waits between polls on the same deterministic backoff the operation waiter
69
+ * uses. When the run reaches a state only the caller can clear, the blocking
70
+ * event is yielded and iteration then waits for the state to move — the
71
+ * caller is expected to answer from inside the loop body.
72
+ */
73
+ async *[Symbol.asyncIterator]() {
74
+ let interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
75
+ let deadline = Date.now() + this.timeoutSeconds * 1000;
76
+ let blockedStatus = null;
77
+ for (;;) {
78
+ const page = await this.#fetch();
79
+ const fresh = this.#absorb(page);
80
+ for (const event of fresh)
81
+ yield event;
82
+ if (this.terminal)
83
+ return;
84
+ if (fresh.length > 0) {
85
+ // Progress resets both the backoff and the stall deadline: a run that is
86
+ // still talking is not stuck, however long it runs.
87
+ interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
88
+ deadline = Date.now() + this.timeoutSeconds * 1000;
89
+ }
90
+ const waitingOnCaller = Boolean(page.pendingApproval) || Boolean(page.needsInput);
91
+ if (waitingOnCaller) {
92
+ if (blockedStatus === null) {
93
+ blockedStatus = this.status;
94
+ }
95
+ else if (this.status !== blockedStatus) {
96
+ // The caller answered; resume at full speed.
97
+ blockedStatus = null;
98
+ interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
99
+ deadline = Date.now() + this.timeoutSeconds * 1000;
100
+ }
101
+ }
102
+ else {
103
+ blockedStatus = null;
104
+ }
105
+ const remaining = (deadline - Date.now()) / 1000;
106
+ if (remaining <= 0) {
107
+ throw new NexusTradeApiError(NO_HTTP_STATUS, waitingOnCaller ? "agent_awaiting_input" : "agent_timeout", `Agent ${this.id} was still '${this.status}' after ` +
108
+ `${this.timeoutSeconds}s. It is still running — answer ` +
109
+ "it, or attach again with the same id.");
110
+ }
111
+ if (interval > 0)
112
+ await sleep(Math.min(interval, remaining));
113
+ interval = Math.min(interval * POLL_BACKOFF_FACTOR, this.maxPollIntervalSeconds);
114
+ }
115
+ }
116
+ async #fetch() {
117
+ const query = new URLSearchParams({
118
+ limit: String(this.eventLimit),
119
+ });
120
+ if (this.#cursor)
121
+ query.set("cursor", this.#cursor);
122
+ return this.#transport.request("GET", `agents/${encodeURIComponent(this.id)}/events?${query.toString()}`);
123
+ }
124
+ /**
125
+ * Fold a page into run state, dropping anything already delivered.
126
+ *
127
+ * The server re-sends rather than risk skipping, so the same id can arrive
128
+ * twice. Deduping here is what turns that guarantee into an exactly-once
129
+ * stream for the caller.
130
+ */
131
+ #absorb(page) {
132
+ if (typeof page.status === "string")
133
+ this.status = page.status;
134
+ this.terminal = Boolean(page.terminal);
135
+ if (typeof page.nextCursor === "string" && page.nextCursor) {
136
+ this.#cursor = page.nextCursor;
137
+ }
138
+ const approval = page.pendingApproval;
139
+ const approvalKind = approval && typeof approval === "object" && !Array.isArray(approval)
140
+ ? String(approval.kind ?? "")
141
+ : null;
142
+ const needsInput = Boolean(page.needsInput);
143
+ const raw = page.events;
144
+ if (!Array.isArray(raw))
145
+ return [];
146
+ const fresh = [];
147
+ raw.forEach((item, index) => {
148
+ if (!item || typeof item !== "object" || Array.isArray(item))
149
+ return;
150
+ const record = item;
151
+ const id = String(record.id ?? "");
152
+ const digest = String(record.digest ?? "");
153
+ if (!id)
154
+ return;
155
+ const previous = this.#seen.get(id);
156
+ if (previous === digest)
157
+ return; // already delivered, unchanged
158
+ this.#seen.set(id, digest);
159
+ const isLast = index === raw.length - 1;
160
+ const event = {
161
+ id,
162
+ digest,
163
+ role: String(record.role ?? "Assistant"),
164
+ text: String(record.text ?? ""),
165
+ data: record.data,
166
+ // Only the final event of a page can be the one the run is blocked on —
167
+ // the state applies to the tail, not the history.
168
+ needsApproval: Boolean(approvalKind) && isLast,
169
+ approvalKind: isLast && approvalKind ? approvalKind : null,
170
+ needsInput: needsInput && isLast,
171
+ supersedes: previous !== undefined,
172
+ };
173
+ fresh.push(event);
174
+ this.events.push(event);
175
+ });
176
+ return fresh;
177
+ }
178
+ /** Approve a pending plan or action. Needs the `trade` scope. */
179
+ approve() {
180
+ return this.#post("approve");
181
+ }
182
+ /** Reject a pending plan or action. */
183
+ reject() {
184
+ return this.#post("reject");
185
+ }
186
+ /** Stop the run. */
187
+ stop() {
188
+ return this.#post("stop");
189
+ }
190
+ /** Append a user message — a follow-up or a course correction. */
191
+ say(content) {
192
+ return this.#post("messages", { content });
193
+ }
194
+ async #post(action, body = {}) {
195
+ const response = await this.#transport.request("POST", `agents/${encodeURIComponent(this.id)}/${action}`, {
196
+ body,
197
+ idempotencyKey: `${this.id}:${action}:${this.events.length}`,
198
+ });
199
+ const agent = response.agent;
200
+ if (agent && typeof agent === "object" && !Array.isArray(agent)) {
201
+ const status = agent.status;
202
+ if (typeof status === "string")
203
+ this.status = status;
204
+ }
205
+ return this.status;
206
+ }
207
+ }
@@ -5,6 +5,7 @@
5
5
  * surfaces stay identical. Transport-generic: callers pass an API key/base URL,
6
6
  * or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
7
7
  */
8
+ import { AgentRun } from "./agent.ts";
8
9
  import type { JobRequest, Portfolio } from "./generated/ntSdk.generated.js";
9
10
  export type JsonValue = string | number | boolean | null | JsonValue[] | {
10
11
  [key: string]: JsonValue;
@@ -24,6 +25,11 @@ export type JsonObject = {
24
25
  */
25
26
  export type PortfolioInput = Portfolio | JsonObject;
26
27
  export type JobInput = JobRequest | JsonObject;
28
+ export declare const NO_HTTP_STATUS = 0;
29
+ export declare const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
30
+ export declare const DEFAULT_POLL_INTERVAL_SECONDS = 2;
31
+ export declare const MAX_POLL_INTERVAL_SECONDS = 15;
32
+ export declare const POLL_BACKOFF_FACTOR = 1.5;
27
33
  export declare class NexusTradeApiError extends Error {
28
34
  readonly status: number;
29
35
  readonly code: string;
@@ -99,6 +105,27 @@ export declare class NexusTradeClient {
99
105
  createBacktest(backtest: JobInput, options: {
100
106
  idempotencyKey: string;
101
107
  }): Promise<JsonObject>;
108
+ /**
109
+ * Start an agent run and return an iterable handle.
110
+ *
111
+ * Unlike the other job kinds this is not fire-and-poll: iterate the run to
112
+ * receive its events, and answer it when it asks. See `AgentRun`.
113
+ */
114
+ createAgent(prompt: string, options: {
115
+ idempotencyKey: string;
116
+ maxIterations?: number;
117
+ }): Promise<AgentRun>;
118
+ /**
119
+ * Reattach to a run already in flight.
120
+ *
121
+ * The run lives server-side and bills whether or not anyone is listening, so
122
+ * a dropped connection must not orphan it. Omit `cursor` to replay from the
123
+ * beginning; events are durable, so replay is exact.
124
+ */
125
+ attachAgent(agentId: string, options?: {
126
+ cursor?: string;
127
+ }): Promise<AgentRun>;
128
+ getAgent(agentId: string): Promise<JsonObject>;
102
129
  getBacktest(backtestId: string): Promise<JsonObject>;
103
130
  createOptimization(handle: JobInput, options: {
104
131
  idempotencyKey: string;
@@ -5,7 +5,8 @@
5
5
  * surfaces stay identical. Transport-generic: callers pass an API key/base URL,
6
6
  * or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
7
7
  */
8
- import { environmentValue, loadDotenvValues } from "./env.js";
8
+ import { AgentRun } from "./agent.js";
9
+ import { LazyDotenv, environmentValue } from "./env.js";
9
10
  /** Boundary adapter: builder output is JSON by construction. */
10
11
  function asJsonObject(value) {
11
12
  return value;
@@ -18,16 +19,16 @@ const MAX_REDIRECTS = 5;
18
19
  // `status` for errors no HTTP status describes: the request never reached the
19
20
  // API, or it returned 2xx with an envelope the client could not use. Reporting
20
21
  // a literal 200 there would misattribute a 201 response.
21
- const NO_HTTP_STATUS = 0;
22
+ export const NO_HTTP_STATUS = 0;
22
23
  // Polling defaults. Every NexusTrade job — backtest, optimization,
23
24
  // walk-forward, and any future operation kind — reports through the same
24
25
  // envelope, so one poller serves all of them. Kept in lockstep with the Python
25
26
  // SDK by checkSdkClientParity.ts; the backoff is deterministic (no jitter) so
26
27
  // both languages issue the identical request sequence.
27
- const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
28
- const DEFAULT_POLL_INTERVAL_SECONDS = 2;
29
- const MAX_POLL_INTERVAL_SECONDS = 15;
30
- const POLL_BACKOFF_FACTOR = 1.5;
28
+ export const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
29
+ export const DEFAULT_POLL_INTERVAL_SECONDS = 2;
30
+ export const MAX_POLL_INTERVAL_SECONDS = 15;
31
+ export const POLL_BACKOFF_FACTOR = 1.5;
31
32
  const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
32
33
  export class NexusTradeApiError extends Error {
33
34
  status;
@@ -335,9 +336,10 @@ export class NexusTradeClient {
335
336
  this.transport = options.transport;
336
337
  return;
337
338
  }
338
- // Read the file once, so a two-variable lookup does not walk the tree
339
- // twice and cannot see two different files mid-resolution.
340
- const dotenv = loadDotenvValues();
339
+ // Lazy and memoized: the tree is walked at most once, and not at all when
340
+ // the environment already answers — which is always true inside
341
+ // run_compute, where the platform injects both variables.
342
+ const dotenv = new LazyDotenv();
341
343
  const apiKey = options.apiKey ?? environmentValue("NEXUSTRADE_API_KEY", dotenv);
342
344
  const baseUrl = options.baseUrl ?? environmentValue("NEXUSTRADE_API_BASE_URL", dotenv);
343
345
  if (!apiKey || !baseUrl) {
@@ -386,6 +388,49 @@ export class NexusTradeClient {
386
388
  }
387
389
  return operations[0];
388
390
  }
391
+ /**
392
+ * Start an agent run and return an iterable handle.
393
+ *
394
+ * Unlike the other job kinds this is not fire-and-poll: iterate the run to
395
+ * receive its events, and answer it when it asks. See `AgentRun`.
396
+ */
397
+ async createAgent(prompt, options) {
398
+ const body = { prompt };
399
+ if (options.maxIterations !== undefined) {
400
+ body.maxIterations = options.maxIterations;
401
+ }
402
+ const response = await this.transport.request("POST", "agents", {
403
+ body,
404
+ idempotencyKey: options.idempotencyKey,
405
+ });
406
+ const agent = response.agent;
407
+ if (!isJsonObject(agent) || !agent.id) {
408
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Agent response is missing agent.");
409
+ }
410
+ return new AgentRun(String(agent.id), this.transport, typeof agent.status === "string" ? agent.status : "initializing");
411
+ }
412
+ /**
413
+ * Reattach to a run already in flight.
414
+ *
415
+ * The run lives server-side and bills whether or not anyone is listening, so
416
+ * a dropped connection must not orphan it. Omit `cursor` to replay from the
417
+ * beginning; events are durable, so replay is exact.
418
+ */
419
+ async attachAgent(agentId, options = {}) {
420
+ const agent = await this.getAgent(agentId);
421
+ const run = new AgentRun(typeof agent.id === "string" ? agent.id : agentId, this.transport, typeof agent.status === "string" ? agent.status : "initializing");
422
+ run.terminal = Boolean(agent.terminal);
423
+ run.setCursor(options.cursor ?? null);
424
+ return run;
425
+ }
426
+ async getAgent(agentId) {
427
+ const response = await this.transport.request("GET", `agents/${encodeURIComponent(agentId)}`);
428
+ const agent = response.agent;
429
+ if (!isJsonObject(agent)) {
430
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Agent response is missing agent.");
431
+ }
432
+ return agent;
433
+ }
389
434
  async getBacktest(backtestId) {
390
435
  const response = await this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}`);
391
436
  return operationOf(response);
package/dist/esm/env.d.ts CHANGED
@@ -45,5 +45,20 @@ export declare function parseDotenv(text: string): Record<string, string>;
45
45
  export declare function findDotenv(start?: string): string | null;
46
46
  /** Values from the nearest `.env`. Never throws; unreadable means empty. */
47
47
  export declare function loadDotenvValues(start?: string): Record<string, string>;
48
+ /**
49
+ * Reads the `.env` at most once, and only if something actually needs it.
50
+ *
51
+ * The file walk is skipped entirely when the environment already answers —
52
+ * which is always the case inside `run_compute`, where the platform injects the
53
+ * variables. Constructing a client should not stat up to 32 directories to
54
+ * discover a file it was never going to consult.
55
+ */
56
+ export declare class LazyDotenv {
57
+ #private;
58
+ constructor(start?: string);
59
+ get(name: string): string | undefined;
60
+ /** True once the file has actually been read. Used by tests. */
61
+ get loaded(): boolean;
62
+ }
48
63
  /** `process.env` first, then `.env`. Blank is treated as absent. */
49
- export declare function environmentValue(name: string, dotenv?: Record<string, string>): string | undefined;
64
+ export declare function environmentValue(name: string, dotenv?: LazyDotenv | Record<string, string>): string | undefined;
package/dist/esm/env.js CHANGED
@@ -140,12 +140,36 @@ export function loadDotenvValues(start) {
140
140
  return {};
141
141
  }
142
142
  }
143
+ /**
144
+ * Reads the `.env` at most once, and only if something actually needs it.
145
+ *
146
+ * The file walk is skipped entirely when the environment already answers —
147
+ * which is always the case inside `run_compute`, where the platform injects the
148
+ * variables. Constructing a client should not stat up to 32 directories to
149
+ * discover a file it was never going to consult.
150
+ */
151
+ export class LazyDotenv {
152
+ #values = null;
153
+ #start;
154
+ constructor(start) {
155
+ this.#start = start;
156
+ }
157
+ get(name) {
158
+ if (this.#values === null)
159
+ this.#values = loadDotenvValues(this.#start);
160
+ return this.#values[name];
161
+ }
162
+ /** True once the file has actually been read. Used by tests. */
163
+ get loaded() {
164
+ return this.#values !== null;
165
+ }
166
+ }
143
167
  /** `process.env` first, then `.env`. Blank is treated as absent. */
144
168
  export function environmentValue(name, dotenv) {
145
169
  const live = process.env[name];
146
170
  if (live && live.trim())
147
171
  return live;
148
- const values = dotenv ?? loadDotenvValues();
149
- const fallback = values[name];
172
+ const source = dotenv ?? new LazyDotenv();
173
+ const fallback = source instanceof LazyDotenv ? source.get(name) : source[name];
150
174
  return fallback && fallback.trim() ? fallback : undefined;
151
175
  }
@@ -1,3 +1,5 @@
1
+ export { AgentRun } from "./agent.js";
2
+ export type { AgentEvent, AgentRunOptions } from "./agent.js";
1
3
  export { HttpTransport, NexusTradeApiError, NexusTradeClient, createPortfolio, waitForOperation, } from "./client.js";
2
4
  export type { HttpTransportOptions, JsonObject, JsonValue, NexusTradeClientOptions, RequestOptions, Transport, WaitOptions, } from "./client.js";
3
5
  export * from "./generated/ntSdk.generated.js";
package/dist/esm/index.js CHANGED
@@ -1,2 +1,3 @@
1
+ export { AgentRun } from "./agent.js";
1
2
  export { HttpTransport, NexusTradeApiError, NexusTradeClient, createPortfolio, waitForOperation, } from "./client.js";
2
3
  export * from "./generated/ntSdk.generated.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexustrade",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Typed TypeScript SDK for NexusTrade portfolio authoring, backtesting, and optimization",
5
5
  "license": "MIT",
6
6
  "author": "Starks Technology",