create-orcha 0.1.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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +32 -0
  3. package/bin/create-orcha.js +177 -0
  4. package/package.json +41 -0
  5. package/template/.env.example +2 -0
  6. package/template/AGENTS.md +30 -0
  7. package/template/README.md +50 -0
  8. package/template/orcha/AGENTS.md +913 -0
  9. package/template/orcha/approvalAgent/actions/requestHumanApproval/index.json +25 -0
  10. package/template/orcha/approvalAgent/evaluations/approvalQuality/index.json +22 -0
  11. package/template/orcha/approvalAgent/evaluations/index.js +5 -0
  12. package/template/orcha/approvalAgent/index.json +7 -0
  13. package/template/orcha/approvalAgent/instructions.md +5 -0
  14. package/template/orcha/approvalAgent/skills/index.js +5 -0
  15. package/template/orcha/approvalAgent/skills/purchaseReview/index.json +8 -0
  16. package/template/orcha/approvalAgent/skills/purchaseReview/instructions.md +5 -0
  17. package/template/orcha/approvalAgent/tests/approvedPurchase/index.json +36 -0
  18. package/template/orcha/approvalAgent/tests/index.js +5 -0
  19. package/template/orcha/assistant/evaluations/index.js +5 -0
  20. package/template/orcha/assistant/evaluations/responseQuality/index.json +22 -0
  21. package/template/orcha/assistant/index.json +7 -0
  22. package/template/orcha/assistant/instructions.md +4 -0
  23. package/template/orcha/assistant/skills/index.js +5 -0
  24. package/template/orcha/assistant/skills/technicalExplanation/index.json +8 -0
  25. package/template/orcha/assistant/skills/technicalExplanation/instructions.md +6 -0
  26. package/template/orcha/assistant/tests/explainsIdempotency/index.json +15 -0
  27. package/template/orcha/assistant/tests/index.js +5 -0
  28. package/template/orcha/index.ts +15 -0
  29. package/template/orcha/orderSupport/actions/lookupOrder/index.js +25 -0
  30. package/template/orcha/orderSupport/actions/lookupOrder/index.json +29 -0
  31. package/template/orcha/orderSupport/evaluations/index.js +5 -0
  32. package/template/orcha/orderSupport/evaluations/supportQuality/index.json +22 -0
  33. package/template/orcha/orderSupport/index.json +7 -0
  34. package/template/orcha/orderSupport/instructions.md +5 -0
  35. package/template/orcha/orderSupport/skills/delayedOrderHandling/index.json +8 -0
  36. package/template/orcha/orderSupport/skills/delayedOrderHandling/instructions.md +6 -0
  37. package/template/orcha/orderSupport/skills/index.js +5 -0
  38. package/template/orcha/orderSupport/tests/delayedOrder/index.json +37 -0
  39. package/template/orcha/orderSupport/tests/index.js +5 -0
  40. package/template/package.json +25 -0
  41. package/template/playground.json +49 -0
  42. package/template/public/app.js +1234 -0
  43. package/template/public/index.html +210 -0
  44. package/template/public/orcha-logo.svg +4 -0
  45. package/template/public/styles.css +548 -0
  46. package/template/scripts/build.mjs +20 -0
  47. package/template/src/server.ts +478 -0
  48. package/template/tsconfig.json +12 -0
@@ -0,0 +1,478 @@
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 AgentRuntime,
8
+ type MessageContent,
9
+ type OrchaClient,
10
+ type SessionEvent,
11
+ type ToolResult,
12
+ } from "orchajs";
13
+ import { listTests, runTests } from "orchajs/testing";
14
+ import "../orcha/index.js";
15
+
16
+ const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
17
+ const publicRoot = resolve(projectRoot, "public");
18
+ const port = Number.parseInt(process.env.PORT ?? "4310", 10);
19
+ const host = "127.0.0.1";
20
+ const playgroundConfiguration = JSON.parse(
21
+ await readFile(resolve(projectRoot, "playground.json"), "utf8"),
22
+ ) as {
23
+ agents?: Record<
24
+ string,
25
+ {
26
+ description?: string;
27
+ examples?: Array<{
28
+ label: string;
29
+ content: string | MessageContent[];
30
+ }>;
31
+ }
32
+ >;
33
+ };
34
+
35
+ const server = createServer(async (request, response) => {
36
+ try {
37
+ await route(request, response);
38
+ } catch (error) {
39
+ sendJson(response, 500, {
40
+ error: error instanceof Error ? error.message : String(error),
41
+ });
42
+ }
43
+ });
44
+
45
+ server.listen(port, host, () => {
46
+ console.log(`Orcha playground: http://${host}:${port}`);
47
+ });
48
+
49
+ async function route(
50
+ request: IncomingMessage,
51
+ response: ServerResponse,
52
+ ): Promise<void> {
53
+ const method = request.method ?? "GET";
54
+ const url = new URL(request.url ?? "/", `http://${host}:${port}`);
55
+ const segments = url.pathname
56
+ .split("/")
57
+ .filter(Boolean)
58
+ .map(decodeURIComponent);
59
+
60
+ if (method === "GET" && url.pathname === "/api/agents") {
61
+ sendJson(response, 200, {
62
+ agents: Object.values(orcha.getCompiledBundle().agents).map(
63
+ publicAgentManifest,
64
+ ),
65
+ });
66
+ return;
67
+ }
68
+
69
+ if (
70
+ method === "GET" &&
71
+ segments.length === 4 &&
72
+ segments[0] === "api" &&
73
+ segments[1] === "agents" &&
74
+ segments[3] === "tests"
75
+ ) {
76
+ getAgent(segments[2]);
77
+ sendJson(response, 200, {
78
+ tests: await listTests(orcha, { agent: segments[2] }),
79
+ });
80
+ return;
81
+ }
82
+
83
+ if (
84
+ method === "POST" &&
85
+ segments.length === 4 &&
86
+ segments[0] === "api" &&
87
+ segments[1] === "agents" &&
88
+ segments[3] === "executions"
89
+ ) {
90
+ await executeAgent(segments[2], request, response);
91
+ return;
92
+ }
93
+
94
+ if (
95
+ method === "POST" &&
96
+ segments.length === 4 &&
97
+ segments[0] === "api" &&
98
+ segments[1] === "agents" &&
99
+ segments[3] === "tests"
100
+ ) {
101
+ getAgent(segments[2]);
102
+ const test = url.searchParams.get("test") ?? undefined;
103
+ sendJson(
104
+ response,
105
+ 200,
106
+ await runTests(orcha, {
107
+ agent: segments[2],
108
+ ...(test ? { test } : {}),
109
+ }),
110
+ );
111
+ return;
112
+ }
113
+
114
+ if (
115
+ method === "GET" &&
116
+ segments.length === 4 &&
117
+ segments[0] === "api" &&
118
+ segments[1] === "agents" &&
119
+ segments[3] === "sessions"
120
+ ) {
121
+ const agent = getAgent(segments[2]);
122
+ sendJson(response, 200, await agent.list({
123
+ page: positiveInteger(url.searchParams.get("page"), 1),
124
+ pageSize: positiveInteger(url.searchParams.get("pageSize"), 50),
125
+ }));
126
+ return;
127
+ }
128
+
129
+ if (
130
+ method === "GET" &&
131
+ segments.length >= 5 &&
132
+ segments[0] === "api" &&
133
+ segments[1] === "agents" &&
134
+ segments[3] === "sessions"
135
+ ) {
136
+ const agent = getAgent(segments[2]);
137
+ const sessionId = segments[4];
138
+ if (segments.length === 5) {
139
+ sendJson(response, 200, await agent.get(sessionId));
140
+ return;
141
+ }
142
+ if (segments.length === 6 && segments[5] === "history") {
143
+ sendJson(response, 200, await agent.history(sessionId, {
144
+ page: positiveInteger(url.searchParams.get("page"), 1),
145
+ pageSize: positiveInteger(url.searchParams.get("pageSize"), 100),
146
+ }));
147
+ return;
148
+ }
149
+ if (segments.length === 6 && segments[5] === "events") {
150
+ sendJson(response, 200, {
151
+ events: await readAllSessionEvents(agent, sessionId),
152
+ });
153
+ return;
154
+ }
155
+ }
156
+
157
+ if (method === "GET") {
158
+ const asset = staticAsset(url.pathname);
159
+ if (asset) {
160
+ const contents = await readFile(resolve(publicRoot, asset.file));
161
+ response.writeHead(200, {
162
+ "content-type": asset.contentType,
163
+ "cache-control": "no-store",
164
+ });
165
+ response.end(contents);
166
+ return;
167
+ }
168
+ }
169
+
170
+ sendJson(response, 404, { error: "Not found." });
171
+ }
172
+
173
+ async function executeAgent(
174
+ agentName: string,
175
+ request: IncomingMessage,
176
+ response: ServerResponse,
177
+ ): Promise<void> {
178
+ const agent = getAgent(agentName);
179
+ const body = await readJsonBody(request);
180
+ const sessionId = optionalString(body.sessionId);
181
+ const clientCapabilities = agent.clientTools.map((tool) => tool.name);
182
+ let execution;
183
+
184
+ if ("toolResults" in body) {
185
+ if (!sessionId) {
186
+ throw new Error("sessionId is required with toolResults.");
187
+ }
188
+ execution = agent.resume(sessionId, {
189
+ toolResults: parseToolResults(body.toolResults),
190
+ });
191
+ } else {
192
+ const content = parseContent(body.content);
193
+ const name = optionalString(body.name) ?? sessionNameFromContent(content);
194
+ execution = sessionId
195
+ ? agent.resume(sessionId, { content, clientCapabilities })
196
+ : agent.run({
197
+ content,
198
+ clientCapabilities,
199
+ ...(name ? { name } : {}),
200
+ });
201
+ }
202
+
203
+ response.writeHead(200, {
204
+ "content-type": "application/x-ndjson; charset=utf-8",
205
+ "cache-control": "no-store",
206
+ connection: "keep-alive",
207
+ });
208
+
209
+ try {
210
+ for await (const snapshot of execution.stream) {
211
+ writeEvent(response, { type: "snapshot", snapshot });
212
+ }
213
+ const result = await execution.result;
214
+ writeEvent(response, { type: "result", result });
215
+ const evaluations = await execution.evaluations;
216
+ writeEvent(response, {
217
+ type: "evaluations",
218
+ sessionId: result.sessionId,
219
+ evaluations,
220
+ });
221
+ response.end();
222
+ } catch (error) {
223
+ writeEvent(response, {
224
+ type: "error",
225
+ error: error instanceof Error ? error.message : String(error),
226
+ });
227
+ response.end();
228
+ }
229
+ }
230
+
231
+ function getAgent(name: string): AgentRuntime {
232
+ const manifest = orcha.getCompiledBundle().agents[name];
233
+ const agent = (orcha as OrchaClient)[name] as AgentRuntime | undefined;
234
+ if (!manifest || !agent) {
235
+ throw new Error(`Unknown agent "${name}".`);
236
+ }
237
+ return agent;
238
+ }
239
+
240
+ function publicAgentManifest(
241
+ manifest: ReturnType<typeof orcha.getCompiledBundle>["agents"][string],
242
+ ) {
243
+ return {
244
+ name: manifest.name,
245
+ description:
246
+ playgroundConfiguration.agents?.[manifest.name]?.description,
247
+ examples:
248
+ playgroundConfiguration.agents?.[manifest.name]?.examples ?? [],
249
+ provider: manifest.provider,
250
+ model: manifest.model,
251
+ region: manifest.region ?? "provider_managed",
252
+ maxTokens: manifest.maxTokens,
253
+ reasoningLevel: manifest.reasoningLevel,
254
+ outputType: manifest.outputType,
255
+ outputSchema: manifest.outputSchema,
256
+ systemPrompt: manifest.systemPrompt,
257
+ actions: Object.values(manifest.actions).map((action) => ({
258
+ name: action.name,
259
+ description: action.description,
260
+ execution: action.execution,
261
+ parameters: action.parameters,
262
+ outputSchema: action.outputSchema,
263
+ permissions: action.permissions,
264
+ timeoutMs: action.timeoutMs,
265
+ sideEffect: action.sideEffect ?? false,
266
+ })),
267
+ skills: Object.values(manifest.skills).map((skill) => ({
268
+ name: skill.name,
269
+ description: skill.description,
270
+ triggers: skill.triggers ?? [],
271
+ instructions: skill.instructions,
272
+ })),
273
+ evaluations: Object.values(manifest.evaluations).map((evaluation) => ({
274
+ name: evaluation.name,
275
+ description: evaluation.description,
276
+ instructions: evaluation.instructions ?? evaluation.description,
277
+ enabled: evaluation.enabled,
278
+ provider: evaluation.provider,
279
+ model: evaluation.model,
280
+ maxTokens: evaluation.maxTokens,
281
+ reasoningLevel: evaluation.reasoningLevel,
282
+ metrics: evaluation.metrics,
283
+ })),
284
+ };
285
+ }
286
+
287
+ async function readJsonBody(
288
+ request: IncomingMessage,
289
+ ): Promise<Record<string, unknown>> {
290
+ const chunks: Buffer[] = [];
291
+ let size = 0;
292
+ for await (const chunk of request) {
293
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
294
+ size += buffer.length;
295
+ if (size > 1_000_000) {
296
+ throw new Error("Request body exceeds 1 MB.");
297
+ }
298
+ chunks.push(buffer);
299
+ }
300
+ const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8"));
301
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
302
+ throw new Error("Request body must be a JSON object.");
303
+ }
304
+ return parsed as Record<string, unknown>;
305
+ }
306
+
307
+ function sendJson(
308
+ response: ServerResponse,
309
+ status: number,
310
+ value: unknown,
311
+ ): void {
312
+ if (response.headersSent) {
313
+ response.end();
314
+ return;
315
+ }
316
+ response.writeHead(status, {
317
+ "content-type": "application/json; charset=utf-8",
318
+ "cache-control": "no-store",
319
+ });
320
+ response.end(JSON.stringify(value));
321
+ }
322
+
323
+ function writeEvent(response: ServerResponse, value: unknown): void {
324
+ response.write(`${JSON.stringify(value)}\n`);
325
+ }
326
+
327
+ function requiredString(value: unknown, name: string): string {
328
+ if (typeof value !== "string" || !value.trim()) {
329
+ throw new Error(`${name} must be a non-empty string.`);
330
+ }
331
+ return value.trim();
332
+ }
333
+
334
+ function parseContent(value: unknown): string | MessageContent[] {
335
+ if (typeof value === "string") {
336
+ return requiredString(value, "content");
337
+ }
338
+ if (!Array.isArray(value) || value.length === 0) {
339
+ throw new Error(
340
+ "content must be a non-empty string or MessageContent array.",
341
+ );
342
+ }
343
+ return value.map((item) => {
344
+ if (!isRecord(item) || typeof item.type !== "string") {
345
+ throw new Error("Every content item requires a valid type.");
346
+ }
347
+ if (item.type === "text" && typeof item.text === "string") {
348
+ return { type: "text", text: item.text };
349
+ }
350
+ if (
351
+ isFileContentType(item.type) &&
352
+ typeof item.mimeType === "string" &&
353
+ typeof item.fileUri === "string"
354
+ ) {
355
+ return {
356
+ type: item.type,
357
+ mimeType: item.mimeType,
358
+ fileUri: item.fileUri,
359
+ };
360
+ }
361
+ throw new Error(
362
+ `Content item "${item.type}" has invalid fields.`,
363
+ );
364
+ });
365
+ }
366
+
367
+ function isFileContentType(
368
+ value: unknown,
369
+ ): value is "image" | "video" | "audio" | "url" {
370
+ return (
371
+ value === "image" ||
372
+ value === "video" ||
373
+ value === "audio" ||
374
+ value === "url"
375
+ );
376
+ }
377
+
378
+ function optionalString(value: unknown): string | undefined {
379
+ return typeof value === "string" && value.trim()
380
+ ? value.trim()
381
+ : undefined;
382
+ }
383
+
384
+ function parseToolResults(value: unknown): ToolResult[] {
385
+ if (!Array.isArray(value) || value.length === 0) {
386
+ throw new Error("toolResults must be a non-empty array.");
387
+ }
388
+ return value.map((item) => {
389
+ if (
390
+ !isRecord(item) ||
391
+ typeof item.callId !== "string" ||
392
+ !("output" in item) ||
393
+ (item.isError !== undefined &&
394
+ typeof item.isError !== "boolean")
395
+ ) {
396
+ throw new Error(
397
+ "Each tool result requires callId, output, and optional boolean isError.",
398
+ );
399
+ }
400
+ return {
401
+ callId: item.callId,
402
+ output: item.output,
403
+ ...(item.isError === true ? { isError: true } : {}),
404
+ };
405
+ });
406
+ }
407
+
408
+ function isRecord(value: unknown): value is Record<string, unknown> {
409
+ return (
410
+ typeof value === "object" &&
411
+ value !== null &&
412
+ !Array.isArray(value)
413
+ );
414
+ }
415
+
416
+ function positiveInteger(
417
+ value: string | null,
418
+ fallback: number,
419
+ ): number {
420
+ const parsed = value ? Number.parseInt(value, 10) : fallback;
421
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
422
+ }
423
+
424
+ async function readAllSessionEvents(
425
+ agent: AgentRuntime,
426
+ sessionId: string,
427
+ ): Promise<Awaited<ReturnType<AgentRuntime["events"]>>["events"]> {
428
+ const pages: SessionEvent[][] = [];
429
+ let page = 1;
430
+ let hasMore = true;
431
+ let throughSequence: number | undefined;
432
+ while (hasMore) {
433
+ const result = await agent.events(sessionId, {
434
+ page,
435
+ pageSize: 100,
436
+ ...(throughSequence ? { throughSequence } : {}),
437
+ });
438
+ throughSequence = result.throughSequence;
439
+ pages.unshift(result.events);
440
+ hasMore = result.hasMore;
441
+ page += 1;
442
+ }
443
+ return pages.flat();
444
+ }
445
+
446
+ function sessionNameFromContent(content: string | MessageContent[]): string {
447
+ const text = typeof content === "string"
448
+ ? content
449
+ : content.find(
450
+ (item): item is Extract<MessageContent, { type: "text" }> =>
451
+ item.type === "text",
452
+ )?.text ?? "Untitled session";
453
+ const normalized = text.replace(/\s+/g, " ").trim();
454
+ return normalized.length > 64
455
+ ? `${normalized.slice(0, 61)}…`
456
+ : normalized;
457
+ }
458
+
459
+ function staticAsset(
460
+ pathname: string,
461
+ ): { file: string; contentType: string } | undefined {
462
+ const assets: Record<string, { file: string; contentType: string }> = {
463
+ "/": { file: "index.html", contentType: "text/html; charset=utf-8" },
464
+ "/app.js": {
465
+ file: "app.js",
466
+ contentType: "text/javascript; charset=utf-8",
467
+ },
468
+ "/styles.css": {
469
+ file: "styles.css",
470
+ contentType: "text/css; charset=utf-8",
471
+ },
472
+ "/orcha-logo.svg": {
473
+ file: "orcha-logo.svg",
474
+ contentType: "image/svg+xml",
475
+ },
476
+ };
477
+ return assets[pathname];
478
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "types": ["node"]
10
+ },
11
+ "include": ["src/**/*.ts", "orcha/**/*.ts"]
12
+ }