nexustrade 0.3.0 → 1.0.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.
@@ -2,14 +2,14 @@
2
2
  /**
3
3
  * Typed NexusTrade JSON API client.
4
4
  *
5
- * Mirrors the Python client method-for-method; `verifyNtSdk.ts` asserts the two
6
- * surfaces stay identical. Transport-generic: callers pass an API key/base URL,
7
- * or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
5
+ * Method names and behavior match the Python SDK. Transport-generic: callers
6
+ * pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
8
7
  */
9
8
  Object.defineProperty(exports, "__esModule", { value: true });
10
9
  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
10
  exports.waitForOperation = waitForOperation;
12
11
  exports.clientTransport = clientTransport;
12
+ exports.createCustomIndicator = createCustomIndicator;
13
13
  exports.createPortfolio = createPortfolio;
14
14
  const agent_ts_1 = require("./agent.js");
15
15
  const env_ts_1 = require("./env.js");
@@ -53,14 +53,33 @@ exports.DEFAULT_POLL_INTERVAL_SECONDS = 2;
53
53
  exports.MAX_POLL_INTERVAL_SECONDS = 15;
54
54
  exports.POLL_BACKOFF_FACTOR = 1.5;
55
55
  const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
56
+ // Point batches larger than this are uploaded rather than sent inline.
57
+ const MAX_INLINE_POINT_BYTES = 512 * 1024;
58
+ const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
59
+ const POINT_FIELDS = {
60
+ timestamp: "timestamp",
61
+ value: "value",
62
+ ticker: "ticker",
63
+ assetType: "assetType",
64
+ asset_type: "assetType",
65
+ availableAt: "availableAt",
66
+ available_at: "availableAt",
67
+ };
56
68
  class NexusTradeApiError extends Error {
57
69
  status;
58
70
  code;
59
- constructor(status, code, message) {
71
+ /**
72
+ * Set for operation errors (timeout / failure). A timed-out job is still
73
+ * running, so the caller needs the id to resume waiting without resubmitting
74
+ * — reading it out of the message is not an interface.
75
+ */
76
+ operationId;
77
+ constructor(status, code, message, operationId) {
60
78
  super(`${code}: ${message}`);
61
79
  this.name = "NexusTradeApiError";
62
80
  this.status = status;
63
81
  this.code = code;
82
+ this.operationId = operationId;
64
83
  }
65
84
  }
66
85
  exports.NexusTradeApiError = NexusTradeApiError;
@@ -81,6 +100,9 @@ function sameOrigin(left, right) {
81
100
  function supportsBinary(transport) {
82
101
  return (typeof transport.requestBytes === "function");
83
102
  }
103
+ function supportsUpload(transport) {
104
+ return typeof transport.putBytes === "function";
105
+ }
84
106
  function assertValidApiKey(apiKey) {
85
107
  const invalid = typeof apiKey !== "string" ||
86
108
  apiKey.length === 0 ||
@@ -187,6 +209,43 @@ class HttpTransport {
187
209
  get baseUrl() {
188
210
  return this.#baseUrl;
189
211
  }
212
+ /** PUT a payload to a presigned storage URL. Sends no credential. */
213
+ async putBytes(url, data, options) {
214
+ let parsed;
215
+ try {
216
+ parsed = new URL(url);
217
+ }
218
+ catch {
219
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a malformed upload URL.");
220
+ }
221
+ if (parsed.protocol.toLowerCase() !== "https:") {
222
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a non-HTTPS upload URL.");
223
+ }
224
+ const controller = new AbortController();
225
+ const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
226
+ try {
227
+ let response;
228
+ try {
229
+ response = await fetch(url, {
230
+ method: "PUT",
231
+ headers: { "Content-Type": options.contentType },
232
+ body: new Blob([data], { type: options.contentType }),
233
+ redirect: "manual",
234
+ signal: controller.signal,
235
+ });
236
+ }
237
+ catch (error) {
238
+ const reason = error instanceof Error ? error.message : String(error);
239
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "transport_error", reason);
240
+ }
241
+ if (!response.ok) {
242
+ throw new NexusTradeApiError(response.status, "upload_failed", `Storage rejected the upload: ${response.statusText || `HTTP ${response.status}`}.`);
243
+ }
244
+ }
245
+ finally {
246
+ clearTimeout(timer);
247
+ }
248
+ }
190
249
  async request(method, path, options = {}) {
191
250
  const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
192
251
  const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
@@ -305,20 +364,52 @@ function operationFailure(operation, operationId, status) {
305
364
  if (error.message)
306
365
  message = String(error.message);
307
366
  }
308
- return new NexusTradeApiError(exports.NO_HTTP_STATUS, code, message);
367
+ return new NexusTradeApiError(exports.NO_HTTP_STATUS, code, message, operationId);
368
+ }
369
+ function pointTimestamp(value) {
370
+ return value instanceof Date ? value.toISOString() : value;
309
371
  }
310
372
  /**
311
- * Poll `fetch(operationId)` until the operation reaches a terminal state.
312
- *
313
- * Works for any operation kind because every NexusTrade job reports the same
314
- * `{id, kind, status, result?, error?}` envelope. Pass any getter with that
315
- * shape — `client.getBacktest`, `getOptimization`, `getWalkForward`.
373
+ * Normalize one point to its wire shape.
316
374
  *
317
- * Resolves with the terminal operation. Rejects with `NexusTradeApiError` on
318
- * timeout, and on a failed/cancelled operation unless `raiseOnFailure` is
319
- * false. Transport errors from `fetch` propagate — a poller that swallowed
320
- * them would report an infrastructure outage as a still-running job.
375
+ * Accepts snake_case or camelCase field names and Date objects. Throws on an
376
+ * unrecognized field rather than dropping it silently.
321
377
  */
378
+ function customIndicatorPoint(point) {
379
+ const normalized = {};
380
+ for (const [key, value] of Object.entries(point)) {
381
+ const target = POINT_FIELDS[key];
382
+ if (target === undefined) {
383
+ throw new Error(`Unknown custom indicator point field "${key}". Points accept ` +
384
+ "timestamp, value, ticker, assetType, and availableAt.");
385
+ }
386
+ if (value === undefined || value === null)
387
+ continue;
388
+ normalized[target] =
389
+ target === "timestamp" || target === "availableAt"
390
+ ? pointTimestamp(value)
391
+ : value;
392
+ }
393
+ if (normalized.timestamp === undefined) {
394
+ throw new Error("Every custom indicator point needs a timestamp.");
395
+ }
396
+ if (normalized.value === undefined) {
397
+ throw new Error("Every custom indicator point needs a value.");
398
+ }
399
+ return normalized;
400
+ }
401
+ function customIndicatorPoints(points) {
402
+ if (!Array.isArray(points)) {
403
+ throw new Error("points must be an array of point objects.");
404
+ }
405
+ return points.map(customIndicatorPoint);
406
+ }
407
+ function pointsJsonl(points) {
408
+ return new TextEncoder().encode(points.map((point) => `${JSON.stringify(point)}\n`).join(""));
409
+ }
410
+ function inlinePointBytes(points) {
411
+ return new TextEncoder().encode(JSON.stringify(points)).length;
412
+ }
322
413
  async function waitForOperation(fetch, operationId, options = {}) {
323
414
  const timeoutSeconds = options.timeoutSeconds ?? exports.DEFAULT_POLL_TIMEOUT_SECONDS;
324
415
  const pollIntervalSeconds = options.pollIntervalSeconds ?? exports.DEFAULT_POLL_INTERVAL_SECONDS;
@@ -345,7 +436,7 @@ async function waitForOperation(fetch, operationId, options = {}) {
345
436
  if (remainingMs <= 0) {
346
437
  throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
347
438
  `${timeoutSeconds}s. It is still running — poll again with the ` +
348
- "same id rather than resubmitting.");
439
+ "same id (error.operationId) rather than resubmitting.", operationId);
349
440
  }
350
441
  if (interval > 0) {
351
442
  const delayMs = Math.min(interval * 1000, remainingMs);
@@ -393,7 +484,7 @@ class NexusTradeClient {
393
484
  return result;
394
485
  }
395
486
  /**
396
- * List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
487
+ * List portfolios with optional filters and pagination.
397
488
  * `includePositions` defaults off when `search` is set.
398
489
  */
399
490
  async listPortfolios(options = {}) {
@@ -472,6 +563,190 @@ class NexusTradeClient {
472
563
  }
473
564
  return result;
474
565
  }
566
+ /**
567
+ * Create a custom data source and return it, including its id.
568
+ *
569
+ * `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so
570
+ * every point needs a `ticker`); it defaults to `"global"` and cannot be
571
+ * changed later. `points` is optional and unlimited in size — small batches
572
+ * are sent with the request, larger ones are uploaded, and the returned
573
+ * indicator reflects what landed either way.
574
+ *
575
+ * The id it returns is what a `CustomIndicator` node binds to:
576
+ *
577
+ * ```ts
578
+ * const series = await client.createCustomIndicator(
579
+ * {
580
+ * name: "WSB NVDA Mentions",
581
+ * scope: "asset",
582
+ * points: [{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" }],
583
+ * },
584
+ * { idempotencyKey: "wsb-mentions-v1" },
585
+ * );
586
+ * CustomIndicator(stockAsset("NVDA"), String(series.customIndicatorId));
587
+ * ```
588
+ *
589
+ * Retrying with the same `idempotencyKey` returns the original series rather
590
+ * than creating a second one.
591
+ */
592
+ async createCustomIndicator(indicator, options) {
593
+ const { name, description, scope, points, ...rest } = indicator;
594
+ if (typeof name !== "string" || !name.trim()) {
595
+ throw new Error("createCustomIndicator requires a name.");
596
+ }
597
+ const unknown = Object.keys(rest);
598
+ if (unknown.length > 0) {
599
+ throw new Error(`Unknown custom indicator field(s): ${unknown.sort().join(", ")}. ` +
600
+ "Expected name, description, scope, and points.");
601
+ }
602
+ const normalized = points ? customIndicatorPoints(points) : [];
603
+ const body = { name: name.trim() };
604
+ if (description !== undefined)
605
+ body.description = description;
606
+ if (scope !== undefined)
607
+ body.scope = scope;
608
+ const inline = normalized.length > 0 &&
609
+ inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES;
610
+ if (inline)
611
+ body.points = normalized;
612
+ const created = customIndicatorOf(await this.transport.request("POST", "custom-indicators", {
613
+ body,
614
+ idempotencyKey: options.idempotencyKey,
615
+ }));
616
+ if (inline || normalized.length === 0)
617
+ return created;
618
+ const customIndicatorId = String(created.customIndicatorId);
619
+ // The same key is safe here: the server namespaces an idempotency claim
620
+ // by operation, and deriving a suffixed key could overrun its
621
+ // 160-character limit.
622
+ const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
623
+ return {
624
+ ...(await this.getCustomIndicator(customIndicatorId)),
625
+ upload,
626
+ };
627
+ }
628
+ /** List the custom data sources this account owns. */
629
+ async listCustomIndicators(options = {}) {
630
+ const query = encodeQuery({
631
+ includeArchived: options.includeArchived === undefined
632
+ ? undefined
633
+ : String(options.includeArchived),
634
+ });
635
+ const response = await this.transport.request("GET", `custom-indicators${query}`);
636
+ const indicators = response.indicators;
637
+ if (!Array.isArray(indicators)) {
638
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator list response is missing indicators.");
639
+ }
640
+ return indicators.filter((row) => isJsonObject(row));
641
+ }
642
+ /** Read one custom data source, including its current point count. */
643
+ async getCustomIndicator(customIndicatorId) {
644
+ return customIndicatorOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}`));
645
+ }
646
+ /**
647
+ * Add points to an existing series and return the updated indicator.
648
+ *
649
+ * Recurring collection must append to the same `customIndicatorId` every
650
+ * run; creating a fresh series per run splits the history into fragments a
651
+ * strategy cannot read. Re-sending an identical batch is safe — the
652
+ * duplicate is not written twice.
653
+ *
654
+ * The batch is unlimited in size and, as with creation, is sent inline or
655
+ * uploaded depending on how large it is.
656
+ */
657
+ async appendCustomIndicatorPoints(customIndicatorId, points, options) {
658
+ const normalized = customIndicatorPoints(points);
659
+ if (normalized.length === 0) {
660
+ throw new Error("appendCustomIndicatorPoints needs at least one point.");
661
+ }
662
+ if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
663
+ const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, { body: { points: normalized }, idempotencyKey: options.idempotencyKey });
664
+ const indicator = response.indicator;
665
+ if (!isJsonObject(indicator)) {
666
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
667
+ }
668
+ return indicator;
669
+ }
670
+ const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
671
+ return {
672
+ ...(await this.getCustomIndicator(customIndicatorId)),
673
+ upload,
674
+ };
675
+ }
676
+ /**
677
+ * Open an upload slot and return a presigned `uploadUrl` to PUT to.
678
+ *
679
+ * Accepts `csv`, `json`, or `jsonl` up to 100 MB. PUT the bytes to the
680
+ * returned URL, then call `completeCustomIndicatorUpload`. Most callers can
681
+ * pass `points` to `createCustomIndicator` or
682
+ * `appendCustomIndicatorPoints` instead and skip all three steps.
683
+ *
684
+ * Retrying with the same `idempotencyKey` re-signs the same job, since the
685
+ * first URL expires in 15 minutes. Once its bytes have arrived the reply
686
+ * carries no `uploadUrl` — there is nothing left to send, so skip the PUT
687
+ * and wait on `jobId`.
688
+ */
689
+ async createCustomIndicatorUpload(customIndicatorId, options) {
690
+ const body = {
691
+ fileName: options.fileName,
692
+ format: options.format ?? "jsonl",
693
+ };
694
+ if (options.contentType !== undefined)
695
+ body.contentType = options.contentType;
696
+ if (options.sizeBytes !== undefined)
697
+ body.sizeBytes = options.sizeBytes;
698
+ const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/uploads`, { body, idempotencyKey: options.idempotencyKey });
699
+ const ticket = response.ticket;
700
+ if (!isJsonObject(ticket) || !ticket.jobId) {
701
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Upload response is missing ticket.");
702
+ }
703
+ return ticket;
704
+ }
705
+ /** Start validation of uploaded bytes and return the operation. */
706
+ async completeCustomIndicatorUpload(customIndicatorId, jobId) {
707
+ return operationOf(await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
708
+ `/uploads/${encodePathSegment(jobId)}/complete`, { body: {} }));
709
+ }
710
+ /** Read an upload operation. `phase` distinguishes the live states. */
711
+ async getCustomIndicatorUpload(customIndicatorId, jobId) {
712
+ return operationOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
713
+ `/uploads/${encodePathSegment(jobId)}`));
714
+ }
715
+ /** Block until an upload is validated. See `waitForOperation`. */
716
+ async waitForCustomIndicatorUpload(customIndicatorId, jobId, options = {}) {
717
+ return waitForOperation((pendingId) => this.getCustomIndicatorUpload(customIndicatorId, pendingId), jobId, options);
718
+ }
719
+ async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey) {
720
+ const payload = pointsJsonl(points);
721
+ if (payload.length > MAX_UPLOAD_BYTES) {
722
+ throw new Error(`${points.length} points serialize to ` +
723
+ `${Math.floor(payload.length / (1024 * 1024))} MB, over the 100 MB ` +
724
+ "upload limit. Send them in several batches.");
725
+ }
726
+ if (!supportsUpload(this.transport)) {
727
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsupported_transport", "Uploading a large point batch requires HttpTransport.putBytes.");
728
+ }
729
+ const ticket = await this.createCustomIndicatorUpload(customIndicatorId, {
730
+ fileName: `${customIndicatorId}-points.jsonl`,
731
+ format: "jsonl",
732
+ sizeBytes: payload.length,
733
+ idempotencyKey,
734
+ });
735
+ const jobId = String(ticket.jobId);
736
+ // No upload URL means this batch already reached the server on an earlier
737
+ // attempt, so resume at polling instead of re-sending it.
738
+ if (ticket.uploadUrl) {
739
+ const headers = ticket.headers;
740
+ const contentType = isJsonObject(headers) && typeof headers["Content-Type"] === "string"
741
+ ? headers["Content-Type"]
742
+ : "application/x-ndjson";
743
+ await this.transport.putBytes(String(ticket.uploadUrl), payload, {
744
+ contentType,
745
+ });
746
+ await this.completeCustomIndicatorUpload(customIndicatorId, jobId);
747
+ }
748
+ return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
749
+ }
475
750
  async createBacktests(backtests, options) {
476
751
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
477
752
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -659,6 +934,13 @@ function backtestInput(item) {
659
934
  }
660
935
  return normalized;
661
936
  }
937
+ function customIndicatorOf(response) {
938
+ const indicator = response.indicator;
939
+ if (!isJsonObject(indicator) || !indicator.customIndicatorId) {
940
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
941
+ }
942
+ return indicator;
943
+ }
662
944
  function operationOf(response) {
663
945
  const operation = response.operation;
664
946
  if (!isJsonObject(operation)) {
@@ -671,6 +953,13 @@ function clientTransport(client) {
671
953
  return client.transport;
672
954
  }
673
955
  /** Convenience wrapper for scripts that do not need a persistent client. */
956
+ async function createCustomIndicator(indicator, options) {
957
+ const client = options.client ?? NexusTradeClient.fromEnvironment();
958
+ return client.createCustomIndicator(indicator, {
959
+ idempotencyKey: options.idempotencyKey,
960
+ });
961
+ }
962
+ /** Convenience wrapper for scripts that do not need a persistent client. */
674
963
  async function createPortfolio(portfolio, options) {
675
964
  const client = options.client ?? NexusTradeClient.fromEnvironment();
676
965
  return client.createPortfolio(portfolio, {
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.walkForward = exports.backtest = exports.SMA = exports.RSI = exports.PriceStdDev = exports.EMA = exports.BBand = exports.portfolio = exports.sessionFlatten = exports.strategy = exports.closeOption = exports.greeksTrigger = exports.daysHeldTrigger = exports.dteTrigger = exports.pnlTrigger = exports.rebalanceOption = exports.sleeve = exports.structureTemplate = exports.openOption = exports.againstParent = exports.optionsBuilder = exports.leg = exports.dynamicRebalance = exports.launchAgent = exports.alert = exports.withdraw = exports.deposit = exports.sell = exports.buy = exports.selectPercentile = exports.selectTop = exports.filter = exports.always = exports.multi = exports.exactly = exports.fewerThan = exports.atMost = exports.atLeast = exports.or = exports.and = exports.neq = exports.eq = exports.lte = exports.gte = exports.lt = exports.gt = exports.cryptoAsset = exports.stockAsset = exports.PORTFOLIO_WIDE = exports.CANDIDATE = void 0;
4
- exports.geneUniversePipelineFilter = exports.geneSelectTopLimit = exports.geneDteBracket = exports.geneStrikeDistance = exports.geneOptionDelta = exports.geneStructureKind = exports.geneTakeProfitPct = exports.geneRollTriggerDte = exports.geneDeploymentPct = exports.geneTotalBudgetPct = exports.geneAllocationPct = exports.geneBuyingPowerPct = exports.geneRankSignal = exports.geneEntryCooldownDays = exports.geneExitCondition = exports.geneEntryCondition = exports.geneSubject = exports.optimization = void 0;
3
+ exports.geneSubject = exports.optimization = exports.walkForward = exports.backtest = exports.SMA = exports.RSI = exports.PriceStdDev = exports.EMA = exports.BBand = exports.portfolio = exports.sessionFlatten = exports.strategy = exports.closeOption = exports.greeksTrigger = exports.daysHeldTrigger = exports.dteTrigger = exports.pnlTrigger = exports.rebalanceOption = exports.sleeve = exports.structureTemplate = exports.openOption = exports.againstParent = exports.optionsBuilder = exports.leg = exports.dynamicRebalance = exports.launchAgent = exports.alert = exports.sell = exports.buy = exports.selectPercentile = exports.selectTop = exports.filter = exports.always = exports.multi = exports.exactly = exports.fewerThan = exports.atMost = exports.atLeast = exports.or = exports.and = exports.neq = exports.eq = exports.lte = exports.gte = exports.lt = exports.gt = exports.cryptoAsset = exports.stockAsset = exports.PORTFOLIO_WIDE = exports.CANDIDATE = void 0;
4
+ exports.geneUniversePipelineFilter = exports.geneSelectTopLimit = exports.geneDteBracket = exports.geneStrikeDistance = exports.geneOptionDelta = exports.geneStructureKind = exports.geneTakeProfitPct = exports.geneRollTriggerDte = exports.geneDeploymentPct = exports.geneTotalBudgetPct = exports.geneAllocationPct = exports.geneBuyingPowerPct = exports.geneRankSignal = exports.geneEntryCooldownDays = exports.geneExitCondition = exports.geneEntryCondition = void 0;
5
5
  exports.universe = universe;
6
6
  exports.AbsoluteValue = AbsoluteValue;
7
7
  exports.AverageTrueRange = AverageTrueRange;
@@ -270,10 +270,6 @@ const buy = (target, amount, type = "percent of portfolio") => ({ type: "Buy", t
270
270
  exports.buy = buy;
271
271
  const sell = (target, amount, type = "percent of portfolio") => ({ type: "Sell", targetAsset: toAsset(target), amount: { type, amount } });
272
272
  exports.sell = sell;
273
- const deposit = (amount, type = "dollars") => ({ type: "Deposit", amount: { type, amount } });
274
- exports.deposit = deposit;
275
- const withdraw = (amount, type = "dollars") => ({ type: "Withdraw", amount: { type, amount } });
276
- exports.withdraw = withdraw;
277
273
  const alert = (message) => ({ type: "Alert", message });
278
274
  exports.alert = alert;
279
275
  const launchAgent = (config) => compact({ type: "LaunchAgent", ...config });
package/dist/cjs/index.js CHANGED
@@ -14,13 +14,14 @@ 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.portfolioHandleFromWire = exports.PortfolioHandle = exports.waitForOperation = exports.createPortfolio = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = exports.AgentRun = void 0;
17
+ exports.portfolioHandleFromWire = exports.PortfolioHandle = exports.waitForOperation = exports.createPortfolio = exports.createCustomIndicator = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = exports.AgentRun = void 0;
18
18
  var agent_js_1 = require("./agent.js");
19
19
  Object.defineProperty(exports, "AgentRun", { enumerable: true, get: function () { return agent_js_1.AgentRun; } });
20
20
  var client_js_1 = require("./client.js");
21
21
  Object.defineProperty(exports, "HttpTransport", { enumerable: true, get: function () { return client_js_1.HttpTransport; } });
22
22
  Object.defineProperty(exports, "NexusTradeApiError", { enumerable: true, get: function () { return client_js_1.NexusTradeApiError; } });
23
23
  Object.defineProperty(exports, "NexusTradeClient", { enumerable: true, get: function () { return client_js_1.NexusTradeClient; } });
24
+ Object.defineProperty(exports, "createCustomIndicator", { enumerable: true, get: function () { return client_js_1.createCustomIndicator; } });
24
25
  Object.defineProperty(exports, "createPortfolio", { enumerable: true, get: function () { return client_js_1.createPortfolio; } });
25
26
  Object.defineProperty(exports, "waitForOperation", { enumerable: true, get: function () { return client_js_1.waitForOperation; } });
26
27
  var portfolio_js_1 = require("./portfolio.js");
@@ -4,12 +4,10 @@
4
4
  *
5
5
  * Keeps the generated `Portfolio` interface as the shape; this class adds
6
6
  * lifecycle methods. `toJSON()` omits `id` so request bodies never leak
7
- * `"id": null`. Mirrors `portfolio_handle.py`.
7
+ * `"id": null`.
8
8
  *
9
9
  * Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
10
10
  * import this module without a cycle through `client.ts`.
11
- *
12
- * See designs/2026-07-26-sdk-portfolio-objects.md.
13
11
  */
14
12
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
13
  if (k2 === undefined) k2 = k;
@@ -19,8 +19,6 @@
19
19
  * if (event.needsApproval) await run.approve();
20
20
  * }
21
21
  * ```
22
- *
23
- * Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
24
22
  */
25
23
  import { type Transport } from "./client.ts";
26
24
  export interface AgentEvent {
@@ -53,9 +51,8 @@ export declare class AgentRun {
53
51
  /** Every event yielded so far, in order. */
54
52
  readonly events: AgentEvent[];
55
53
  /**
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.
54
+ * Polling pacing. Mutable so callers can widen the timeout on a run they
55
+ * expect to sit blocked for a while.
59
56
  */
60
57
  timeoutSeconds: number;
61
58
  pollIntervalSeconds: number;
package/dist/esm/agent.js CHANGED
@@ -19,8 +19,6 @@
19
19
  * if (event.needsApproval) await run.approve();
20
20
  * }
21
21
  * ```
22
- *
23
- * Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
24
22
  */
25
23
  import { DEFAULT_POLL_INTERVAL_SECONDS, DEFAULT_POLL_TIMEOUT_SECONDS, MAX_POLL_INTERVAL_SECONDS, NO_HTTP_STATUS, NexusTradeApiError, POLL_BACKOFF_FACTOR, } from "./client.js";
26
24
  const DEFAULT_EVENT_LIMIT = 50;
@@ -35,9 +33,8 @@ export class AgentRun {
35
33
  /** Every event yielded so far, in order. */
36
34
  events = [];
37
35
  /**
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.
36
+ * Polling pacing. Mutable so callers can widen the timeout on a run they
37
+ * expect to sit blocked for a while.
41
38
  */
42
39
  timeoutSeconds;
43
40
  pollIntervalSeconds;
@@ -46,6 +43,14 @@ export class AgentRun {
46
43
  #transport;
47
44
  #cursor = null;
48
45
  #seen = new Map();
46
+ /**
47
+ * Advances only after a POST is acknowledged, so a retry of a call that
48
+ * failed reuses its key and is deduped, while two different calls never
49
+ * collide. Keying on `events.length` did the latter wrong: two messages sent
50
+ * without iterating between them shared a key and the second was rejected as
51
+ * an idempotency conflict.
52
+ */
53
+ #actionSeq = 0;
49
54
  constructor(id, transport, status = "initializing", options = {}) {
50
55
  this.id = id;
51
56
  this.status = status;
@@ -206,8 +211,9 @@ export class AgentRun {
206
211
  async #post(action, body = {}) {
207
212
  const response = await this.#transport.request("POST", `agents/${encodeURIComponent(this.id)}/${action}`, {
208
213
  body,
209
- idempotencyKey: `${this.id}:${action}:${this.events.length}`,
214
+ idempotencyKey: `${this.id}:${action}:${this.#actionSeq}`,
210
215
  });
216
+ this.#actionSeq += 1;
211
217
  const agent = response.agent;
212
218
  if (agent && typeof agent === "object" && !Array.isArray(agent)) {
213
219
  const status = agent.status;