@poncho-ai/cli 0.2.0 → 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.
@@ -0,0 +1,1994 @@
1
+ import {
2
+ LoginRateLimiter,
3
+ SessionStore,
4
+ consumeFirstRunIntro,
5
+ getRequestIp,
6
+ inferConversationTitle,
7
+ initializeOnboardingMarker,
8
+ parseCookies,
9
+ renderIconSvg,
10
+ renderManifest,
11
+ renderServiceWorker,
12
+ renderWebUiHtml,
13
+ setCookie,
14
+ verifyPassphrase
15
+ } from "./chunk-3BEWSRFW.js";
16
+
17
+ // src/index.ts
18
+ import { spawn } from "child_process";
19
+ import { access, cp, mkdir, readFile, writeFile } from "fs/promises";
20
+ import { existsSync } from "fs";
21
+ import {
22
+ createServer
23
+ } from "http";
24
+ import { dirname, relative, resolve } from "path";
25
+ import { createRequire } from "module";
26
+ import { fileURLToPath } from "url";
27
+ import {
28
+ AgentHarness,
29
+ LocalMcpBridge,
30
+ TelemetryEmitter,
31
+ createConversationStore,
32
+ loadPonchoConfig,
33
+ resolveStateConfig
34
+ } from "@poncho-ai/harness";
35
+ import { Command } from "commander";
36
+ import dotenv from "dotenv";
37
+ import YAML from "yaml";
38
+ import { createInterface } from "readline/promises";
39
+
40
+ // src/init-onboarding.ts
41
+ import { stdin, stdout } from "process";
42
+ import { input, password, select } from "@inquirer/prompts";
43
+ import {
44
+ fieldsForScope
45
+ } from "@poncho-ai/sdk";
46
+ var C = {
47
+ reset: "\x1B[0m",
48
+ bold: "\x1B[1m",
49
+ dim: "\x1B[2m",
50
+ cyan: "\x1B[36m"
51
+ };
52
+ var dim = (s) => `${C.dim}${s}${C.reset}`;
53
+ var bold = (s) => `${C.bold}${s}${C.reset}`;
54
+ var INPUT_CARET = "\xBB";
55
+ var shouldAskField = (field, answers) => {
56
+ if (!field.dependsOn) {
57
+ return true;
58
+ }
59
+ const value = answers[field.dependsOn.fieldId];
60
+ if (typeof field.dependsOn.equals !== "undefined") {
61
+ return value === field.dependsOn.equals;
62
+ }
63
+ if (field.dependsOn.oneOf) {
64
+ return field.dependsOn.oneOf.includes(value);
65
+ }
66
+ return true;
67
+ };
68
+ var parsePromptValue = (field, answer) => {
69
+ if (field.kind === "boolean") {
70
+ const normalized = answer.trim().toLowerCase();
71
+ if (normalized === "y" || normalized === "yes" || normalized === "true") {
72
+ return true;
73
+ }
74
+ if (normalized === "n" || normalized === "no" || normalized === "false") {
75
+ return false;
76
+ }
77
+ return Boolean(field.defaultValue);
78
+ }
79
+ if (field.kind === "number") {
80
+ const parsed = Number.parseInt(answer.trim(), 10);
81
+ if (Number.isFinite(parsed)) {
82
+ return parsed;
83
+ }
84
+ return Number(field.defaultValue);
85
+ }
86
+ if (field.kind === "select") {
87
+ const trimmed2 = answer.trim();
88
+ if (field.options && field.options.some((option) => option.value === trimmed2)) {
89
+ return trimmed2;
90
+ }
91
+ const asNumber = Number.parseInt(trimmed2, 10);
92
+ if (Number.isFinite(asNumber) && field.options && asNumber >= 1 && asNumber <= field.options.length) {
93
+ return field.options[asNumber - 1]?.value ?? String(field.defaultValue);
94
+ }
95
+ return String(field.defaultValue);
96
+ }
97
+ const trimmed = answer.trim();
98
+ if (trimmed.length === 0) {
99
+ return String(field.defaultValue);
100
+ }
101
+ return trimmed;
102
+ };
103
+ var askSecret = async (field) => {
104
+ if (!stdin.isTTY) {
105
+ return void 0;
106
+ }
107
+ const hint = field.placeholder ? dim(` (${field.placeholder})`) : "";
108
+ const message = `${field.prompt}${hint}`;
109
+ const value = await password(
110
+ {
111
+ message,
112
+ // true invisible input while typing/pasting
113
+ mask: false,
114
+ theme: {
115
+ prefix: {
116
+ idle: dim(INPUT_CARET),
117
+ done: dim("\u2713")
118
+ },
119
+ style: {
120
+ help: () => ""
121
+ }
122
+ }
123
+ },
124
+ { input: stdin, output: stdout }
125
+ );
126
+ return value ?? "";
127
+ };
128
+ var askSelectWithArrowKeys = async (field) => {
129
+ if (!field.options || field.options.length === 0) {
130
+ return void 0;
131
+ }
132
+ if (!stdin.isTTY) {
133
+ return void 0;
134
+ }
135
+ const selected = await select(
136
+ {
137
+ message: field.prompt,
138
+ choices: field.options.map((option) => ({
139
+ name: option.label,
140
+ value: option.value
141
+ })),
142
+ default: String(field.defaultValue),
143
+ theme: {
144
+ prefix: {
145
+ idle: dim(INPUT_CARET),
146
+ done: dim("\u2713")
147
+ }
148
+ }
149
+ },
150
+ { input: stdin, output: stdout }
151
+ );
152
+ return selected;
153
+ };
154
+ var askBooleanWithArrowKeys = async (field) => {
155
+ if (!stdin.isTTY) {
156
+ return void 0;
157
+ }
158
+ const selected = await select(
159
+ {
160
+ message: field.prompt,
161
+ choices: [
162
+ { name: "Yes", value: "true" },
163
+ { name: "No", value: "false" }
164
+ ],
165
+ default: field.defaultValue ? "true" : "false",
166
+ theme: {
167
+ prefix: {
168
+ idle: dim(INPUT_CARET),
169
+ done: dim("\u2713")
170
+ }
171
+ }
172
+ },
173
+ { input: stdin, output: stdout }
174
+ );
175
+ return selected;
176
+ };
177
+ var askTextInput = async (field) => {
178
+ if (!stdin.isTTY) {
179
+ return void 0;
180
+ }
181
+ const answer = await input(
182
+ {
183
+ message: field.prompt,
184
+ default: String(field.defaultValue ?? ""),
185
+ theme: {
186
+ prefix: {
187
+ idle: dim(INPUT_CARET),
188
+ done: dim("\u2713")
189
+ }
190
+ }
191
+ },
192
+ { input: stdin, output: stdout }
193
+ );
194
+ return answer;
195
+ };
196
+ var buildDefaultAnswers = () => {
197
+ const answers = {};
198
+ for (const field of fieldsForScope("light")) {
199
+ answers[field.id] = field.defaultValue;
200
+ }
201
+ return answers;
202
+ };
203
+ var askOnboardingQuestions = async (options) => {
204
+ const answers = buildDefaultAnswers();
205
+ const interactive = options.yes === true ? false : options.interactive ?? (stdin.isTTY === true && stdout.isTTY === true);
206
+ if (!interactive) {
207
+ return answers;
208
+ }
209
+ stdout.write("\n");
210
+ stdout.write(` ${bold("Poncho")} ${dim("\xB7 quick setup")}
211
+ `);
212
+ stdout.write("\n");
213
+ const fields = fieldsForScope("light");
214
+ for (const field of fields) {
215
+ if (!shouldAskField(field, answers)) {
216
+ continue;
217
+ }
218
+ stdout.write("\n");
219
+ let value;
220
+ if (field.secret) {
221
+ value = await askSecret(field);
222
+ } else if (field.kind === "select") {
223
+ value = await askSelectWithArrowKeys(field);
224
+ } else if (field.kind === "boolean") {
225
+ value = await askBooleanWithArrowKeys(field);
226
+ } else {
227
+ value = await askTextInput(field);
228
+ }
229
+ if (!value || value.trim().length === 0) {
230
+ continue;
231
+ }
232
+ answers[field.id] = parsePromptValue(field, value);
233
+ }
234
+ return answers;
235
+ };
236
+ var getProviderModelName = (provider) => provider === "openai" ? "gpt-4.1" : "claude-opus-4-5";
237
+ var maybeSet = (target, key, value) => {
238
+ if (typeof value === "string" && value.trim().length === 0) {
239
+ return;
240
+ }
241
+ if (typeof value === "undefined") {
242
+ return;
243
+ }
244
+ target[key] = value;
245
+ };
246
+ var buildConfigFromOnboardingAnswers = (answers) => {
247
+ const storageProvider = String(answers["storage.provider"] ?? "local");
248
+ const memoryEnabled = Boolean(answers["storage.memory.enabled"] ?? true);
249
+ const maxRecallConversations = Number(
250
+ answers["storage.memory.maxRecallConversations"] ?? 20
251
+ );
252
+ const storage = {
253
+ provider: storageProvider,
254
+ memory: {
255
+ enabled: memoryEnabled,
256
+ maxRecallConversations
257
+ }
258
+ };
259
+ maybeSet(storage, "url", answers["storage.url"]);
260
+ maybeSet(storage, "token", answers["storage.token"]);
261
+ maybeSet(storage, "table", answers["storage.table"]);
262
+ maybeSet(storage, "region", answers["storage.region"]);
263
+ const authRequired = Boolean(answers["auth.required"] ?? false);
264
+ const authType = answers["auth.type"] ?? "bearer";
265
+ const auth = {
266
+ required: authRequired,
267
+ type: authType
268
+ };
269
+ if (authType === "header") {
270
+ maybeSet(auth, "headerName", answers["auth.headerName"]);
271
+ }
272
+ const telemetryEnabled = Boolean(answers["telemetry.enabled"] ?? true);
273
+ const telemetry = {
274
+ enabled: telemetryEnabled
275
+ };
276
+ maybeSet(telemetry, "otlp", answers["telemetry.otlp"]);
277
+ return {
278
+ mcp: [],
279
+ auth,
280
+ storage,
281
+ telemetry
282
+ };
283
+ };
284
+ var collectEnvVars = (answers) => {
285
+ const envVars = /* @__PURE__ */ new Set();
286
+ const provider = String(answers["model.provider"] ?? "anthropic");
287
+ if (provider === "openai") {
288
+ envVars.add("OPENAI_API_KEY=sk-...");
289
+ } else {
290
+ envVars.add("ANTHROPIC_API_KEY=sk-ant-...");
291
+ }
292
+ const storageProvider = String(answers["storage.provider"] ?? "local");
293
+ if (storageProvider === "redis") {
294
+ envVars.add("REDIS_URL=redis://localhost:6379");
295
+ }
296
+ if (storageProvider === "upstash") {
297
+ envVars.add("UPSTASH_REDIS_REST_URL=https://...");
298
+ envVars.add("UPSTASH_REDIS_REST_TOKEN=...");
299
+ }
300
+ if (storageProvider === "dynamodb") {
301
+ envVars.add("PONCHO_DYNAMODB_TABLE=poncho-conversations");
302
+ envVars.add("AWS_REGION=us-east-1");
303
+ }
304
+ const authRequired = Boolean(answers["auth.required"] ?? false);
305
+ if (authRequired) {
306
+ envVars.add("PONCHO_AUTH_TOKEN=...");
307
+ }
308
+ return Array.from(envVars);
309
+ };
310
+ var collectEnvFileLines = (answers) => {
311
+ const lines = [
312
+ "# Poncho environment configuration",
313
+ "# Fill in empty values before running `poncho dev` or `poncho run --interactive`.",
314
+ "# Tip: keep secrets in `.env` only (never commit them).",
315
+ ""
316
+ ];
317
+ const modelProvider = String(answers["model.provider"] ?? "anthropic");
318
+ const modelEnvKey = modelProvider === "openai" ? "env.OPENAI_API_KEY" : "env.ANTHROPIC_API_KEY";
319
+ const modelEnvVar = modelProvider === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY";
320
+ const modelEnvValue = String(answers[modelEnvKey] ?? "");
321
+ lines.push("# Model");
322
+ if (modelEnvValue.length === 0) {
323
+ lines.push(
324
+ modelProvider === "openai" ? "# OpenAI: create an API key at https://platform.openai.com/api-keys" : "# Anthropic: create an API key at https://console.anthropic.com/settings/keys"
325
+ );
326
+ }
327
+ lines.push(`${modelEnvVar}=${modelEnvValue}`);
328
+ lines.push("");
329
+ const authRequired = Boolean(answers["auth.required"] ?? false);
330
+ const authType = answers["auth.type"] ?? "bearer";
331
+ const authHeaderName = String(answers["auth.headerName"] ?? "x-poncho-key");
332
+ if (authRequired) {
333
+ lines.push("# Auth (API request authentication)");
334
+ if (authType === "bearer") {
335
+ lines.push("# Requests should include: Authorization: Bearer <token>");
336
+ } else if (authType === "header") {
337
+ lines.push(`# Requests should include: ${authHeaderName}: <token>`);
338
+ } else {
339
+ lines.push("# Custom auth mode: read this token in your auth.validate function.");
340
+ }
341
+ lines.push("PONCHO_AUTH_TOKEN=");
342
+ lines.push("");
343
+ }
344
+ const storageProvider = String(answers["storage.provider"] ?? "local");
345
+ if (storageProvider === "redis") {
346
+ lines.push("# Storage (Redis)");
347
+ lines.push("# Run local Redis: docker run -p 6379:6379 redis:7");
348
+ lines.push("# Or use a managed Redis URL from your cloud provider.");
349
+ lines.push("REDIS_URL=");
350
+ lines.push("");
351
+ } else if (storageProvider === "upstash") {
352
+ lines.push("# Storage (Upstash)");
353
+ lines.push("# Create a Redis database at https://console.upstash.com/");
354
+ lines.push("# Copy REST URL + REST TOKEN from the Upstash dashboard.");
355
+ lines.push("UPSTASH_REDIS_REST_URL=");
356
+ lines.push("UPSTASH_REDIS_REST_TOKEN=");
357
+ lines.push("");
358
+ } else if (storageProvider === "dynamodb") {
359
+ lines.push("# Storage (DynamoDB)");
360
+ lines.push("# Create a DynamoDB table for Poncho conversation/state storage.");
361
+ lines.push("# Ensure AWS credentials are configured (AWS_PROFILE or access keys).");
362
+ lines.push("PONCHO_DYNAMODB_TABLE=");
363
+ lines.push("AWS_REGION=");
364
+ lines.push("");
365
+ } else if (storageProvider === "local" || storageProvider === "memory") {
366
+ lines.push(
367
+ storageProvider === "local" ? "# Storage (Local file): no extra env vars required." : "# Storage (In-memory): no extra env vars required, data resets on restart."
368
+ );
369
+ lines.push("");
370
+ }
371
+ const telemetryEnabled = Boolean(answers["telemetry.enabled"] ?? true);
372
+ if (telemetryEnabled) {
373
+ lines.push("# Telemetry (optional)");
374
+ lines.push("# Latitude telemetry setup: https://docs.latitude.so/");
375
+ lines.push("# If not using Latitude yet, you can leave these empty.");
376
+ lines.push("LATITUDE_API_KEY=");
377
+ lines.push("LATITUDE_PROJECT_ID=");
378
+ lines.push("LATITUDE_PATH=");
379
+ lines.push("");
380
+ }
381
+ while (lines.length > 0 && lines[lines.length - 1] === "") {
382
+ lines.pop();
383
+ }
384
+ return lines;
385
+ };
386
+ var runInitOnboarding = async (options) => {
387
+ const answers = await askOnboardingQuestions(options);
388
+ const provider = String(answers["model.provider"] ?? "anthropic");
389
+ const config = buildConfigFromOnboardingAnswers(answers);
390
+ const envExampleLines = collectEnvVars(answers);
391
+ const envFileLines = collectEnvFileLines(answers);
392
+ const envNeedsUserInput = envFileLines.some(
393
+ (line) => line.includes("=") && !line.startsWith("#") && line.endsWith("=")
394
+ );
395
+ return {
396
+ answers,
397
+ config,
398
+ envExample: `${envExampleLines.join("\n")}
399
+ `,
400
+ envFile: envFileLines.length > 0 ? `${envFileLines.join("\n")}
401
+ ` : "",
402
+ envNeedsUserInput,
403
+ agentModel: {
404
+ provider: provider === "openai" ? "openai" : "anthropic",
405
+ name: getProviderModelName(provider)
406
+ }
407
+ };
408
+ };
409
+
410
+ // src/index.ts
411
+ var __dirname = dirname(fileURLToPath(import.meta.url));
412
+ var require2 = createRequire(import.meta.url);
413
+ var writeJson = (response, statusCode, payload) => {
414
+ response.writeHead(statusCode, { "Content-Type": "application/json" });
415
+ response.end(JSON.stringify(payload));
416
+ };
417
+ var writeHtml = (response, statusCode, payload) => {
418
+ response.writeHead(statusCode, { "Content-Type": "text/html; charset=utf-8" });
419
+ response.end(payload);
420
+ };
421
+ var readRequestBody = async (request) => {
422
+ const chunks = [];
423
+ for await (const chunk of request) {
424
+ chunks.push(Buffer.from(chunk));
425
+ }
426
+ const body = Buffer.concat(chunks).toString("utf8");
427
+ return body.length > 0 ? JSON.parse(body) : {};
428
+ };
429
+ var resolveHarnessEnvironment = () => {
430
+ const value = (process.env.PONCHO_ENV ?? process.env.NODE_ENV ?? "development").toLowerCase();
431
+ if (value === "production" || value === "staging") {
432
+ return value;
433
+ }
434
+ return "development";
435
+ };
436
+ var listenOnAvailablePort = async (server, preferredPort) => await new Promise((resolveListen, rejectListen) => {
437
+ let currentPort = preferredPort;
438
+ const tryListen = () => {
439
+ const onListening = () => {
440
+ server.off("error", onError);
441
+ const address = server.address();
442
+ if (address && typeof address === "object" && typeof address.port === "number") {
443
+ resolveListen(address.port);
444
+ return;
445
+ }
446
+ resolveListen(currentPort);
447
+ };
448
+ const onError = (error) => {
449
+ server.off("listening", onListening);
450
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EADDRINUSE") {
451
+ currentPort += 1;
452
+ if (currentPort > 65535) {
453
+ rejectListen(
454
+ new Error(
455
+ "No available ports found from the requested port up to 65535."
456
+ )
457
+ );
458
+ return;
459
+ }
460
+ setImmediate(tryListen);
461
+ return;
462
+ }
463
+ rejectListen(error);
464
+ };
465
+ server.once("listening", onListening);
466
+ server.once("error", onError);
467
+ server.listen(currentPort);
468
+ };
469
+ tryListen();
470
+ });
471
+ var parseParams = (values) => {
472
+ const params = {};
473
+ for (const value of values) {
474
+ const [key, ...rest] = value.split("=");
475
+ if (!key) {
476
+ continue;
477
+ }
478
+ params[key] = rest.join("=");
479
+ }
480
+ return params;
481
+ };
482
+ var AGENT_TEMPLATE = (name, options) => `---
483
+ name: ${name}
484
+ description: A helpful Poncho assistant
485
+ model:
486
+ provider: ${options.modelProvider}
487
+ name: ${options.modelName}
488
+ temperature: 0.2
489
+ limits:
490
+ maxSteps: 50
491
+ timeout: 300
492
+ ---
493
+
494
+ # {{name}}
495
+
496
+ You are **{{name}}**, a helpful assistant built with Poncho.
497
+
498
+ Working directory: {{runtime.workingDir}}
499
+ Environment: {{runtime.environment}}
500
+
501
+ ## Task Guidance
502
+
503
+ - Use tools when needed
504
+ - Explain your reasoning clearly
505
+ - Ask clarifying questions when requirements are ambiguous
506
+ - For setup/configuration/skills/MCP questions, proactively read \`README.md\` with \`read_file\` before answering.
507
+ - Prefer concrete commands and examples from \`README.md\` over assumptions.
508
+ - Never claim a file/tool change unless the corresponding tool call actually succeeded
509
+
510
+ ## Default Capabilities in a Fresh Project
511
+
512
+ - Built-in tools: \`list_directory\` and \`read_file\`
513
+ - \`write_file\` is available in development, and disabled by default in production
514
+ - A starter local skill is included (\`starter-echo\`)
515
+ - Bash/shell commands are **not** available unless you install and enable a shell tool/skill
516
+ - Git operations are only available if a git-capable tool/skill is configured
517
+ `;
518
+ var resolveLocalPackagesRoot = () => {
519
+ const candidate = resolve(__dirname, "..", "..", "harness", "package.json");
520
+ if (existsSync(candidate)) {
521
+ return resolve(__dirname, "..", "..");
522
+ }
523
+ return null;
524
+ };
525
+ var resolveCoreDeps = (projectDir) => {
526
+ const packagesRoot = resolveLocalPackagesRoot();
527
+ if (packagesRoot) {
528
+ const harnessAbs = resolve(packagesRoot, "harness");
529
+ const sdkAbs = resolve(packagesRoot, "sdk");
530
+ return {
531
+ harness: `link:${relative(projectDir, harnessAbs)}`,
532
+ sdk: `link:${relative(projectDir, sdkAbs)}`
533
+ };
534
+ }
535
+ return { harness: "^0.1.0", sdk: "^0.1.0" };
536
+ };
537
+ var PACKAGE_TEMPLATE = (name, projectDir) => {
538
+ const deps = resolveCoreDeps(projectDir);
539
+ return JSON.stringify(
540
+ {
541
+ name,
542
+ private: true,
543
+ type: "module",
544
+ dependencies: {
545
+ "@poncho-ai/harness": deps.harness,
546
+ "@poncho-ai/sdk": deps.sdk
547
+ }
548
+ },
549
+ null,
550
+ 2
551
+ );
552
+ };
553
+ var README_TEMPLATE = (name) => `# ${name}
554
+
555
+ An AI agent built with [Poncho](https://github.com/cesr/poncho-ai).
556
+
557
+ ## Prerequisites
558
+
559
+ - Node.js 20+
560
+ - npm (or pnpm/yarn)
561
+ - Anthropic or OpenAI API key
562
+
563
+ ## Quick Start
564
+
565
+ \`\`\`bash
566
+ npm install
567
+ # If you didn't enter an API key during init:
568
+ cp .env.example .env
569
+ # Then edit .env and add your API key
570
+ poncho dev
571
+ \`\`\`
572
+
573
+ Open \`http://localhost:3000\` for the web UI.
574
+
575
+ On your first interactive session, the agent introduces its configurable capabilities.
576
+
577
+ ## Common Commands
578
+
579
+ \`\`\`bash
580
+ # Local web UI + API server
581
+ poncho dev
582
+
583
+ # Local interactive CLI
584
+ poncho run --interactive
585
+
586
+ # One-off run
587
+ poncho run "Your task here"
588
+
589
+ # Run tests
590
+ poncho test
591
+
592
+ # List available tools
593
+ poncho tools
594
+ \`\`\`
595
+
596
+ ## Add Skills
597
+
598
+ Install skills from a local path or remote repository, then verify discovery:
599
+
600
+ \`\`\`bash
601
+ # Install skills into ./skills
602
+ poncho add <repo-or-path>
603
+
604
+ # Verify loaded tools
605
+ poncho tools
606
+ \`\`\`
607
+
608
+ After adding skills, run \`poncho dev\` or \`poncho run --interactive\` and ask the agent to use them.
609
+
610
+ ## Configure MCP Servers (Remote)
611
+
612
+ Connect remote MCP servers and expose their tools to the agent:
613
+
614
+ \`\`\`bash
615
+ # Add remote MCP server
616
+ poncho mcp add --url https://mcp.example.com/github --name github --env GITHUB_TOKEN
617
+
618
+ # List configured servers
619
+ poncho mcp list
620
+
621
+ # Remove a server
622
+ poncho mcp remove github
623
+ \`\`\`
624
+
625
+ Set required secrets in \`.env\` (for example, \`GITHUB_TOKEN=...\`).
626
+
627
+ ## Configuration
628
+
629
+ Core files:
630
+
631
+ - \`AGENT.md\`: behavior, model selection, runtime guidance
632
+ - \`poncho.config.js\`: runtime config (storage, auth, telemetry, MCP, tools)
633
+ - \`.env\`: secrets and environment variables
634
+
635
+ Example \`poncho.config.js\`:
636
+
637
+ \`\`\`javascript
638
+ export default {
639
+ storage: {
640
+ provider: "local", // local | memory | redis | upstash | dynamodb
641
+ memory: {
642
+ enabled: true,
643
+ maxRecallConversations: 20,
644
+ },
645
+ },
646
+ auth: {
647
+ required: false,
648
+ },
649
+ telemetry: {
650
+ enabled: true,
651
+ },
652
+ tools: {
653
+ defaults: {
654
+ list_directory: true,
655
+ read_file: true,
656
+ write_file: true, // still gated by environment/policy
657
+ },
658
+ byEnvironment: {
659
+ production: {
660
+ read_file: false, // example override
661
+ },
662
+ },
663
+ },
664
+ };
665
+ \`\`\`
666
+
667
+ ## Project Structure
668
+
669
+ \`\`\`
670
+ ${name}/
671
+ \u251C\u2500\u2500 AGENT.md # Agent definition and system prompt
672
+ \u251C\u2500\u2500 poncho.config.js # Configuration (MCP servers, auth, etc.)
673
+ \u251C\u2500\u2500 package.json # Dependencies
674
+ \u251C\u2500\u2500 .env.example # Environment variables template
675
+ \u251C\u2500\u2500 tests/
676
+ \u2502 \u2514\u2500\u2500 basic.yaml # Test suite
677
+ \u2514\u2500\u2500 skills/
678
+ \u2514\u2500\u2500 starter/
679
+ \u251C\u2500\u2500 SKILL.md
680
+ \u2514\u2500\u2500 scripts/
681
+ \u2514\u2500\u2500 starter-echo.ts
682
+ \`\`\`
683
+
684
+ ## Deployment
685
+
686
+ \`\`\`bash
687
+ # Build for Vercel
688
+ poncho build vercel
689
+ cd .poncho-build/vercel && vercel deploy --prod
690
+
691
+ # Build for Docker
692
+ poncho build docker
693
+ docker build -t ${name} .
694
+ \`\`\`
695
+
696
+ For full reference:
697
+ https://github.com/cesr/poncho-ai
698
+ `;
699
+ var ENV_TEMPLATE = "ANTHROPIC_API_KEY=sk-ant-...\n";
700
+ var GITIGNORE_TEMPLATE = ".env\nnode_modules\ndist\n.poncho-build\n.poncho/\ninteractive-session.json\n";
701
+ var VERCEL_RUNTIME_DEPENDENCIES = {
702
+ "@anthropic-ai/sdk": "^0.74.0",
703
+ "@aws-sdk/client-dynamodb": "^3.988.0",
704
+ "@latitude-data/telemetry": "^2.0.2",
705
+ commander: "^12.0.0",
706
+ dotenv: "^16.4.0",
707
+ jiti: "^2.6.1",
708
+ mustache: "^4.2.0",
709
+ openai: "^6.3.0",
710
+ redis: "^5.10.0",
711
+ yaml: "^2.8.1"
712
+ };
713
+ var TEST_TEMPLATE = `tests:
714
+ - name: "Basic sanity"
715
+ task: "What is 2 + 2?"
716
+ expect:
717
+ contains: "4"
718
+ `;
719
+ var SKILL_TEMPLATE = `---
720
+ name: starter-skill
721
+ description: Starter local skill template
722
+ ---
723
+
724
+ # Starter Skill
725
+
726
+ This is a starter local skill created by \`poncho init\`.
727
+
728
+ ## Authoring Notes
729
+
730
+ - Put executable JavaScript/TypeScript files in \`scripts/\`.
731
+ - Ask the agent to call \`run_skill_script\` with \`skill\`, \`script\`, and optional \`input\`.
732
+ `;
733
+ var SKILL_TOOL_TEMPLATE = `export default async function run(input) {
734
+ const message = typeof input?.message === "string" ? input.message : "";
735
+ return { echoed: message };
736
+ }
737
+ `;
738
+ var ensureFile = async (path, content) => {
739
+ await mkdir(dirname(path), { recursive: true });
740
+ await writeFile(path, content, { encoding: "utf8", flag: "wx" });
741
+ };
742
+ var copyIfExists = async (sourcePath, destinationPath) => {
743
+ try {
744
+ await access(sourcePath);
745
+ } catch {
746
+ return;
747
+ }
748
+ await mkdir(dirname(destinationPath), { recursive: true });
749
+ await cp(sourcePath, destinationPath, { recursive: true });
750
+ };
751
+ var resolveCliEntrypoint = async () => {
752
+ const sourceEntrypoint = resolve(packageRoot, "src", "index.ts");
753
+ try {
754
+ await access(sourceEntrypoint);
755
+ return sourceEntrypoint;
756
+ } catch {
757
+ return resolve(packageRoot, "dist", "index.js");
758
+ }
759
+ };
760
+ var buildVercelHandlerBundle = async (outDir) => {
761
+ const { build: esbuild } = await import("esbuild");
762
+ const cliEntrypoint = await resolveCliEntrypoint();
763
+ const tempEntry = resolve(outDir, "api", "_entry.js");
764
+ await writeFile(
765
+ tempEntry,
766
+ `import { createRequestHandler } from ${JSON.stringify(cliEntrypoint)};
767
+ let handlerPromise;
768
+ export default async function handler(req, res) {
769
+ try {
770
+ if (!handlerPromise) {
771
+ handlerPromise = createRequestHandler({ workingDir: process.cwd() });
772
+ }
773
+ const requestHandler = await handlerPromise;
774
+ await requestHandler(req, res);
775
+ } catch (error) {
776
+ console.error("Handler error:", error);
777
+ if (!res.headersSent) {
778
+ res.writeHead(500, { "Content-Type": "application/json" });
779
+ res.end(JSON.stringify({ error: "Internal server error", message: error?.message || "Unknown error" }));
780
+ }
781
+ }
782
+ }
783
+ `,
784
+ "utf8"
785
+ );
786
+ await esbuild({
787
+ entryPoints: [tempEntry],
788
+ bundle: true,
789
+ platform: "node",
790
+ format: "esm",
791
+ target: "node20",
792
+ outfile: resolve(outDir, "api", "index.js"),
793
+ sourcemap: false,
794
+ legalComments: "none",
795
+ external: [
796
+ ...Object.keys(VERCEL_RUNTIME_DEPENDENCIES),
797
+ "@anthropic-ai/sdk/*",
798
+ "child_process",
799
+ "fs",
800
+ "fs/promises",
801
+ "http",
802
+ "https",
803
+ "path",
804
+ "module",
805
+ "url",
806
+ "readline",
807
+ "readline/promises",
808
+ "crypto",
809
+ "stream",
810
+ "events",
811
+ "util",
812
+ "os",
813
+ "zlib",
814
+ "net",
815
+ "tls",
816
+ "dns",
817
+ "assert",
818
+ "buffer",
819
+ "timers",
820
+ "timers/promises",
821
+ "node:child_process",
822
+ "node:fs",
823
+ "node:fs/promises",
824
+ "node:http",
825
+ "node:https",
826
+ "node:path",
827
+ "node:module",
828
+ "node:url",
829
+ "node:readline",
830
+ "node:readline/promises",
831
+ "node:crypto",
832
+ "node:stream",
833
+ "node:events",
834
+ "node:util",
835
+ "node:os",
836
+ "node:zlib",
837
+ "node:net",
838
+ "node:tls",
839
+ "node:dns",
840
+ "node:assert",
841
+ "node:buffer",
842
+ "node:timers",
843
+ "node:timers/promises"
844
+ ]
845
+ });
846
+ };
847
+ var renderConfigFile = (config) => `export default ${JSON.stringify(config, null, 2)}
848
+ `;
849
+ var writeConfigFile = async (workingDir, config) => {
850
+ const serialized = renderConfigFile(config);
851
+ await writeFile(resolve(workingDir, "poncho.config.js"), serialized, "utf8");
852
+ };
853
+ var gitInit = (cwd) => new Promise((resolve2) => {
854
+ const child = spawn("git", ["init"], { cwd, stdio: "ignore" });
855
+ child.on("error", () => resolve2(false));
856
+ child.on("close", (code) => resolve2(code === 0));
857
+ });
858
+ var initProject = async (projectName, options) => {
859
+ const baseDir = options?.workingDir ?? process.cwd();
860
+ const projectDir = resolve(baseDir, projectName);
861
+ await mkdir(projectDir, { recursive: true });
862
+ const onboardingOptions = options?.onboarding ?? {
863
+ yes: true,
864
+ interactive: false
865
+ };
866
+ const onboarding = await runInitOnboarding(onboardingOptions);
867
+ const G = "\x1B[32m";
868
+ const D = "\x1B[2m";
869
+ const B = "\x1B[1m";
870
+ const CY = "\x1B[36m";
871
+ const YW = "\x1B[33m";
872
+ const R = "\x1B[0m";
873
+ process.stdout.write("\n");
874
+ const scaffoldFiles = [
875
+ { path: "AGENT.md", content: AGENT_TEMPLATE(projectName, { modelProvider: onboarding.agentModel.provider, modelName: onboarding.agentModel.name }) },
876
+ { path: "poncho.config.js", content: renderConfigFile(onboarding.config) },
877
+ { path: "package.json", content: PACKAGE_TEMPLATE(projectName, projectDir) },
878
+ { path: "README.md", content: README_TEMPLATE(projectName) },
879
+ { path: ".env.example", content: options?.envExampleOverride ?? onboarding.envExample ?? ENV_TEMPLATE },
880
+ { path: ".gitignore", content: GITIGNORE_TEMPLATE },
881
+ { path: "tests/basic.yaml", content: TEST_TEMPLATE },
882
+ { path: "skills/starter/SKILL.md", content: SKILL_TEMPLATE },
883
+ { path: "skills/starter/scripts/starter-echo.ts", content: SKILL_TOOL_TEMPLATE }
884
+ ];
885
+ if (onboarding.envFile) {
886
+ scaffoldFiles.push({ path: ".env", content: onboarding.envFile });
887
+ }
888
+ for (const file of scaffoldFiles) {
889
+ await ensureFile(resolve(projectDir, file.path), file.content);
890
+ process.stdout.write(` ${D}+${R} ${D}${file.path}${R}
891
+ `);
892
+ }
893
+ await initializeOnboardingMarker(projectDir, {
894
+ allowIntro: !(onboardingOptions.yes ?? false)
895
+ });
896
+ process.stdout.write("\n");
897
+ try {
898
+ await runPnpmInstall(projectDir);
899
+ process.stdout.write(` ${G}\u2713${R} ${D}Installed dependencies${R}
900
+ `);
901
+ } catch {
902
+ process.stdout.write(
903
+ ` ${YW}!${R} Could not install dependencies \u2014 run ${D}pnpm install${R} manually
904
+ `
905
+ );
906
+ }
907
+ const gitOk = await gitInit(projectDir);
908
+ if (gitOk) {
909
+ process.stdout.write(` ${G}\u2713${R} ${D}Initialized git${R}
910
+ `);
911
+ }
912
+ process.stdout.write(` ${G}\u2713${R} ${B}${projectName}${R} is ready
913
+ `);
914
+ process.stdout.write("\n");
915
+ process.stdout.write(` ${B}Get started${R}
916
+ `);
917
+ process.stdout.write("\n");
918
+ process.stdout.write(` ${D}$${R} cd ${projectName}
919
+ `);
920
+ process.stdout.write("\n");
921
+ process.stdout.write(` ${CY}Web UI${R} ${D}$${R} poncho dev
922
+ `);
923
+ process.stdout.write(` ${CY}CLI interactive${R} ${D}$${R} poncho run --interactive
924
+ `);
925
+ process.stdout.write("\n");
926
+ if (onboarding.envNeedsUserInput) {
927
+ process.stdout.write(
928
+ ` ${YW}!${R} Make sure you add your keys to the ${B}.env${R} file.
929
+ `
930
+ );
931
+ }
932
+ process.stdout.write(` ${D}The agent will introduce itself on your first session.${R}
933
+ `);
934
+ process.stdout.write("\n");
935
+ };
936
+ var updateAgentGuidance = async (workingDir) => {
937
+ const agentPath = resolve(workingDir, "AGENT.md");
938
+ const content = await readFile(agentPath, "utf8");
939
+ const guidanceSectionPattern = /\n## Configuration Assistant Context[\s\S]*?(?=\n## |\n# |$)|\n## Skill Authoring Guidance[\s\S]*?(?=\n## |\n# |$)/g;
940
+ const normalized = content.replace(/\s+$/g, "");
941
+ const updated = normalized.replace(guidanceSectionPattern, "").replace(/\n{3,}/g, "\n\n");
942
+ if (updated === normalized) {
943
+ process.stdout.write("AGENT.md does not contain deprecated embedded local guidance.\n");
944
+ return false;
945
+ }
946
+ await writeFile(agentPath, `${updated}
947
+ `, "utf8");
948
+ process.stdout.write("Removed deprecated embedded local guidance from AGENT.md.\n");
949
+ return true;
950
+ };
951
+ var formatSseEvent = (event) => `event: ${event.type}
952
+ data: ${JSON.stringify(event)}
953
+
954
+ `;
955
+ var createRequestHandler = async (options) => {
956
+ const workingDir = options?.workingDir ?? process.cwd();
957
+ dotenv.config({ path: resolve(workingDir, ".env") });
958
+ const config = await loadPonchoConfig(workingDir);
959
+ let agentName = "Agent";
960
+ let agentModelProvider = "anthropic";
961
+ let agentModelName = "claude-opus-4-5";
962
+ try {
963
+ const agentMd = await readFile(resolve(workingDir, "AGENT.md"), "utf8");
964
+ const nameMatch = agentMd.match(/^name:\s*(.+)$/m);
965
+ const providerMatch = agentMd.match(/^\s{2}provider:\s*(.+)$/m);
966
+ const modelMatch = agentMd.match(/^\s{2}name:\s*(.+)$/m);
967
+ if (nameMatch?.[1]) {
968
+ agentName = nameMatch[1].trim().replace(/^["']|["']$/g, "");
969
+ }
970
+ if (providerMatch?.[1]) {
971
+ agentModelProvider = providerMatch[1].trim().replace(/^["']|["']$/g, "");
972
+ }
973
+ if (modelMatch?.[1]) {
974
+ agentModelName = modelMatch[1].trim().replace(/^["']|["']$/g, "");
975
+ }
976
+ } catch {
977
+ }
978
+ const harness = new AgentHarness({ workingDir });
979
+ await harness.initialize();
980
+ const telemetry = new TelemetryEmitter(config?.telemetry);
981
+ const conversationStore = createConversationStore(resolveStateConfig(config), { workingDir });
982
+ const sessionStore = new SessionStore();
983
+ const loginRateLimiter = new LoginRateLimiter();
984
+ const passphrase = process.env.AGENT_UI_PASSPHRASE ?? "";
985
+ const isProduction = resolveHarnessEnvironment() === "production";
986
+ const requireUiAuth = passphrase.length > 0;
987
+ const secureCookies = isProduction;
988
+ return async (request, response) => {
989
+ if (!request.url || !request.method) {
990
+ writeJson(response, 404, { error: "Not found" });
991
+ return;
992
+ }
993
+ const [pathname] = request.url.split("?");
994
+ if (request.method === "GET" && (pathname === "/" || pathname.startsWith("/c/"))) {
995
+ writeHtml(response, 200, renderWebUiHtml({ agentName }));
996
+ return;
997
+ }
998
+ if (pathname === "/manifest.json" && request.method === "GET") {
999
+ response.writeHead(200, { "Content-Type": "application/manifest+json" });
1000
+ response.end(renderManifest({ agentName }));
1001
+ return;
1002
+ }
1003
+ if (pathname === "/sw.js" && request.method === "GET") {
1004
+ response.writeHead(200, {
1005
+ "Content-Type": "application/javascript",
1006
+ "Service-Worker-Allowed": "/"
1007
+ });
1008
+ response.end(renderServiceWorker());
1009
+ return;
1010
+ }
1011
+ if (pathname === "/icon.svg" && request.method === "GET") {
1012
+ response.writeHead(200, { "Content-Type": "image/svg+xml" });
1013
+ response.end(renderIconSvg({ agentName }));
1014
+ return;
1015
+ }
1016
+ if ((pathname === "/icon-192.png" || pathname === "/icon-512.png") && request.method === "GET") {
1017
+ response.writeHead(302, { Location: "/icon.svg" });
1018
+ response.end();
1019
+ return;
1020
+ }
1021
+ if (pathname === "/health" && request.method === "GET") {
1022
+ writeJson(response, 200, { status: "ok" });
1023
+ return;
1024
+ }
1025
+ const cookies = parseCookies(request);
1026
+ const sessionId = cookies.poncho_session;
1027
+ const session = sessionId ? sessionStore.get(sessionId) : void 0;
1028
+ const ownerId = session?.ownerId ?? "local-owner";
1029
+ const requiresCsrfValidation = request.method !== "GET" && request.method !== "HEAD" && request.method !== "OPTIONS";
1030
+ if (pathname === "/api/auth/session" && request.method === "GET") {
1031
+ if (!requireUiAuth) {
1032
+ writeJson(response, 200, { authenticated: true, csrfToken: "" });
1033
+ return;
1034
+ }
1035
+ if (!session) {
1036
+ writeJson(response, 200, { authenticated: false });
1037
+ return;
1038
+ }
1039
+ writeJson(response, 200, {
1040
+ authenticated: true,
1041
+ sessionId: session.sessionId,
1042
+ ownerId: session.ownerId,
1043
+ csrfToken: session.csrfToken
1044
+ });
1045
+ return;
1046
+ }
1047
+ if (pathname === "/api/auth/login" && request.method === "POST") {
1048
+ if (!requireUiAuth) {
1049
+ writeJson(response, 200, { authenticated: true, csrfToken: "" });
1050
+ return;
1051
+ }
1052
+ const ip = getRequestIp(request);
1053
+ const canAttempt = loginRateLimiter.canAttempt(ip);
1054
+ if (!canAttempt.allowed) {
1055
+ writeJson(response, 429, {
1056
+ code: "AUTH_RATE_LIMIT",
1057
+ message: "Too many failed login attempts. Try again later.",
1058
+ retryAfterSeconds: canAttempt.retryAfterSeconds
1059
+ });
1060
+ return;
1061
+ }
1062
+ const body = await readRequestBody(request);
1063
+ const provided = body.passphrase ?? "";
1064
+ if (!verifyPassphrase(provided, passphrase)) {
1065
+ const failure = loginRateLimiter.registerFailure(ip);
1066
+ writeJson(response, 401, {
1067
+ code: "AUTH_ERROR",
1068
+ message: "Invalid passphrase",
1069
+ retryAfterSeconds: failure.retryAfterSeconds
1070
+ });
1071
+ return;
1072
+ }
1073
+ loginRateLimiter.registerSuccess(ip);
1074
+ const createdSession = sessionStore.create(ownerId);
1075
+ setCookie(response, "poncho_session", createdSession.sessionId, {
1076
+ httpOnly: true,
1077
+ secure: secureCookies,
1078
+ sameSite: "Lax",
1079
+ path: "/",
1080
+ maxAge: 60 * 60 * 8
1081
+ });
1082
+ writeJson(response, 200, {
1083
+ authenticated: true,
1084
+ csrfToken: createdSession.csrfToken
1085
+ });
1086
+ return;
1087
+ }
1088
+ if (pathname === "/api/auth/logout" && request.method === "POST") {
1089
+ if (session?.sessionId) {
1090
+ sessionStore.delete(session.sessionId);
1091
+ }
1092
+ setCookie(response, "poncho_session", "", {
1093
+ httpOnly: true,
1094
+ secure: secureCookies,
1095
+ sameSite: "Lax",
1096
+ path: "/",
1097
+ maxAge: 0
1098
+ });
1099
+ writeJson(response, 200, { ok: true });
1100
+ return;
1101
+ }
1102
+ if (pathname.startsWith("/api/")) {
1103
+ if (requireUiAuth && !session) {
1104
+ writeJson(response, 401, {
1105
+ code: "AUTH_ERROR",
1106
+ message: "Authentication required"
1107
+ });
1108
+ return;
1109
+ }
1110
+ if (requireUiAuth && requiresCsrfValidation && pathname !== "/api/auth/login" && request.headers["x-csrf-token"] !== session?.csrfToken) {
1111
+ writeJson(response, 403, {
1112
+ code: "CSRF_ERROR",
1113
+ message: "Invalid CSRF token"
1114
+ });
1115
+ return;
1116
+ }
1117
+ }
1118
+ if (pathname === "/api/conversations" && request.method === "GET") {
1119
+ const conversations = await conversationStore.list(ownerId);
1120
+ writeJson(response, 200, {
1121
+ conversations: conversations.map((conversation) => ({
1122
+ conversationId: conversation.conversationId,
1123
+ title: conversation.title,
1124
+ runtimeRunId: conversation.runtimeRunId,
1125
+ ownerId: conversation.ownerId,
1126
+ tenantId: conversation.tenantId,
1127
+ createdAt: conversation.createdAt,
1128
+ updatedAt: conversation.updatedAt,
1129
+ messageCount: conversation.messages.length
1130
+ }))
1131
+ });
1132
+ return;
1133
+ }
1134
+ if (pathname === "/api/conversations" && request.method === "POST") {
1135
+ const body = await readRequestBody(request);
1136
+ const conversation = await conversationStore.create(ownerId, body.title);
1137
+ const introMessage = await consumeFirstRunIntro(workingDir, {
1138
+ agentName,
1139
+ provider: agentModelProvider,
1140
+ model: agentModelName,
1141
+ config
1142
+ });
1143
+ if (introMessage) {
1144
+ conversation.messages = [{ role: "assistant", content: introMessage }];
1145
+ await conversationStore.update(conversation);
1146
+ }
1147
+ writeJson(response, 201, { conversation });
1148
+ return;
1149
+ }
1150
+ const conversationPathMatch = pathname.match(/^\/api\/conversations\/([^/]+)$/);
1151
+ if (conversationPathMatch) {
1152
+ const conversationId = decodeURIComponent(conversationPathMatch[1] ?? "");
1153
+ const conversation = await conversationStore.get(conversationId);
1154
+ if (!conversation || conversation.ownerId !== ownerId) {
1155
+ writeJson(response, 404, {
1156
+ code: "CONVERSATION_NOT_FOUND",
1157
+ message: "Conversation not found"
1158
+ });
1159
+ return;
1160
+ }
1161
+ if (request.method === "GET") {
1162
+ writeJson(response, 200, { conversation });
1163
+ return;
1164
+ }
1165
+ if (request.method === "PATCH") {
1166
+ const body = await readRequestBody(request);
1167
+ if (!body.title || body.title.trim().length === 0) {
1168
+ writeJson(response, 400, {
1169
+ code: "VALIDATION_ERROR",
1170
+ message: "title is required"
1171
+ });
1172
+ return;
1173
+ }
1174
+ const updated = await conversationStore.rename(conversationId, body.title);
1175
+ writeJson(response, 200, { conversation: updated });
1176
+ return;
1177
+ }
1178
+ if (request.method === "DELETE") {
1179
+ await conversationStore.delete(conversationId);
1180
+ writeJson(response, 200, { ok: true });
1181
+ return;
1182
+ }
1183
+ }
1184
+ const conversationMessageMatch = pathname.match(/^\/api\/conversations\/([^/]+)\/messages$/);
1185
+ if (conversationMessageMatch && request.method === "POST") {
1186
+ const conversationId = decodeURIComponent(conversationMessageMatch[1] ?? "");
1187
+ const conversation = await conversationStore.get(conversationId);
1188
+ if (!conversation || conversation.ownerId !== ownerId) {
1189
+ writeJson(response, 404, {
1190
+ code: "CONVERSATION_NOT_FOUND",
1191
+ message: "Conversation not found"
1192
+ });
1193
+ return;
1194
+ }
1195
+ const body = await readRequestBody(request);
1196
+ const messageText = body.message?.trim() ?? "";
1197
+ if (!messageText) {
1198
+ writeJson(response, 400, {
1199
+ code: "VALIDATION_ERROR",
1200
+ message: "message is required"
1201
+ });
1202
+ return;
1203
+ }
1204
+ if (conversation.messages.length === 0 && (conversation.title === "New conversation" || conversation.title.trim().length === 0)) {
1205
+ conversation.title = inferConversationTitle(messageText);
1206
+ }
1207
+ response.writeHead(200, {
1208
+ "Content-Type": "text/event-stream",
1209
+ "Cache-Control": "no-cache",
1210
+ Connection: "keep-alive"
1211
+ });
1212
+ let latestRunId = conversation.runtimeRunId ?? "";
1213
+ let assistantResponse = "";
1214
+ const toolTimeline = [];
1215
+ try {
1216
+ const recallCorpus = (await conversationStore.list(ownerId)).filter((item) => item.conversationId !== conversationId).slice(0, 20).map((item) => ({
1217
+ conversationId: item.conversationId,
1218
+ title: item.title,
1219
+ updatedAt: item.updatedAt,
1220
+ content: item.messages.slice(-6).map((message) => `${message.role}: ${message.content}`).join("\n").slice(0, 2e3)
1221
+ })).filter((item) => item.content.length > 0);
1222
+ for await (const event of harness.run({
1223
+ task: messageText,
1224
+ parameters: {
1225
+ ...body.parameters ?? {},
1226
+ __conversationRecallCorpus: recallCorpus,
1227
+ __activeConversationId: conversationId
1228
+ },
1229
+ messages: conversation.messages
1230
+ })) {
1231
+ if (event.type === "run:started") {
1232
+ latestRunId = event.runId;
1233
+ }
1234
+ if (event.type === "model:chunk") {
1235
+ assistantResponse += event.content;
1236
+ }
1237
+ if (event.type === "tool:started") {
1238
+ toolTimeline.push(`- start \`${event.tool}\``);
1239
+ }
1240
+ if (event.type === "tool:completed") {
1241
+ toolTimeline.push(`- done \`${event.tool}\` (${event.duration}ms)`);
1242
+ }
1243
+ if (event.type === "tool:error") {
1244
+ toolTimeline.push(`- error \`${event.tool}\`: ${event.error}`);
1245
+ }
1246
+ if (event.type === "tool:approval:required") {
1247
+ toolTimeline.push(`- approval required \`${event.tool}\``);
1248
+ }
1249
+ if (event.type === "tool:approval:granted") {
1250
+ toolTimeline.push(`- approval granted (${event.approvalId})`);
1251
+ }
1252
+ if (event.type === "tool:approval:denied") {
1253
+ toolTimeline.push(`- approval denied (${event.approvalId})`);
1254
+ }
1255
+ if (event.type === "run:completed" && assistantResponse.length === 0 && event.result.response) {
1256
+ assistantResponse = event.result.response;
1257
+ }
1258
+ await telemetry.emit(event);
1259
+ response.write(formatSseEvent(event));
1260
+ }
1261
+ conversation.messages = [
1262
+ ...conversation.messages,
1263
+ { role: "user", content: messageText },
1264
+ {
1265
+ role: "assistant",
1266
+ content: assistantResponse,
1267
+ metadata: toolTimeline.length > 0 ? { toolActivity: toolTimeline } : void 0
1268
+ }
1269
+ ];
1270
+ conversation.runtimeRunId = latestRunId || conversation.runtimeRunId;
1271
+ conversation.updatedAt = Date.now();
1272
+ await conversationStore.update(conversation);
1273
+ } catch (error) {
1274
+ response.write(
1275
+ formatSseEvent({
1276
+ type: "run:error",
1277
+ runId: latestRunId || "run_unknown",
1278
+ error: {
1279
+ code: "RUN_ERROR",
1280
+ message: error instanceof Error ? error.message : "Unknown error"
1281
+ }
1282
+ })
1283
+ );
1284
+ } finally {
1285
+ response.end();
1286
+ }
1287
+ return;
1288
+ }
1289
+ writeJson(response, 404, { error: "Not found" });
1290
+ };
1291
+ };
1292
+ var startDevServer = async (port, options) => {
1293
+ const handler = await createRequestHandler(options);
1294
+ const server = createServer(handler);
1295
+ const actualPort = await listenOnAvailablePort(server, port);
1296
+ if (actualPort !== port) {
1297
+ process.stdout.write(`Port ${port} is in use, switched to ${actualPort}.
1298
+ `);
1299
+ }
1300
+ process.stdout.write(`Poncho dev server running at http://localhost:${actualPort}
1301
+ `);
1302
+ const shutdown = () => {
1303
+ server.close();
1304
+ server.closeAllConnections?.();
1305
+ process.exit(0);
1306
+ };
1307
+ process.on("SIGINT", shutdown);
1308
+ process.on("SIGTERM", shutdown);
1309
+ return server;
1310
+ };
1311
+ var runOnce = async (task, options) => {
1312
+ const workingDir = options.workingDir ?? process.cwd();
1313
+ dotenv.config({ path: resolve(workingDir, ".env") });
1314
+ const config = await loadPonchoConfig(workingDir);
1315
+ const harness = new AgentHarness({ workingDir });
1316
+ const telemetry = new TelemetryEmitter(config?.telemetry);
1317
+ await harness.initialize();
1318
+ const fileBlobs = await Promise.all(
1319
+ options.filePaths.map(async (path) => {
1320
+ const content = await readFile(resolve(workingDir, path), "utf8");
1321
+ return `# File: ${path}
1322
+ ${content}`;
1323
+ })
1324
+ );
1325
+ const input2 = {
1326
+ task: fileBlobs.length > 0 ? `${task}
1327
+
1328
+ ${fileBlobs.join("\n\n")}` : task,
1329
+ parameters: options.params
1330
+ };
1331
+ if (options.json) {
1332
+ const output = await harness.runToCompletion(input2);
1333
+ for (const event of output.events) {
1334
+ await telemetry.emit(event);
1335
+ }
1336
+ process.stdout.write(`${JSON.stringify(output, null, 2)}
1337
+ `);
1338
+ return;
1339
+ }
1340
+ for await (const event of harness.run(input2)) {
1341
+ await telemetry.emit(event);
1342
+ if (event.type === "model:chunk") {
1343
+ process.stdout.write(event.content);
1344
+ }
1345
+ if (event.type === "run:error") {
1346
+ process.stderr.write(`
1347
+ Error: ${event.error.message}
1348
+ `);
1349
+ }
1350
+ if (event.type === "run:completed") {
1351
+ process.stdout.write("\n");
1352
+ }
1353
+ }
1354
+ };
1355
+ var runInteractive = async (workingDir, params) => {
1356
+ dotenv.config({ path: resolve(workingDir, ".env") });
1357
+ const config = await loadPonchoConfig(workingDir);
1358
+ let pendingApproval = null;
1359
+ let onApprovalRequest = null;
1360
+ const approvalHandler = async (request) => {
1361
+ return new Promise((resolveApproval) => {
1362
+ const req = {
1363
+ tool: request.tool,
1364
+ input: request.input,
1365
+ approvalId: request.approvalId,
1366
+ resolve: resolveApproval
1367
+ };
1368
+ pendingApproval = req;
1369
+ if (onApprovalRequest) {
1370
+ onApprovalRequest(req);
1371
+ }
1372
+ });
1373
+ };
1374
+ const harness = new AgentHarness({
1375
+ workingDir,
1376
+ environment: resolveHarnessEnvironment(),
1377
+ approvalHandler
1378
+ });
1379
+ await harness.initialize();
1380
+ try {
1381
+ const { runInteractiveInk } = await import("./run-interactive-ink-4EKHIHGU.js");
1382
+ await runInteractiveInk({
1383
+ harness,
1384
+ params,
1385
+ workingDir,
1386
+ config,
1387
+ conversationStore: createConversationStore(resolveStateConfig(config), { workingDir }),
1388
+ onSetApprovalCallback: (cb) => {
1389
+ onApprovalRequest = cb;
1390
+ if (pendingApproval) {
1391
+ cb(pendingApproval);
1392
+ }
1393
+ }
1394
+ });
1395
+ } finally {
1396
+ await harness.shutdown();
1397
+ }
1398
+ };
1399
+ var listTools = async (workingDir) => {
1400
+ dotenv.config({ path: resolve(workingDir, ".env") });
1401
+ const harness = new AgentHarness({ workingDir });
1402
+ await harness.initialize();
1403
+ const tools = harness.listTools();
1404
+ if (tools.length === 0) {
1405
+ process.stdout.write("No tools registered.\n");
1406
+ return;
1407
+ }
1408
+ process.stdout.write("Available tools:\n");
1409
+ for (const tool of tools) {
1410
+ process.stdout.write(`- ${tool.name}: ${tool.description}
1411
+ `);
1412
+ }
1413
+ };
1414
+ var runPnpmInstall = async (workingDir) => await new Promise((resolveInstall, rejectInstall) => {
1415
+ const child = spawn("pnpm", ["install"], {
1416
+ cwd: workingDir,
1417
+ stdio: "inherit",
1418
+ env: process.env
1419
+ });
1420
+ child.on("exit", (code) => {
1421
+ if (code === 0) {
1422
+ resolveInstall();
1423
+ return;
1424
+ }
1425
+ rejectInstall(new Error(`pnpm install failed with exit code ${code ?? -1}`));
1426
+ });
1427
+ });
1428
+ var runInstallCommand = async (workingDir, packageNameOrPath) => await new Promise((resolveInstall, rejectInstall) => {
1429
+ const child = spawn("pnpm", ["add", packageNameOrPath], {
1430
+ cwd: workingDir,
1431
+ stdio: "inherit",
1432
+ env: process.env
1433
+ });
1434
+ child.on("exit", (code) => {
1435
+ if (code === 0) {
1436
+ resolveInstall();
1437
+ return;
1438
+ }
1439
+ rejectInstall(new Error(`pnpm add failed with exit code ${code ?? -1}`));
1440
+ });
1441
+ });
1442
+ var resolveInstalledPackageName = (packageNameOrPath) => {
1443
+ if (packageNameOrPath.startsWith(".") || packageNameOrPath.startsWith("/")) {
1444
+ return null;
1445
+ }
1446
+ if (packageNameOrPath.startsWith("@")) {
1447
+ return packageNameOrPath;
1448
+ }
1449
+ if (packageNameOrPath.includes("/")) {
1450
+ return packageNameOrPath.split("/").pop() ?? packageNameOrPath;
1451
+ }
1452
+ return packageNameOrPath;
1453
+ };
1454
+ var resolveSkillRoot = (workingDir, packageNameOrPath) => {
1455
+ if (packageNameOrPath.startsWith(".") || packageNameOrPath.startsWith("/")) {
1456
+ return resolve(workingDir, packageNameOrPath);
1457
+ }
1458
+ const moduleName = resolveInstalledPackageName(packageNameOrPath) ?? packageNameOrPath;
1459
+ try {
1460
+ const packageJsonPath = require2.resolve(`${moduleName}/package.json`, {
1461
+ paths: [workingDir]
1462
+ });
1463
+ return resolve(packageJsonPath, "..");
1464
+ } catch {
1465
+ const candidate = resolve(workingDir, "node_modules", moduleName);
1466
+ if (existsSync(candidate)) {
1467
+ return candidate;
1468
+ }
1469
+ throw new Error(
1470
+ `Could not locate installed package "${moduleName}" in ${workingDir}`
1471
+ );
1472
+ }
1473
+ };
1474
+ var findSkillManifest = async (dir, depth = 2) => {
1475
+ try {
1476
+ await access(resolve(dir, "SKILL.md"));
1477
+ return true;
1478
+ } catch {
1479
+ }
1480
+ if (depth <= 0) return false;
1481
+ try {
1482
+ const { readdir } = await import("fs/promises");
1483
+ const entries = await readdir(dir, { withFileTypes: true });
1484
+ for (const entry of entries) {
1485
+ if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
1486
+ const found = await findSkillManifest(resolve(dir, entry.name), depth - 1);
1487
+ if (found) return true;
1488
+ }
1489
+ }
1490
+ } catch {
1491
+ }
1492
+ return false;
1493
+ };
1494
+ var validateSkillPackage = async (workingDir, packageNameOrPath) => {
1495
+ const skillRoot = resolveSkillRoot(workingDir, packageNameOrPath);
1496
+ const hasSkill = await findSkillManifest(skillRoot);
1497
+ if (!hasSkill) {
1498
+ throw new Error(`Skill validation failed: no SKILL.md found in ${skillRoot}`);
1499
+ }
1500
+ };
1501
+ var addSkill = async (workingDir, packageNameOrPath) => {
1502
+ await runInstallCommand(workingDir, packageNameOrPath);
1503
+ await validateSkillPackage(workingDir, packageNameOrPath);
1504
+ process.stdout.write(`Added skill: ${packageNameOrPath}
1505
+ `);
1506
+ };
1507
+ var runTests = async (workingDir, filePath) => {
1508
+ dotenv.config({ path: resolve(workingDir, ".env") });
1509
+ const testFilePath = filePath ?? resolve(workingDir, "tests", "basic.yaml");
1510
+ const content = await readFile(testFilePath, "utf8");
1511
+ const parsed = YAML.parse(content);
1512
+ const tests = parsed.tests ?? [];
1513
+ const harness = new AgentHarness({ workingDir });
1514
+ await harness.initialize();
1515
+ let passed = 0;
1516
+ let failed = 0;
1517
+ for (const testCase of tests) {
1518
+ try {
1519
+ const output = await harness.runToCompletion({ task: testCase.task });
1520
+ const response = output.result.response ?? "";
1521
+ const events = output.events;
1522
+ const expectation = testCase.expect ?? {};
1523
+ const checks = [];
1524
+ if (expectation.contains) {
1525
+ checks.push(response.includes(expectation.contains));
1526
+ }
1527
+ if (typeof expectation.maxSteps === "number") {
1528
+ checks.push(output.result.steps <= expectation.maxSteps);
1529
+ }
1530
+ if (typeof expectation.maxTokens === "number") {
1531
+ checks.push(
1532
+ output.result.tokens.input + output.result.tokens.output <= expectation.maxTokens
1533
+ );
1534
+ }
1535
+ if (expectation.refusal) {
1536
+ checks.push(
1537
+ response.toLowerCase().includes("can't") || response.toLowerCase().includes("cannot")
1538
+ );
1539
+ }
1540
+ if (expectation.toolCalled) {
1541
+ checks.push(
1542
+ events.some(
1543
+ (event) => event.type === "tool:started" && event.tool === expectation.toolCalled
1544
+ )
1545
+ );
1546
+ }
1547
+ const ok = checks.length === 0 ? output.result.status === "completed" : checks.every(Boolean);
1548
+ if (ok) {
1549
+ passed += 1;
1550
+ process.stdout.write(`PASS ${testCase.name}
1551
+ `);
1552
+ } else {
1553
+ failed += 1;
1554
+ process.stdout.write(`FAIL ${testCase.name}
1555
+ `);
1556
+ }
1557
+ } catch (error) {
1558
+ failed += 1;
1559
+ process.stdout.write(
1560
+ `FAIL ${testCase.name} (${error instanceof Error ? error.message : "Unknown test error"})
1561
+ `
1562
+ );
1563
+ }
1564
+ }
1565
+ process.stdout.write(`
1566
+ Test summary: ${passed} passed, ${failed} failed
1567
+ `);
1568
+ return { passed, failed };
1569
+ };
1570
+ var buildTarget = async (workingDir, target) => {
1571
+ const outDir = resolve(workingDir, ".poncho-build", target);
1572
+ await mkdir(outDir, { recursive: true });
1573
+ const serverEntrypoint = `import { startDevServer } from "@poncho-ai/cli";
1574
+
1575
+ const port = Number.parseInt(process.env.PORT ?? "3000", 10);
1576
+ await startDevServer(Number.isNaN(port) ? 3000 : port, { workingDir: process.cwd() });
1577
+ `;
1578
+ const runtimePackageJson = JSON.stringify(
1579
+ {
1580
+ name: "poncho-runtime-bundle",
1581
+ private: true,
1582
+ type: "module",
1583
+ scripts: {
1584
+ start: "node server.js"
1585
+ },
1586
+ dependencies: {
1587
+ "@poncho-ai/cli": "^0.1.0"
1588
+ }
1589
+ },
1590
+ null,
1591
+ 2
1592
+ );
1593
+ if (target === "vercel") {
1594
+ await mkdir(resolve(outDir, "api"), { recursive: true });
1595
+ await copyIfExists(resolve(workingDir, "AGENT.md"), resolve(outDir, "AGENT.md"));
1596
+ await copyIfExists(
1597
+ resolve(workingDir, "poncho.config.js"),
1598
+ resolve(outDir, "poncho.config.js")
1599
+ );
1600
+ await copyIfExists(resolve(workingDir, "skills"), resolve(outDir, "skills"));
1601
+ await copyIfExists(resolve(workingDir, "tests"), resolve(outDir, "tests"));
1602
+ await writeFile(
1603
+ resolve(outDir, "vercel.json"),
1604
+ JSON.stringify(
1605
+ {
1606
+ version: 2,
1607
+ functions: {
1608
+ "api/index.js": {
1609
+ includeFiles: "{AGENT.md,poncho.config.js,skills/**,tests/**}"
1610
+ }
1611
+ },
1612
+ routes: [{ src: "/(.*)", dest: "/api/index.js" }]
1613
+ },
1614
+ null,
1615
+ 2
1616
+ ),
1617
+ "utf8"
1618
+ );
1619
+ await buildVercelHandlerBundle(outDir);
1620
+ await writeFile(
1621
+ resolve(outDir, "package.json"),
1622
+ JSON.stringify(
1623
+ {
1624
+ private: true,
1625
+ type: "module",
1626
+ engines: {
1627
+ node: "20.x"
1628
+ },
1629
+ dependencies: VERCEL_RUNTIME_DEPENDENCIES
1630
+ },
1631
+ null,
1632
+ 2
1633
+ ),
1634
+ "utf8"
1635
+ );
1636
+ } else if (target === "docker") {
1637
+ await writeFile(
1638
+ resolve(outDir, "Dockerfile"),
1639
+ `FROM node:20-slim
1640
+ WORKDIR /app
1641
+ COPY package.json package.json
1642
+ COPY AGENT.md AGENT.md
1643
+ COPY poncho.config.js poncho.config.js
1644
+ COPY skills skills
1645
+ COPY tests tests
1646
+ COPY .env.example .env.example
1647
+ RUN corepack enable && npm install -g @poncho-ai/cli
1648
+ COPY server.js server.js
1649
+ EXPOSE 3000
1650
+ CMD ["node","server.js"]
1651
+ `,
1652
+ "utf8"
1653
+ );
1654
+ await writeFile(resolve(outDir, "server.js"), serverEntrypoint, "utf8");
1655
+ await writeFile(resolve(outDir, "package.json"), runtimePackageJson, "utf8");
1656
+ } else if (target === "lambda") {
1657
+ await writeFile(
1658
+ resolve(outDir, "lambda-handler.js"),
1659
+ `import { startDevServer } from "@poncho-ai/cli";
1660
+ let serverPromise;
1661
+ export const handler = async (event = {}) => {
1662
+ if (!serverPromise) {
1663
+ serverPromise = startDevServer(0, { workingDir: process.cwd() });
1664
+ }
1665
+ const body = JSON.stringify({
1666
+ status: "ready",
1667
+ route: event.rawPath ?? event.path ?? "/",
1668
+ });
1669
+ return { statusCode: 200, headers: { "content-type": "application/json" }, body };
1670
+ };
1671
+ `,
1672
+ "utf8"
1673
+ );
1674
+ await writeFile(resolve(outDir, "package.json"), runtimePackageJson, "utf8");
1675
+ } else if (target === "fly") {
1676
+ await writeFile(
1677
+ resolve(outDir, "fly.toml"),
1678
+ `app = "poncho-app"
1679
+ [env]
1680
+ PORT = "3000"
1681
+ [http_service]
1682
+ internal_port = 3000
1683
+ force_https = true
1684
+ auto_start_machines = true
1685
+ auto_stop_machines = "stop"
1686
+ min_machines_running = 0
1687
+ `,
1688
+ "utf8"
1689
+ );
1690
+ await writeFile(
1691
+ resolve(outDir, "Dockerfile"),
1692
+ `FROM node:20-slim
1693
+ WORKDIR /app
1694
+ COPY package.json package.json
1695
+ COPY AGENT.md AGENT.md
1696
+ COPY poncho.config.js poncho.config.js
1697
+ COPY skills skills
1698
+ COPY tests tests
1699
+ RUN npm install -g @poncho-ai/cli
1700
+ COPY server.js server.js
1701
+ EXPOSE 3000
1702
+ CMD ["node","server.js"]
1703
+ `,
1704
+ "utf8"
1705
+ );
1706
+ await writeFile(resolve(outDir, "server.js"), serverEntrypoint, "utf8");
1707
+ await writeFile(resolve(outDir, "package.json"), runtimePackageJson, "utf8");
1708
+ } else {
1709
+ throw new Error(`Unsupported build target: ${target}`);
1710
+ }
1711
+ process.stdout.write(`Build artifacts generated at ${outDir}
1712
+ `);
1713
+ };
1714
+ var normalizeMcpName = (entry) => entry.name ?? entry.url ?? `mcp_${Date.now()}`;
1715
+ var mcpAdd = async (workingDir, options) => {
1716
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
1717
+ const mcp = [...config.mcp ?? []];
1718
+ if (!options.url) {
1719
+ throw new Error("Remote MCP only: provide --url for a remote MCP server.");
1720
+ }
1721
+ if (options.url.startsWith("ws://") || options.url.startsWith("wss://")) {
1722
+ throw new Error("WebSocket MCP URLs are no longer supported. Use an HTTP MCP endpoint.");
1723
+ }
1724
+ if (!options.url.startsWith("http://") && !options.url.startsWith("https://")) {
1725
+ throw new Error("Invalid MCP URL. Expected http:// or https://.");
1726
+ }
1727
+ mcp.push({
1728
+ name: options.name ?? normalizeMcpName({ url: options.url }),
1729
+ url: options.url,
1730
+ env: options.envVars ?? [],
1731
+ auth: options.authBearerEnv ? {
1732
+ type: "bearer",
1733
+ tokenEnv: options.authBearerEnv
1734
+ } : void 0
1735
+ });
1736
+ await writeConfigFile(workingDir, { ...config, mcp });
1737
+ process.stdout.write("MCP server added.\n");
1738
+ };
1739
+ var mcpList = async (workingDir) => {
1740
+ const config = await loadPonchoConfig(workingDir);
1741
+ const mcp = config?.mcp ?? [];
1742
+ if (mcp.length === 0) {
1743
+ process.stdout.write("No MCP servers configured.\n");
1744
+ return;
1745
+ }
1746
+ process.stdout.write("Configured MCP servers:\n");
1747
+ for (const entry of mcp) {
1748
+ const auth = entry.auth?.type === "bearer" ? `auth=bearer:${entry.auth.tokenEnv}` : "auth=none";
1749
+ const mode = entry.tools?.mode ?? "all";
1750
+ process.stdout.write(
1751
+ `- ${entry.name ?? entry.url} (remote: ${entry.url}, ${auth}, mode=${mode})
1752
+ `
1753
+ );
1754
+ }
1755
+ };
1756
+ var mcpRemove = async (workingDir, name) => {
1757
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
1758
+ const before = config.mcp ?? [];
1759
+ const filtered = before.filter((entry) => normalizeMcpName(entry) !== name);
1760
+ await writeConfigFile(workingDir, { ...config, mcp: filtered });
1761
+ process.stdout.write(`Removed MCP server: ${name}
1762
+ `);
1763
+ };
1764
+ var resolveMcpEntry = async (workingDir, serverName) => {
1765
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
1766
+ const entries = config.mcp ?? [];
1767
+ const index = entries.findIndex((entry) => normalizeMcpName(entry) === serverName);
1768
+ if (index < 0) {
1769
+ throw new Error(`MCP server "${serverName}" is not configured.`);
1770
+ }
1771
+ return { config, index };
1772
+ };
1773
+ var discoverMcpTools = async (workingDir, serverName) => {
1774
+ const { config, index } = await resolveMcpEntry(workingDir, serverName);
1775
+ const entry = (config.mcp ?? [])[index];
1776
+ const bridge = new LocalMcpBridge({ mcp: [entry] });
1777
+ try {
1778
+ await bridge.startLocalServers();
1779
+ await bridge.discoverTools();
1780
+ return bridge.listDiscoveredTools(normalizeMcpName(entry));
1781
+ } finally {
1782
+ await bridge.stopLocalServers();
1783
+ }
1784
+ };
1785
+ var mcpToolsList = async (workingDir, serverName) => {
1786
+ const discovered = await discoverMcpTools(workingDir, serverName);
1787
+ if (discovered.length === 0) {
1788
+ process.stdout.write(`No tools discovered for MCP server "${serverName}".
1789
+ `);
1790
+ return;
1791
+ }
1792
+ process.stdout.write(`Discovered tools for "${serverName}":
1793
+ `);
1794
+ for (const tool of discovered) {
1795
+ process.stdout.write(`- ${tool}
1796
+ `);
1797
+ }
1798
+ };
1799
+ var mcpToolsSelect = async (workingDir, serverName, options) => {
1800
+ const discovered = await discoverMcpTools(workingDir, serverName);
1801
+ if (discovered.length === 0) {
1802
+ process.stdout.write(`No tools discovered for MCP server "${serverName}".
1803
+ `);
1804
+ return;
1805
+ }
1806
+ let selected = [];
1807
+ if (options.all) {
1808
+ selected = [...discovered];
1809
+ } else if (options.toolsCsv && options.toolsCsv.trim().length > 0) {
1810
+ const requested = options.toolsCsv.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
1811
+ selected = discovered.filter((tool) => requested.includes(tool));
1812
+ } else {
1813
+ process.stdout.write(`Discovered tools for "${serverName}":
1814
+ `);
1815
+ discovered.forEach((tool, idx) => {
1816
+ process.stdout.write(`${idx + 1}. ${tool}
1817
+ `);
1818
+ });
1819
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1820
+ const answer = await rl.question(
1821
+ "Enter comma-separated tool numbers/names to allow (or * for all): "
1822
+ );
1823
+ rl.close();
1824
+ const raw = answer.trim();
1825
+ if (raw === "*") {
1826
+ selected = [...discovered];
1827
+ } else {
1828
+ const tokens = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
1829
+ const fromIndex = tokens.map((token) => Number.parseInt(token, 10)).filter((value) => !Number.isNaN(value)).map((index2) => discovered[index2 - 1]).filter((value) => typeof value === "string");
1830
+ const byName = discovered.filter((tool) => tokens.includes(tool));
1831
+ selected = [.../* @__PURE__ */ new Set([...fromIndex, ...byName])];
1832
+ }
1833
+ }
1834
+ if (selected.length === 0) {
1835
+ throw new Error("No valid tools selected.");
1836
+ }
1837
+ const { config, index } = await resolveMcpEntry(workingDir, serverName);
1838
+ const mcp = [...config.mcp ?? []];
1839
+ const existing = mcp[index];
1840
+ mcp[index] = {
1841
+ ...existing,
1842
+ tools: {
1843
+ ...existing.tools ?? {},
1844
+ mode: "allowlist",
1845
+ include: selected.sort()
1846
+ }
1847
+ };
1848
+ await writeConfigFile(workingDir, { ...config, mcp });
1849
+ process.stdout.write(
1850
+ `Updated ${serverName} to allowlist ${selected.length} tools in poncho.config.js.
1851
+ `
1852
+ );
1853
+ process.stdout.write(
1854
+ "\nDeclare selected MCP tools explicitly in AGENT.md and/or SKILL.md:\n"
1855
+ );
1856
+ process.stdout.write(
1857
+ "AGENT.md frontmatter snippet:\n---\ntools:\n mcp:\n" + selected.map((tool) => ` - ${tool}`).join("\n") + "\n---\n"
1858
+ );
1859
+ process.stdout.write(
1860
+ "SKILL.md frontmatter snippet:\n---\ntools:\n mcp:\n" + selected.map((tool) => ` - ${tool}`).join("\n") + "\n---\n"
1861
+ );
1862
+ };
1863
+ var buildCli = () => {
1864
+ const program = new Command();
1865
+ program.name("poncho").description("CLI for building and running Poncho agents").version("0.1.0");
1866
+ program.command("init").argument("<name>", "project name").option("--yes", "accept defaults and skip prompts", false).description("Scaffold a new Poncho project").action(async (name, options) => {
1867
+ await initProject(name, {
1868
+ onboarding: {
1869
+ yes: options.yes,
1870
+ interactive: !options.yes && process.stdin.isTTY === true && process.stdout.isTTY === true
1871
+ }
1872
+ });
1873
+ });
1874
+ program.command("dev").description("Run local development server").option("--port <port>", "server port", "3000").action(async (options) => {
1875
+ const port = Number.parseInt(options.port, 10);
1876
+ await startDevServer(Number.isNaN(port) ? 3e3 : port);
1877
+ });
1878
+ program.command("run").argument("[task]", "task to run").description("Execute the agent once").option("--param <keyValue>", "parameter key=value", (value, all) => {
1879
+ all.push(value);
1880
+ return all;
1881
+ }, []).option("--file <path>", "include file contents", (value, all) => {
1882
+ all.push(value);
1883
+ return all;
1884
+ }, []).option("--json", "output json", false).option("--interactive", "run in interactive mode", false).action(
1885
+ async (task, options) => {
1886
+ const params = parseParams(options.param);
1887
+ if (options.interactive) {
1888
+ await runInteractive(process.cwd(), params);
1889
+ return;
1890
+ }
1891
+ if (!task) {
1892
+ throw new Error("Task is required unless --interactive is used.");
1893
+ }
1894
+ await runOnce(task, {
1895
+ params,
1896
+ json: options.json,
1897
+ filePaths: options.file
1898
+ });
1899
+ }
1900
+ );
1901
+ program.command("tools").description("List all tools available to the agent").action(async () => {
1902
+ await listTools(process.cwd());
1903
+ });
1904
+ program.command("add").argument("<packageOrPath>", "skill package name/path").description("Add a skill package and validate SKILL.md").action(async (packageOrPath) => {
1905
+ await addSkill(process.cwd(), packageOrPath);
1906
+ });
1907
+ program.command("update-agent").description("Remove deprecated embedded local guidance from AGENT.md").action(async () => {
1908
+ await updateAgentGuidance(process.cwd());
1909
+ });
1910
+ program.command("test").argument("[file]", "test file path (yaml)").description("Run yaml-defined agent tests").action(async (file) => {
1911
+ const testFile = file ? resolve(process.cwd(), file) : void 0;
1912
+ const result = await runTests(process.cwd(), testFile);
1913
+ if (result.failed > 0) {
1914
+ process.exitCode = 1;
1915
+ }
1916
+ });
1917
+ program.command("build").argument("<target>", "vercel|docker|lambda|fly").description("Generate build artifacts for deployment target").action(async (target) => {
1918
+ await buildTarget(process.cwd(), target);
1919
+ });
1920
+ const mcpCommand = program.command("mcp").description("Manage MCP servers");
1921
+ mcpCommand.command("add").requiredOption("--url <url>", "remote MCP url").option("--name <name>", "server name").option(
1922
+ "--auth-bearer-env <name>",
1923
+ "env var name containing bearer token for this MCP server"
1924
+ ).option("--env <name>", "env variable (repeatable)", (value, all) => {
1925
+ all.push(value);
1926
+ return all;
1927
+ }, []).action(
1928
+ async (options) => {
1929
+ await mcpAdd(process.cwd(), {
1930
+ url: options.url,
1931
+ name: options.name,
1932
+ envVars: options.env,
1933
+ authBearerEnv: options.authBearerEnv
1934
+ });
1935
+ }
1936
+ );
1937
+ mcpCommand.command("list").description("List configured MCP servers").action(async () => {
1938
+ await mcpList(process.cwd());
1939
+ });
1940
+ mcpCommand.command("remove").argument("<name>", "server name").description("Remove an MCP server by name").action(async (name) => {
1941
+ await mcpRemove(process.cwd(), name);
1942
+ });
1943
+ const mcpToolsCommand = mcpCommand.command("tools").description("Discover and curate tools for a configured MCP server");
1944
+ mcpToolsCommand.command("list").argument("<name>", "server name").description("Discover and list tools from a configured MCP server").action(async (name) => {
1945
+ await mcpToolsList(process.cwd(), name);
1946
+ });
1947
+ mcpToolsCommand.command("select").argument("<name>", "server name").description("Select MCP tools and store as config allowlist").option("--all", "select all discovered tools", false).option("--tools <csv>", "comma-separated discovered tool names").action(
1948
+ async (name, options) => {
1949
+ await mcpToolsSelect(process.cwd(), name, {
1950
+ all: options.all,
1951
+ toolsCsv: options.tools
1952
+ });
1953
+ }
1954
+ );
1955
+ return program;
1956
+ };
1957
+ var main = async (argv = process.argv) => {
1958
+ try {
1959
+ await buildCli().parseAsync(argv);
1960
+ } catch (error) {
1961
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EADDRINUSE") {
1962
+ const message = "Port is already in use. Try `poncho dev --port 3001` or stop the process using port 3000.";
1963
+ process.stderr.write(`${message}
1964
+ `);
1965
+ process.exitCode = 1;
1966
+ return;
1967
+ }
1968
+ process.stderr.write(`${error instanceof Error ? error.message : "Unknown CLI error"}
1969
+ `);
1970
+ process.exitCode = 1;
1971
+ }
1972
+ };
1973
+ var packageRoot = resolve(__dirname, "..");
1974
+
1975
+ export {
1976
+ initProject,
1977
+ updateAgentGuidance,
1978
+ createRequestHandler,
1979
+ startDevServer,
1980
+ runOnce,
1981
+ runInteractive,
1982
+ listTools,
1983
+ addSkill,
1984
+ runTests,
1985
+ buildTarget,
1986
+ mcpAdd,
1987
+ mcpList,
1988
+ mcpRemove,
1989
+ mcpToolsList,
1990
+ mcpToolsSelect,
1991
+ buildCli,
1992
+ main,
1993
+ packageRoot
1994
+ };