-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
191 lines (170 loc) · 5.67 KB
/
api.js
File metadata and controls
191 lines (170 loc) · 5.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/**
* API client for EmbiPay agent endpoints.
* Uses public API routes only. Never accesses internal DB.
* All authenticated requests use Authorization: Bearer <agent_key>
*/
import { logger } from './logger.js'
/**
* @param {string} baseUrl
* @param {string} agentApiKey
* @param {string} path - e.g. '/api/agent/tasks'
* @param {'GET'|'POST'|'PATCH'} method
* @param {Record<string, unknown>|null} body
* @returns {Promise<{ ok: boolean, status: number, data: unknown }>}
*/
export async function apiRequest(baseUrl, agentApiKey, path, method, body = null) {
const url = `${baseUrl}${path}`
const headers = {
'Content-Type': 'application/json',
...(agentApiKey ? { Authorization: `Bearer ${agentApiKey}` } : {}),
}
const options = { method, headers }
if (body && (method === 'POST' || method === 'PATCH')) {
options.body = JSON.stringify(body)
}
const response = await fetch(url, options)
let data
try {
data = await response.json()
} catch {
data = { error: 'Invalid JSON response' }
}
return {
ok: response.ok,
status: response.status,
data,
}
}
/**
* Registers a new agent. No auth required.
* @param {string} baseUrl
* @returns {Promise<{ agent_id: number, agent_key: string, wallet: object }>}
*/
export async function registerAgent(baseUrl) {
const { ok, status, data } = await apiRequest(baseUrl, '', '/api/agent/register', 'POST', {
name: process.env.AGENT_NAME || 'ReferenceAgent',
description: 'Canonical EmbiPay reference integration',
})
if (!ok) {
throw new Error(`Registration failed: ${status} ${JSON.stringify(data)}`)
}
return data
}
/**
* Fetches tasks assigned to the agent.
* @param {string} baseUrl
* @param {string} agentApiKey
* @returns {Promise<Array<{ id: number, task_type: string, payload: object, status: string }>>}
*/
export async function fetchTasks(baseUrl, agentApiKey) {
const { ok, status, data } = await apiRequest(baseUrl, agentApiKey, '/api/agent/tasks', 'GET')
if (!ok) {
if (status === 401) throw new Error('Unauthorized: invalid or expired API key')
if (status === 403) throw new Error(`Forbidden: ${data?.error || 'agent paused or frozen'}`)
throw new Error(`Fetch tasks failed: ${status}`)
}
return data.tasks || []
}
/**
* Updates task status. Supports processing, completed, failed.
* @param {string} baseUrl
* @param {string} agentApiKey
* @param {number} taskId
* @param {'processing'|'completed'|'failed'} status
* @param {string} [failureReason] - required when status is 'failed'
* @returns {Promise<object>}
*/
export async function updateTask(baseUrl, agentApiKey, taskId, status, failureReason = undefined) {
const body = { status }
if (status === 'failed' && failureReason) {
body.failure_reason = String(failureReason).slice(0, 2000)
}
const { ok, status: httpStatus, data } = await apiRequest(
baseUrl,
agentApiKey,
`/api/agent/tasks/${taskId}`,
'PATCH',
body
)
if (!ok) {
if (httpStatus === 401) throw new Error('Unauthorized: invalid or expired API key')
if (httpStatus === 403) throw new Error(`Forbidden: ${data?.error || 'agent paused or frozen'}`)
if (httpStatus === 404) throw new Error(`Task not found: ${taskId}`)
throw new Error(`Update task failed: ${httpStatus} ${JSON.stringify(data)}`)
}
return data.task
}
/**
* Fetches agent wallet. May return 404 if endpoint is not yet available.
* @param {string} baseUrl
* @param {string} agentApiKey
* @returns {Promise<{ balance: number, wallet_frozen?: boolean, is_paused?: boolean }|null>}
*/
export async function fetchWallet(baseUrl, agentApiKey) {
const { ok, status, data } = await apiRequest(baseUrl, agentApiKey, '/api/agent/wallet', 'GET')
if (status === 404) {
logger.info('Wallet endpoint not available (404) — balance check skipped')
return null
}
if (!ok) {
logger.warn('Wallet fetch failed', { status })
return null
}
return data
}
/**
* Lists available pools. May return 404 if endpoint is not yet available.
* @param {string} baseUrl
* @param {string} agentApiKey
* @returns {Promise<Array<object>|null>}
*/
export async function fetchPools(baseUrl, agentApiKey) {
const { ok, status, data } = await apiRequest(baseUrl, agentApiKey, '/api/agent/pools', 'GET')
if (status === 404) {
return null
}
if (!ok || status === 400) {
logger.warn('Pools fetch failed or empty', { status })
return null
}
return Array.isArray(data.pools) ? data.pools : (data.pools ? [data.pools] : [])
}
/**
* Contributes to a pool. Call only when budget allows and pool is active.
* @param {string} baseUrl
* @param {string} agentApiKey
* @param {number} poolId
* @param {number} amount
* @returns {Promise<{ success: boolean }|null>}
*/
export async function contributeToPool(baseUrl, agentApiKey, poolId, amount) {
const { ok, status, data } = await apiRequest(baseUrl, agentApiKey, '/api/agent/pools/contribute', 'POST', {
pool_id: poolId,
amount,
})
if (status === 404 || status === 400) {
return null
}
if (!ok) return null
return data
}
/**
* Requests a loan. Call only when config allows and task explicitly permits.
* Never auto-borrow repeatedly.
* @param {string} baseUrl
* @param {string} agentApiKey
* @param {number} amount
* @param {string} [reason]
* @returns {Promise<{ success: boolean, loan_id?: number }|null>}
*/
export async function requestLoan(baseUrl, agentApiKey, amount, reason = undefined) {
const { ok, status, data } = await apiRequest(baseUrl, agentApiKey, '/api/agent/request-loan', 'POST', {
amount,
reason: reason || 'Reference agent loan request',
})
if (status === 404 || status === 400) {
return null
}
if (!ok) return null
return data
}