nexustrade 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +27 -1
- package/dist/cjs/agent.js +223 -0
- package/dist/cjs/client.js +175 -23
- package/dist/cjs/env.js +28 -2
- package/dist/cjs/generated/ntSdk.generated.js +2 -4
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/portfolio.js +300 -0
- package/dist/esm/agent.d.ts +86 -0
- package/dist/esm/agent.js +219 -0
- package/dist/esm/client.d.ts +52 -0
- package/dist/esm/client.js +160 -9
- package/dist/esm/env.d.ts +16 -1
- package/dist/esm/env.js +26 -2
- package/dist/esm/generated/ntSdk.generated.d.ts +2 -1
- package/dist/esm/generated/ntSdk.generated.js +2 -4
- package/dist/esm/index.d.ts +5 -1
- package/dist/esm/index.js +2 -0
- package/dist/esm/portfolio.d.ts +89 -0
- package/dist/esm/portfolio.js +262 -0
- package/package.json +1 -1
package/dist/cjs/index.js
CHANGED
|
@@ -14,11 +14,16 @@ 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.portfolioHandleFromWire = exports.PortfolioHandle = 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; } });
|
|
21
23
|
Object.defineProperty(exports, "NexusTradeClient", { enumerable: true, get: function () { return client_js_1.NexusTradeClient; } });
|
|
22
24
|
Object.defineProperty(exports, "createPortfolio", { enumerable: true, get: function () { return client_js_1.createPortfolio; } });
|
|
23
25
|
Object.defineProperty(exports, "waitForOperation", { enumerable: true, get: function () { return client_js_1.waitForOperation; } });
|
|
26
|
+
var portfolio_js_1 = require("./portfolio.js");
|
|
27
|
+
Object.defineProperty(exports, "PortfolioHandle", { enumerable: true, get: function () { return portfolio_js_1.PortfolioHandle; } });
|
|
28
|
+
Object.defineProperty(exports, "portfolioHandleFromWire", { enumerable: true, get: function () { return portfolio_js_1.portfolioHandleFromWire; } });
|
|
24
29
|
__exportStar(require("./generated/ntSdk.generated.js"), exports);
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* PortfolioHandle — one object you author, save, deploy, fetch, and backtest.
|
|
4
|
+
*
|
|
5
|
+
* Keeps the generated `Portfolio` interface as the shape; this class adds
|
|
6
|
+
* lifecycle methods. `toJSON()` omits `id` so request bodies never leak
|
|
7
|
+
* `"id": null`. Mirrors `portfolio_handle.py`.
|
|
8
|
+
*
|
|
9
|
+
* Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
|
|
10
|
+
* import this module without a cycle through `client.ts`.
|
|
11
|
+
*
|
|
12
|
+
* See designs/2026-07-26-sdk-portfolio-objects.md.
|
|
13
|
+
*/
|
|
14
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
15
|
+
if (k2 === undefined) k2 = k;
|
|
16
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
17
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
18
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
19
|
+
}
|
|
20
|
+
Object.defineProperty(o, k2, desc);
|
|
21
|
+
}) : (function(o, m, k, k2) {
|
|
22
|
+
if (k2 === undefined) k2 = k;
|
|
23
|
+
o[k2] = m[k];
|
|
24
|
+
}));
|
|
25
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
26
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
27
|
+
}) : function(o, v) {
|
|
28
|
+
o["default"] = v;
|
|
29
|
+
});
|
|
30
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
31
|
+
var ownKeys = function(o) {
|
|
32
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
33
|
+
var ar = [];
|
|
34
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
35
|
+
return ar;
|
|
36
|
+
};
|
|
37
|
+
return ownKeys(o);
|
|
38
|
+
};
|
|
39
|
+
return function (mod) {
|
|
40
|
+
if (mod && mod.__esModule) return mod;
|
|
41
|
+
var result = {};
|
|
42
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
43
|
+
__setModuleDefault(result, mod);
|
|
44
|
+
return result;
|
|
45
|
+
};
|
|
46
|
+
})();
|
|
47
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
48
|
+
exports.PortfolioHandle = void 0;
|
|
49
|
+
exports.portfolioHandleFromWire = portfolioHandleFromWire;
|
|
50
|
+
const client_ts_1 = require("./client.js");
|
|
51
|
+
function isJsonObject(value) {
|
|
52
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
53
|
+
}
|
|
54
|
+
function encodePathSegment(value) {
|
|
55
|
+
return encodeURIComponent(value);
|
|
56
|
+
}
|
|
57
|
+
/** Runtime portfolio object. Implements the generated `Portfolio` shape. */
|
|
58
|
+
class PortfolioHandle {
|
|
59
|
+
name;
|
|
60
|
+
initialValue;
|
|
61
|
+
strategies;
|
|
62
|
+
main;
|
|
63
|
+
supportsFractionalShares;
|
|
64
|
+
supportsCrypto;
|
|
65
|
+
alertsEnabled;
|
|
66
|
+
/** Chat draft id after `save()`, or fetched portfolio id. Not serialized. */
|
|
67
|
+
id = null;
|
|
68
|
+
/** Present on list/get summaries: paper | live | chat. */
|
|
69
|
+
type;
|
|
70
|
+
isActive;
|
|
71
|
+
strategyNames;
|
|
72
|
+
createdAt;
|
|
73
|
+
updatedAt;
|
|
74
|
+
brokerage;
|
|
75
|
+
#transport;
|
|
76
|
+
constructor(data, options = {}) {
|
|
77
|
+
const record = { ...data };
|
|
78
|
+
const wireId = options.id ??
|
|
79
|
+
(typeof record.portfolioId === "string" ? record.portfolioId : null) ??
|
|
80
|
+
(typeof record.id === "string" ? record.id : null);
|
|
81
|
+
delete record.portfolioId;
|
|
82
|
+
delete record.id;
|
|
83
|
+
this.name = String(record.name ?? "");
|
|
84
|
+
if (typeof record.initialValue === "number") {
|
|
85
|
+
this.initialValue = record.initialValue;
|
|
86
|
+
}
|
|
87
|
+
this.strategies = Array.isArray(record.strategies)
|
|
88
|
+
? record.strategies.filter((s) => typeof s === "object" && s !== null && !Array.isArray(s))
|
|
89
|
+
: [];
|
|
90
|
+
if (typeof record.main === "boolean")
|
|
91
|
+
this.main = record.main;
|
|
92
|
+
if (typeof record.supportsFractionalShares === "boolean") {
|
|
93
|
+
this.supportsFractionalShares = record.supportsFractionalShares;
|
|
94
|
+
}
|
|
95
|
+
if (typeof record.supportsCrypto === "boolean") {
|
|
96
|
+
this.supportsCrypto = record.supportsCrypto;
|
|
97
|
+
}
|
|
98
|
+
if (typeof record.alertsEnabled === "boolean") {
|
|
99
|
+
this.alertsEnabled = record.alertsEnabled;
|
|
100
|
+
}
|
|
101
|
+
if (record.type === "paper" ||
|
|
102
|
+
record.type === "live" ||
|
|
103
|
+
record.type === "chat") {
|
|
104
|
+
this.type = record.type;
|
|
105
|
+
}
|
|
106
|
+
if (typeof record.isActive === "boolean")
|
|
107
|
+
this.isActive = record.isActive;
|
|
108
|
+
if (Array.isArray(record.strategyNames)) {
|
|
109
|
+
this.strategyNames = record.strategyNames.map(String);
|
|
110
|
+
}
|
|
111
|
+
if (typeof record.createdAt === "string")
|
|
112
|
+
this.createdAt = record.createdAt;
|
|
113
|
+
if (typeof record.updatedAt === "string")
|
|
114
|
+
this.updatedAt = record.updatedAt;
|
|
115
|
+
if (typeof record.brokerage === "string")
|
|
116
|
+
this.brokerage = record.brokerage;
|
|
117
|
+
for (const [key, value] of Object.entries(record)) {
|
|
118
|
+
if (key === "name" ||
|
|
119
|
+
key === "initialValue" ||
|
|
120
|
+
key === "strategies" ||
|
|
121
|
+
key === "main" ||
|
|
122
|
+
key === "supportsFractionalShares" ||
|
|
123
|
+
key === "supportsCrypto" ||
|
|
124
|
+
key === "alertsEnabled" ||
|
|
125
|
+
key === "type" ||
|
|
126
|
+
key === "isActive" ||
|
|
127
|
+
key === "strategyNames" ||
|
|
128
|
+
key === "createdAt" ||
|
|
129
|
+
key === "updatedAt" ||
|
|
130
|
+
key === "brokerage") {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
// `__proto__`/`constructor` arrive as own enumerable keys from
|
|
134
|
+
// JSON.parse; assigning them replaces the instance prototype and the
|
|
135
|
+
// handle silently loses save/deploy/toJSON.
|
|
136
|
+
if (key === "__proto__" || key === "constructor")
|
|
137
|
+
continue;
|
|
138
|
+
Object.defineProperty(this, key, {
|
|
139
|
+
value,
|
|
140
|
+
writable: true,
|
|
141
|
+
enumerable: true,
|
|
142
|
+
configurable: true,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
this.id = wireId;
|
|
146
|
+
this.#transport = options.transport ?? null;
|
|
147
|
+
}
|
|
148
|
+
static from(data, options = {}) {
|
|
149
|
+
return new PortfolioHandle(data, options);
|
|
150
|
+
}
|
|
151
|
+
/** Omit `id` — class fields would otherwise serialize as `"id": null`. */
|
|
152
|
+
toJSON() {
|
|
153
|
+
const body = {
|
|
154
|
+
name: this.name,
|
|
155
|
+
strategies: this.strategies,
|
|
156
|
+
};
|
|
157
|
+
if (this.initialValue !== undefined)
|
|
158
|
+
body.initialValue = this.initialValue;
|
|
159
|
+
if (this.main !== undefined)
|
|
160
|
+
body.main = this.main;
|
|
161
|
+
if (this.supportsFractionalShares !== undefined) {
|
|
162
|
+
body.supportsFractionalShares = this.supportsFractionalShares;
|
|
163
|
+
}
|
|
164
|
+
if (this.supportsCrypto !== undefined) {
|
|
165
|
+
body.supportsCrypto = this.supportsCrypto;
|
|
166
|
+
}
|
|
167
|
+
if (this.alertsEnabled !== undefined) {
|
|
168
|
+
body.alertsEnabled = this.alertsEnabled;
|
|
169
|
+
}
|
|
170
|
+
if (this.type !== undefined)
|
|
171
|
+
body.type = this.type;
|
|
172
|
+
if (this.isActive !== undefined)
|
|
173
|
+
body.isActive = this.isActive;
|
|
174
|
+
if (this.strategyNames !== undefined) {
|
|
175
|
+
body.strategyNames = this.strategyNames;
|
|
176
|
+
}
|
|
177
|
+
if (this.createdAt !== undefined)
|
|
178
|
+
body.createdAt = this.createdAt;
|
|
179
|
+
if (this.updatedAt !== undefined)
|
|
180
|
+
body.updatedAt = this.updatedAt;
|
|
181
|
+
if (this.brokerage !== undefined)
|
|
182
|
+
body.brokerage = this.brokerage;
|
|
183
|
+
return body;
|
|
184
|
+
}
|
|
185
|
+
async #resolveTransport(transport) {
|
|
186
|
+
if (transport)
|
|
187
|
+
return transport;
|
|
188
|
+
if (this.#transport)
|
|
189
|
+
return this.#transport;
|
|
190
|
+
// Lazy: avoids importing NexusTradeClient at module load (cycle with client).
|
|
191
|
+
const { NexusTradeClient, clientTransport } = await Promise.resolve().then(() => __importStar(require("./client.js")));
|
|
192
|
+
this.#transport = clientTransport(NexusTradeClient.fromEnvironment());
|
|
193
|
+
return this.#transport;
|
|
194
|
+
}
|
|
195
|
+
/** Persist as a chat draft. Sets `.id` to the ChatPortfolio id. */
|
|
196
|
+
async save(options) {
|
|
197
|
+
const transport = await this.#resolveTransport(options.transport);
|
|
198
|
+
const response = await transport.request("POST", "portfolios", {
|
|
199
|
+
body: this.toJSON(),
|
|
200
|
+
idempotencyKey: options.idempotencyKey,
|
|
201
|
+
});
|
|
202
|
+
const result = response.portfolio;
|
|
203
|
+
if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
|
|
204
|
+
throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Portfolio save response is missing portfolioId.");
|
|
205
|
+
}
|
|
206
|
+
this.id = result.portfolioId;
|
|
207
|
+
this.#transport = transport;
|
|
208
|
+
return this;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Mint/activate the real paper portfolio.
|
|
212
|
+
* Returns a *different* id than `save()` — see `DeployResult.portfolioId`.
|
|
213
|
+
*/
|
|
214
|
+
async deploy(options = {}) {
|
|
215
|
+
if (!this.id) {
|
|
216
|
+
throw new Error("Portfolio must be saved before deploy().");
|
|
217
|
+
}
|
|
218
|
+
const transport = await this.#resolveTransport(options.transport);
|
|
219
|
+
const body = {};
|
|
220
|
+
if (options.frequency !== undefined)
|
|
221
|
+
body.frequency = options.frequency;
|
|
222
|
+
const response = await transport.request("POST", `portfolios/${encodePathSegment(this.id)}/deploy`, { body });
|
|
223
|
+
const result = isJsonObject(response.deployment)
|
|
224
|
+
? response.deployment
|
|
225
|
+
: response;
|
|
226
|
+
if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
|
|
227
|
+
throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Deploy response is missing portfolioId.");
|
|
228
|
+
}
|
|
229
|
+
return {
|
|
230
|
+
portfolioId: String(result.portfolioId),
|
|
231
|
+
chatPortfolioId: typeof result.chatPortfolioId === "string"
|
|
232
|
+
? result.chatPortfolioId
|
|
233
|
+
: undefined,
|
|
234
|
+
name: typeof result.name === "string" ? result.name : "",
|
|
235
|
+
outcome: typeof result.outcome === "string" ? result.outcome : "",
|
|
236
|
+
deploymentType: typeof result.deploymentType === "string"
|
|
237
|
+
? result.deploymentType
|
|
238
|
+
: undefined,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
async undeploy(options = {}) {
|
|
242
|
+
if (!this.id) {
|
|
243
|
+
throw new Error("Portfolio must be saved before undeploy().");
|
|
244
|
+
}
|
|
245
|
+
const transport = await this.#resolveTransport(options.transport);
|
|
246
|
+
const response = await transport.request("POST", `portfolios/${encodePathSegment(this.id)}/undeploy`, { body: {} });
|
|
247
|
+
const result = isJsonObject(response.undeployment)
|
|
248
|
+
? response.undeployment
|
|
249
|
+
: response;
|
|
250
|
+
if (!isJsonObject(result)) {
|
|
251
|
+
throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Undeploy response is missing body.");
|
|
252
|
+
}
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
/** By id once saved; inline body before. */
|
|
256
|
+
async backtest(options) {
|
|
257
|
+
const transport = await this.#resolveTransport(options.transport);
|
|
258
|
+
const input = this.id
|
|
259
|
+
? {
|
|
260
|
+
portfolioId: this.id,
|
|
261
|
+
startDate: options.startDate,
|
|
262
|
+
endDate: options.endDate,
|
|
263
|
+
}
|
|
264
|
+
: {
|
|
265
|
+
portfolio: this.toJSON(),
|
|
266
|
+
startDate: options.startDate,
|
|
267
|
+
endDate: options.endDate,
|
|
268
|
+
};
|
|
269
|
+
if (options.baseline !== undefined)
|
|
270
|
+
input.baseline = options.baseline;
|
|
271
|
+
if (options.interval !== undefined)
|
|
272
|
+
input.interval = options.interval;
|
|
273
|
+
if (options.initialValue !== undefined) {
|
|
274
|
+
input.initialValue = options.initialValue;
|
|
275
|
+
}
|
|
276
|
+
if (options.generateEvents !== undefined) {
|
|
277
|
+
input.generateEvents = options.generateEvents;
|
|
278
|
+
}
|
|
279
|
+
if (options.feeConfig !== undefined)
|
|
280
|
+
input.feeConfig = options.feeConfig;
|
|
281
|
+
const response = await transport.request("POST", "backtests/batch", {
|
|
282
|
+
body: { backtests: [input] },
|
|
283
|
+
idempotencyKey: options.idempotencyKey,
|
|
284
|
+
});
|
|
285
|
+
const operations = response.operations;
|
|
286
|
+
if (!Array.isArray(operations) ||
|
|
287
|
+
operations.length !== 1 ||
|
|
288
|
+
!isJsonObject(operations[0])) {
|
|
289
|
+
throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Backtest response is missing operations.");
|
|
290
|
+
}
|
|
291
|
+
return operations[0];
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
exports.PortfolioHandle = PortfolioHandle;
|
|
295
|
+
function portfolioHandleFromWire(data, options = {}) {
|
|
296
|
+
if (!isJsonObject(data)) {
|
|
297
|
+
throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Portfolio response is not an object.");
|
|
298
|
+
}
|
|
299
|
+
return PortfolioHandle.from(data, options);
|
|
300
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
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
|
+
/** Re-read status without consuming events. */
|
|
68
|
+
refresh(): Promise<string>;
|
|
69
|
+
/**
|
|
70
|
+
* Yield events until the run is terminal.
|
|
71
|
+
*
|
|
72
|
+
* Waits between polls on the same deterministic backoff the operation waiter
|
|
73
|
+
* uses. When the run reaches a state only the caller can clear, the blocking
|
|
74
|
+
* event is yielded and iteration then waits for the state to move — the
|
|
75
|
+
* caller is expected to answer from inside the loop body.
|
|
76
|
+
*/
|
|
77
|
+
[Symbol.asyncIterator](): AsyncIterator<AgentEvent>;
|
|
78
|
+
/** Approve a pending plan or action. Needs the `trade` scope. */
|
|
79
|
+
approve(): Promise<string>;
|
|
80
|
+
/** Reject a pending plan or action. */
|
|
81
|
+
reject(): Promise<string>;
|
|
82
|
+
/** Stop the run. */
|
|
83
|
+
stop(): Promise<string>;
|
|
84
|
+
/** Append a user message — a follow-up or a course correction. */
|
|
85
|
+
say(content: string): Promise<string>;
|
|
86
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
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
|
+
/** Re-read status without consuming events. */
|
|
66
|
+
async refresh() {
|
|
67
|
+
const response = await this.#transport.request("GET", `agents/${encodeURIComponent(this.id)}`);
|
|
68
|
+
const agent = response.agent;
|
|
69
|
+
if (agent && typeof agent === "object" && !Array.isArray(agent)) {
|
|
70
|
+
const status = agent.status;
|
|
71
|
+
if (typeof status === "string")
|
|
72
|
+
this.status = status;
|
|
73
|
+
this.terminal = Boolean(agent.terminal);
|
|
74
|
+
}
|
|
75
|
+
return this.status;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Yield events until the run is terminal.
|
|
79
|
+
*
|
|
80
|
+
* Waits between polls on the same deterministic backoff the operation waiter
|
|
81
|
+
* uses. When the run reaches a state only the caller can clear, the blocking
|
|
82
|
+
* event is yielded and iteration then waits for the state to move — the
|
|
83
|
+
* caller is expected to answer from inside the loop body.
|
|
84
|
+
*/
|
|
85
|
+
async *[Symbol.asyncIterator]() {
|
|
86
|
+
let interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
|
|
87
|
+
let deadline = Date.now() + this.timeoutSeconds * 1000;
|
|
88
|
+
let blockedStatus = null;
|
|
89
|
+
for (;;) {
|
|
90
|
+
const page = await this.#fetch();
|
|
91
|
+
const fresh = this.#absorb(page);
|
|
92
|
+
for (const event of fresh)
|
|
93
|
+
yield event;
|
|
94
|
+
if (this.terminal)
|
|
95
|
+
return;
|
|
96
|
+
if (fresh.length > 0) {
|
|
97
|
+
// Progress resets both the backoff and the stall deadline: a run that is
|
|
98
|
+
// still talking is not stuck, however long it runs.
|
|
99
|
+
interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
|
|
100
|
+
deadline = Date.now() + this.timeoutSeconds * 1000;
|
|
101
|
+
}
|
|
102
|
+
const waitingOnCaller = Boolean(page.pendingApproval) || Boolean(page.needsInput);
|
|
103
|
+
if (waitingOnCaller) {
|
|
104
|
+
if (blockedStatus === null) {
|
|
105
|
+
blockedStatus = this.status;
|
|
106
|
+
}
|
|
107
|
+
else if (this.status !== blockedStatus) {
|
|
108
|
+
// The caller answered; resume at full speed.
|
|
109
|
+
blockedStatus = null;
|
|
110
|
+
interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
|
|
111
|
+
deadline = Date.now() + this.timeoutSeconds * 1000;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
blockedStatus = null;
|
|
116
|
+
}
|
|
117
|
+
const remaining = (deadline - Date.now()) / 1000;
|
|
118
|
+
if (remaining <= 0) {
|
|
119
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, waitingOnCaller ? "agent_awaiting_input" : "agent_timeout", `Agent ${this.id} was still '${this.status}' after ` +
|
|
120
|
+
`${this.timeoutSeconds}s. It is still running — answer ` +
|
|
121
|
+
"it, or attach again with the same id.");
|
|
122
|
+
}
|
|
123
|
+
if (interval > 0)
|
|
124
|
+
await sleep(Math.min(interval, remaining));
|
|
125
|
+
interval = Math.min(interval * POLL_BACKOFF_FACTOR, this.maxPollIntervalSeconds);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async #fetch() {
|
|
129
|
+
const query = new URLSearchParams({
|
|
130
|
+
limit: String(this.eventLimit),
|
|
131
|
+
});
|
|
132
|
+
if (this.#cursor)
|
|
133
|
+
query.set("cursor", this.#cursor);
|
|
134
|
+
return this.#transport.request("GET", `agents/${encodeURIComponent(this.id)}/events?${query.toString()}`);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Fold a page into run state, dropping anything already delivered.
|
|
138
|
+
*
|
|
139
|
+
* The server re-sends rather than risk skipping, so the same id can arrive
|
|
140
|
+
* twice. Deduping here is what turns that guarantee into an exactly-once
|
|
141
|
+
* stream for the caller.
|
|
142
|
+
*/
|
|
143
|
+
#absorb(page) {
|
|
144
|
+
if (typeof page.status === "string")
|
|
145
|
+
this.status = page.status;
|
|
146
|
+
this.terminal = Boolean(page.terminal);
|
|
147
|
+
if (typeof page.nextCursor === "string" && page.nextCursor) {
|
|
148
|
+
this.#cursor = page.nextCursor;
|
|
149
|
+
}
|
|
150
|
+
const approval = page.pendingApproval;
|
|
151
|
+
const approvalKind = approval && typeof approval === "object" && !Array.isArray(approval)
|
|
152
|
+
? String(approval.kind ?? "")
|
|
153
|
+
: null;
|
|
154
|
+
const needsInput = Boolean(page.needsInput);
|
|
155
|
+
const raw = page.events;
|
|
156
|
+
if (!Array.isArray(raw))
|
|
157
|
+
return [];
|
|
158
|
+
const fresh = [];
|
|
159
|
+
raw.forEach((item, index) => {
|
|
160
|
+
if (!item || typeof item !== "object" || Array.isArray(item))
|
|
161
|
+
return;
|
|
162
|
+
const record = item;
|
|
163
|
+
const id = String(record.id ?? "");
|
|
164
|
+
const digest = String(record.digest ?? "");
|
|
165
|
+
if (!id)
|
|
166
|
+
return;
|
|
167
|
+
const previous = this.#seen.get(id);
|
|
168
|
+
if (previous === digest)
|
|
169
|
+
return; // already delivered, unchanged
|
|
170
|
+
this.#seen.set(id, digest);
|
|
171
|
+
const isLast = index === raw.length - 1;
|
|
172
|
+
const event = {
|
|
173
|
+
id,
|
|
174
|
+
digest,
|
|
175
|
+
role: String(record.role ?? "Assistant"),
|
|
176
|
+
text: String(record.text ?? ""),
|
|
177
|
+
data: record.data,
|
|
178
|
+
// Only the final event of a page can be the one the run is blocked on —
|
|
179
|
+
// the state applies to the tail, not the history.
|
|
180
|
+
needsApproval: Boolean(approvalKind) && isLast,
|
|
181
|
+
approvalKind: isLast && approvalKind ? approvalKind : null,
|
|
182
|
+
needsInput: needsInput && isLast,
|
|
183
|
+
supersedes: previous !== undefined,
|
|
184
|
+
};
|
|
185
|
+
fresh.push(event);
|
|
186
|
+
this.events.push(event);
|
|
187
|
+
});
|
|
188
|
+
return fresh;
|
|
189
|
+
}
|
|
190
|
+
/** Approve a pending plan or action. Needs the `trade` scope. */
|
|
191
|
+
approve() {
|
|
192
|
+
return this.#post("approve");
|
|
193
|
+
}
|
|
194
|
+
/** Reject a pending plan or action. */
|
|
195
|
+
reject() {
|
|
196
|
+
return this.#post("reject");
|
|
197
|
+
}
|
|
198
|
+
/** Stop the run. */
|
|
199
|
+
stop() {
|
|
200
|
+
return this.#post("stop");
|
|
201
|
+
}
|
|
202
|
+
/** Append a user message — a follow-up or a course correction. */
|
|
203
|
+
say(content) {
|
|
204
|
+
return this.#post("messages", { content });
|
|
205
|
+
}
|
|
206
|
+
async #post(action, body = {}) {
|
|
207
|
+
const response = await this.#transport.request("POST", `agents/${encodeURIComponent(this.id)}/${action}`, {
|
|
208
|
+
body,
|
|
209
|
+
idempotencyKey: `${this.id}:${action}:${this.events.length}`,
|
|
210
|
+
});
|
|
211
|
+
const agent = response.agent;
|
|
212
|
+
if (agent && typeof agent === "object" && !Array.isArray(agent)) {
|
|
213
|
+
const status = agent.status;
|
|
214
|
+
if (typeof status === "string")
|
|
215
|
+
this.status = status;
|
|
216
|
+
}
|
|
217
|
+
return this.status;
|
|
218
|
+
}
|
|
219
|
+
}
|