@axlsdk/studio 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs ADDED
@@ -0,0 +1,880 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli.ts
27
+ var import_node_path = require("path");
28
+ var import_node_fs = require("fs");
29
+ var import_node_server = require("@hono/node-server");
30
+ var import_node_ws = require("@hono/node-ws");
31
+
32
+ // src/server/index.ts
33
+ var import_hono12 = require("hono");
34
+ var import_cors = require("hono/cors");
35
+ var import_serve_static = require("@hono/node-server/serve-static");
36
+
37
+ // src/server/middleware/error-handler.ts
38
+ async function errorHandler(c, next) {
39
+ try {
40
+ await next();
41
+ } catch (err) {
42
+ const message = err instanceof Error ? err.message : String(err);
43
+ const code = err.code ?? "INTERNAL_ERROR";
44
+ let status = 500;
45
+ if ("status" in err) {
46
+ const errStatus = err.status;
47
+ if (typeof errStatus === "number" && errStatus >= 400 && errStatus < 600) {
48
+ status = errStatus;
49
+ }
50
+ } else if (code === "NOT_FOUND" || message.includes("not found") || message.includes("not registered")) {
51
+ status = 404;
52
+ } else if (code === "VALIDATION_ERROR" || message.includes("Expected") || message.includes("invalid")) {
53
+ status = 400;
54
+ }
55
+ const body = {
56
+ ok: false,
57
+ error: { code, message }
58
+ };
59
+ return c.json(body, status);
60
+ }
61
+ }
62
+
63
+ // src/server/ws/connection-manager.ts
64
+ var ConnectionManager = class {
65
+ /** channel -> set of WS connections */
66
+ channels = /* @__PURE__ */ new Map();
67
+ /** ws -> set of subscribed channels (for cleanup) */
68
+ connections = /* @__PURE__ */ new Map();
69
+ /** Register a new WS connection. */
70
+ add(ws) {
71
+ this.connections.set(ws, /* @__PURE__ */ new Set());
72
+ }
73
+ /** Remove a WS connection and all its subscriptions. */
74
+ remove(ws) {
75
+ const channels = this.connections.get(ws);
76
+ if (channels) {
77
+ for (const ch of channels) {
78
+ this.channels.get(ch)?.delete(ws);
79
+ if (this.channels.get(ch)?.size === 0) {
80
+ this.channels.delete(ch);
81
+ }
82
+ }
83
+ }
84
+ this.connections.delete(ws);
85
+ }
86
+ /** Subscribe a connection to a channel. */
87
+ subscribe(ws, channel) {
88
+ let subs = this.channels.get(channel);
89
+ if (!subs) {
90
+ subs = /* @__PURE__ */ new Set();
91
+ this.channels.set(channel, subs);
92
+ }
93
+ subs.add(ws);
94
+ this.connections.get(ws)?.add(channel);
95
+ }
96
+ /** Unsubscribe a connection from a channel. */
97
+ unsubscribe(ws, channel) {
98
+ this.channels.get(channel)?.delete(ws);
99
+ if (this.channels.get(channel)?.size === 0) {
100
+ this.channels.delete(channel);
101
+ }
102
+ this.connections.get(ws)?.delete(channel);
103
+ }
104
+ /** Broadcast data to all subscribers of a channel. */
105
+ broadcast(channel, data) {
106
+ const subs = this.channels.get(channel);
107
+ if (!subs || subs.size === 0) return;
108
+ const msg = JSON.stringify({ type: "event", channel, data });
109
+ for (const ws of [...subs]) {
110
+ try {
111
+ ws.send(msg);
112
+ } catch {
113
+ this.remove(ws);
114
+ }
115
+ }
116
+ }
117
+ /** Broadcast to channel and all wildcard subscribers (e.g., trace:* matches trace:abc). */
118
+ broadcastWithWildcard(channel, data) {
119
+ this.broadcast(channel, data);
120
+ const colonIdx = channel.indexOf(":");
121
+ if (colonIdx > 0) {
122
+ const wildcardChannel = channel.substring(0, colonIdx) + ":*";
123
+ this.broadcast(wildcardChannel, data);
124
+ }
125
+ }
126
+ /** Get the number of active connections. */
127
+ get connectionCount() {
128
+ return this.connections.size;
129
+ }
130
+ /** Check if any connections are subscribed to a channel. */
131
+ hasSubscribers(channel) {
132
+ return (this.channels.get(channel)?.size ?? 0) > 0;
133
+ }
134
+ };
135
+
136
+ // src/server/ws/handler.ts
137
+ function createWsHandlers(connMgr) {
138
+ return {
139
+ onOpen(_event, ws) {
140
+ connMgr.add(ws);
141
+ },
142
+ onMessage(event, ws) {
143
+ let msg;
144
+ try {
145
+ msg = JSON.parse(String(event.data));
146
+ } catch {
147
+ const err = { type: "error", message: "Invalid JSON" };
148
+ ws.send(JSON.stringify(err));
149
+ return;
150
+ }
151
+ switch (msg.type) {
152
+ case "subscribe": {
153
+ connMgr.subscribe(ws, msg.channel);
154
+ const reply = { type: "subscribed", channel: msg.channel };
155
+ ws.send(JSON.stringify(reply));
156
+ break;
157
+ }
158
+ case "unsubscribe": {
159
+ connMgr.unsubscribe(ws, msg.channel);
160
+ const reply = { type: "unsubscribed", channel: msg.channel };
161
+ ws.send(JSON.stringify(reply));
162
+ break;
163
+ }
164
+ case "ping": {
165
+ const reply = { type: "pong" };
166
+ ws.send(JSON.stringify(reply));
167
+ break;
168
+ }
169
+ default: {
170
+ const err = { type: "error", message: `Unknown message type` };
171
+ ws.send(JSON.stringify(err));
172
+ }
173
+ }
174
+ },
175
+ onClose(_event, ws) {
176
+ connMgr.remove(ws);
177
+ },
178
+ onError(_event, ws) {
179
+ connMgr.remove(ws);
180
+ }
181
+ };
182
+ }
183
+
184
+ // src/server/cost-aggregator.ts
185
+ var CostAggregator = class {
186
+ constructor(connMgr) {
187
+ this.connMgr = connMgr;
188
+ }
189
+ data = {
190
+ totalCost: 0,
191
+ totalTokens: { input: 0, output: 0, reasoning: 0 },
192
+ byAgent: {},
193
+ byModel: {},
194
+ byWorkflow: {}
195
+ };
196
+ /** Process a trace event and update cost data. */
197
+ onTrace(event) {
198
+ if (!event.cost && !event.tokens) return;
199
+ const cost = event.cost ?? 0;
200
+ const tokens = event.tokens ?? {};
201
+ this.data.totalCost += cost;
202
+ this.data.totalTokens.input += tokens.input ?? 0;
203
+ this.data.totalTokens.output += tokens.output ?? 0;
204
+ this.data.totalTokens.reasoning += tokens.reasoning ?? 0;
205
+ if (event.agent) {
206
+ const entry = this.data.byAgent[event.agent] ?? { cost: 0, calls: 0 };
207
+ entry.cost += cost;
208
+ entry.calls += 1;
209
+ this.data.byAgent[event.agent] = entry;
210
+ }
211
+ if (event.model) {
212
+ const entry = this.data.byModel[event.model] ?? {
213
+ cost: 0,
214
+ calls: 0,
215
+ tokens: { input: 0, output: 0 }
216
+ };
217
+ entry.cost += cost;
218
+ entry.calls += 1;
219
+ entry.tokens.input += tokens.input ?? 0;
220
+ entry.tokens.output += tokens.output ?? 0;
221
+ this.data.byModel[event.model] = entry;
222
+ }
223
+ if (event.workflow) {
224
+ const entry = this.data.byWorkflow[event.workflow] ?? { cost: 0, executions: 0 };
225
+ entry.cost += cost;
226
+ if (event.type === "workflow_start") entry.executions += 1;
227
+ this.data.byWorkflow[event.workflow] = entry;
228
+ }
229
+ this.connMgr.broadcast("costs", this.data);
230
+ }
231
+ /** Get current aggregated cost data. */
232
+ getData() {
233
+ return this.data;
234
+ }
235
+ /** Reset all accumulated data. */
236
+ reset() {
237
+ this.data = {
238
+ totalCost: 0,
239
+ totalTokens: { input: 0, output: 0, reasoning: 0 },
240
+ byAgent: {},
241
+ byModel: {},
242
+ byWorkflow: {}
243
+ };
244
+ }
245
+ };
246
+
247
+ // src/server/routes/health.ts
248
+ var import_hono = require("hono");
249
+ var app = new import_hono.Hono();
250
+ app.get("/health", (c) => {
251
+ const runtime = c.get("runtime");
252
+ return c.json({
253
+ ok: true,
254
+ data: {
255
+ status: "healthy",
256
+ workflows: runtime.getWorkflowNames().length,
257
+ agents: runtime.getAgents().length,
258
+ tools: runtime.getTools().length
259
+ }
260
+ });
261
+ });
262
+ var health_default = app;
263
+
264
+ // src/server/routes/workflows.ts
265
+ var import_hono2 = require("hono");
266
+ var import_axl = require("@axlsdk/axl");
267
+ function createWorkflowRoutes(connMgr) {
268
+ const app8 = new import_hono2.Hono();
269
+ app8.get("/workflows", (c) => {
270
+ const runtime = c.get("runtime");
271
+ const workflows = runtime.getWorkflows().map((w) => ({
272
+ name: w.name,
273
+ hasInputSchema: !!w.inputSchema,
274
+ hasOutputSchema: !!w.outputSchema
275
+ }));
276
+ return c.json({ ok: true, data: workflows });
277
+ });
278
+ app8.get("/workflows/:name", (c) => {
279
+ const runtime = c.get("runtime");
280
+ const name = c.req.param("name");
281
+ const workflow = runtime.getWorkflow(name);
282
+ if (!workflow) {
283
+ return c.json(
284
+ { ok: false, error: { code: "NOT_FOUND", message: `Workflow "${name}" not found` } },
285
+ 404
286
+ );
287
+ }
288
+ return c.json({
289
+ ok: true,
290
+ data: {
291
+ name: workflow.name,
292
+ inputSchema: workflow.inputSchema ? (0, import_axl.zodToJsonSchema)(workflow.inputSchema) : null,
293
+ outputSchema: workflow.outputSchema ? (0, import_axl.zodToJsonSchema)(workflow.outputSchema) : null
294
+ }
295
+ });
296
+ });
297
+ app8.post("/workflows/:name/execute", async (c) => {
298
+ const runtime = c.get("runtime");
299
+ const name = c.req.param("name");
300
+ const workflow = runtime.getWorkflow(name);
301
+ if (!workflow) {
302
+ return c.json(
303
+ { ok: false, error: { code: "NOT_FOUND", message: `Workflow "${name}" not found` } },
304
+ 404
305
+ );
306
+ }
307
+ const body = await c.req.json();
308
+ if (body.stream) {
309
+ const stream = runtime.stream(name, body.input ?? {}, { metadata: body.metadata });
310
+ const executionId = `stream-${Date.now()}`;
311
+ (async () => {
312
+ try {
313
+ for await (const event of stream) {
314
+ connMgr.broadcastWithWildcard(`execution:${executionId}`, event);
315
+ }
316
+ } catch (err) {
317
+ connMgr.broadcastWithWildcard(`execution:${executionId}`, {
318
+ type: "error",
319
+ message: err instanceof Error ? err.message : "Stream error"
320
+ });
321
+ }
322
+ })();
323
+ return c.json({ ok: true, data: { executionId, streaming: true } });
324
+ }
325
+ const result = await runtime.execute(name, body.input ?? {}, { metadata: body.metadata });
326
+ return c.json({ ok: true, data: { result } });
327
+ });
328
+ return app8;
329
+ }
330
+
331
+ // src/server/routes/executions.ts
332
+ var import_hono3 = require("hono");
333
+ var app2 = new import_hono3.Hono();
334
+ app2.get("/executions", (c) => {
335
+ const runtime = c.get("runtime");
336
+ const executions = runtime.getExecutions();
337
+ return c.json({ ok: true, data: executions });
338
+ });
339
+ app2.get("/executions/:id", async (c) => {
340
+ const runtime = c.get("runtime");
341
+ const id = c.req.param("id");
342
+ const execution = await runtime.getExecution(id);
343
+ if (!execution) {
344
+ return c.json(
345
+ { ok: false, error: { code: "NOT_FOUND", message: `Execution "${id}" not found` } },
346
+ 404
347
+ );
348
+ }
349
+ return c.json({ ok: true, data: execution });
350
+ });
351
+ app2.post("/executions/:id/abort", (c) => {
352
+ const runtime = c.get("runtime");
353
+ const id = c.req.param("id");
354
+ runtime.abort(id);
355
+ return c.json({ ok: true, data: { aborted: true } });
356
+ });
357
+ var executions_default = app2;
358
+
359
+ // src/server/routes/sessions.ts
360
+ var import_hono4 = require("hono");
361
+ function createSessionRoutes(connMgr) {
362
+ const app8 = new import_hono4.Hono();
363
+ app8.get("/sessions", async (c) => {
364
+ const runtime = c.get("runtime");
365
+ const store = runtime.getStateStore();
366
+ if (!store.listSessions) {
367
+ return c.json({ ok: true, data: [] });
368
+ }
369
+ const ids = await store.listSessions();
370
+ const sessions = [];
371
+ for (const id of ids) {
372
+ const history = await store.getSession(id);
373
+ sessions.push({ id, messageCount: history.length });
374
+ }
375
+ return c.json({ ok: true, data: sessions });
376
+ });
377
+ app8.get("/sessions/:id", async (c) => {
378
+ const runtime = c.get("runtime");
379
+ const store = runtime.getStateStore();
380
+ const id = c.req.param("id");
381
+ const history = await store.getSession(id);
382
+ const handoffHistory = await store.getSessionMeta(id, "handoffHistory");
383
+ return c.json({ ok: true, data: { id, history, handoffHistory: handoffHistory ?? [] } });
384
+ });
385
+ app8.post("/sessions/:id/send", async (c) => {
386
+ const runtime = c.get("runtime");
387
+ const id = c.req.param("id");
388
+ const body = await c.req.json();
389
+ const session = runtime.session(id);
390
+ const result = await session.send(body.workflow, body.message);
391
+ return c.json({ ok: true, data: { result } });
392
+ });
393
+ app8.post("/sessions/:id/stream", async (c) => {
394
+ const runtime = c.get("runtime");
395
+ const id = c.req.param("id");
396
+ const body = await c.req.json();
397
+ const session = runtime.session(id);
398
+ const stream = await session.stream(body.workflow, body.message);
399
+ const executionId = `session-${id}-${Date.now()}`;
400
+ (async () => {
401
+ try {
402
+ for await (const event of stream) {
403
+ connMgr.broadcastWithWildcard(`execution:${executionId}`, event);
404
+ }
405
+ } catch (err) {
406
+ connMgr.broadcastWithWildcard(`execution:${executionId}`, {
407
+ type: "error",
408
+ message: err instanceof Error ? err.message : "Stream error"
409
+ });
410
+ }
411
+ })();
412
+ return c.json({ ok: true, data: { executionId, streaming: true } });
413
+ });
414
+ app8.delete("/sessions/:id", async (c) => {
415
+ const runtime = c.get("runtime");
416
+ const store = runtime.getStateStore();
417
+ const id = c.req.param("id");
418
+ await store.deleteSession(id);
419
+ return c.json({ ok: true, data: { deleted: true } });
420
+ });
421
+ return app8;
422
+ }
423
+
424
+ // src/server/routes/agents.ts
425
+ var import_hono5 = require("hono");
426
+ var import_axl2 = require("@axlsdk/axl");
427
+ var app3 = new import_hono5.Hono();
428
+ app3.get("/agents", (c) => {
429
+ const runtime = c.get("runtime");
430
+ const agents = runtime.getAgents().map((a) => ({
431
+ name: a._name,
432
+ model: a.resolveModel(),
433
+ system: a.resolveSystem(),
434
+ tools: a._config.tools?.map((t) => t.name) ?? [],
435
+ handoffs: a._config.handoffs?.map((h) => h.agent._name) ?? [],
436
+ maxTurns: a._config.maxTurns,
437
+ temperature: a._config.temperature
438
+ }));
439
+ return c.json({ ok: true, data: agents });
440
+ });
441
+ app3.get("/agents/:name", (c) => {
442
+ const runtime = c.get("runtime");
443
+ const name = c.req.param("name");
444
+ const agent = runtime.getAgent(name);
445
+ if (!agent) {
446
+ return c.json(
447
+ { ok: false, error: { code: "NOT_FOUND", message: `Agent "${name}" not found` } },
448
+ 404
449
+ );
450
+ }
451
+ const cfg = agent._config;
452
+ return c.json({
453
+ ok: true,
454
+ data: {
455
+ name: agent._name,
456
+ model: agent.resolveModel(),
457
+ system: agent.resolveSystem(),
458
+ tools: cfg.tools?.map((t) => ({
459
+ name: t.name,
460
+ description: t.description,
461
+ inputSchema: (0, import_axl2.zodToJsonSchema)(t.inputSchema)
462
+ })) ?? [],
463
+ handoffs: cfg.handoffs?.map((h) => ({
464
+ agent: h.agent._name,
465
+ description: h.description,
466
+ mode: h.mode ?? "oneway"
467
+ })) ?? [],
468
+ maxTurns: cfg.maxTurns,
469
+ temperature: cfg.temperature,
470
+ timeout: cfg.timeout,
471
+ maxContext: cfg.maxContext,
472
+ version: cfg.version,
473
+ mcp: cfg.mcp,
474
+ mcpTools: cfg.mcpTools,
475
+ hasGuardrails: !!cfg.guardrails,
476
+ guardrails: cfg.guardrails ? {
477
+ hasInput: !!cfg.guardrails.input,
478
+ hasOutput: !!cfg.guardrails.output,
479
+ onBlock: cfg.guardrails.onBlock ?? "throw",
480
+ maxRetries: cfg.guardrails.maxRetries
481
+ } : null
482
+ }
483
+ });
484
+ });
485
+ var agents_default = app3;
486
+
487
+ // src/server/routes/tools.ts
488
+ var import_hono6 = require("hono");
489
+ var import_axl3 = require("@axlsdk/axl");
490
+ var app4 = new import_hono6.Hono();
491
+ app4.get("/tools", (c) => {
492
+ const runtime = c.get("runtime");
493
+ const tools = runtime.getTools().map((t) => ({
494
+ name: t.name,
495
+ description: t.description,
496
+ inputSchema: t.inputSchema ? (0, import_axl3.zodToJsonSchema)(t.inputSchema) : {},
497
+ sensitive: t.sensitive ?? false,
498
+ requireApproval: t.requireApproval ?? false
499
+ }));
500
+ return c.json({ ok: true, data: tools });
501
+ });
502
+ app4.get("/tools/:name", (c) => {
503
+ const runtime = c.get("runtime");
504
+ const name = c.req.param("name");
505
+ const tool = runtime.getTool(name);
506
+ if (!tool) {
507
+ return c.json(
508
+ { ok: false, error: { code: "NOT_FOUND", message: `Tool "${name}" not found` } },
509
+ 404
510
+ );
511
+ }
512
+ return c.json({
513
+ ok: true,
514
+ data: {
515
+ name: tool.name,
516
+ description: tool.description,
517
+ inputSchema: tool.inputSchema ? (0, import_axl3.zodToJsonSchema)(tool.inputSchema) : {},
518
+ sensitive: tool.sensitive,
519
+ requireApproval: tool.requireApproval,
520
+ retry: tool.retry,
521
+ hasHooks: !!tool.hooks,
522
+ hooks: tool.hooks ? {
523
+ hasBefore: !!tool.hooks.before,
524
+ hasAfter: !!tool.hooks.after
525
+ } : null
526
+ }
527
+ });
528
+ });
529
+ app4.post("/tools/:name/test", async (c) => {
530
+ const runtime = c.get("runtime");
531
+ const name = c.req.param("name");
532
+ const tool = runtime.getTool(name);
533
+ if (!tool) {
534
+ return c.json(
535
+ { ok: false, error: { code: "NOT_FOUND", message: `Tool "${name}" not found` } },
536
+ 404
537
+ );
538
+ }
539
+ const body = await c.req.json();
540
+ const result = await tool._execute(body.input);
541
+ return c.json({ ok: true, data: { result } });
542
+ });
543
+ var tools_default = app4;
544
+
545
+ // src/server/routes/memory.ts
546
+ var import_hono7 = require("hono");
547
+ var app5 = new import_hono7.Hono();
548
+ app5.get("/memory/:scope", async (c) => {
549
+ const runtime = c.get("runtime");
550
+ const store = runtime.getStateStore();
551
+ const scope = c.req.param("scope");
552
+ if (!store.getAllMemory) {
553
+ return c.json({ ok: true, data: [] });
554
+ }
555
+ const entries = await store.getAllMemory(scope);
556
+ return c.json({ ok: true, data: entries });
557
+ });
558
+ app5.get("/memory/:scope/:key", async (c) => {
559
+ const runtime = c.get("runtime");
560
+ const store = runtime.getStateStore();
561
+ const scope = c.req.param("scope");
562
+ const key = c.req.param("key");
563
+ if (!store.getMemory) {
564
+ return c.json(
565
+ { ok: false, error: { code: "NOT_SUPPORTED", message: "Memory not supported" } },
566
+ 501
567
+ );
568
+ }
569
+ const value = await store.getMemory(scope, key);
570
+ if (value === null) {
571
+ return c.json(
572
+ { ok: false, error: { code: "NOT_FOUND", message: `Memory "${scope}/${key}" not found` } },
573
+ 404
574
+ );
575
+ }
576
+ return c.json({ ok: true, data: { key, value } });
577
+ });
578
+ app5.put("/memory/:scope/:key", async (c) => {
579
+ const runtime = c.get("runtime");
580
+ const store = runtime.getStateStore();
581
+ const scope = c.req.param("scope");
582
+ const key = c.req.param("key");
583
+ if (!store.saveMemory) {
584
+ return c.json(
585
+ { ok: false, error: { code: "NOT_SUPPORTED", message: "Memory not supported" } },
586
+ 501
587
+ );
588
+ }
589
+ const body = await c.req.json();
590
+ await store.saveMemory(scope, key, body.value);
591
+ return c.json({ ok: true, data: { saved: true } });
592
+ });
593
+ app5.delete("/memory/:scope/:key", async (c) => {
594
+ const runtime = c.get("runtime");
595
+ const store = runtime.getStateStore();
596
+ const scope = c.req.param("scope");
597
+ const key = c.req.param("key");
598
+ if (!store.deleteMemory) {
599
+ return c.json(
600
+ { ok: false, error: { code: "NOT_SUPPORTED", message: "Memory not supported" } },
601
+ 501
602
+ );
603
+ }
604
+ await store.deleteMemory(scope, key);
605
+ return c.json({ ok: true, data: { deleted: true } });
606
+ });
607
+ app5.post("/memory/search", async (c) => {
608
+ return c.json({
609
+ ok: true,
610
+ data: { results: [], message: "Semantic search requires MemoryManager with vector store" }
611
+ });
612
+ });
613
+ var memory_default = app5;
614
+
615
+ // src/server/routes/decisions.ts
616
+ var import_hono8 = require("hono");
617
+ var app6 = new import_hono8.Hono();
618
+ app6.get("/decisions", async (c) => {
619
+ const runtime = c.get("runtime");
620
+ const decisions = await runtime.getPendingDecisions();
621
+ return c.json({ ok: true, data: decisions });
622
+ });
623
+ app6.post("/decisions/:executionId/resolve", async (c) => {
624
+ const runtime = c.get("runtime");
625
+ const executionId = c.req.param("executionId");
626
+ const body = await c.req.json();
627
+ await runtime.resolveDecision(executionId, body);
628
+ return c.json({ ok: true, data: { resolved: true } });
629
+ });
630
+ var decisions_default = app6;
631
+
632
+ // src/server/routes/costs.ts
633
+ var import_hono9 = require("hono");
634
+ function createCostRoutes(costAggregator) {
635
+ const app8 = new import_hono9.Hono();
636
+ app8.get("/costs", (c) => {
637
+ return c.json({ ok: true, data: costAggregator.getData() });
638
+ });
639
+ app8.post("/costs/reset", (c) => {
640
+ costAggregator.reset();
641
+ return c.json({ ok: true, data: { reset: true } });
642
+ });
643
+ return app8;
644
+ }
645
+
646
+ // src/server/routes/evals.ts
647
+ var import_hono10 = require("hono");
648
+ var app7 = new import_hono10.Hono();
649
+ app7.get("/evals", async (c) => {
650
+ return c.json({ ok: true, data: { message: "Eval discovery requires @axlsdk/eval" } });
651
+ });
652
+ app7.post("/evals/run", async (c) => {
653
+ const runtime = c.get("runtime");
654
+ const body = await c.req.json();
655
+ try {
656
+ const result = await runtime.eval(body);
657
+ return c.json({ ok: true, data: result });
658
+ } catch (err) {
659
+ const message = err instanceof Error ? err.message : String(err);
660
+ return c.json({ ok: false, error: { code: "EVAL_ERROR", message } }, 400);
661
+ }
662
+ });
663
+ app7.post("/evals/compare", async (c) => {
664
+ const runtime = c.get("runtime");
665
+ const body = await c.req.json();
666
+ try {
667
+ const result = await runtime.evalCompare(body.baseline, body.candidate);
668
+ return c.json({ ok: true, data: result });
669
+ } catch (err) {
670
+ const message = err instanceof Error ? err.message : String(err);
671
+ return c.json({ ok: false, error: { code: "EVAL_ERROR", message } }, 400);
672
+ }
673
+ });
674
+ var evals_default = app7;
675
+
676
+ // src/server/routes/playground.ts
677
+ var import_hono11 = require("hono");
678
+ function createPlaygroundRoutes(connMgr) {
679
+ const app8 = new import_hono11.Hono();
680
+ app8.post("/playground/chat", async (c) => {
681
+ const runtime = c.get("runtime");
682
+ const body = await c.req.json();
683
+ const workflowName = body.workflow ?? runtime.getWorkflowNames()[0];
684
+ if (!workflowName) {
685
+ return c.json(
686
+ { ok: false, error: { code: "NO_WORKFLOW", message: "No workflows registered" } },
687
+ 400
688
+ );
689
+ }
690
+ const sessionId = body.sessionId ?? `playground-${Date.now()}`;
691
+ const session = runtime.session(sessionId);
692
+ const stream = await session.stream(workflowName, body.message);
693
+ const executionId = `playground-${sessionId}-${Date.now()}`;
694
+ (async () => {
695
+ try {
696
+ for await (const event of stream) {
697
+ connMgr.broadcastWithWildcard(`execution:${executionId}`, event);
698
+ }
699
+ } catch (err) {
700
+ connMgr.broadcastWithWildcard(`execution:${executionId}`, {
701
+ type: "error",
702
+ message: err instanceof Error ? err.message : "Stream error"
703
+ });
704
+ }
705
+ })();
706
+ return c.json({
707
+ ok: true,
708
+ data: { sessionId, executionId, streaming: true }
709
+ });
710
+ });
711
+ return app8;
712
+ }
713
+
714
+ // src/server/index.ts
715
+ function createServer(options) {
716
+ const { runtime, staticRoot } = options;
717
+ const app8 = new import_hono12.Hono();
718
+ const connMgr = new ConnectionManager();
719
+ const costAggregator = new CostAggregator(connMgr);
720
+ app8.use("*", (0, import_cors.cors)());
721
+ app8.use("*", errorHandler);
722
+ app8.use("*", async (c, next) => {
723
+ c.set("runtime", runtime);
724
+ await next();
725
+ });
726
+ const api = new import_hono12.Hono();
727
+ api.route("/", health_default);
728
+ api.route("/", createWorkflowRoutes(connMgr));
729
+ api.route("/", executions_default);
730
+ api.route("/", createSessionRoutes(connMgr));
731
+ api.route("/", agents_default);
732
+ api.route("/", tools_default);
733
+ api.route("/", memory_default);
734
+ api.route("/", decisions_default);
735
+ api.route("/", createCostRoutes(costAggregator));
736
+ api.route("/", evals_default);
737
+ api.route("/", createPlaygroundRoutes(connMgr));
738
+ app8.route("/api", api);
739
+ runtime.on("trace", (event) => {
740
+ const traceEvent = event;
741
+ if (traceEvent.executionId) {
742
+ connMgr.broadcastWithWildcard(`trace:${traceEvent.executionId}`, traceEvent);
743
+ }
744
+ costAggregator.onTrace(traceEvent);
745
+ if (traceEvent.type === "await_human") {
746
+ connMgr.broadcast("decisions", traceEvent);
747
+ }
748
+ });
749
+ if (staticRoot) {
750
+ app8.use("/*", (0, import_serve_static.serveStatic)({ root: staticRoot }));
751
+ app8.get("*", (0, import_serve_static.serveStatic)({ root: staticRoot, path: "/index.html" }));
752
+ }
753
+ return { app: app8, connMgr, costAggregator, createWsHandlers: () => createWsHandlers(connMgr) };
754
+ }
755
+
756
+ // src/cli.ts
757
+ var import_meta = {};
758
+ function parseArgs(argv) {
759
+ let port = 4400;
760
+ let config = "./axl.config.ts";
761
+ let open = false;
762
+ for (let i = 2; i < argv.length; i++) {
763
+ const arg = argv[i];
764
+ if (arg === "--port" && argv[i + 1]) {
765
+ port = parseInt(argv[i + 1], 10);
766
+ i++;
767
+ } else if (arg === "--config" && argv[i + 1]) {
768
+ config = argv[i + 1];
769
+ i++;
770
+ } else if (arg === "--open") {
771
+ open = true;
772
+ } else if (arg === "--help" || arg === "-h") {
773
+ console.log(`
774
+ Axl Studio \u2014 Local development UI for Axl agents and workflows
775
+
776
+ Usage:
777
+ axl-studio [options]
778
+
779
+ Options:
780
+ --port <number> Server port (default: 4400)
781
+ --config <path> Path to axl.config.ts (default: ./axl.config.ts)
782
+ --open Auto-open browser
783
+ -h, --help Show this help message
784
+ `);
785
+ process.exit(0);
786
+ }
787
+ }
788
+ if (isNaN(port) || port < 1 || port > 65535) {
789
+ console.error(`Invalid port: ${port}. Must be between 1 and 65535.`);
790
+ process.exit(1);
791
+ }
792
+ return { port, config, open };
793
+ }
794
+ async function main() {
795
+ const args = parseArgs(process.argv);
796
+ const configPath = (0, import_node_path.resolve)(process.cwd(), args.config);
797
+ if (!(0, import_node_fs.existsSync)(configPath)) {
798
+ console.error(`Config file not found: ${configPath}`);
799
+ console.error(`Create an axl.config.ts that exports a default AxlRuntime instance.`);
800
+ process.exit(1);
801
+ }
802
+ if (configPath.endsWith(".ts") || configPath.endsWith(".tsx")) {
803
+ try {
804
+ const { register } = await import("tsx/esm/api");
805
+ register();
806
+ } catch {
807
+ }
808
+ }
809
+ console.log(`[axl-studio] Loading config from ${configPath}`);
810
+ let runtime;
811
+ try {
812
+ const mod = await import(configPath);
813
+ runtime = mod.default ?? mod.runtime;
814
+ if (!runtime || typeof runtime.execute !== "function") {
815
+ console.error(`Config must export a default AxlRuntime instance.`);
816
+ console.error(
817
+ `Example:
818
+ import { AxlRuntime } from '@axlsdk/axl';
819
+ export default new AxlRuntime({ ... });`
820
+ );
821
+ process.exit(1);
822
+ }
823
+ } catch (err) {
824
+ console.error(`Failed to load config:`, err);
825
+ process.exit(1);
826
+ }
827
+ const staticRoot = (0, import_node_path.resolve)(import_meta.dirname ?? __dirname, "client");
828
+ const hasStaticAssets = (0, import_node_fs.existsSync)((0, import_node_path.resolve)(staticRoot, "index.html"));
829
+ const { app: app8, createWsHandlers: createWsHandlers2 } = createServer({
830
+ runtime,
831
+ staticRoot: hasStaticAssets ? staticRoot : void 0
832
+ });
833
+ const { injectWebSocket, upgradeWebSocket } = (0, import_node_ws.createNodeWebSocket)({ app: void 0 });
834
+ const wsHandlers = createWsHandlers2();
835
+ app8.get(
836
+ "/ws",
837
+ upgradeWebSocket(() => wsHandlers)
838
+ );
839
+ const server = (0, import_node_server.serve)(
840
+ {
841
+ fetch: app8.fetch,
842
+ port: args.port
843
+ },
844
+ (info) => {
845
+ console.log(`[axl-studio] Server running at http://localhost:${info.port}`);
846
+ console.log(`[axl-studio] Workflows: ${runtime.getWorkflowNames().join(", ") || "(none)"}`);
847
+ console.log(
848
+ `[axl-studio] Agents: ${runtime.getAgents().map((a) => a._name).join(", ") || "(none)"}`
849
+ );
850
+ console.log(
851
+ `[axl-studio] Tools: ${runtime.getTools().map((t) => t.name).join(", ") || "(none)"}`
852
+ );
853
+ if (!hasStaticAssets) {
854
+ console.log(
855
+ `[axl-studio] No pre-built UI found. Run 'pnpm build:client' or use Vite dev server on port 4401.`
856
+ );
857
+ }
858
+ }
859
+ );
860
+ injectWebSocket(server);
861
+ if (args.open) {
862
+ const url = `http://localhost:${args.port}`;
863
+ const { exec } = await import("child_process");
864
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
865
+ exec(`${cmd} ${url}`);
866
+ }
867
+ const shutdown = async () => {
868
+ console.log("\n[axl-studio] Shutting down...");
869
+ await runtime.shutdown().catch(() => {
870
+ });
871
+ process.exit(0);
872
+ };
873
+ process.on("SIGINT", shutdown);
874
+ process.on("SIGTERM", shutdown);
875
+ }
876
+ main().catch((err) => {
877
+ console.error("[axl-studio] Fatal error:", err);
878
+ process.exit(1);
879
+ });
880
+ //# sourceMappingURL=cli.cjs.map