create-orcha 0.1.6 → 0.3.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,624 +0,0 @@
1
- import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
2
- import { readFile } from "node:fs/promises";
3
- import { dirname, resolve } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import {
6
- orcha,
7
- type AgentContentInput,
8
- type AgentRuntime,
9
- type Execution,
10
- type MessageContent,
11
- type MessageContentInput,
12
- type OrchaClient,
13
- type SessionEvent,
14
- type ToolResult,
15
- } from "orchajs";
16
- import { listTests, runTests } from "orchajs/testing";
17
- import "../orcha/index.js";
18
-
19
- const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
20
- const publicRoot = resolve(projectRoot, "public");
21
- const port = Number.parseInt(process.env.PORT ?? "4310", 10);
22
- const host = "127.0.0.1";
23
- const playgroundConfiguration = JSON.parse(
24
- await readFile(resolve(projectRoot, "playground.json"), "utf8"),
25
- ) as {
26
- agents?: Record<
27
- string,
28
- {
29
- description?: string;
30
- examples?: Array<{
31
- label: string;
32
- content: AgentContentInput;
33
- }>;
34
- }
35
- >;
36
- };
37
-
38
- const server = createServer(async (request, response) => {
39
- try {
40
- await route(request, response);
41
- } catch (error) {
42
- sendJson(response, 500, {
43
- error: error instanceof Error ? error.message : String(error),
44
- });
45
- }
46
- });
47
-
48
- server.listen(port, host, () => {
49
- console.log(`Orcha playground: http://${host}:${port}`);
50
- });
51
-
52
- async function route(
53
- request: IncomingMessage,
54
- response: ServerResponse,
55
- ): Promise<void> {
56
- const method = request.method ?? "GET";
57
- const url = new URL(request.url ?? "/", `http://${host}:${port}`);
58
- const segments = url.pathname
59
- .split("/")
60
- .filter(Boolean)
61
- .map(decodeURIComponent);
62
-
63
- if (method === "GET" && url.pathname === "/api/agents") {
64
- sendJson(response, 200, {
65
- agents: Object.values(orcha.getCompiledBundle().agents).map(
66
- publicAgentManifest,
67
- ),
68
- });
69
- return;
70
- }
71
-
72
- if (
73
- method === "GET" &&
74
- segments.length === 4 &&
75
- segments[0] === "api" &&
76
- segments[1] === "agents" &&
77
- segments[3] === "tests"
78
- ) {
79
- getAgent(segments[2]);
80
- sendJson(response, 200, {
81
- tests: await listTests(orcha, { agent: segments[2] }),
82
- });
83
- return;
84
- }
85
-
86
- if (
87
- method === "POST" &&
88
- segments.length === 4 &&
89
- segments[0] === "api" &&
90
- segments[1] === "agents" &&
91
- segments[3] === "executions"
92
- ) {
93
- await executeAgent(segments[2], request, response);
94
- return;
95
- }
96
-
97
- if (
98
- method === "POST" &&
99
- segments.length === 4 &&
100
- segments[0] === "api" &&
101
- segments[1] === "agents" &&
102
- segments[3] === "tests"
103
- ) {
104
- getAgent(segments[2]);
105
- const test = url.searchParams.get("test") ?? undefined;
106
- sendJson(
107
- response,
108
- 200,
109
- await runTests(orcha, {
110
- agent: segments[2],
111
- ...(test ? { test } : {}),
112
- }),
113
- );
114
- return;
115
- }
116
-
117
- if (
118
- method === "GET" &&
119
- segments.length === 4 &&
120
- segments[0] === "api" &&
121
- segments[1] === "agents" &&
122
- segments[3] === "sessions"
123
- ) {
124
- const agent = getAgent(segments[2]);
125
- sendJson(response, 200, await agent.list({
126
- page: positiveInteger(url.searchParams.get("page"), 1),
127
- pageSize: positiveInteger(url.searchParams.get("pageSize"), 50),
128
- }));
129
- return;
130
- }
131
-
132
- if (
133
- method === "POST" &&
134
- segments.length === 6 &&
135
- segments[0] === "api" &&
136
- segments[1] === "agents" &&
137
- segments[3] === "sessions" &&
138
- segments[5] === "pause"
139
- ) {
140
- const agent = getAgent(segments[2]);
141
- sendJson(response, 200, await agent.pause(segments[4]));
142
- return;
143
- }
144
-
145
- if (
146
- method === "GET" &&
147
- segments.length >= 5 &&
148
- segments[0] === "api" &&
149
- segments[1] === "agents" &&
150
- segments[3] === "children"
151
- ) {
152
- if (segments.length === 6 && segments[5] === "history") {
153
- sendJson(response, 200, await getAgent(segments[2]).subagentHistory(
154
- segments[4],
155
- {
156
- page: positiveInteger(url.searchParams.get("page"), 1),
157
- pageSize: positiveInteger(url.searchParams.get("pageSize"), 100),
158
- },
159
- ));
160
- return;
161
- }
162
- }
163
-
164
- if (
165
- method === "GET" &&
166
- segments.length >= 5 &&
167
- segments[0] === "api" &&
168
- segments[1] === "agents" &&
169
- segments[3] === "sessions"
170
- ) {
171
- const agent = getAgent(segments[2]);
172
- const sessionId = segments[4];
173
- if (segments.length === 5) {
174
- sendJson(response, 200, await agent.get(sessionId));
175
- return;
176
- }
177
- if (segments.length === 6 && segments[5] === "history") {
178
- sendJson(response, 200, await agent.history(sessionId, {
179
- page: positiveInteger(url.searchParams.get("page"), 1),
180
- pageSize: positiveInteger(url.searchParams.get("pageSize"), 100),
181
- }));
182
- return;
183
- }
184
- if (segments.length === 6 && segments[5] === "events") {
185
- sendJson(response, 200, {
186
- events: await readAllSessionEvents(agent, sessionId),
187
- });
188
- return;
189
- }
190
- if (segments.length === 6 && segments[5] === "children") {
191
- sendJson(response, 200, await childSessionSnapshots(agent, sessionId));
192
- return;
193
- }
194
- }
195
-
196
- if (method === "GET") {
197
- const asset = staticAsset(url.pathname);
198
- if (asset) {
199
- const contents = await readFile(resolve(publicRoot, asset.file));
200
- response.writeHead(200, {
201
- "content-type": asset.contentType,
202
- "cache-control": "no-store",
203
- });
204
- response.end(contents);
205
- return;
206
- }
207
- }
208
-
209
- sendJson(response, 404, { error: "Not found." });
210
- }
211
-
212
- async function childSessionSnapshots(
213
- agent: AgentRuntime,
214
- parentSessionId: string,
215
- ) {
216
- const history = await readAllSessionHistory(agent, parentSessionId);
217
- const childSessionIds = [
218
- ...new Set(
219
- history.items.flatMap((item) =>
220
- item.type === "subagent" && item.childSessionId
221
- ? [item.childSessionId]
222
- : [],
223
- ),
224
- ),
225
- ];
226
- const items = await Promise.all(
227
- childSessionIds.map(async (childSessionId) => {
228
- const child = await agent.subagentHistory(childSessionId, {
229
- page: 1,
230
- pageSize: 1,
231
- });
232
- const {
233
- items: _items,
234
- page: _page,
235
- pageSize: _pageSize,
236
- total: _total,
237
- hasMore: _hasMore,
238
- ...snapshot
239
- } = child;
240
- return snapshot;
241
- }),
242
- );
243
- return {
244
- items: items.sort((left, right) =>
245
- right.updatedAt.localeCompare(left.updatedAt),
246
- ),
247
- page: 1,
248
- pageSize: items.length,
249
- total: items.length,
250
- hasMore: false,
251
- };
252
- }
253
-
254
- async function executeAgent(
255
- agentName: string,
256
- request: IncomingMessage,
257
- response: ServerResponse,
258
- ): Promise<void> {
259
- const agent = getAgent(agentName);
260
- const body = await readJsonBody(request);
261
- const sessionId = optionalString(body.sessionId);
262
- const clientCapabilities = agent.clientTools.map((tool) => tool.name);
263
- let execution;
264
-
265
- if ("toolResults" in body) {
266
- if (!sessionId) {
267
- throw new Error("sessionId is required with toolResults.");
268
- }
269
- execution = agent.resume(sessionId, {
270
- toolResults: parseToolResults(body.toolResults),
271
- });
272
- } else {
273
- const content = parseContent(body.content);
274
- const name = optionalString(body.name) ?? sessionNameFromContent(content);
275
- execution = sessionId
276
- ? agent.resume(sessionId, { content, clientCapabilities })
277
- : agent.run({
278
- content,
279
- clientCapabilities,
280
- ...(name ? { name } : {}),
281
- });
282
- }
283
-
284
- await streamExecution(execution, response);
285
- }
286
-
287
- async function streamExecution(
288
- execution: Execution,
289
- response: ServerResponse,
290
- ): Promise<void> {
291
- response.writeHead(200, {
292
- "content-type": "application/x-ndjson; charset=utf-8",
293
- "cache-control": "no-store",
294
- connection: "keep-alive",
295
- });
296
-
297
- try {
298
- for await (const snapshot of execution.stream) {
299
- writeEvent(response, { type: "snapshot", snapshot });
300
- }
301
- const result = await execution.result;
302
- writeEvent(response, { type: "result", result });
303
- const evaluations = await execution.evaluations;
304
- writeEvent(response, {
305
- type: "evaluations",
306
- sessionId: result.sessionId,
307
- evaluations,
308
- });
309
- response.end();
310
- } catch (error) {
311
- writeEvent(response, {
312
- type: "error",
313
- error: error instanceof Error ? error.message : String(error),
314
- });
315
- response.end();
316
- }
317
- }
318
-
319
- function getAgent(name: string): AgentRuntime {
320
- const manifest = orcha.getCompiledBundle().agents[name];
321
- const agent = (orcha as OrchaClient)[name] as AgentRuntime | undefined;
322
- if (!manifest || !agent) {
323
- throw new Error(`Unknown agent "${name}".`);
324
- }
325
- return agent;
326
- }
327
-
328
- function publicAgentManifest(
329
- manifest: ReturnType<typeof orcha.getCompiledBundle>["agents"][string],
330
- ) {
331
- return {
332
- name: manifest.key,
333
- displayName: manifest.name,
334
- description: manifest.description,
335
- examples:
336
- playgroundConfiguration.agents?.[manifest.key]?.examples ?? [],
337
- provider: manifest.provider,
338
- model: manifest.model,
339
- region: manifest.region ?? "provider_managed",
340
- maxTokens: manifest.maxTokens,
341
- reasoningLevel: manifest.reasoningLevel,
342
- outputType: manifest.outputType,
343
- outputSchema: manifest.outputSchema,
344
- systemPrompt: manifest.systemPrompt,
345
- actions: Object.values(manifest.actions).map((action) => ({
346
- name: action.name,
347
- description: action.description,
348
- execution: action.execution,
349
- parameters: action.parameters,
350
- outputSchema: action.outputSchema,
351
- permissions: action.permissions,
352
- timeoutMs: action.timeoutMs,
353
- sideEffect: action.sideEffect ?? false,
354
- })),
355
- skills: Object.values(manifest.skills).map((skill) => ({
356
- name: skill.name,
357
- description: skill.description,
358
- triggers: skill.triggers ?? [],
359
- instructions: skill.instructions,
360
- })),
361
- evaluations: Object.values(manifest.evaluations).map((evaluation) => ({
362
- name: evaluation.name,
363
- description: evaluation.description,
364
- instructions: evaluation.instructions ?? evaluation.description,
365
- enabled: evaluation.enabled,
366
- provider: evaluation.provider,
367
- model: evaluation.model,
368
- maxTokens: evaluation.maxTokens,
369
- reasoningLevel: evaluation.reasoningLevel,
370
- metrics: evaluation.metrics,
371
- })),
372
- subagents: Object.entries(manifest.subagents).map(([key, subagent]) => ({
373
- key,
374
- name: subagent.name,
375
- description: subagent.description,
376
- provider: subagent.provider,
377
- model: subagent.model,
378
- })),
379
- };
380
- }
381
-
382
- async function readJsonBody(
383
- request: IncomingMessage,
384
- ): Promise<Record<string, unknown>> {
385
- const chunks: Buffer[] = [];
386
- let size = 0;
387
- for await (const chunk of request) {
388
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
389
- size += buffer.length;
390
- if (size > 1_000_000) {
391
- throw new Error("Request body exceeds 1 MB.");
392
- }
393
- chunks.push(buffer);
394
- }
395
- const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8"));
396
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
397
- throw new Error("Request body must be a JSON object.");
398
- }
399
- return parsed as Record<string, unknown>;
400
- }
401
-
402
- function sendJson(
403
- response: ServerResponse,
404
- status: number,
405
- value: unknown,
406
- ): void {
407
- if (response.headersSent) {
408
- response.end();
409
- return;
410
- }
411
- response.writeHead(status, {
412
- "content-type": "application/json; charset=utf-8",
413
- "cache-control": "no-store",
414
- });
415
- response.end(JSON.stringify(value));
416
- }
417
-
418
- function writeEvent(response: ServerResponse, value: unknown): void {
419
- response.write(`${JSON.stringify(value)}\n`);
420
- }
421
-
422
- function requiredString(value: unknown, name: string): string {
423
- if (typeof value !== "string" || !value.trim()) {
424
- throw new Error(`${name} must be a non-empty string.`);
425
- }
426
- return value.trim();
427
- }
428
-
429
- function parseContent(value: unknown): AgentContentInput {
430
- if (typeof value === "string") {
431
- return requiredString(value, "content");
432
- }
433
- const items = Array.isArray(value) ? value : [value];
434
- if (items.length === 0) {
435
- throw new Error(
436
- "content must be a non-empty string, content item, or content array.",
437
- );
438
- }
439
- const parsed = items.map(parseContentItem);
440
- return Array.isArray(value) ? parsed : parsed[0];
441
- }
442
-
443
- function parseContentItem(item: unknown): MessageContentInput {
444
- if (!isRecord(item)) {
445
- throw new Error("Every content item must be an object.");
446
- }
447
- if (typeof item.filePath === "string") {
448
- return {
449
- filePath: item.filePath,
450
- ...(typeof item.mimeType === "string"
451
- ? { mimeType: item.mimeType }
452
- : {}),
453
- };
454
- }
455
- if (typeof item.url === "string") {
456
- return {
457
- url: item.url,
458
- ...(typeof item.mimeType === "string"
459
- ? { mimeType: item.mimeType }
460
- : {}),
461
- };
462
- }
463
- if (typeof item.type === "string") {
464
- if (item.type === "text" && typeof item.text === "string") {
465
- return { type: "text", text: item.text };
466
- }
467
- if (
468
- isFileContentType(item.type) &&
469
- typeof item.mimeType === "string" &&
470
- typeof item.fileUri === "string"
471
- ) {
472
- return {
473
- type: item.type,
474
- mimeType: item.mimeType,
475
- fileUri: item.fileUri,
476
- };
477
- }
478
- }
479
- throw new Error("Content item has invalid fields.");
480
- }
481
-
482
- function isFileContentType(
483
- value: unknown,
484
- ): value is "image" | "video" | "audio" | "url" {
485
- return (
486
- value === "image" ||
487
- value === "video" ||
488
- value === "audio" ||
489
- value === "url"
490
- );
491
- }
492
-
493
- function optionalString(value: unknown): string | undefined {
494
- return typeof value === "string" && value.trim()
495
- ? value.trim()
496
- : undefined;
497
- }
498
-
499
- function parseToolResults(value: unknown): ToolResult[] {
500
- if (!Array.isArray(value) || value.length === 0) {
501
- throw new Error("toolResults must be a non-empty array.");
502
- }
503
- return value.map((item) => {
504
- if (
505
- !isRecord(item) ||
506
- typeof item.callId !== "string" ||
507
- !("output" in item) ||
508
- (item.isError !== undefined &&
509
- typeof item.isError !== "boolean")
510
- ) {
511
- throw new Error(
512
- "Each tool result requires callId, output, and optional boolean isError.",
513
- );
514
- }
515
- return {
516
- callId: item.callId,
517
- output: item.output,
518
- ...(item.isError === true ? { isError: true } : {}),
519
- };
520
- });
521
- }
522
-
523
- function isRecord(value: unknown): value is Record<string, unknown> {
524
- return (
525
- typeof value === "object" &&
526
- value !== null &&
527
- !Array.isArray(value)
528
- );
529
- }
530
-
531
- function positiveInteger(
532
- value: string | null,
533
- fallback: number,
534
- ): number {
535
- const parsed = value ? Number.parseInt(value, 10) : fallback;
536
- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
537
- }
538
-
539
- async function readAllSessionEvents(
540
- agent: AgentRuntime,
541
- sessionId: string,
542
- ): Promise<Awaited<ReturnType<AgentRuntime["events"]>>["events"]> {
543
- const pages: SessionEvent[][] = [];
544
- let page = 1;
545
- let hasMore = true;
546
- let throughSequence: number | undefined;
547
- while (hasMore) {
548
- const result = await agent.events(sessionId, {
549
- page,
550
- pageSize: 100,
551
- ...(throughSequence ? { throughSequence } : {}),
552
- });
553
- throughSequence = result.throughSequence;
554
- pages.unshift(result.events);
555
- hasMore = result.hasMore;
556
- page += 1;
557
- }
558
- return pages.flat();
559
- }
560
-
561
- async function readAllSessionHistory(
562
- agent: AgentRuntime,
563
- sessionId: string,
564
- ) {
565
- const pages = [];
566
- let page = 1;
567
- let hasMore = true;
568
- let latest;
569
- while (hasMore) {
570
- latest = await agent.history(sessionId, {
571
- page,
572
- pageSize: 100,
573
- });
574
- pages.unshift(latest.items);
575
- hasMore = latest.hasMore;
576
- page += 1;
577
- }
578
- if (!latest) {
579
- throw new Error(`Session "${sessionId}" has no history.`);
580
- }
581
- const items = pages.flat();
582
- return {
583
- ...latest,
584
- items,
585
- page: 1,
586
- pageSize: items.length,
587
- total: items.length,
588
- hasMore: false,
589
- };
590
- }
591
-
592
- function sessionNameFromContent(content: AgentContentInput): string {
593
- const text = typeof content === "string"
594
- ? content
595
- : (Array.isArray(content) ? content : [content]).find(
596
- (item): item is Extract<MessageContent, { type: "text" }> =>
597
- "type" in item && item.type === "text",
598
- )?.text ?? "Untitled session";
599
- const normalized = text.replace(/\s+/g, " ").trim();
600
- return normalized.length > 64
601
- ? `${normalized.slice(0, 61)}…`
602
- : normalized;
603
- }
604
-
605
- function staticAsset(
606
- pathname: string,
607
- ): { file: string; contentType: string } | undefined {
608
- const assets: Record<string, { file: string; contentType: string }> = {
609
- "/": { file: "index.html", contentType: "text/html; charset=utf-8" },
610
- "/app.js": {
611
- file: "app.js",
612
- contentType: "text/javascript; charset=utf-8",
613
- },
614
- "/styles.css": {
615
- file: "styles.css",
616
- contentType: "text/css; charset=utf-8",
617
- },
618
- "/orcha-logo.svg": {
619
- file: "orcha-logo.svg",
620
- contentType: "image/svg+xml",
621
- },
622
- };
623
- return assets[pathname];
624
- }