-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathorchestrator.js
More file actions
566 lines (510 loc) · 17 KB
/
Copy pathorchestrator.js
File metadata and controls
566 lines (510 loc) · 17 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import { config } from '../config.js'
import { AGENTS, getAgentById } from './registry.js'
import {
runResearch,
runSummary,
runAnalysis,
runCode,
createAnthropicMessage,
} from './services.js'
import { getBalance, sendPayment } from '../stellar/wallet.js'
import { logger } from '../logger.js'
import { x402Client, x402HTTPClient, wrapFetchWithPayment } from '@x402/fetch'
import { ExactStellarScheme, createEd25519Signer } from '@x402/stellar'
import { parseSettlementHeader, extractTxHash } from './settlement-header.js'
import {
agentCost,
exceedsBudget,
buildSkipResult,
buildBudgetLimitEvent,
paymentBucket,
paymentProtocolSummary,
isBudgetExhausted,
countUsed,
countSkipped,
} from './budget.js'
// const anthropic = ... (imported from services.js)
const SERVICE_MAP = {
'research-bot': runResearch,
'summary-bot': runSummary,
'analyst-bot': runAnalysis,
'code-bot': runCode,
}
const PREMIUM_ENDPOINT_MAP = {
'research-bot': (input) => `/api/premium/research?topic=${encodeURIComponent(input)}`,
'summary-bot': (input) => `/api/premium/summarize?text=${encodeURIComponent(input)}`,
'analyst-bot': (input) => `/api/premium/analyze?topic=${encodeURIComponent(input)}`,
'code-bot': (input) => `/api/premium/code?prompt=${encodeURIComponent(input)}`,
}
const EXPLORER_NETWORK_SEGMENT = config.network.includes('testnet') ? 'testnet' : 'public'
const EXPLORER_BASE_URL = `https://stellar.expert/explorer/${EXPLORER_NETWORK_SEGMENT}/tx/`
let x402Fetch = null
let x402InitError = null
let x402WalletReady = null
let x402WalletHint = null
if (config.orchestratorSecret) {
try {
const signer = createEd25519Signer(config.orchestratorSecret, config.network)
const rpcConfig = config.stellarRpcUrl ? { url: config.stellarRpcUrl } : undefined
const stellarClientScheme = new ExactStellarScheme(signer, rpcConfig)
const client = x402Client.fromConfig({
schemes: [{ network: config.network, client: stellarClientScheme }],
})
const httpClient = new x402HTTPClient(client)
x402Fetch = wrapFetchWithPayment(fetch, httpClient)
logger.info('x402_client_configured')
} catch (err) {
x402InitError = err?.message || 'unknown x402 client init error'
logger.warn('x402_client_init_failed', { error: x402InitError })
}
} else {
x402InitError = 'ORCHESTRATOR_STELLAR_SECRET is not configured'
logger.warn('x402_client_disabled', { reason: x402InitError })
}
async function checkX402WalletReadiness() {
if (!config.orchestratorAddress) {
x402WalletReady = false
x402WalletHint = 'ORCHESTRATOR_STELLAR_ADDRESS is not configured'
logger.warn('x402_wallet_not_ready', { reason: x402WalletHint })
return
}
try {
const balances = await getBalance(config.orchestratorAddress)
const usdcBalance = balances.find((balance) => balance.asset === 'USDC')
const usdcAmount = Number.parseFloat(usdcBalance?.balance || '0')
if (!usdcBalance) {
x402WalletReady = false
x402WalletHint = 'No USDC trustline on orchestrator wallet. Run: npm run setup:usdc'
logger.warn('x402_wallet_not_ready', { reason: x402WalletHint })
return
}
if (!Number.isFinite(usdcAmount) || usdcAmount <= 0) {
x402WalletReady = false
x402WalletHint = 'USDC balance is 0. Fund testnet USDC via https://faucet.circle.com'
logger.warn('x402_wallet_not_ready', { reason: x402WalletHint })
return
}
x402WalletReady = true
x402WalletHint = null
logger.info('x402_wallet_ready', { usdcBalance: usdcBalance.balance })
} catch (err) {
x402WalletReady = false
x402WalletHint = `Unable to verify x402 wallet readiness: ${summarizeError(err)}`
logger.warn('x402_wallet_not_ready', { reason: x402WalletHint })
}
}
if (x402Fetch) {
checkX402WalletReadiness().catch((err) => {
x402WalletReady = false
x402WalletHint = `Wallet readiness check failed: ${summarizeError(err)}`
logger.warn('x402_wallet_not_ready', { reason: x402WalletHint })
})
}
function summarizeError(err) {
return (err?.message || 'unknown error').substring(0, 180)
}
function buildExplorerUrl(txHash) {
return txHash ? `${EXPLORER_BASE_URL}${txHash}` : null
}
async function parseResponseBody(response) {
const contentType = response.headers.get('content-type') || ''
if (contentType.includes('application/json')) return response.json()
const text = await response.text()
try {
return JSON.parse(text)
} catch {
return { result: text }
}
}
async function callAgentViaX402(agent, input, broadcastFn, context = {}) {
const baseUrl = config.internalBaseUrl
const endpointFn = PREMIUM_ENDPOINT_MAP[agent.id]
if (x402Fetch && endpointFn) {
try {
const url = `${baseUrl}${endpointFn(input)}`
logger.info('x402_request_start', {
correlationId: context.correlationId,
agentId: agent.id,
paymentMethod: 'x402',
endpoint: url,
})
const response = await x402Fetch(url)
const data = await parseResponseBody(response)
if (response.ok) {
const settle = parseSettlementHeader(response)
const txHash = extractTxHash(settle)
const settlementFailed =
settle?.success === false || Boolean(settle?.error || settle?.errorReason)
if (settlementFailed) {
const reason = settle?.errorReason || settle?.error || 'x402 settlement failed'
broadcastFn?.({
type: 'x402_retry',
agent: agent.name,
agentId: agent.id,
reason,
fallback: true,
timestamp: new Date().toISOString(),
})
logger.warn('x402_settlement_reported_failure', {
correlationId: context.correlationId,
agentId: agent.id,
paymentMethod: 'x402',
reason,
})
} else {
const verification = txHash ? 'verified' : 'unverified'
broadcastFn?.({
type: 'x402_payment',
agent: agent.name,
agentId: agent.id,
flow: '402 -> sign -> settle -> 200',
protocol: 'x402',
amount: agent.price,
currency: agent.currency,
verification,
txHash: txHash || null,
explorerUrl: buildExplorerUrl(txHash),
timestamp: new Date().toISOString(),
})
}
return {
result: data.result || JSON.stringify(data),
paymentMethod: 'x402',
paymentSuccess: !settlementFailed,
paidVia: !settlementFailed ? 'x402' : 'none',
txHash: !settlementFailed ? txHash || null : null,
explorerUrl: !settlementFailed ? buildExplorerUrl(txHash) : null,
warning:
!settlementFailed && !txHash
? 'x402 settlement completed without transaction hash header'
: undefined,
}
}
const responseExcerpt =
typeof data === 'string' ? data.substring(0, 120) : JSON.stringify(data).substring(0, 120)
const reason = `x402 endpoint returned ${response.status}: ${responseExcerpt}`
broadcastFn?.({
type: 'x402_retry',
agent: agent.name,
agentId: agent.id,
reason,
fallback: true,
timestamp: new Date().toISOString(),
})
logger.warn('x402_request_failed_status', {
correlationId: context.correlationId,
agentId: agent.id,
paymentMethod: 'x402',
reason,
})
} catch (err) {
const reason = summarizeError(err)
broadcastFn?.({
type: 'x402_retry',
agent: agent.name,
agentId: agent.id,
reason,
fallback: true,
timestamp: new Date().toISOString(),
})
logger.warn('x402_flow_failed_falling_back', {
correlationId: context.correlationId,
agentId: agent.id,
paymentMethod: 'x402',
reason,
})
}
}
const serviceFn = SERVICE_MAP[agent.id]
let result
try {
result = await serviceFn(input, {
onRetryAttempt: (retry) => {
broadcastFn?.({
type: 'anthropic_retry',
agent: agent.name,
agentId: agent.id,
attempt: retry.attempt,
maxRetries: retry.maxRetries,
delayMs: retry.delayMs,
status: retry.status,
error: retry.error,
timestamp: new Date().toISOString(),
})
},
})
} catch (err) {
result = `Error: ${err.message}`
}
let paymentResult = { success: false, txHash: null }
if (config.orchestratorSecret && config.serverAddress) {
try {
paymentResult = await sendPayment(
config.orchestratorSecret,
config.serverAddress,
parseFloat(agent.price).toFixed(2),
`pay:${agent.id}`
)
} catch (err) {
logger.error('xlm_fallback_payment_failed', {
correlationId: context.correlationId,
agentId: agent.id,
paymentMethod: 'stellar-xlm-direct',
error: err.message,
})
}
}
const txHash = paymentResult.txHash || null
return {
result,
paymentMethod: paymentResult.success ? 'stellar-xlm' : 'none',
paymentSuccess: paymentResult.success,
paidVia: paymentResult.success ? 'stellar-xlm-direct' : 'none',
txHash,
explorerUrl: paymentResult.explorerUrl || buildExplorerUrl(txHash),
}
}
export async function orchestrate(task, budget, broadcastFn, context = {}) {
const startTime = Date.now()
const results = []
const payments = []
let totalSpent = 0
let x402PaymentCount = 0
let xlmFallbackCount = 0
let unpaidCount = 0
let accumulatedContext = ''
broadcastFn?.({
type: 'orchestrator_start',
task,
budget,
x402Configured: !!x402Fetch,
x402InitError,
x402WalletReady,
x402WalletHint,
paymentFlow: x402Fetch ? 'x402-http402' : 'stellar-xlm-fallback',
timestamp: new Date().toISOString(),
})
const agentList = AGENTS.map(
(a) => `- ${a.id}: ${a.capability} (cost: ${a.price} ${a.currency})`
).join('\n')
let plan
try {
const planResponse = await createAnthropicMessage(
{
model: 'claude-haiku-4-5-20251001',
max_tokens: 400,
messages: [
{
role: 'user',
content: `You are a task orchestrator for an AI agent marketplace. Break this task into 2-3 subtasks and choose which agents to use.
Available agents:
${agentList}
Task: "${task}"
Budget: ${budget} USDC
IMPORTANT: Only select agents whose total cost fits within the budget of ${budget} USDC.
Respond ONLY with valid JSON (no markdown, no code fences):
{
"plan": "brief description of your approach",
"subtasks": [
{"agentId": "agent-id-here", "input": "what to send to the agent", "cost": "0.01"}
]
}`,
},
],
},
{
onRetryAttempt: (retry) => {
broadcastFn?.({
type: 'anthropic_retry',
phase: 'planning',
attempt: retry.attempt,
maxRetries: retry.maxRetries,
delayMs: retry.delayMs,
status: retry.status,
error: retry.error,
timestamp: new Date().toISOString(),
})
},
}
)
const planText = planResponse.content[0].type === 'text' ? planResponse.content[0].text : '{}'
const cleanJson = planText
.replace(/```json\n?/g, '')
.replace(/```\n?/g, '')
.trim()
plan = JSON.parse(cleanJson)
} catch (err) {
logger.warn('orchestrator_planning_fallback', {
correlationId: context.correlationId,
error: err.message?.substring(0, 120),
})
const subtasks = []
let remaining = budget
if (remaining >= 0.01) {
subtasks.push({ agentId: 'research-bot', input: task, cost: '0.01' })
remaining -= 0.01
}
if (remaining >= 0.01) {
subtasks.push({
agentId: 'summary-bot',
input: `Summarize findings about: ${task}`,
cost: '0.01',
})
remaining -= 0.01
}
if (remaining >= 0.05) {
subtasks.push({ agentId: 'analyst-bot', input: task, cost: '0.05' })
remaining -= 0.05
}
if (remaining >= 0.03) {
subtasks.push({
agentId: 'code-bot',
input: `Write an implementation related to: ${task}`,
cost: '0.03',
})
remaining -= 0.03
}
plan = {
plan: `Multi-agent workflow: ${subtasks.map((s) => s.agentId).join(' → ')} (${subtasks.length} agents, ${budget} USDC budget)`,
subtasks,
}
}
broadcastFn?.({
type: 'orchestrator_plan',
plan: plan.plan,
subtaskCount: plan.subtasks?.length || 0,
timestamp: new Date().toISOString(),
})
for (const subtask of plan.subtasks || []) {
const agent = getAgentById(subtask.agentId)
if (!agent) {
results.push({ agentId: subtask.agentId, error: 'Agent not found' })
continue
}
const cost = agentCost(agent)
if (exceedsBudget(totalSpent, cost, budget)) {
broadcastFn?.({
...buildBudgetLimitEvent(agent, budget, totalSpent),
timestamp: new Date().toISOString(),
})
results.push(buildSkipResult(agent, budget, totalSpent))
continue
}
let activeInput = subtask.input
if (accumulatedContext) {
if (agent.id === 'summary-bot')
activeInput = `Summarize the following findings related to "${subtask.input}":\n\n${accumulatedContext.substring(0, 3000)}`
else if (agent.id === 'analyst-bot')
activeInput = `Analyze this topic: "${subtask.input}"\n\nContext:\n${accumulatedContext.substring(0, 3000)}`
else if (agent.id === 'code-bot')
activeInput = `Action: "${subtask.input}"\n\nContext:\n${accumulatedContext.substring(0, 3000)}`
}
broadcastFn?.({
type: 'agent_call',
agent: agent.name,
agentId: agent.id,
input: activeInput.substring(0, 100) + (activeInput.length > 100 ? '...' : ''),
cost: agent.price,
paymentFlow: x402Fetch ? 'x402-http402' : 'stellar-xlm-fallback',
timestamp: new Date().toISOString(),
})
const agentResponse = await callAgentViaX402(agent, activeInput, broadcastFn, context)
if (agentResponse && agentResponse.result) {
accumulatedContext =
typeof agentResponse.result === 'string'
? agentResponse.result
: JSON.stringify(agentResponse.result)
}
totalSpent += cost
const bucket = paymentBucket(agentResponse.paidVia)
if (bucket === 'x402') x402PaymentCount += 1
else if (bucket === 'stellar-xlm') xlmFallbackCount += 1
else unpaidCount += 1
const agentResult = {
agentId: agent.id,
agentName: agent.name,
model: agent.model,
input: subtask.input,
output: agentResponse.result,
cost: agent.price,
currency: agent.currency,
paidVia: agentResponse.paidVia,
paymentSuccess: agentResponse.paymentSuccess,
txHash: agentResponse.txHash || null,
explorerUrl: agentResponse.explorerUrl || null,
}
results.push(agentResult)
payments.push(agentResponse)
broadcastFn?.({
type: 'agent_response',
agent: agent.name,
agentId: agent.id,
resultPreview:
typeof agentResponse.result === 'string' ? agentResponse.result.substring(0, 150) : '',
cost: agent.price,
paidVia: agentResponse.paidVia,
txHash: agentResponse.txHash || null,
explorerUrl: agentResponse.explorerUrl || null,
timestamp: new Date().toISOString(),
})
if (agentResponse.paymentSuccess) {
logger.info('payment_settled', {
correlationId: context.correlationId,
agentId: agent.id,
paymentMethod: agentResponse.paidVia,
txHash: agentResponse.txHash || null,
})
broadcastFn?.({
type: 'payment',
from: 'Orchestrator',
to: agent.name,
amount: agent.price,
currency: agent.currency,
method: agentResponse.paidVia,
txHash: agentResponse.txHash,
explorerUrl: agentResponse.explorerUrl,
timestamp: new Date().toISOString(),
})
}
}
const elapsed = Date.now() - startTime
const budgetExhausted = isBudgetExhausted(totalSpent, budget)
const paymentProtocol = paymentProtocolSummary(x402PaymentCount, xlmFallbackCount)
const successfulPayments = payments.filter((p) => p.paymentSuccess)
const successfulTxs = successfulPayments.filter((p) => p.txHash)
broadcastFn?.({
type: 'orchestrator_complete',
totalSpent: totalSpent.toFixed(4),
agentsUsed: countUsed(results),
agentsSkipped: countSkipped(results),
elapsed: `${elapsed}ms`,
budgetExhausted,
paymentProtocol,
x402PaymentCount,
xlmFallbackCount,
unpaidCount,
x402WalletReady,
x402WalletHint,
timestamp: new Date().toISOString(),
})
return {
task,
plan: plan.plan,
budget,
totalSpent: totalSpent.toFixed(4),
budgetExhausted,
agentsUsed: countUsed(results),
agentsSkipped: countSkipped(results),
paymentProtocol,
x402PaymentCount,
xlmFallbackCount,
unpaidCount,
x402Configured: !!x402Fetch,
x402WalletReady,
x402WalletHint,
results,
payments: successfulPayments,
txCount: successfulTxs.length,
elapsed: `${elapsed}ms`,
}
}