@hypercli.com/sdk 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +629 -0
- package/dist/acp-driver.d.ts +72 -0
- package/dist/acp-driver.d.ts.map +1 -0
- package/dist/acp-driver.js +147 -0
- package/dist/acp-driver.js.map +1 -0
- package/dist/acp-pool.d.ts +70 -0
- package/dist/acp-pool.d.ts.map +1 -0
- package/dist/acp-pool.js +181 -0
- package/dist/acp-pool.js.map +1 -0
- package/dist/acp.d.ts +179 -0
- package/dist/acp.d.ts.map +1 -0
- package/dist/acp.js +487 -0
- package/dist/acp.js.map +1 -0
- package/dist/agent-persona.d.ts +68 -0
- package/dist/agent-persona.d.ts.map +1 -0
- package/dist/agent-persona.js +78 -0
- package/dist/agent-persona.js.map +1 -0
- package/dist/agent-slots.d.ts +18 -0
- package/dist/agent-slots.d.ts.map +1 -0
- package/dist/agent-slots.js +24 -0
- package/dist/agent-slots.js.map +1 -0
- package/dist/agent-urls.d.ts +47 -0
- package/dist/agent-urls.d.ts.map +1 -0
- package/dist/agent-urls.js +178 -0
- package/dist/agent-urls.js.map +1 -0
- package/dist/agent.d.ts +482 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +926 -0
- package/dist/agent.js.map +1 -0
- package/dist/agents.d.ts +1452 -0
- package/dist/agents.d.ts.map +1 -0
- package/dist/agents.js +4022 -0
- package/dist/agents.js.map +1 -0
- package/dist/billing.d.ts +72 -0
- package/dist/billing.d.ts.map +1 -0
- package/dist/billing.js +93 -0
- package/dist/billing.js.map +1 -0
- package/dist/browser-jobs.d.ts +24 -0
- package/dist/browser-jobs.d.ts.map +1 -0
- package/dist/browser-jobs.js +209 -0
- package/dist/browser-jobs.js.map +1 -0
- package/dist/browser.d.ts +41 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +57 -0
- package/dist/browser.js.map +1 -0
- package/dist/buzz-activity.d.ts +169 -0
- package/dist/buzz-activity.d.ts.map +1 -0
- package/dist/buzz-activity.js +844 -0
- package/dist/buzz-activity.js.map +1 -0
- package/dist/channels.d.ts +99 -0
- package/dist/channels.d.ts.map +1 -0
- package/dist/channels.js +27 -0
- package/dist/channels.js.map +1 -0
- package/dist/chat-integrations.d.ts +44 -0
- package/dist/chat-integrations.d.ts.map +1 -0
- package/dist/chat-integrations.js +138 -0
- package/dist/chat-integrations.js.map +1 -0
- package/dist/client.d.ts +88 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +144 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +44 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +192 -0
- package/dist/config.js.map +1 -0
- package/dist/connectors.d.ts +80 -0
- package/dist/connectors.d.ts.map +1 -0
- package/dist/connectors.js +2 -0
- package/dist/connectors.js.map +1 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +26 -0
- package/dist/errors.js.map +1 -0
- package/dist/files.d.ts +60 -0
- package/dist/files.d.ts.map +1 -0
- package/dist/files.js +128 -0
- package/dist/files.js.map +1 -0
- package/dist/http.d.ts +56 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +362 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +64 -0
- package/dist/index.js.map +1 -0
- package/dist/instances.d.ts +94 -0
- package/dist/instances.d.ts.map +1 -0
- package/dist/instances.js +197 -0
- package/dist/instances.js.map +1 -0
- package/dist/integrations.d.ts +111 -0
- package/dist/integrations.d.ts.map +1 -0
- package/dist/integrations.js +206 -0
- package/dist/integrations.js.map +1 -0
- package/dist/job/base.d.ts +86 -0
- package/dist/job/base.d.ts.map +1 -0
- package/dist/job/base.js +206 -0
- package/dist/job/base.js.map +1 -0
- package/dist/job/comfyui.d.ts +259 -0
- package/dist/job/comfyui.d.ts.map +1 -0
- package/dist/job/comfyui.js +1563 -0
- package/dist/job/comfyui.js.map +1 -0
- package/dist/job/gradio.d.ts +48 -0
- package/dist/job/gradio.d.ts.map +1 -0
- package/dist/job/gradio.js +90 -0
- package/dist/job/gradio.js.map +1 -0
- package/dist/job-codecs.d.ts +66 -0
- package/dist/job-codecs.d.ts.map +1 -0
- package/dist/job-codecs.js +132 -0
- package/dist/job-codecs.js.map +1 -0
- package/dist/jobs.d.ts +148 -0
- package/dist/jobs.d.ts.map +1 -0
- package/dist/jobs.js +480 -0
- package/dist/jobs.js.map +1 -0
- package/dist/keys.d.ts +99 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +145 -0
- package/dist/keys.js.map +1 -0
- package/dist/logs.d.ts +54 -0
- package/dist/logs.d.ts.map +1 -0
- package/dist/logs.js +256 -0
- package/dist/logs.js.map +1 -0
- package/dist/managed-context.d.ts +20 -0
- package/dist/managed-context.d.ts.map +1 -0
- package/dist/managed-context.js +95 -0
- package/dist/managed-context.js.map +1 -0
- package/dist/mcp.d.ts +7 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +8 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory.d.ts +87 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +79 -0
- package/dist/memory.js.map +1 -0
- package/dist/models.d.ts +15 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +19 -0
- package/dist/models.js.map +1 -0
- package/dist/openclaw-control-ui-origin.d.ts +23 -0
- package/dist/openclaw-control-ui-origin.d.ts.map +1 -0
- package/dist/openclaw-control-ui-origin.js +53 -0
- package/dist/openclaw-control-ui-origin.js.map +1 -0
- package/dist/renders.d.ts +187 -0
- package/dist/renders.d.ts.map +1 -0
- package/dist/renders.js +360 -0
- package/dist/renders.js.map +1 -0
- package/dist/routines.d.ts +59 -0
- package/dist/routines.d.ts.map +1 -0
- package/dist/routines.js +135 -0
- package/dist/routines.js.map +1 -0
- package/dist/runners.d.ts +61 -0
- package/dist/runners.d.ts.map +1 -0
- package/dist/runners.js +127 -0
- package/dist/runners.js.map +1 -0
- package/dist/sessions.d.ts +280 -0
- package/dist/sessions.d.ts.map +1 -0
- package/dist/sessions.js +292 -0
- package/dist/sessions.js.map +1 -0
- package/dist/skills.d.ts +170 -0
- package/dist/skills.d.ts.map +1 -0
- package/dist/skills.js +2 -0
- package/dist/skills.js.map +1 -0
- package/dist/user.d.ts +78 -0
- package/dist/user.d.ts.map +1 -0
- package/dist/user.js +143 -0
- package/dist/user.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +3 -0
- package/dist/version.js.map +1 -0
- package/dist/voice-session.d.ts +66 -0
- package/dist/voice-session.d.ts.map +1 -0
- package/dist/voice-session.js +366 -0
- package/dist/voice-session.js.map +1 -0
- package/dist/voice-transcription-session.d.ts +64 -0
- package/dist/voice-transcription-session.d.ts.map +1 -0
- package/dist/voice-transcription-session.js +228 -0
- package/dist/voice-transcription-session.js.map +1 -0
- package/dist/voice.d.ts +62 -0
- package/dist/voice.d.ts.map +1 -0
- package/dist/voice.js +134 -0
- package/dist/voice.js.map +1 -0
- package/dist/workspace-tomd.d.ts +61 -0
- package/dist/workspace-tomd.d.ts.map +1 -0
- package/dist/workspace-tomd.js +177 -0
- package/dist/workspace-tomd.js.map +1 -0
- package/dist/workspaces.d.ts +255 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +653 -0
- package/dist/workspaces.js.map +1 -0
- package/package.json +115 -0
- package/runtime/config-require.browser.js +4 -0
- package/runtime/config-require.d.ts +2 -0
- package/runtime/config-require.node.js +8 -0
package/dist/agent.js
ADDED
|
@@ -0,0 +1,926 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HyperAgent API client - AI agent inference using OpenAI-compatible API
|
|
3
|
+
*
|
|
4
|
+
* Note: OpenAI client integration is not included in this SDK.
|
|
5
|
+
* Use the OpenAI Node.js SDK directly with HyperClaw endpoints.
|
|
6
|
+
*/
|
|
7
|
+
import { responseAPIError } from './http.js';
|
|
8
|
+
import { getAgentsApiBaseUrl, getApiUrl } from './config.js';
|
|
9
|
+
import { resolveAgentsApiBase } from './agent-urls.js';
|
|
10
|
+
import { agentSlotFromDict } from './agent-slots.js';
|
|
11
|
+
function resolveHyperAgentBaseUrl(productApiBaseUrl) {
|
|
12
|
+
const raw = (productApiBaseUrl || '').replace(/\/+$/, '');
|
|
13
|
+
if (!raw) {
|
|
14
|
+
const fallback = getApiUrl();
|
|
15
|
+
return resolveHyperAgentBaseUrl(fallback);
|
|
16
|
+
}
|
|
17
|
+
const parsed = new URL(raw.includes('://') ? raw : `https://${raw}`);
|
|
18
|
+
const host = parsed.host.toLowerCase();
|
|
19
|
+
if (host === 'api.hypercli.com' || host === 'api.hyperclaw.app' || host === 'api.agents.hypercli.com') {
|
|
20
|
+
return 'https://api.agents.hypercli.com/v1';
|
|
21
|
+
}
|
|
22
|
+
if (host === 'api.dev.hypercli.com' ||
|
|
23
|
+
host === 'api.dev.hyperclaw.app' ||
|
|
24
|
+
host === 'dev-api.hyperclaw.app' ||
|
|
25
|
+
host === 'api.agents.dev.hypercli.com') {
|
|
26
|
+
return 'https://api.agents.dev.hypercli.com/v1';
|
|
27
|
+
}
|
|
28
|
+
if (raw.endsWith('/api')) {
|
|
29
|
+
return `${raw.slice(0, -4)}/v1`;
|
|
30
|
+
}
|
|
31
|
+
if (raw.endsWith('/agents')) {
|
|
32
|
+
return `${raw.slice(0, -7)}/v1`;
|
|
33
|
+
}
|
|
34
|
+
return `${raw}/v1`;
|
|
35
|
+
}
|
|
36
|
+
function resolveHyperAgentControlBaseUrl(productApiBaseUrl, agentsApiBaseUrl, dev) {
|
|
37
|
+
return resolveAgentsApiBase(agentsApiBaseUrl || getAgentsApiBaseUrl(dev, productApiBaseUrl), true);
|
|
38
|
+
}
|
|
39
|
+
export const HYPER_AGENT_CANONICAL_PLAN_IDS = ['solo', 'team', 'pro'];
|
|
40
|
+
export function parseHyperAgentPlanId(value) {
|
|
41
|
+
const normalized = String(value ?? '').trim().toLowerCase();
|
|
42
|
+
return HYPER_AGENT_CANONICAL_PLAN_IDS.includes(normalized)
|
|
43
|
+
? normalized
|
|
44
|
+
: null;
|
|
45
|
+
}
|
|
46
|
+
/** Whether any subscription or direct entitlement is currently active. */
|
|
47
|
+
export function hasActivePlan(summary) {
|
|
48
|
+
return summary.activeSubscriptionCount > 0 || summary.activeEntitlementCount > 0;
|
|
49
|
+
}
|
|
50
|
+
function hyperAgentPlanFromDict(data) {
|
|
51
|
+
const agents = Number(data.agents ?? 0);
|
|
52
|
+
const maxAgentSize = ['small', 'medium', 'large'].includes(data.max_agent_size)
|
|
53
|
+
? data.max_agent_size
|
|
54
|
+
: null;
|
|
55
|
+
const resources = data.agent_resources;
|
|
56
|
+
const explicitSlotGrants = data.slot_grants && typeof data.slot_grants === 'object'
|
|
57
|
+
? Object.fromEntries(Object.entries(data.slot_grants)
|
|
58
|
+
.map(([tier, count]) => [tier, Number(count)])
|
|
59
|
+
.filter(([, count]) => Number.isFinite(count) && count > 0))
|
|
60
|
+
: {};
|
|
61
|
+
const slotGrants = Object.keys(explicitSlotGrants).length > 0
|
|
62
|
+
? explicitSlotGrants
|
|
63
|
+
: maxAgentSize && agents > 0
|
|
64
|
+
? { [maxAgentSize]: agents }
|
|
65
|
+
: {};
|
|
66
|
+
return {
|
|
67
|
+
id: data.id,
|
|
68
|
+
canonicalId: parseHyperAgentPlanId(data.id),
|
|
69
|
+
name: data.name,
|
|
70
|
+
price: data.price ?? data.price_usd ?? 0,
|
|
71
|
+
priceUsd: data.price_usd ?? data.price ?? 0,
|
|
72
|
+
aiu: data.aiu == null ? undefined : Number(data.aiu),
|
|
73
|
+
agents,
|
|
74
|
+
amountCents: Number(data.amount_cents ?? 0),
|
|
75
|
+
contractVersion: data.contract_version == null ? null : String(data.contract_version),
|
|
76
|
+
maxAgentSize,
|
|
77
|
+
slotGrants,
|
|
78
|
+
agentResources: resources && typeof resources === 'object' ? {
|
|
79
|
+
maxAgents: Number(resources.max_agents ?? agents),
|
|
80
|
+
totalCpu: Number(resources.total_cpu ?? 0),
|
|
81
|
+
totalMemory: Number(resources.total_memory ?? 0),
|
|
82
|
+
} : null,
|
|
83
|
+
features: data.features || [],
|
|
84
|
+
models: data.models || [],
|
|
85
|
+
highlighted: Boolean(data.highlighted),
|
|
86
|
+
expiresAt: data.expires_at ? new Date(String(data.expires_at).replace('Z', '+00:00')) : null,
|
|
87
|
+
limits: {
|
|
88
|
+
tpd: data.limits?.tpd || 0,
|
|
89
|
+
tpm: data.limits?.tpm || 0,
|
|
90
|
+
burstTpm: data.limits?.burst_tpm || 0,
|
|
91
|
+
rpm: data.limits?.rpm || 0,
|
|
92
|
+
},
|
|
93
|
+
tpmLimit: data.tpm_limit || data.limits?.tpm || 0,
|
|
94
|
+
rpmLimit: data.rpm_limit || data.limits?.rpm || 0,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function hyperAgentCurrentPlanFromDict(data) {
|
|
98
|
+
return {
|
|
99
|
+
id: data.id,
|
|
100
|
+
name: data.name,
|
|
101
|
+
price: data.price,
|
|
102
|
+
aiu: data.aiu,
|
|
103
|
+
agents: data.agents,
|
|
104
|
+
tpmLimit: data.tpm_limit || 0,
|
|
105
|
+
rpmLimit: data.rpm_limit || 0,
|
|
106
|
+
expiresAt: data.expires_at ? new Date(String(data.expires_at).replace('Z', '+00:00')) : null,
|
|
107
|
+
cancelAtPeriodEnd: Boolean(data.cancel_at_period_end),
|
|
108
|
+
provider: data.provider || undefined,
|
|
109
|
+
secondsRemaining: data.seconds_remaining ?? null,
|
|
110
|
+
pooledTpd: data.pooled_tpd || 0,
|
|
111
|
+
maxAgentSize: ['small', 'medium', 'large'].includes(data.max_agent_size)
|
|
112
|
+
? data.max_agent_size
|
|
113
|
+
: null,
|
|
114
|
+
slotInventory: data.slot_inventory || undefined,
|
|
115
|
+
agentSlots: (data.agent_slots || []).map(agentSlotFromDict),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
const ACTIVE_LIKE_SUBSCRIPTION_STATUSES = new Set(['active', 'trialing']);
|
|
119
|
+
function nullableNumberFromDict(value) {
|
|
120
|
+
if (value === undefined || value === null || value === '')
|
|
121
|
+
return null;
|
|
122
|
+
const parsed = Number(value);
|
|
123
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
124
|
+
}
|
|
125
|
+
function validDateFromDict(value) {
|
|
126
|
+
if (value === undefined || value === null || value === '')
|
|
127
|
+
return null;
|
|
128
|
+
const numericValue = typeof value === 'number'
|
|
129
|
+
? value
|
|
130
|
+
: typeof value === 'string' && /^-?\d+(?:\.\d+)?$/.test(value.trim())
|
|
131
|
+
? Number(value)
|
|
132
|
+
: null;
|
|
133
|
+
const date = numericValue !== null && Number.isFinite(numericValue)
|
|
134
|
+
? new Date(Math.abs(numericValue) < 1_000_000_000_000 ? numericValue * 1000 : numericValue)
|
|
135
|
+
: dateFromDict(value);
|
|
136
|
+
return date && Number.isFinite(date.getTime()) ? date : null;
|
|
137
|
+
}
|
|
138
|
+
function firstValidDateFromDict(...values) {
|
|
139
|
+
for (const value of values) {
|
|
140
|
+
const date = validDateFromDict(value);
|
|
141
|
+
if (date)
|
|
142
|
+
return date;
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
function hyperAgentSubscriptionTrialFromDict(data, meta, entitlements) {
|
|
147
|
+
if (Object.prototype.hasOwnProperty.call(data || {}, 'trial')) {
|
|
148
|
+
const trial = data.trial;
|
|
149
|
+
if (!trial || typeof trial !== 'object' || Array.isArray(trial))
|
|
150
|
+
return null;
|
|
151
|
+
return {
|
|
152
|
+
active: trial.active === true,
|
|
153
|
+
days: nullableNumberFromDict(trial.days),
|
|
154
|
+
startsAt: validDateFromDict(trial.starts_at),
|
|
155
|
+
endsAt: validDateFromDict(trial.ends_at),
|
|
156
|
+
secondsRemaining: nullableNumberFromDict(trial.seconds_remaining),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
const trialMarker = meta?.trial;
|
|
160
|
+
const hasTrialMarker = trialMarker === true
|
|
161
|
+
|| (typeof trialMarker === 'string' && trialMarker.trim().toLowerCase() === 'true');
|
|
162
|
+
const trialActiveMarker = meta?.trial_active;
|
|
163
|
+
const explicitlyInactive = trialActiveMarker === false
|
|
164
|
+
|| (typeof trialActiveMarker === 'string' && trialActiveMarker.trim().toLowerCase() === 'false')
|
|
165
|
+
|| Boolean(meta?.trial_ended_at)
|
|
166
|
+
|| Boolean(data?.cancel_at_period_end);
|
|
167
|
+
const status = String(data?.status || '').trim().toLowerCase();
|
|
168
|
+
const trialDays = nullableNumberFromDict(meta?.trial_days);
|
|
169
|
+
const metadataStartsAt = firstValidDateFromDict(meta?.trial_starts_at, meta?.trial_started_at, meta?.trial_start_at, meta?.trial_start);
|
|
170
|
+
const metadataEndsAt = firstValidDateFromDict(meta?.trial_ends_at, meta?.trial_ended_at, meta?.trial_end_at, meta?.trial_end);
|
|
171
|
+
const entitlementStartsAt = entitlements
|
|
172
|
+
.map((entitlement) => entitlement.startsAt)
|
|
173
|
+
.filter((value) => Boolean(value && Number.isFinite(value.getTime())))
|
|
174
|
+
.sort((left, right) => left.getTime() - right.getTime())[0] ?? null;
|
|
175
|
+
const fallbackStartsAt = metadataStartsAt ?? entitlementStartsAt;
|
|
176
|
+
const derivedEndsAt = fallbackStartsAt && trialDays && trialDays > 0
|
|
177
|
+
? new Date(fallbackStartsAt.getTime() + trialDays * 24 * 60 * 60 * 1000)
|
|
178
|
+
: null;
|
|
179
|
+
const periodEndsAt = validDateFromDict(data?.current_period_end ?? data?.expires_at);
|
|
180
|
+
const authoritativeEndsAt = metadataEndsAt ?? periodEndsAt;
|
|
181
|
+
let startsAt = metadataStartsAt;
|
|
182
|
+
if (!startsAt && authoritativeEndsAt && trialDays && trialDays > 0) {
|
|
183
|
+
startsAt = new Date(authoritativeEndsAt.getTime() - trialDays * 24 * 60 * 60 * 1000);
|
|
184
|
+
}
|
|
185
|
+
startsAt ??= entitlementStartsAt;
|
|
186
|
+
const hasPersistedTrialTiming = Boolean(metadataStartsAt
|
|
187
|
+
|| metadataEndsAt
|
|
188
|
+
|| (entitlementStartsAt && trialDays && trialDays > 0));
|
|
189
|
+
const now = Date.now();
|
|
190
|
+
const periodWouldReviveExpiredTrial = Boolean(!metadataEndsAt
|
|
191
|
+
&& periodEndsAt
|
|
192
|
+
&& periodEndsAt.getTime() > now
|
|
193
|
+
&& derivedEndsAt
|
|
194
|
+
&& derivedEndsAt.getTime() <= now);
|
|
195
|
+
const endsAt = authoritativeEndsAt ?? derivedEndsAt;
|
|
196
|
+
if (!hasTrialMarker
|
|
197
|
+
|| explicitlyInactive
|
|
198
|
+
|| !ACTIVE_LIKE_SUBSCRIPTION_STATUSES.has(status)
|
|
199
|
+
|| !hasPersistedTrialTiming
|
|
200
|
+
|| periodWouldReviveExpiredTrial
|
|
201
|
+
|| !endsAt
|
|
202
|
+
|| endsAt.getTime() <= now) {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
active: true,
|
|
207
|
+
days: trialDays,
|
|
208
|
+
startsAt,
|
|
209
|
+
endsAt,
|
|
210
|
+
secondsRemaining: Math.max(0, Math.floor((endsAt.getTime() - now) / 1000)),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
function hyperAgentPaymentMethodSummaryFromDict(data) {
|
|
214
|
+
if (!data || typeof data !== 'object' || Array.isArray(data))
|
|
215
|
+
return null;
|
|
216
|
+
const brand = data.brand == null ? null : String(data.brand);
|
|
217
|
+
const last4 = data.last4 == null ? null : String(data.last4);
|
|
218
|
+
if (!brand && !last4)
|
|
219
|
+
return null;
|
|
220
|
+
return {
|
|
221
|
+
brand,
|
|
222
|
+
last4,
|
|
223
|
+
expMonth: nullableNumberFromDict(data.exp_month),
|
|
224
|
+
expYear: nullableNumberFromDict(data.exp_year),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function hyperAgentSubscriptionFromDict(data) {
|
|
228
|
+
const periodEnd = data.current_period_end || data.expires_at || null;
|
|
229
|
+
const expiresAt = validDateFromDict(periodEnd);
|
|
230
|
+
const meta = data.meta ?? null;
|
|
231
|
+
const entitlements = (data.entitlements || []).map(hyperAgentEntitlementFromDict);
|
|
232
|
+
const directAgentSlots = (data.agent_slots || []).map(agentSlotFromDict);
|
|
233
|
+
const slotGrants = mergeSlotGrants(data.slot_grants, ...entitlements.map((entitlement) => entitlement.slotGrants));
|
|
234
|
+
return {
|
|
235
|
+
id: data.id || '',
|
|
236
|
+
userId: data.user_id || '',
|
|
237
|
+
planId: data.plan_id || '',
|
|
238
|
+
planName: data.plan_name || data.plan_id || '',
|
|
239
|
+
provider: data.provider || '',
|
|
240
|
+
status: data.status || '',
|
|
241
|
+
quantity: data.quantity || 1,
|
|
242
|
+
expiresAt,
|
|
243
|
+
updatedAt: data.updated_at ? new Date(String(data.updated_at).replace('Z', '+00:00')) : null,
|
|
244
|
+
stripeSubscriptionId: data.stripe_subscription_id || null,
|
|
245
|
+
paymentMethod: hyperAgentPaymentMethodSummaryFromDict(data.payment_method),
|
|
246
|
+
cancelAtPeriodEnd: Boolean(data.cancel_at_period_end),
|
|
247
|
+
canCancel: Boolean(data.can_cancel),
|
|
248
|
+
isCurrent: Boolean(data.is_current),
|
|
249
|
+
meta,
|
|
250
|
+
trial: hyperAgentSubscriptionTrialFromDict(data, meta, entitlements),
|
|
251
|
+
planTpmLimit: data.plan_tpm_limit || 0,
|
|
252
|
+
planRpmLimit: data.plan_rpm_limit || 0,
|
|
253
|
+
planTpd: data.plan_tpd || 0,
|
|
254
|
+
planAgentTier: data.plan_agent_tier || null,
|
|
255
|
+
slotGrants,
|
|
256
|
+
entitlements,
|
|
257
|
+
agentSlots: directAgentSlots.length > 0
|
|
258
|
+
? directAgentSlots
|
|
259
|
+
: entitlements.flatMap((entitlement) => entitlement.agentSlots),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
function mergeSlotGrants(...sources) {
|
|
263
|
+
const merged = {};
|
|
264
|
+
for (const source of sources) {
|
|
265
|
+
if (!source)
|
|
266
|
+
continue;
|
|
267
|
+
for (const [tier, value] of Object.entries(source)) {
|
|
268
|
+
const granted = Number(value || 0);
|
|
269
|
+
if (!Number.isFinite(granted) || granted <= 0)
|
|
270
|
+
continue;
|
|
271
|
+
merged[tier] = Math.max(merged[tier] || 0, granted);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return Object.keys(merged).length > 0 ? merged : null;
|
|
275
|
+
}
|
|
276
|
+
function hyperAgentEntitlementFromDict(data) {
|
|
277
|
+
return {
|
|
278
|
+
id: data.id || '',
|
|
279
|
+
userId: data.user_id || '',
|
|
280
|
+
subscriptionId: data.subscription_id || null,
|
|
281
|
+
planId: data.plan_id || '',
|
|
282
|
+
planName: data.plan_name || data.plan_id || '',
|
|
283
|
+
provider: data.provider || '',
|
|
284
|
+
status: data.status || '',
|
|
285
|
+
startsAt: dateFromDict(data.starts_at),
|
|
286
|
+
expiresAt: data.expires_at ? new Date(String(data.expires_at).replace('Z', '+00:00')) : null,
|
|
287
|
+
updatedAt: data.updated_at ? new Date(String(data.updated_at).replace('Z', '+00:00')) : null,
|
|
288
|
+
tpmLimit: data.tpm_limit || 0,
|
|
289
|
+
rpmLimit: data.rpm_limit || 0,
|
|
290
|
+
tpdLimit: data.tpd_limit || 0,
|
|
291
|
+
agentTier: data.agent_tier || null,
|
|
292
|
+
features: data.features || {},
|
|
293
|
+
tags: data.tags || [],
|
|
294
|
+
meta: data.meta || null,
|
|
295
|
+
slotGrants: data.slot_grants || null,
|
|
296
|
+
activeAgentCount: data.active_agent_count || 0,
|
|
297
|
+
activeAgentIds: data.active_agent_ids || [],
|
|
298
|
+
agentSlots: (data.agent_slots || []).map(agentSlotFromDict),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
function hyperAgentGrantFromDict(data) {
|
|
302
|
+
return {
|
|
303
|
+
id: String(data?.id || ''),
|
|
304
|
+
userId: data?.user_id ?? null,
|
|
305
|
+
entitlementId: data?.entitlement_id ?? null,
|
|
306
|
+
type: String(data?.type || ''),
|
|
307
|
+
planId: String(data?.plan_id || ''),
|
|
308
|
+
duration: Number(data?.duration || 0),
|
|
309
|
+
code: data?.code ?? null,
|
|
310
|
+
tags: Array.isArray(data?.tags) ? data.tags.map(String) : [],
|
|
311
|
+
meta: data?.meta || null,
|
|
312
|
+
appliedAt: dateFromDict(data?.applied_at),
|
|
313
|
+
createdAt: dateFromDict(data?.created_at),
|
|
314
|
+
updatedAt: dateFromDict(data?.updated_at),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
function hyperAgentEntitlementsFromDict(data) {
|
|
318
|
+
const payload = data?.entitlements && typeof data.entitlements === 'object' ? data.entitlements : data;
|
|
319
|
+
const billingResetAt = payload?.billing_reset_at || data?.billing_reset_at || null;
|
|
320
|
+
return {
|
|
321
|
+
effectivePlanId: payload?.effective_plan_id || data?.effective_plan_id || '',
|
|
322
|
+
pooledTpmLimit: payload?.pooled_tpm_limit || data?.pooled_tpm_limit || 0,
|
|
323
|
+
pooledRpmLimit: payload?.pooled_rpm_limit || data?.pooled_rpm_limit || 0,
|
|
324
|
+
pooledTpd: payload?.pooled_tpd || data?.pooled_tpd || 0,
|
|
325
|
+
slotInventory: payload?.slot_inventory || data?.slot_inventory || {},
|
|
326
|
+
activeEntitlementCount: payload?.active_entitlement_count || data?.active_entitlement_count || data?.active_subscription_count || 0,
|
|
327
|
+
billingResetAt: billingResetAt ? new Date(String(billingResetAt).replace('Z', '+00:00')) : null,
|
|
328
|
+
agentSlots: (payload?.agent_slots || data?.agent_slots || []).map(agentSlotFromDict),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
function hyperAgentSubscriptionSummaryFromDict(data) {
|
|
332
|
+
const entitlementItems = (data.entitlement_items || []).map(hyperAgentEntitlementFromDict);
|
|
333
|
+
return {
|
|
334
|
+
effectivePlanId: data.effective_plan_id || '',
|
|
335
|
+
currentSubscriptionId: data.current_subscription_id || null,
|
|
336
|
+
currentEntitlementId: data.current_entitlement_id || data.current_subscription_id || null,
|
|
337
|
+
pooledTpmLimit: data.pooled_tpm_limit || 0,
|
|
338
|
+
pooledRpmLimit: data.pooled_rpm_limit || 0,
|
|
339
|
+
pooledTpd: data.pooled_tpd || 0,
|
|
340
|
+
slotInventory: data.slot_inventory || {},
|
|
341
|
+
billingResetAt: data.billing_reset_at ? new Date(String(data.billing_reset_at).replace('Z', '+00:00')) : null,
|
|
342
|
+
activeSubscriptionCount: data.active_subscription_count || 0,
|
|
343
|
+
activeEntitlementCount: data.active_entitlement_count || data.active_subscription_count || 0,
|
|
344
|
+
entitlements: hyperAgentEntitlementsFromDict(data),
|
|
345
|
+
entitlementItems,
|
|
346
|
+
activeSubscriptions: (data.active_subscriptions || []).map(hyperAgentSubscriptionFromDict),
|
|
347
|
+
subscriptions: (data.subscriptions || []).map(hyperAgentSubscriptionFromDict),
|
|
348
|
+
user: data.user || {},
|
|
349
|
+
agentSlots: (data.agent_slots || []).map(agentSlotFromDict),
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
function hyperAgentModelFromDict(data) {
|
|
353
|
+
const caps = data.capabilities || {};
|
|
354
|
+
return {
|
|
355
|
+
id: data.id,
|
|
356
|
+
name: data.name || data.id,
|
|
357
|
+
contextLength: data.context_length || 0,
|
|
358
|
+
supportsVision: caps.supports_vision || false,
|
|
359
|
+
supportsFunctionCalling: caps.supports_function_calling || false,
|
|
360
|
+
supportsToolChoice: caps.supports_tool_choice || false,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
function dateFromDict(value) {
|
|
364
|
+
return value ? new Date(String(value).replace('Z', '+00:00')) : null;
|
|
365
|
+
}
|
|
366
|
+
function hyperAgentUsageSummaryFromDict(data) {
|
|
367
|
+
return {
|
|
368
|
+
totalTokens: Number(data?.total_tokens || 0),
|
|
369
|
+
promptTokens: Number(data?.prompt_tokens || 0),
|
|
370
|
+
completionTokens: Number(data?.completion_tokens || 0),
|
|
371
|
+
requestCount: Number(data?.request_count || 0),
|
|
372
|
+
activeKeys: Number(data?.active_keys || 0),
|
|
373
|
+
currentTpm: Number(data?.current_tpm || 0),
|
|
374
|
+
currentRpm: Number(data?.current_rpm || 0),
|
|
375
|
+
period: String(data?.period || ''),
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function hyperAgentUsageHistoryEntryFromDict(data) {
|
|
379
|
+
return {
|
|
380
|
+
date: String(data?.date || ''),
|
|
381
|
+
totalTokens: Number(data?.total_tokens || 0),
|
|
382
|
+
promptTokens: Number(data?.prompt_tokens || 0),
|
|
383
|
+
completionTokens: Number(data?.completion_tokens || 0),
|
|
384
|
+
requests: Number(data?.requests || 0),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
function hyperAgentUsageHistoryFromDict(data) {
|
|
388
|
+
return {
|
|
389
|
+
history: (data?.history || []).map(hyperAgentUsageHistoryEntryFromDict),
|
|
390
|
+
days: Number(data?.days || 0),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function hyperAgentKeyUsageEntryFromDict(data) {
|
|
394
|
+
return {
|
|
395
|
+
keyHash: String(data?.key_hash || ''),
|
|
396
|
+
name: String(data?.name || ''),
|
|
397
|
+
totalTokens: Number(data?.total_tokens || 0),
|
|
398
|
+
promptTokens: Number(data?.prompt_tokens || 0),
|
|
399
|
+
completionTokens: Number(data?.completion_tokens || 0),
|
|
400
|
+
requests: Number(data?.requests || 0),
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
function hyperAgentKeyUsageFromDict(data) {
|
|
404
|
+
return {
|
|
405
|
+
keys: (data?.keys || []).map(hyperAgentKeyUsageEntryFromDict),
|
|
406
|
+
days: Number(data?.days || 0),
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
function hyperAgentUsageMetricsFromDict(data) {
|
|
410
|
+
return {
|
|
411
|
+
totalTokens: Number(data?.total_tokens || 0),
|
|
412
|
+
promptTokens: Number(data?.prompt_tokens || 0),
|
|
413
|
+
completionTokens: Number(data?.completion_tokens || 0),
|
|
414
|
+
requests: Number(data?.requests || 0),
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
function hyperAgentAgentUsageFromDict(data) {
|
|
418
|
+
return {
|
|
419
|
+
agents: (data?.agents || []).map((entry) => ({
|
|
420
|
+
agentId: String(entry?.agent_id || ''),
|
|
421
|
+
name: String(entry?.name || ''),
|
|
422
|
+
managed: Boolean(entry?.managed),
|
|
423
|
+
avatarUrl: entry?.avatar_url || null,
|
|
424
|
+
...hyperAgentUsageMetricsFromDict(entry),
|
|
425
|
+
})),
|
|
426
|
+
unattributed: hyperAgentUsageMetricsFromDict(data?.unattributed),
|
|
427
|
+
days: Number(data?.days || 0),
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
function hyperAgentTypeCatalogFromDict(data) {
|
|
431
|
+
return {
|
|
432
|
+
types: (data?.types || []).map((item) => ({
|
|
433
|
+
id: String(item?.id || ''),
|
|
434
|
+
name: String(item?.name || ''),
|
|
435
|
+
cpu: Number(item?.cpu || 0),
|
|
436
|
+
memory: Number(item?.memory || 0),
|
|
437
|
+
})),
|
|
438
|
+
plans: (data?.plans || []).map((item) => ({
|
|
439
|
+
id: String(item?.id || ''),
|
|
440
|
+
name: String(item?.name || ''),
|
|
441
|
+
price: Number(item?.price || 0),
|
|
442
|
+
agents: Number(item?.agents || 0),
|
|
443
|
+
agentType: String(item?.agent_type || ''),
|
|
444
|
+
highlighted: Boolean(item?.highlighted),
|
|
445
|
+
})),
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
function hyperAgentBillingProfileFieldsFromDict(data) {
|
|
449
|
+
return {
|
|
450
|
+
billingName: data?.billing_name ?? null,
|
|
451
|
+
billingCompany: data?.billing_company ?? null,
|
|
452
|
+
billingTaxId: data?.billing_tax_id ?? null,
|
|
453
|
+
billingLine1: data?.billing_line1 ?? null,
|
|
454
|
+
billingLine2: data?.billing_line2 ?? null,
|
|
455
|
+
billingCity: data?.billing_city ?? null,
|
|
456
|
+
billingState: data?.billing_state ?? null,
|
|
457
|
+
billingPostalCode: data?.billing_postal_code ?? null,
|
|
458
|
+
billingCountry: data?.billing_country ?? null,
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
function hyperAgentBillingProfileFieldsToDict(data) {
|
|
462
|
+
return {
|
|
463
|
+
billing_name: data.billingName,
|
|
464
|
+
billing_company: data.billingCompany,
|
|
465
|
+
billing_tax_id: data.billingTaxId,
|
|
466
|
+
billing_line1: data.billingLine1,
|
|
467
|
+
billing_line2: data.billingLine2,
|
|
468
|
+
billing_city: data.billingCity,
|
|
469
|
+
billing_state: data.billingState,
|
|
470
|
+
billing_postal_code: data.billingPostalCode,
|
|
471
|
+
billing_country: data.billingCountry,
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
function hyperAgentBillingInfoFromDict(data) {
|
|
475
|
+
return {
|
|
476
|
+
address: Array.isArray(data?.address) ? data.address.map(String) : [],
|
|
477
|
+
email: String(data?.email || ''),
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
function hyperAgentBillingProfileResponseFromDict(data) {
|
|
481
|
+
return {
|
|
482
|
+
companyBilling: hyperAgentBillingInfoFromDict(data?.company_billing || {}),
|
|
483
|
+
profile: data?.profile ? hyperAgentBillingProfileFieldsFromDict(data.profile) : null,
|
|
484
|
+
syncedStripeCustomerIds: Array.isArray(data?.synced_stripe_customer_ids) ? data.synced_stripe_customer_ids.map(String) : undefined,
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
function hyperAgentPaymentFromDict(data) {
|
|
488
|
+
return {
|
|
489
|
+
id: String(data?.id || ''),
|
|
490
|
+
userId: String(data?.user_id || ''),
|
|
491
|
+
subscriptionId: data?.subscription_id ?? null,
|
|
492
|
+
entitlementId: data?.entitlement_id ?? null,
|
|
493
|
+
provider: String(data?.provider || ''),
|
|
494
|
+
status: String(data?.status || ''),
|
|
495
|
+
amount: String(data?.amount || ''),
|
|
496
|
+
currency: String(data?.currency || ''),
|
|
497
|
+
externalPaymentId: data?.external_payment_id ?? null,
|
|
498
|
+
createdAt: dateFromDict(data?.created_at),
|
|
499
|
+
updatedAt: dateFromDict(data?.updated_at),
|
|
500
|
+
user: data?.user ? {
|
|
501
|
+
id: String(data.user.id || ''),
|
|
502
|
+
email: data.user.email ?? null,
|
|
503
|
+
walletAddress: data.user.wallet_address ?? null,
|
|
504
|
+
teamId: data.user.team_id ?? null,
|
|
505
|
+
planId: data.user.plan_id ?? null,
|
|
506
|
+
billingName: data.user.billing_name ?? null,
|
|
507
|
+
billingCompany: data.user.billing_company ?? null,
|
|
508
|
+
billingTaxId: data.user.billing_tax_id ?? null,
|
|
509
|
+
billingLine1: data.user.billing_line1 ?? null,
|
|
510
|
+
billingLine2: data.user.billing_line2 ?? null,
|
|
511
|
+
billingCity: data.user.billing_city ?? null,
|
|
512
|
+
billingState: data.user.billing_state ?? null,
|
|
513
|
+
billingPostalCode: data.user.billing_postal_code ?? null,
|
|
514
|
+
billingCountry: data.user.billing_country ?? null,
|
|
515
|
+
} : null,
|
|
516
|
+
subscription: data?.subscription ? {
|
|
517
|
+
id: String(data.subscription.id || ''),
|
|
518
|
+
planId: String(data.subscription.plan_id || ''),
|
|
519
|
+
provider: String(data.subscription.provider || ''),
|
|
520
|
+
status: String(data.subscription.status || ''),
|
|
521
|
+
currentPeriodEnd: dateFromDict(data.subscription.current_period_end),
|
|
522
|
+
stripeSubscriptionId: data.subscription.stripe_subscription_id ?? null,
|
|
523
|
+
} : null,
|
|
524
|
+
entitlement: data?.entitlement ? {
|
|
525
|
+
id: String(data.entitlement.id || ''),
|
|
526
|
+
planId: String(data.entitlement.plan_id || ''),
|
|
527
|
+
provider: String(data.entitlement.provider || ''),
|
|
528
|
+
status: String(data.entitlement.status || ''),
|
|
529
|
+
expiresAt: dateFromDict(data.entitlement.expires_at),
|
|
530
|
+
agentTier: data.entitlement.agent_tier ?? null,
|
|
531
|
+
features: data.entitlement.features || {},
|
|
532
|
+
tags: Array.isArray(data.entitlement.tags) ? data.entitlement.tags.map(String) : [],
|
|
533
|
+
} : null,
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
function hyperAgentPaymentsResponseFromDict(data) {
|
|
537
|
+
return {
|
|
538
|
+
items: (data?.items || []).map(hyperAgentPaymentFromDict),
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
function hyperAgentGrantRedemptionResponseFromDict(data) {
|
|
542
|
+
return {
|
|
543
|
+
grant: hyperAgentGrantFromDict(data?.grant || {}),
|
|
544
|
+
entitlement: hyperAgentEntitlementFromDict(data?.entitlement || {}),
|
|
545
|
+
...(data?.payment ? { payment: hyperAgentPaymentFromDict(data.payment) } : {}),
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
function hyperAgentStripeCheckoutResponseFromDict(data) {
|
|
549
|
+
return {
|
|
550
|
+
checkoutUrl: String(data?.checkout_url || ''),
|
|
551
|
+
checkoutSessionId: data?.session_id ? String(data.session_id) : null,
|
|
552
|
+
checkoutAttemptId: data?.checkout_attempt_id ? String(data.checkout_attempt_id) : null,
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function hyperAgentStripeBillingPortalSessionResponseFromDict(data) {
|
|
556
|
+
return {
|
|
557
|
+
id: data?.id ? String(data.id) : null,
|
|
558
|
+
url: String(data?.url || ''),
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
function hyperAgentX402CheckoutResponseFromDict(data) {
|
|
562
|
+
return {
|
|
563
|
+
ok: Boolean(data?.ok),
|
|
564
|
+
key: String(data?.key || ''),
|
|
565
|
+
planId: String(data?.plan_id || ''),
|
|
566
|
+
quantity: Number(data?.quantity || 0),
|
|
567
|
+
bundle: data?.bundle || {},
|
|
568
|
+
amountPaid: String(data?.amount_paid || ''),
|
|
569
|
+
durationDays: Number(data?.duration_days || 0),
|
|
570
|
+
expiresAt: dateFromDict(data?.expires_at),
|
|
571
|
+
tpmLimit: Number(data?.tpm_limit || 0),
|
|
572
|
+
rpmLimit: Number(data?.rpm_limit || 0),
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* HyperAgent API Client
|
|
577
|
+
*
|
|
578
|
+
* For chat completions, use the OpenAI Node.js SDK directly:
|
|
579
|
+
*
|
|
580
|
+
* ```typescript
|
|
581
|
+
* import OpenAI from 'openai';
|
|
582
|
+
*
|
|
583
|
+
* const openai = new OpenAI({
|
|
584
|
+
* apiKey: client.agent.apiKey,
|
|
585
|
+
* baseURL: client.agent.baseUrl,
|
|
586
|
+
* });
|
|
587
|
+
* ```
|
|
588
|
+
*/
|
|
589
|
+
export class HyperAgent {
|
|
590
|
+
static AGENT_API_BASE = 'https://api.hypercli.com/v1';
|
|
591
|
+
static DEV_API_BASE = 'https://api.dev.hypercli.com/v1';
|
|
592
|
+
apiKey;
|
|
593
|
+
baseUrl;
|
|
594
|
+
controlBaseUrl;
|
|
595
|
+
constructor(http, agentApiKey, dev = false, agentsApiBaseUrl) {
|
|
596
|
+
this.apiKey = agentApiKey || http['apiKey'];
|
|
597
|
+
const productBaseUrl = typeof http['baseUrl'] === 'string' ? http['baseUrl'] : getApiUrl();
|
|
598
|
+
const configuredBaseUrl = agentsApiBaseUrl || getAgentsApiBaseUrl(dev, productBaseUrl);
|
|
599
|
+
this.baseUrl = resolveHyperAgentBaseUrl(productBaseUrl);
|
|
600
|
+
this.controlBaseUrl = resolveHyperAgentControlBaseUrl(http['baseUrl'], configuredBaseUrl, dev);
|
|
601
|
+
}
|
|
602
|
+
get baseUrlWithoutV1() {
|
|
603
|
+
return this.baseUrl.replace(/\/v1$/, '');
|
|
604
|
+
}
|
|
605
|
+
async controlGet(path, params) {
|
|
606
|
+
const url = new URL(`${this.controlBaseUrl}${path}`);
|
|
607
|
+
if (params) {
|
|
608
|
+
for (const [key, value] of Object.entries(params)) {
|
|
609
|
+
if (value !== undefined && value !== null) {
|
|
610
|
+
url.searchParams.set(key, String(value));
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
const response = await fetch(url.toString(), {
|
|
615
|
+
headers: {
|
|
616
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
617
|
+
},
|
|
618
|
+
});
|
|
619
|
+
if (!response.ok) {
|
|
620
|
+
throw new Error(`Failed to GET ${path}: ${response.statusText}`);
|
|
621
|
+
}
|
|
622
|
+
return response.json();
|
|
623
|
+
}
|
|
624
|
+
async controlPost(path, body) {
|
|
625
|
+
const url = `${this.controlBaseUrl}${path}`;
|
|
626
|
+
const response = await fetch(url, {
|
|
627
|
+
method: 'POST',
|
|
628
|
+
headers: {
|
|
629
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
630
|
+
'Content-Type': 'application/json',
|
|
631
|
+
},
|
|
632
|
+
body: JSON.stringify(body ?? {}),
|
|
633
|
+
});
|
|
634
|
+
if (!response.ok) {
|
|
635
|
+
throw await responseAPIError(response, 'POST', url);
|
|
636
|
+
}
|
|
637
|
+
return response.json();
|
|
638
|
+
}
|
|
639
|
+
async controlPut(path, body) {
|
|
640
|
+
const response = await fetch(`${this.controlBaseUrl}${path}`, {
|
|
641
|
+
method: 'PUT',
|
|
642
|
+
headers: {
|
|
643
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
644
|
+
'Content-Type': 'application/json',
|
|
645
|
+
},
|
|
646
|
+
body: JSON.stringify(body ?? {}),
|
|
647
|
+
});
|
|
648
|
+
if (!response.ok) {
|
|
649
|
+
throw new Error(`Failed to PUT ${path}: ${response.statusText}`);
|
|
650
|
+
}
|
|
651
|
+
return response.json();
|
|
652
|
+
}
|
|
653
|
+
async plans() {
|
|
654
|
+
const response = await fetch(`${this.controlBaseUrl}/plans`, {
|
|
655
|
+
headers: {
|
|
656
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
657
|
+
},
|
|
658
|
+
});
|
|
659
|
+
if (!response.ok) {
|
|
660
|
+
throw new Error(`Failed to get plans: ${response.statusText}`);
|
|
661
|
+
}
|
|
662
|
+
const data = await response.json();
|
|
663
|
+
return (data.plans || []).map(hyperAgentPlanFromDict);
|
|
664
|
+
}
|
|
665
|
+
async currentPlan() {
|
|
666
|
+
const response = await fetch(`${this.controlBaseUrl}/plans/current`, {
|
|
667
|
+
headers: {
|
|
668
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
669
|
+
},
|
|
670
|
+
});
|
|
671
|
+
if (!response.ok) {
|
|
672
|
+
throw new Error(`Failed to get current plan: ${response.statusText}`);
|
|
673
|
+
}
|
|
674
|
+
const data = await response.json();
|
|
675
|
+
return hyperAgentCurrentPlanFromDict(data);
|
|
676
|
+
}
|
|
677
|
+
async subscriptions() {
|
|
678
|
+
const response = await fetch(`${this.controlBaseUrl}/subscriptions`, {
|
|
679
|
+
headers: {
|
|
680
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
681
|
+
},
|
|
682
|
+
});
|
|
683
|
+
if (!response.ok) {
|
|
684
|
+
throw new Error(`Failed to get subscriptions: ${response.statusText}`);
|
|
685
|
+
}
|
|
686
|
+
const data = await response.json();
|
|
687
|
+
return (data.items || []).map(hyperAgentSubscriptionFromDict);
|
|
688
|
+
}
|
|
689
|
+
async subscriptionSummary() {
|
|
690
|
+
const response = await fetch(`${this.controlBaseUrl}/subscriptions/summary`, {
|
|
691
|
+
headers: {
|
|
692
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
693
|
+
},
|
|
694
|
+
});
|
|
695
|
+
if (!response.ok) {
|
|
696
|
+
throw new Error(`Failed to get subscription summary: ${response.statusText}`);
|
|
697
|
+
}
|
|
698
|
+
const data = await response.json();
|
|
699
|
+
return hyperAgentSubscriptionSummaryFromDict(data);
|
|
700
|
+
}
|
|
701
|
+
async entitlements() {
|
|
702
|
+
const response = await fetch(`${this.controlBaseUrl}/entitlements`, {
|
|
703
|
+
headers: {
|
|
704
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
705
|
+
},
|
|
706
|
+
});
|
|
707
|
+
if (!response.ok) {
|
|
708
|
+
throw new Error(`Failed to get entitlements: ${response.statusText}`);
|
|
709
|
+
}
|
|
710
|
+
const data = await response.json();
|
|
711
|
+
return hyperAgentSubscriptionSummaryFromDict(data);
|
|
712
|
+
}
|
|
713
|
+
async cancelSubscription(subscriptionId) {
|
|
714
|
+
const response = await fetch(`${this.controlBaseUrl}/subscriptions/${subscriptionId}/cancel`, {
|
|
715
|
+
method: 'POST',
|
|
716
|
+
headers: {
|
|
717
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
718
|
+
},
|
|
719
|
+
});
|
|
720
|
+
if (!response.ok) {
|
|
721
|
+
throw new Error(`Failed to get entitlements: ${response.statusText}`);
|
|
722
|
+
}
|
|
723
|
+
const data = await response.json();
|
|
724
|
+
return {
|
|
725
|
+
ok: Boolean(data.ok),
|
|
726
|
+
message: data.message || '',
|
|
727
|
+
subscription: data.subscription ? hyperAgentSubscriptionFromDict(data.subscription) : undefined,
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
async updateSubscription(subscriptionId, request) {
|
|
731
|
+
const normalizedSubscriptionId = subscriptionId.trim();
|
|
732
|
+
const planId = request.planId.trim();
|
|
733
|
+
const quantity = request.quantity ?? 1;
|
|
734
|
+
if (!normalizedSubscriptionId) {
|
|
735
|
+
throw new Error('subscriptionId is required');
|
|
736
|
+
}
|
|
737
|
+
if (!planId) {
|
|
738
|
+
throw new Error('planId is required');
|
|
739
|
+
}
|
|
740
|
+
if (!Number.isInteger(quantity) || quantity < 1) {
|
|
741
|
+
throw new Error('quantity must be a positive integer');
|
|
742
|
+
}
|
|
743
|
+
const response = await fetch(`${this.controlBaseUrl}/subscriptions/${encodeURIComponent(normalizedSubscriptionId)}/update`, {
|
|
744
|
+
method: 'POST',
|
|
745
|
+
headers: {
|
|
746
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
747
|
+
'Content-Type': 'application/json',
|
|
748
|
+
},
|
|
749
|
+
body: JSON.stringify({
|
|
750
|
+
plan_id: planId,
|
|
751
|
+
quantity,
|
|
752
|
+
}),
|
|
753
|
+
});
|
|
754
|
+
if (!response.ok) {
|
|
755
|
+
throw new Error(`Failed to update subscription: ${response.statusText}`);
|
|
756
|
+
}
|
|
757
|
+
const data = await response.json();
|
|
758
|
+
return {
|
|
759
|
+
ok: Boolean(data.ok),
|
|
760
|
+
message: data.message || '',
|
|
761
|
+
subscription: data.subscription ? hyperAgentSubscriptionFromDict(data.subscription) : undefined,
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
async models() {
|
|
765
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
766
|
+
headers: {
|
|
767
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
768
|
+
},
|
|
769
|
+
});
|
|
770
|
+
if (!response.ok) {
|
|
771
|
+
throw new Error(`Failed to get models: ${response.statusText}`);
|
|
772
|
+
}
|
|
773
|
+
const data = await response.json();
|
|
774
|
+
return (data.data || []).map((model) => hyperAgentModelFromDict({
|
|
775
|
+
id: model.id,
|
|
776
|
+
name: model.name || model.id,
|
|
777
|
+
context_length: model.context_length || 0,
|
|
778
|
+
capabilities: model.capabilities || {},
|
|
779
|
+
}));
|
|
780
|
+
}
|
|
781
|
+
async discoveryHealth() {
|
|
782
|
+
const response = await fetch(`${this.baseUrlWithoutV1}/discovery/health`);
|
|
783
|
+
if (!response.ok) {
|
|
784
|
+
throw new Error(`Failed to get discovery health: ${response.statusText}`);
|
|
785
|
+
}
|
|
786
|
+
return (await response.json());
|
|
787
|
+
}
|
|
788
|
+
async discoveryConfig(apiKey) {
|
|
789
|
+
const headers = {};
|
|
790
|
+
if (apiKey) {
|
|
791
|
+
headers['X-API-KEY'] = apiKey;
|
|
792
|
+
}
|
|
793
|
+
const response = await fetch(`${this.baseUrlWithoutV1}/discovery/config`, {
|
|
794
|
+
headers,
|
|
795
|
+
});
|
|
796
|
+
if (!response.ok) {
|
|
797
|
+
throw new Error(`Failed to get discovery config: ${response.statusText}`);
|
|
798
|
+
}
|
|
799
|
+
return await response.json();
|
|
800
|
+
}
|
|
801
|
+
async usageSummary() {
|
|
802
|
+
return hyperAgentUsageSummaryFromDict(await this.controlGet('/usage'));
|
|
803
|
+
}
|
|
804
|
+
async usageHistory(days = 7) {
|
|
805
|
+
return hyperAgentUsageHistoryFromDict(await this.controlGet('/usage/history', { days }));
|
|
806
|
+
}
|
|
807
|
+
async keyUsage(days = 7) {
|
|
808
|
+
return hyperAgentKeyUsageFromDict(await this.controlGet('/usage/keys', { days }));
|
|
809
|
+
}
|
|
810
|
+
async agentUsage(days = 1) {
|
|
811
|
+
return hyperAgentAgentUsageFromDict(await this.controlGet('/usage/agents', { days }));
|
|
812
|
+
}
|
|
813
|
+
async usageReport(days = 7) {
|
|
814
|
+
const clamped = Math.min(Math.max(Math.trunc(days) || 7, 1), 90);
|
|
815
|
+
const attempt = (promise) => promise.catch(() => null);
|
|
816
|
+
const [history, keys, agents] = await Promise.all([
|
|
817
|
+
attempt(this.usageHistory(clamped)),
|
|
818
|
+
attempt(this.keyUsage(clamped)),
|
|
819
|
+
attempt(this.agentUsage(clamped)),
|
|
820
|
+
]);
|
|
821
|
+
return {
|
|
822
|
+
days: clamped,
|
|
823
|
+
history: history?.history ?? null,
|
|
824
|
+
keys: keys?.keys ?? null,
|
|
825
|
+
agents: agents?.agents ?? null,
|
|
826
|
+
unattributed: agents?.unattributed ?? null,
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
async agentTypes() {
|
|
830
|
+
return hyperAgentTypeCatalogFromDict(await this.controlGet('/types'));
|
|
831
|
+
}
|
|
832
|
+
async billingInfo() {
|
|
833
|
+
const data = await this.controlGet('/billing/info');
|
|
834
|
+
return hyperAgentBillingInfoFromDict(data?.company_billing || {});
|
|
835
|
+
}
|
|
836
|
+
async billingProfile() {
|
|
837
|
+
return hyperAgentBillingProfileResponseFromDict(await this.controlGet('/billing/profile'));
|
|
838
|
+
}
|
|
839
|
+
async updateBillingProfile(profile) {
|
|
840
|
+
return hyperAgentBillingProfileResponseFromDict(await this.controlPut('/billing/profile', hyperAgentBillingProfileFieldsToDict(profile)));
|
|
841
|
+
}
|
|
842
|
+
async payments(options = {}) {
|
|
843
|
+
const params = {};
|
|
844
|
+
if (options.limit !== undefined)
|
|
845
|
+
params.limit = options.limit;
|
|
846
|
+
if (options.provider)
|
|
847
|
+
params.provider = options.provider;
|
|
848
|
+
if (options.status)
|
|
849
|
+
params.status = options.status;
|
|
850
|
+
return hyperAgentPaymentsResponseFromDict(await this.controlGet('/billing/payments', params));
|
|
851
|
+
}
|
|
852
|
+
async payment(paymentId) {
|
|
853
|
+
return hyperAgentPaymentFromDict(await this.controlGet(`/billing/payments/${encodeURIComponent(paymentId)}`));
|
|
854
|
+
}
|
|
855
|
+
async billingHistory() {
|
|
856
|
+
const [subscriptions, payments] = await Promise.all([
|
|
857
|
+
this.subscriptions(),
|
|
858
|
+
this.payments({ limit: 1 }),
|
|
859
|
+
]);
|
|
860
|
+
const subscriptionCount = subscriptions.length;
|
|
861
|
+
const paymentCount = payments.items.length;
|
|
862
|
+
return {
|
|
863
|
+
hasBillingHistory: subscriptionCount > 0 || paymentCount > 0,
|
|
864
|
+
subscriptionCount,
|
|
865
|
+
paymentCount,
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
async purchaseEntitlementFromBalance(planId, request) {
|
|
869
|
+
return hyperAgentGrantRedemptionResponseFromDict(await this.controlPost(`/billing/balance/${encodeURIComponent(planId)}`, {
|
|
870
|
+
duration: request.duration,
|
|
871
|
+
...(request.tags ? { tags: request.tags } : {}),
|
|
872
|
+
...(request.extendExisting !== undefined ? { extend_existing: Boolean(request.extendExisting) } : {}),
|
|
873
|
+
}));
|
|
874
|
+
}
|
|
875
|
+
async redeemGrantCode(code, request = {}) {
|
|
876
|
+
return hyperAgentGrantRedemptionResponseFromDict(await this.controlPost('/billing/grants/redeem', {
|
|
877
|
+
code,
|
|
878
|
+
...(request.extendExisting !== undefined ? { extend_existing: Boolean(request.extendExisting) } : {}),
|
|
879
|
+
}));
|
|
880
|
+
}
|
|
881
|
+
async createStripeCheckout(request = {}, planId) {
|
|
882
|
+
if (request.bundle != null) {
|
|
883
|
+
throw new Error('Arbitrary slot bundles are no longer supported; purchase a canonical plan');
|
|
884
|
+
}
|
|
885
|
+
const payload = {
|
|
886
|
+
...(request.successUrl ? { success_url: request.successUrl } : {}),
|
|
887
|
+
...(request.cancelUrl ? { cancel_url: request.cancelUrl } : {}),
|
|
888
|
+
...(request.quantity !== undefined ? { quantity: request.quantity } : {}),
|
|
889
|
+
};
|
|
890
|
+
const path = planId ? `/stripe/${encodeURIComponent(planId)}` : '/stripe/checkout';
|
|
891
|
+
return hyperAgentStripeCheckoutResponseFromDict(await this.controlPost(path, payload));
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Create the account's one-time Team trial checkout.
|
|
895
|
+
*
|
|
896
|
+
* Maps to `POST {agentsBase}/stripe/trial` and returns a Stripe `checkout_url`.
|
|
897
|
+
*/
|
|
898
|
+
async createStripeTrialCheckout(options = {}) {
|
|
899
|
+
return hyperAgentStripeCheckoutResponseFromDict(await this.controlPost('/stripe/trial', {
|
|
900
|
+
...(options.successUrl !== undefined ? { success_url: options.successUrl } : {}),
|
|
901
|
+
...(options.cancelUrl !== undefined ? { cancel_url: options.cancelUrl } : {}),
|
|
902
|
+
}));
|
|
903
|
+
}
|
|
904
|
+
async createStripeBillingPortalSession(request) {
|
|
905
|
+
return hyperAgentStripeBillingPortalSessionResponseFromDict(await this.controlPost('/stripe/billing-portal', {
|
|
906
|
+
return_url: request.returnUrl,
|
|
907
|
+
flow_data: { type: request.flowType },
|
|
908
|
+
}));
|
|
909
|
+
}
|
|
910
|
+
async purchaseViaX402(planId, request = {}) {
|
|
911
|
+
if (request.bundle != null) {
|
|
912
|
+
throw new Error('Arbitrary slot bundles are no longer supported; purchase a canonical plan');
|
|
913
|
+
}
|
|
914
|
+
const payload = {
|
|
915
|
+
...(request.quantity !== undefined ? { quantity: request.quantity } : {}),
|
|
916
|
+
};
|
|
917
|
+
return hyperAgentX402CheckoutResponseFromDict(await this.controlPost(`/x402/${encodeURIComponent(planId)}`, payload));
|
|
918
|
+
}
|
|
919
|
+
async purchaseBundleViaX402(_request = {}) {
|
|
920
|
+
throw new Error('Arbitrary slot bundles are no longer supported; purchase a solo, team, or pro plan');
|
|
921
|
+
}
|
|
922
|
+
async createX402Checkout(_request = {}) {
|
|
923
|
+
throw new Error('A canonical plan ID is required; use purchaseViaX402(planId, request)');
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
//# sourceMappingURL=agent.js.map
|