@axlsdk/studio 0.14.0 → 0.15.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.
@@ -1,1163 +0,0 @@
1
- // src/server/index.ts
2
- import { existsSync, readFileSync } from "fs";
3
- import { resolve } from "path";
4
- import { Hono as Hono12 } from "hono";
5
- import { cors } from "hono/cors";
6
- import { serveStatic } from "@hono/node-server/serve-static";
7
-
8
- // src/server/middleware/error-handler.ts
9
- async function errorHandler(c, next) {
10
- try {
11
- await next();
12
- } catch (err) {
13
- const message = err instanceof Error ? err.message : String(err);
14
- const code = err.code ?? "INTERNAL_ERROR";
15
- let status = 500;
16
- if ("status" in err) {
17
- const errStatus = err.status;
18
- if (typeof errStatus === "number" && errStatus >= 400 && errStatus < 600) {
19
- status = errStatus;
20
- }
21
- } else if (code === "NOT_FOUND" || message.includes("not found") || message.includes("not registered")) {
22
- status = 404;
23
- } else if (code === "VALIDATION_ERROR" || message.includes("Expected") || message.includes("invalid")) {
24
- status = 400;
25
- }
26
- const body = {
27
- ok: false,
28
- error: { code, message }
29
- };
30
- return c.json(body, status);
31
- }
32
- }
33
-
34
- // src/server/ws/connection-manager.ts
35
- function isBufferedChannel(channel) {
36
- return channel.startsWith("execution:");
37
- }
38
- var BUFFER_TTL_MS = 3e4;
39
- var MAX_BUFFER_EVENTS = 500;
40
- var ConnectionManager = class {
41
- /** channel -> set of WS connections */
42
- channels = /* @__PURE__ */ new Map();
43
- /** ws -> set of subscribed channels (for cleanup) */
44
- connections = /* @__PURE__ */ new Map();
45
- /** channel -> replay buffer for execution streams */
46
- buffers = /* @__PURE__ */ new Map();
47
- maxConnections = 100;
48
- /** Register a new WS connection. */
49
- add(ws) {
50
- if (this.connections.size >= this.maxConnections) {
51
- ws.close?.();
52
- return;
53
- }
54
- this.connections.set(ws, /* @__PURE__ */ new Set());
55
- }
56
- /** Remove a WS connection and all its subscriptions. */
57
- remove(ws) {
58
- const channels = this.connections.get(ws);
59
- if (channels) {
60
- for (const ch of channels) {
61
- this.channels.get(ch)?.delete(ws);
62
- if (this.channels.get(ch)?.size === 0) {
63
- this.channels.delete(ch);
64
- }
65
- }
66
- }
67
- this.connections.delete(ws);
68
- }
69
- /** Subscribe a connection to a channel. Replays buffered events for execution channels. */
70
- subscribe(ws, channel) {
71
- if (!this.connections.has(ws)) return;
72
- let subs = this.channels.get(channel);
73
- if (!subs) {
74
- subs = /* @__PURE__ */ new Set();
75
- this.channels.set(channel, subs);
76
- }
77
- subs.add(ws);
78
- this.connections.get(ws).add(channel);
79
- const buffer = this.buffers.get(channel);
80
- if (buffer) {
81
- for (const msg of buffer.events) {
82
- try {
83
- ws.send(msg);
84
- } catch {
85
- this.remove(ws);
86
- return;
87
- }
88
- }
89
- }
90
- }
91
- /** Unsubscribe a connection from a channel. */
92
- unsubscribe(ws, channel) {
93
- this.channels.get(channel)?.delete(ws);
94
- if (this.channels.get(channel)?.size === 0) {
95
- this.channels.delete(channel);
96
- }
97
- this.connections.get(ws)?.delete(channel);
98
- }
99
- /** Broadcast data to all subscribers of a channel. Buffers events for execution channels. */
100
- broadcast(channel, data) {
101
- const msg = JSON.stringify({ type: "event", channel, data });
102
- if (isBufferedChannel(channel)) {
103
- let buffer = this.buffers.get(channel);
104
- if (!buffer) {
105
- buffer = { events: [], complete: false };
106
- this.buffers.set(channel, buffer);
107
- }
108
- const event = data;
109
- const isTerminal = event.type === "done" || event.type === "error";
110
- if (buffer.events.length < MAX_BUFFER_EVENTS || isTerminal) {
111
- buffer.events.push(msg);
112
- }
113
- if (isTerminal) {
114
- buffer.complete = true;
115
- if (buffer.timer) clearTimeout(buffer.timer);
116
- buffer.timer = setTimeout(() => {
117
- this.buffers.delete(channel);
118
- }, BUFFER_TTL_MS);
119
- }
120
- }
121
- const subs = this.channels.get(channel);
122
- if (!subs || subs.size === 0) return;
123
- for (const ws of [...subs]) {
124
- try {
125
- ws.send(msg);
126
- } catch {
127
- this.remove(ws);
128
- }
129
- }
130
- }
131
- /** Broadcast to channel and all wildcard subscribers (e.g., trace:* matches trace:abc). */
132
- broadcastWithWildcard(channel, data) {
133
- this.broadcast(channel, data);
134
- const colonIdx = channel.indexOf(":");
135
- if (colonIdx > 0) {
136
- const wildcardChannel = channel.substring(0, colonIdx) + ":*";
137
- const subs = this.channels.get(wildcardChannel);
138
- if (!subs || subs.size === 0) return;
139
- const msg = JSON.stringify({ type: "event", channel, data });
140
- for (const ws of [...subs]) {
141
- try {
142
- ws.send(msg);
143
- } catch {
144
- this.remove(ws);
145
- }
146
- }
147
- }
148
- }
149
- /** Close all connections, clear all state and buffers. Used during shutdown. */
150
- closeAll() {
151
- for (const ws of this.connections.keys()) {
152
- ws.close?.();
153
- }
154
- for (const buffer of this.buffers.values()) {
155
- if (buffer.timer) clearTimeout(buffer.timer);
156
- }
157
- this.connections.clear();
158
- this.channels.clear();
159
- this.buffers.clear();
160
- }
161
- /** Get the number of active connections. */
162
- get connectionCount() {
163
- return this.connections.size;
164
- }
165
- /** Check if any connections are subscribed to a channel. */
166
- hasSubscribers(channel) {
167
- return (this.channels.get(channel)?.size ?? 0) > 0;
168
- }
169
- };
170
-
171
- // src/server/ws/protocol.ts
172
- var VALID_CHANNEL_PREFIXES = ["execution:", "trace:"];
173
- var VALID_EXACT_CHANNELS = ["costs", "decisions"];
174
- var MAX_CHANNEL_LENGTH = 256;
175
- function handleWsMessage(raw, socket, connMgr) {
176
- if (raw.length > 65536) {
177
- return JSON.stringify({ type: "error", message: "Message too large" });
178
- }
179
- let msg;
180
- try {
181
- msg = JSON.parse(raw);
182
- } catch {
183
- return JSON.stringify({ type: "error", message: "Invalid JSON" });
184
- }
185
- switch (msg.type) {
186
- case "subscribe": {
187
- const error = validateChannel(msg.channel);
188
- if (error) return JSON.stringify({ type: "error", message: error });
189
- connMgr.subscribe(socket, msg.channel);
190
- return JSON.stringify({ type: "subscribed", channel: msg.channel });
191
- }
192
- case "unsubscribe": {
193
- const error = validateChannel(msg.channel);
194
- if (error) return JSON.stringify({ type: "error", message: error });
195
- connMgr.unsubscribe(socket, msg.channel);
196
- return JSON.stringify({ type: "unsubscribed", channel: msg.channel });
197
- }
198
- case "ping":
199
- return JSON.stringify({ type: "pong" });
200
- default:
201
- return JSON.stringify({ type: "error", message: "Unknown message type" });
202
- }
203
- }
204
- function validateChannel(channel) {
205
- if (typeof channel !== "string" || !channel) {
206
- return "Missing or invalid channel";
207
- }
208
- if (channel.length > MAX_CHANNEL_LENGTH) {
209
- return `Channel name exceeds ${MAX_CHANNEL_LENGTH} characters`;
210
- }
211
- if (!VALID_EXACT_CHANNELS.includes(channel) && !VALID_CHANNEL_PREFIXES.some((p) => channel.startsWith(p))) {
212
- return `Invalid channel: ${channel}`;
213
- }
214
- return null;
215
- }
216
-
217
- // src/server/ws/handler.ts
218
- function createWsHandlers(connMgr) {
219
- return {
220
- onOpen(_event, ws) {
221
- connMgr.add(ws);
222
- },
223
- onMessage(event, ws) {
224
- const reply = handleWsMessage(String(event.data), ws, connMgr);
225
- if (reply) ws.send(reply);
226
- },
227
- onClose(_event, ws) {
228
- connMgr.remove(ws);
229
- },
230
- onError(_event, ws) {
231
- connMgr.remove(ws);
232
- }
233
- };
234
- }
235
-
236
- // src/server/cost-aggregator.ts
237
- var CostAggregator = class {
238
- constructor(connMgr) {
239
- this.connMgr = connMgr;
240
- }
241
- data = {
242
- totalCost: 0,
243
- totalTokens: { input: 0, output: 0, reasoning: 0 },
244
- byAgent: {},
245
- byModel: {},
246
- byWorkflow: {}
247
- };
248
- /** Process a trace event and update cost data. */
249
- onTrace(event) {
250
- if (event.cost == null && !event.tokens) return;
251
- const cost = Number.isFinite(event.cost) ? event.cost : 0;
252
- const tokens = event.tokens ?? {};
253
- this.data.totalCost += cost;
254
- this.data.totalTokens.input += tokens.input ?? 0;
255
- this.data.totalTokens.output += tokens.output ?? 0;
256
- this.data.totalTokens.reasoning += tokens.reasoning ?? 0;
257
- if (event.agent) {
258
- const entry = this.data.byAgent[event.agent] ?? { cost: 0, calls: 0 };
259
- entry.cost += cost;
260
- entry.calls += 1;
261
- this.data.byAgent[event.agent] = entry;
262
- }
263
- if (event.model) {
264
- const entry = this.data.byModel[event.model] ?? {
265
- cost: 0,
266
- calls: 0,
267
- tokens: { input: 0, output: 0 }
268
- };
269
- entry.cost += cost;
270
- entry.calls += 1;
271
- entry.tokens.input += tokens.input ?? 0;
272
- entry.tokens.output += tokens.output ?? 0;
273
- this.data.byModel[event.model] = entry;
274
- }
275
- if (event.workflow) {
276
- const entry = this.data.byWorkflow[event.workflow] ?? { cost: 0, executions: 0 };
277
- entry.cost += cost;
278
- if (event.type === "workflow_start") entry.executions += 1;
279
- this.data.byWorkflow[event.workflow] = entry;
280
- }
281
- this.connMgr.broadcast("costs", this.data);
282
- }
283
- /** Get current aggregated cost data. */
284
- getData() {
285
- return this.data;
286
- }
287
- /** Reset all accumulated data. */
288
- reset() {
289
- this.data = {
290
- totalCost: 0,
291
- totalTokens: { input: 0, output: 0, reasoning: 0 },
292
- byAgent: {},
293
- byModel: {},
294
- byWorkflow: {}
295
- };
296
- }
297
- };
298
-
299
- // src/server/routes/health.ts
300
- import { Hono } from "hono";
301
- function createHealthRoutes(readOnly) {
302
- const app6 = new Hono();
303
- app6.get("/health", (c) => {
304
- const runtime = c.get("runtime");
305
- return c.json({
306
- ok: true,
307
- data: {
308
- status: "healthy",
309
- readOnly,
310
- workflows: runtime.getWorkflowNames().length,
311
- agents: runtime.getAgents().length,
312
- tools: runtime.getTools().length
313
- }
314
- });
315
- });
316
- return app6;
317
- }
318
-
319
- // src/server/routes/workflows.ts
320
- import { Hono as Hono2 } from "hono";
321
- import { zodToJsonSchema } from "@axlsdk/axl";
322
- function createWorkflowRoutes(connMgr) {
323
- const app6 = new Hono2();
324
- app6.get("/workflows", (c) => {
325
- const runtime = c.get("runtime");
326
- const workflows = runtime.getWorkflows().map((w) => ({
327
- name: w.name,
328
- hasInputSchema: !!w.inputSchema,
329
- hasOutputSchema: !!w.outputSchema
330
- }));
331
- return c.json({ ok: true, data: workflows });
332
- });
333
- app6.get("/workflows/:name", (c) => {
334
- const runtime = c.get("runtime");
335
- const name = c.req.param("name");
336
- const workflow = runtime.getWorkflow(name);
337
- if (!workflow) {
338
- return c.json(
339
- { ok: false, error: { code: "NOT_FOUND", message: `Workflow "${name}" not found` } },
340
- 404
341
- );
342
- }
343
- return c.json({
344
- ok: true,
345
- data: {
346
- name: workflow.name,
347
- inputSchema: workflow.inputSchema ? zodToJsonSchema(workflow.inputSchema) : null,
348
- outputSchema: workflow.outputSchema ? zodToJsonSchema(workflow.outputSchema) : null
349
- }
350
- });
351
- });
352
- app6.post("/workflows/:name/execute", async (c) => {
353
- const runtime = c.get("runtime");
354
- const name = c.req.param("name");
355
- const workflow = runtime.getWorkflow(name);
356
- if (!workflow) {
357
- return c.json(
358
- { ok: false, error: { code: "NOT_FOUND", message: `Workflow "${name}" not found` } },
359
- 404
360
- );
361
- }
362
- const body = await c.req.json();
363
- if (body.stream) {
364
- const stream = runtime.stream(name, body.input ?? {}, { metadata: body.metadata });
365
- const executionId = `stream-${Date.now()}`;
366
- (async () => {
367
- for await (const event of stream) {
368
- connMgr.broadcastWithWildcard(`execution:${executionId}`, event);
369
- }
370
- })();
371
- return c.json({ ok: true, data: { executionId, streaming: true } });
372
- }
373
- const result = await runtime.execute(name, body.input ?? {}, { metadata: body.metadata });
374
- return c.json({ ok: true, data: { result } });
375
- });
376
- return app6;
377
- }
378
-
379
- // src/server/routes/executions.ts
380
- import { Hono as Hono3 } from "hono";
381
- var app = new Hono3();
382
- app.get("/executions", async (c) => {
383
- const runtime = c.get("runtime");
384
- const executions = await runtime.getExecutions();
385
- return c.json({ ok: true, data: executions });
386
- });
387
- app.get("/executions/:id", async (c) => {
388
- const runtime = c.get("runtime");
389
- const id = c.req.param("id");
390
- const execution = await runtime.getExecution(id);
391
- if (!execution) {
392
- return c.json(
393
- { ok: false, error: { code: "NOT_FOUND", message: `Execution "${id}" not found` } },
394
- 404
395
- );
396
- }
397
- return c.json({ ok: true, data: execution });
398
- });
399
- app.post("/executions/:id/abort", (c) => {
400
- const runtime = c.get("runtime");
401
- const id = c.req.param("id");
402
- runtime.abort(id);
403
- return c.json({ ok: true, data: { aborted: true } });
404
- });
405
- var executions_default = app;
406
-
407
- // src/server/routes/sessions.ts
408
- import { Hono as Hono4 } from "hono";
409
- function createSessionRoutes(connMgr) {
410
- const app6 = new Hono4();
411
- app6.get("/sessions", async (c) => {
412
- const runtime = c.get("runtime");
413
- const store = runtime.getStateStore();
414
- if (!store.listSessions) {
415
- return c.json({ ok: true, data: [] });
416
- }
417
- const ids = await store.listSessions();
418
- const sessions = [];
419
- for (const id of ids) {
420
- const history = await store.getSession(id);
421
- sessions.push({ id, messageCount: history.length });
422
- }
423
- return c.json({ ok: true, data: sessions });
424
- });
425
- app6.get("/sessions/:id", async (c) => {
426
- const runtime = c.get("runtime");
427
- const store = runtime.getStateStore();
428
- const id = c.req.param("id");
429
- const history = await store.getSession(id);
430
- const handoffHistory = await store.getSessionMeta(id, "handoffHistory");
431
- return c.json({ ok: true, data: { id, history, handoffHistory: handoffHistory ?? [] } });
432
- });
433
- app6.post("/sessions/:id/send", async (c) => {
434
- const runtime = c.get("runtime");
435
- const id = c.req.param("id");
436
- const body = await c.req.json();
437
- const session = runtime.session(id);
438
- const result = await session.send(body.workflow, body.message);
439
- return c.json({ ok: true, data: { result } });
440
- });
441
- app6.post("/sessions/:id/stream", async (c) => {
442
- const runtime = c.get("runtime");
443
- const id = c.req.param("id");
444
- const body = await c.req.json();
445
- const session = runtime.session(id);
446
- const stream = await session.stream(body.workflow, body.message);
447
- const executionId = `session-${id}-${Date.now()}`;
448
- (async () => {
449
- for await (const event of stream) {
450
- connMgr.broadcastWithWildcard(`execution:${executionId}`, event);
451
- }
452
- })();
453
- return c.json({ ok: true, data: { executionId, streaming: true } });
454
- });
455
- app6.delete("/sessions/:id", async (c) => {
456
- const runtime = c.get("runtime");
457
- const store = runtime.getStateStore();
458
- const id = c.req.param("id");
459
- await store.deleteSession(id);
460
- return c.json({ ok: true, data: { deleted: true } });
461
- });
462
- return app6;
463
- }
464
-
465
- // src/server/routes/agents.ts
466
- import { Hono as Hono5 } from "hono";
467
- import { zodToJsonSchema as zodToJsonSchema2 } from "@axlsdk/axl";
468
- var app2 = new Hono5();
469
- app2.get("/agents", (c) => {
470
- const runtime = c.get("runtime");
471
- const agents = runtime.getAgents().map((a) => ({
472
- name: a._name,
473
- model: a.resolveModel(),
474
- system: a.resolveSystem(),
475
- tools: a._config.tools?.map((t) => t.name) ?? [],
476
- handoffs: typeof a._config.handoffs === "function" ? ["(dynamic)"] : a._config.handoffs?.map((h) => h.agent._name) ?? [],
477
- maxTurns: a._config.maxTurns,
478
- temperature: a._config.temperature,
479
- maxTokens: a._config.maxTokens,
480
- effort: a._config.effort,
481
- thinkingBudget: a._config.thinkingBudget,
482
- includeThoughts: a._config.includeThoughts,
483
- toolChoice: a._config.toolChoice,
484
- stop: a._config.stop
485
- }));
486
- return c.json({ ok: true, data: agents });
487
- });
488
- app2.get("/agents/:name", (c) => {
489
- const runtime = c.get("runtime");
490
- const name = c.req.param("name");
491
- const agent = runtime.getAgent(name);
492
- if (!agent) {
493
- return c.json(
494
- { ok: false, error: { code: "NOT_FOUND", message: `Agent "${name}" not found` } },
495
- 404
496
- );
497
- }
498
- const cfg = agent._config;
499
- return c.json({
500
- ok: true,
501
- data: {
502
- name: agent._name,
503
- model: agent.resolveModel(),
504
- system: agent.resolveSystem(),
505
- tools: cfg.tools?.map((t) => ({
506
- name: t.name,
507
- description: t.description,
508
- inputSchema: zodToJsonSchema2(t.inputSchema)
509
- })) ?? [],
510
- handoffs: typeof cfg.handoffs === "function" ? [
511
- {
512
- agent: "(dynamic)",
513
- description: "Resolved at runtime from metadata",
514
- mode: "oneway"
515
- }
516
- ] : cfg.handoffs?.map((h) => ({
517
- agent: h.agent._name,
518
- description: h.description,
519
- mode: h.mode ?? "oneway"
520
- })) ?? [],
521
- maxTurns: cfg.maxTurns,
522
- temperature: cfg.temperature,
523
- maxTokens: cfg.maxTokens,
524
- effort: cfg.effort,
525
- thinkingBudget: cfg.thinkingBudget,
526
- includeThoughts: cfg.includeThoughts,
527
- toolChoice: cfg.toolChoice,
528
- stop: cfg.stop,
529
- timeout: cfg.timeout,
530
- maxContext: cfg.maxContext,
531
- version: cfg.version,
532
- mcp: cfg.mcp,
533
- mcpTools: cfg.mcpTools,
534
- hasGuardrails: !!cfg.guardrails,
535
- guardrails: cfg.guardrails ? {
536
- hasInput: !!cfg.guardrails.input,
537
- hasOutput: !!cfg.guardrails.output,
538
- onBlock: cfg.guardrails.onBlock ?? "throw",
539
- maxRetries: cfg.guardrails.maxRetries
540
- } : null
541
- }
542
- });
543
- });
544
- var agents_default = app2;
545
-
546
- // src/server/routes/tools.ts
547
- import { Hono as Hono6 } from "hono";
548
- import { zodToJsonSchema as zodToJsonSchema3 } from "@axlsdk/axl";
549
- var app3 = new Hono6();
550
- app3.get("/tools", (c) => {
551
- const runtime = c.get("runtime");
552
- const tools = runtime.getTools().map((t) => ({
553
- name: t.name,
554
- description: t.description,
555
- inputSchema: t.inputSchema ? zodToJsonSchema3(t.inputSchema) : {},
556
- sensitive: t.sensitive ?? false,
557
- requireApproval: t.requireApproval ?? false
558
- }));
559
- return c.json({ ok: true, data: tools });
560
- });
561
- app3.get("/tools/:name", (c) => {
562
- const runtime = c.get("runtime");
563
- const name = c.req.param("name");
564
- const tool = runtime.getTool(name);
565
- if (!tool) {
566
- return c.json(
567
- { ok: false, error: { code: "NOT_FOUND", message: `Tool "${name}" not found` } },
568
- 404
569
- );
570
- }
571
- return c.json({
572
- ok: true,
573
- data: {
574
- name: tool.name,
575
- description: tool.description,
576
- inputSchema: tool.inputSchema ? zodToJsonSchema3(tool.inputSchema) : {},
577
- sensitive: tool.sensitive,
578
- requireApproval: tool.requireApproval,
579
- retry: tool.retry,
580
- hasHooks: !!tool.hooks,
581
- hooks: tool.hooks ? {
582
- hasBefore: !!tool.hooks.before,
583
- hasAfter: !!tool.hooks.after
584
- } : null
585
- }
586
- });
587
- });
588
- app3.post("/tools/:name/test", async (c) => {
589
- const runtime = c.get("runtime");
590
- const name = c.req.param("name");
591
- const tool = runtime.getTool(name);
592
- if (!tool) {
593
- return c.json(
594
- { ok: false, error: { code: "NOT_FOUND", message: `Tool "${name}" not found` } },
595
- 404
596
- );
597
- }
598
- const body = await c.req.json();
599
- const ctx = runtime.createContext();
600
- const result = await tool.run(ctx, body.input);
601
- return c.json({ ok: true, data: { result } });
602
- });
603
- var tools_default = app3;
604
-
605
- // src/server/routes/memory.ts
606
- import { Hono as Hono7 } from "hono";
607
- var app4 = new Hono7();
608
- app4.get("/memory/:scope", async (c) => {
609
- const runtime = c.get("runtime");
610
- const store = runtime.getStateStore();
611
- const scope = c.req.param("scope");
612
- if (!store.getAllMemory) {
613
- return c.json({ ok: true, data: [] });
614
- }
615
- const entries = await store.getAllMemory(scope);
616
- return c.json({ ok: true, data: entries });
617
- });
618
- app4.get("/memory/:scope/:key", async (c) => {
619
- const runtime = c.get("runtime");
620
- const store = runtime.getStateStore();
621
- const scope = c.req.param("scope");
622
- const key = c.req.param("key");
623
- if (!store.getMemory) {
624
- return c.json(
625
- { ok: false, error: { code: "NOT_SUPPORTED", message: "Memory not supported" } },
626
- 501
627
- );
628
- }
629
- const value = await store.getMemory(scope, key);
630
- if (value === null) {
631
- return c.json(
632
- { ok: false, error: { code: "NOT_FOUND", message: `Memory "${scope}/${key}" not found` } },
633
- 404
634
- );
635
- }
636
- return c.json({ ok: true, data: { key, value } });
637
- });
638
- app4.put("/memory/:scope/:key", async (c) => {
639
- const runtime = c.get("runtime");
640
- const store = runtime.getStateStore();
641
- const scope = c.req.param("scope");
642
- const key = c.req.param("key");
643
- if (!store.saveMemory) {
644
- return c.json(
645
- { ok: false, error: { code: "NOT_SUPPORTED", message: "Memory not supported" } },
646
- 501
647
- );
648
- }
649
- const body = await c.req.json();
650
- await store.saveMemory(scope, key, body.value);
651
- return c.json({ ok: true, data: { saved: true } });
652
- });
653
- app4.delete("/memory/:scope/:key", async (c) => {
654
- const runtime = c.get("runtime");
655
- const store = runtime.getStateStore();
656
- const scope = c.req.param("scope");
657
- const key = c.req.param("key");
658
- if (!store.deleteMemory) {
659
- return c.json(
660
- { ok: false, error: { code: "NOT_SUPPORTED", message: "Memory not supported" } },
661
- 501
662
- );
663
- }
664
- await store.deleteMemory(scope, key);
665
- return c.json({ ok: true, data: { deleted: true } });
666
- });
667
- app4.post("/memory/search", async (c) => {
668
- return c.json({
669
- ok: true,
670
- data: { results: [], message: "Semantic search requires MemoryManager with vector store" }
671
- });
672
- });
673
- var memory_default = app4;
674
-
675
- // src/server/routes/decisions.ts
676
- import { Hono as Hono8 } from "hono";
677
- var app5 = new Hono8();
678
- app5.get("/decisions", async (c) => {
679
- const runtime = c.get("runtime");
680
- const decisions = await runtime.getPendingDecisions();
681
- return c.json({ ok: true, data: decisions });
682
- });
683
- app5.post("/decisions/:executionId/resolve", async (c) => {
684
- const runtime = c.get("runtime");
685
- const executionId = c.req.param("executionId");
686
- const body = await c.req.json();
687
- await runtime.resolveDecision(executionId, body);
688
- return c.json({ ok: true, data: { resolved: true } });
689
- });
690
- var decisions_default = app5;
691
-
692
- // src/server/routes/costs.ts
693
- import { Hono as Hono9 } from "hono";
694
- function createCostRoutes(costAggregator) {
695
- const app6 = new Hono9();
696
- app6.get("/costs", (c) => {
697
- return c.json({ ok: true, data: costAggregator.getData() });
698
- });
699
- app6.post("/costs/reset", (c) => {
700
- costAggregator.reset();
701
- return c.json({ ok: true, data: { reset: true } });
702
- });
703
- return app6;
704
- }
705
-
706
- // src/server/routes/evals.ts
707
- import { randomUUID } from "crypto";
708
- import { Hono as Hono10 } from "hono";
709
- function createEvalRoutes(evalLoader) {
710
- const app6 = new Hono10();
711
- app6.get("/evals", async (c) => {
712
- if (evalLoader) await evalLoader();
713
- const runtime = c.get("runtime");
714
- const evals = runtime.getRegisteredEvals();
715
- return c.json({ ok: true, data: evals });
716
- });
717
- app6.get("/evals/history", async (c) => {
718
- const runtime = c.get("runtime");
719
- const history = await runtime.getEvalHistory();
720
- return c.json({ ok: true, data: history });
721
- });
722
- app6.delete("/evals/history/:id", async (c) => {
723
- const runtime = c.get("runtime");
724
- const id = c.req.param("id");
725
- const deleted = await runtime.deleteEvalResult(id);
726
- if (!deleted) {
727
- return c.json(
728
- {
729
- ok: false,
730
- error: { code: "NOT_FOUND", message: `Eval history entry "${id}" not found` }
731
- },
732
- 404
733
- );
734
- }
735
- return c.json({ ok: true, data: { id, deleted: true } });
736
- });
737
- app6.post("/evals/:name/run", async (c) => {
738
- if (evalLoader) await evalLoader();
739
- const runtime = c.get("runtime");
740
- const name = c.req.param("name");
741
- const entry = runtime.getRegisteredEval(name);
742
- if (!entry) {
743
- return c.json(
744
- { ok: false, error: { code: "NOT_FOUND", message: `Eval "${name}" not found` } },
745
- 404
746
- );
747
- }
748
- let runs = 1;
749
- try {
750
- const body = await c.req.json().catch(() => ({}));
751
- if (typeof body.runs === "number" && Number.isFinite(body.runs) && body.runs > 1) {
752
- runs = Math.min(Math.floor(body.runs), 25);
753
- }
754
- } catch {
755
- }
756
- try {
757
- if (runs > 1) {
758
- const { aggregateRuns } = await import("@axlsdk/eval");
759
- const runGroupId = randomUUID();
760
- const results = [];
761
- for (let r = 0; r < runs; r++) {
762
- const result2 = await runtime.runRegisteredEval(name, {
763
- metadata: { runGroupId, runIndex: r }
764
- });
765
- results.push(result2);
766
- }
767
- const typedResults = results;
768
- const aggregate = aggregateRuns(typedResults);
769
- const first = typedResults[0];
770
- const result = { ...first, _multiRun: { aggregate, allRuns: typedResults } };
771
- return c.json({ ok: true, data: result });
772
- } else {
773
- const result = await runtime.runRegisteredEval(name);
774
- return c.json({ ok: true, data: result });
775
- }
776
- } catch (err) {
777
- const message = err instanceof Error ? err.message : String(err);
778
- return c.json({ ok: false, error: { code: "EVAL_ERROR", message } }, 400);
779
- }
780
- });
781
- app6.post("/evals/:name/rescore", async (c) => {
782
- if (evalLoader) await evalLoader();
783
- const runtime = c.get("runtime");
784
- const name = c.req.param("name");
785
- const body = await c.req.json();
786
- if (!body.resultId || typeof body.resultId !== "string") {
787
- return c.json(
788
- { ok: false, error: { code: "BAD_REQUEST", message: "resultId is required" } },
789
- 400
790
- );
791
- }
792
- const entry = runtime.getRegisteredEval(name);
793
- if (!entry) {
794
- return c.json(
795
- { ok: false, error: { code: "NOT_FOUND", message: `Eval "${name}" not found` } },
796
- 404
797
- );
798
- }
799
- const history = await runtime.getEvalHistory();
800
- const historyEntry = history.find((h) => h.id === body.resultId);
801
- if (!historyEntry) {
802
- return c.json(
803
- { ok: false, error: { code: "NOT_FOUND", message: `Result "${body.resultId}" not found` } },
804
- 404
805
- );
806
- }
807
- try {
808
- const { rescore } = await import("@axlsdk/eval");
809
- const config = entry.config;
810
- const result = await rescore(
811
- historyEntry.data,
812
- config.scorers,
813
- runtime
814
- );
815
- await runtime.saveEvalResult({
816
- id: result.id,
817
- eval: name,
818
- timestamp: Date.now(),
819
- data: result
820
- });
821
- return c.json({ ok: true, data: result });
822
- } catch (err) {
823
- const message = err instanceof Error ? err.message : String(err);
824
- return c.json({ ok: false, error: { code: "EVAL_ERROR", message } }, 400);
825
- }
826
- });
827
- app6.post("/evals/compare", async (c) => {
828
- const runtime = c.get("runtime");
829
- const body = await c.req.json();
830
- const validateIdParam = (v, name) => {
831
- if (typeof v === "string") return v === "" ? `${name} must be non-empty` : null;
832
- if (Array.isArray(v)) {
833
- if (v.length === 0) return `${name} must be a non-empty array`;
834
- for (const elem of v) {
835
- if (typeof elem !== "string" || elem === "") {
836
- return `${name} array must contain only non-empty strings`;
837
- }
838
- }
839
- return null;
840
- }
841
- return `${name} is required (string or string[])`;
842
- };
843
- const baselineErr = validateIdParam(body.baselineId, "baselineId");
844
- const candidateErr = validateIdParam(body.candidateId, "candidateId");
845
- if (baselineErr || candidateErr) {
846
- return c.json(
847
- {
848
- ok: false,
849
- error: {
850
- code: "BAD_REQUEST",
851
- message: [baselineErr, candidateErr].filter(Boolean).join("; ")
852
- }
853
- },
854
- 400
855
- );
856
- }
857
- const history = await runtime.getEvalHistory();
858
- const byId = new Map(history.map((h) => [h.id, h.data]));
859
- const missing = [];
860
- const resolveOne = (id) => {
861
- const data = byId.get(id);
862
- if (!data) missing.push(id);
863
- return data;
864
- };
865
- const resolveSelection = (idOrIds) => {
866
- if (Array.isArray(idOrIds)) {
867
- const unique = Array.from(new Set(idOrIds));
868
- if (unique.length === 1) return resolveOne(unique[0]);
869
- const results = [];
870
- for (const id of unique) {
871
- const data = resolveOne(id);
872
- if (data) results.push(data);
873
- }
874
- return results;
875
- }
876
- return resolveOne(idOrIds);
877
- };
878
- const baseline = resolveSelection(body.baselineId);
879
- const candidate = resolveSelection(body.candidateId);
880
- if (missing.length > 0) {
881
- return c.json(
882
- {
883
- ok: false,
884
- error: {
885
- code: "NOT_FOUND",
886
- message: `Eval result(s) not found in history: ${missing.join(", ")}`
887
- }
888
- },
889
- 404
890
- );
891
- }
892
- try {
893
- const result = await runtime.evalCompare(baseline, candidate, body.options);
894
- return c.json({ ok: true, data: result });
895
- } catch (err) {
896
- const message = err instanceof Error ? err.message : String(err);
897
- return c.json({ ok: false, error: { code: "COMPARE_FAILED", message } }, 400);
898
- }
899
- });
900
- app6.post("/evals/import", async (c) => {
901
- const runtime = c.get("runtime");
902
- const body = await c.req.json();
903
- const bad = (message) => c.json({ ok: false, error: { code: "BAD_REQUEST", message } }, 400);
904
- if (!body.result || typeof body.result !== "object") {
905
- return bad("result is required");
906
- }
907
- const result = body.result;
908
- if (!Array.isArray(result.items)) {
909
- return bad("result.items must be an array");
910
- }
911
- if (typeof result.summary !== "object" || result.summary == null) {
912
- return bad("result.summary must be an object");
913
- }
914
- if (typeof result.dataset !== "string" || !result.dataset) {
915
- return bad("result.dataset must be a non-empty string (required for compare)");
916
- }
917
- const summary = result.summary;
918
- if (typeof summary.scorers !== "object" || summary.scorers == null) {
919
- return bad("result.summary.scorers must be an object");
920
- }
921
- const summaryScorerNames = Object.keys(summary.scorers);
922
- const items = result.items;
923
- const summaryScorerSet = new Set(summaryScorerNames);
924
- const uncoveredAcrossItems = /* @__PURE__ */ new Set();
925
- for (const item of items) {
926
- const itemScores = item?.scores;
927
- if (itemScores && typeof itemScores === "object") {
928
- for (const name of Object.keys(itemScores)) {
929
- if (!summaryScorerSet.has(name)) uncoveredAcrossItems.add(name);
930
- }
931
- }
932
- }
933
- if (uncoveredAcrossItems.size > 0) {
934
- return bad(
935
- `item scores reference scorer(s) not in summary.scorers: ${[...uncoveredAcrossItems].join(", ")}`
936
- );
937
- }
938
- const trim = (v) => typeof v === "string" && v.trim() !== "" ? v.trim() : void 0;
939
- const metadataObj = typeof result.metadata === "object" && result.metadata != null ? result.metadata : {};
940
- const workflowsFromMeta = Array.isArray(metadataObj.workflows) ? metadataObj.workflows : [];
941
- const primaryWorkflow = workflowsFromMeta.find((w) => typeof w === "string");
942
- const evalName = trim(body.eval) ?? trim(primaryWorkflow) ?? // Legacy fallback: pre-0.14 CLI artifacts had workflow at the top level.
943
- trim(result.workflow) ?? "imported";
944
- const id = randomUUID();
945
- const timestamp = Date.now();
946
- const imported = {
947
- ...result,
948
- id,
949
- metadata: typeof result.metadata === "object" && result.metadata != null ? result.metadata : {}
950
- };
951
- await runtime.saveEvalResult({
952
- id,
953
- eval: evalName,
954
- timestamp,
955
- data: imported
956
- });
957
- return c.json({ ok: true, data: { id, eval: evalName, timestamp } });
958
- });
959
- return app6;
960
- }
961
-
962
- // src/server/routes/playground.ts
963
- import { Hono as Hono11 } from "hono";
964
- function createPlaygroundRoutes(connMgr) {
965
- const app6 = new Hono11();
966
- app6.post("/playground/chat", async (c) => {
967
- const runtime = c.get("runtime");
968
- const body = await c.req.json();
969
- if (!body.message || typeof body.message !== "string" || !body.message.trim()) {
970
- return c.json(
971
- {
972
- ok: false,
973
- error: {
974
- code: "INVALID_INPUT",
975
- message: "message is required and must be a non-empty string"
976
- }
977
- },
978
- 400
979
- );
980
- }
981
- const agents = runtime.getAgents();
982
- const agent = body.agent ? agents.find((a) => a._name === body.agent) : agents[0];
983
- if (!agent) {
984
- return c.json(
985
- {
986
- ok: false,
987
- error: { code: "NO_AGENT", message: `Agent "${body.agent ?? ""}" not found` }
988
- },
989
- 400
990
- );
991
- }
992
- const sessionId = body.sessionId ?? `playground-${Date.now()}`;
993
- const executionId = `playground-${sessionId}-${Date.now()}`;
994
- const store = runtime.getStateStore();
995
- const history = await store.getSession(sessionId);
996
- history.push({ role: "user", content: body.message });
997
- const ctx = runtime.createContext({
998
- sessionHistory: history,
999
- onToken: (token) => {
1000
- connMgr.broadcastWithWildcard(`execution:${executionId}`, {
1001
- type: "token",
1002
- data: token
1003
- });
1004
- }
1005
- });
1006
- (async () => {
1007
- try {
1008
- const result = await ctx.ask(agent, body.message);
1009
- const resultText = typeof result === "string" ? result : JSON.stringify(result);
1010
- history.push({ role: "assistant", content: resultText });
1011
- await store.saveSession(sessionId, history);
1012
- connMgr.broadcastWithWildcard(`execution:${executionId}`, {
1013
- type: "done",
1014
- data: resultText
1015
- });
1016
- } catch (err) {
1017
- connMgr.broadcastWithWildcard(`execution:${executionId}`, {
1018
- type: "error",
1019
- message: err instanceof Error ? err.message : String(err)
1020
- });
1021
- }
1022
- })();
1023
- return c.json({
1024
- ok: true,
1025
- data: { sessionId, executionId, streaming: true }
1026
- });
1027
- });
1028
- return app6;
1029
- }
1030
-
1031
- // src/server/index.ts
1032
- function createServer(options) {
1033
- const { runtime, staticRoot, basePath = "", readOnly = false } = options;
1034
- const app6 = new Hono12();
1035
- const connMgr = new ConnectionManager();
1036
- const costAggregator = new CostAggregator(connMgr);
1037
- if (options.cors !== false) {
1038
- app6.use("*", cors());
1039
- }
1040
- app6.use("*", errorHandler);
1041
- app6.use("*", async (c, next) => {
1042
- c.set("runtime", runtime);
1043
- await next();
1044
- });
1045
- if (readOnly) {
1046
- const blocked = [
1047
- /^POST \/api\/workflows(\/|$)/,
1048
- /^POST \/api\/executions(\/|$)/,
1049
- /^POST \/api\/sessions(\/|$)/,
1050
- /^DELETE \/api\/sessions(\/|$)/,
1051
- /^PUT \/api\/memory(\/|$)/,
1052
- /^DELETE \/api\/memory(\/|$)/,
1053
- /^POST \/api\/decisions(\/|$)/,
1054
- /^POST \/api\/costs(\/|$)/,
1055
- /^POST \/api\/tools(\/|$)/,
1056
- /^POST \/api\/evals\/import$/,
1057
- /^POST \/api\/evals\/[^/]+\/run$/,
1058
- /^POST \/api\/evals\/[^/]+\/rescore$/,
1059
- /^DELETE \/api\/evals\/history\/[^/]+$/,
1060
- /^POST \/api\/playground(\/|$)/
1061
- ];
1062
- app6.use("/api/*", async (c, next) => {
1063
- const apiIdx = c.req.path.indexOf("/api/");
1064
- const apiPath = apiIdx >= 0 ? c.req.path.slice(apiIdx) : c.req.path;
1065
- const key = `${c.req.method} ${apiPath}`;
1066
- if (blocked.some((re) => re.test(key))) {
1067
- return c.json(
1068
- {
1069
- ok: false,
1070
- error: { code: "READ_ONLY", message: "Studio is mounted in read-only mode" }
1071
- },
1072
- 405
1073
- );
1074
- }
1075
- await next();
1076
- });
1077
- }
1078
- const api = new Hono12();
1079
- api.route("/", createHealthRoutes(readOnly));
1080
- api.route("/", createWorkflowRoutes(connMgr));
1081
- api.route("/", executions_default);
1082
- api.route("/", createSessionRoutes(connMgr));
1083
- api.route("/", agents_default);
1084
- api.route("/", tools_default);
1085
- api.route("/", memory_default);
1086
- api.route("/", decisions_default);
1087
- api.route("/", createCostRoutes(costAggregator));
1088
- api.route("/", createEvalRoutes(options.evalLoader));
1089
- api.route("/", createPlaygroundRoutes(connMgr));
1090
- app6.route("/api", api);
1091
- const traceListener = (event) => {
1092
- const traceEvent = event;
1093
- if (traceEvent.executionId) {
1094
- connMgr.broadcastWithWildcard(`trace:${traceEvent.executionId}`, traceEvent);
1095
- }
1096
- costAggregator.onTrace(traceEvent);
1097
- if (traceEvent.type === "await_human") {
1098
- connMgr.broadcast("decisions", traceEvent);
1099
- }
1100
- };
1101
- runtime.on("trace", traceListener);
1102
- if (staticRoot) {
1103
- const indexPath = resolve(staticRoot, "index.html");
1104
- let spaHtml;
1105
- if (!existsSync(indexPath)) {
1106
- console.warn(`[axl-studio] index.html not found at ${indexPath}`);
1107
- } else {
1108
- const rawHtml = readFileSync(indexPath, "utf-8");
1109
- if (basePath) {
1110
- const safeBasePath = JSON.stringify(basePath).replace(/</g, "\\u003c");
1111
- const injected = rawHtml.replace(
1112
- "<head>",
1113
- `<head>
1114
- <base href="${basePath}/">
1115
- <script>window.__AXL_STUDIO_BASE__=${safeBasePath}</script>`
1116
- );
1117
- if (injected === rawHtml) {
1118
- console.warn(
1119
- "[axl-studio] Could not inject basePath into index.html \u2014 <head> tag not found. The SPA may not route correctly."
1120
- );
1121
- }
1122
- spaHtml = injected;
1123
- } else {
1124
- spaHtml = rawHtml;
1125
- }
1126
- }
1127
- const staticHandler = serveStatic({
1128
- root: staticRoot,
1129
- rewriteRequestPath: basePath ? (path) => path.startsWith(basePath) ? path.slice(basePath.length) || "/" : path : void 0
1130
- });
1131
- app6.use("/*", async (c, next) => {
1132
- const reqPath = c.req.path;
1133
- const resolved = basePath && reqPath.startsWith(basePath) ? reqPath.slice(basePath.length) || "/" : reqPath;
1134
- if (resolved === "/" || resolved === "/index.html" || resolved === "/ws") {
1135
- return next();
1136
- }
1137
- return staticHandler(c, next);
1138
- });
1139
- if (spaHtml) {
1140
- app6.get("*", async (c, next) => {
1141
- const resolved = basePath && c.req.path.startsWith(basePath) ? c.req.path.slice(basePath.length) || "/" : c.req.path;
1142
- if (resolved === "/ws") return next();
1143
- return c.html(spaHtml);
1144
- });
1145
- }
1146
- }
1147
- return {
1148
- app: app6,
1149
- connMgr,
1150
- costAggregator,
1151
- /** Create WS handlers. Call before registering static/SPA routes are reached. */
1152
- createWsHandlers: () => createWsHandlers(connMgr),
1153
- traceListener
1154
- };
1155
- }
1156
-
1157
- export {
1158
- ConnectionManager,
1159
- handleWsMessage,
1160
- CostAggregator,
1161
- createServer
1162
- };
1163
- //# sourceMappingURL=chunk-HUKUQDYL.js.map