@poncho-ai/cli 0.3.0 → 0.3.2

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,2145 @@
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
+ - Never claim a file/tool change unless the corresponding tool call actually succeeded
507
+ `;
508
+ var resolveLocalPackagesRoot = () => {
509
+ const candidate = resolve(__dirname, "..", "..", "harness", "package.json");
510
+ if (existsSync(candidate)) {
511
+ return resolve(__dirname, "..", "..");
512
+ }
513
+ return null;
514
+ };
515
+ var resolveCoreDeps = (projectDir) => {
516
+ const packagesRoot = resolveLocalPackagesRoot();
517
+ if (packagesRoot) {
518
+ const harnessAbs = resolve(packagesRoot, "harness");
519
+ const sdkAbs = resolve(packagesRoot, "sdk");
520
+ return {
521
+ harness: `link:${relative(projectDir, harnessAbs)}`,
522
+ sdk: `link:${relative(projectDir, sdkAbs)}`
523
+ };
524
+ }
525
+ return { harness: "^0.1.0", sdk: "^0.1.0" };
526
+ };
527
+ var PACKAGE_TEMPLATE = (name, projectDir) => {
528
+ const deps = resolveCoreDeps(projectDir);
529
+ return JSON.stringify(
530
+ {
531
+ name,
532
+ private: true,
533
+ type: "module",
534
+ dependencies: {
535
+ "@poncho-ai/harness": deps.harness,
536
+ "@poncho-ai/sdk": deps.sdk
537
+ }
538
+ },
539
+ null,
540
+ 2
541
+ );
542
+ };
543
+ var README_TEMPLATE = (name) => `# ${name}
544
+
545
+ An AI agent built with [Poncho](https://github.com/cesr/poncho-ai).
546
+
547
+ ## Prerequisites
548
+
549
+ - Node.js 20+
550
+ - npm (or pnpm/yarn)
551
+ - Anthropic or OpenAI API key
552
+
553
+ ## Quick Start
554
+
555
+ \`\`\`bash
556
+ npm install
557
+ # If you didn't enter an API key during init:
558
+ cp .env.example .env
559
+ # Then edit .env and add your API key
560
+ poncho dev
561
+ \`\`\`
562
+
563
+ Open \`http://localhost:3000\` for the web UI.
564
+
565
+ On your first interactive session, the agent introduces its configurable capabilities.
566
+
567
+ ## Common Commands
568
+
569
+ \`\`\`bash
570
+ # Local web UI + API server
571
+ poncho dev
572
+
573
+ # Local interactive CLI
574
+ poncho run --interactive
575
+
576
+ # One-off run
577
+ poncho run "Your task here"
578
+
579
+ # Run tests
580
+ poncho test
581
+
582
+ # List available tools
583
+ poncho tools
584
+ \`\`\`
585
+
586
+ ## Add Skills
587
+
588
+ Install skills from a local path or remote repository, then verify discovery:
589
+
590
+ \`\`\`bash
591
+ # Install skills into ./skills
592
+ poncho add <repo-or-path>
593
+
594
+ # Verify loaded tools
595
+ poncho tools
596
+ \`\`\`
597
+
598
+ After adding skills, run \`poncho dev\` or \`poncho run --interactive\` and ask the agent to use them.
599
+
600
+ ## Configure MCP Servers (Remote)
601
+
602
+ Connect remote MCP servers and expose their tools to the agent:
603
+
604
+ \`\`\`bash
605
+ # Add remote MCP server
606
+ poncho mcp add --url https://mcp.example.com/github --name github --auth-bearer-env GITHUB_TOKEN
607
+
608
+ # List configured servers
609
+ poncho mcp list
610
+
611
+ # Discover and select MCP tools into config allowlist
612
+ poncho mcp tools list github
613
+ poncho mcp tools select github
614
+
615
+ # Remove a server
616
+ poncho mcp remove github
617
+ \`\`\`
618
+
619
+ Set required secrets in \`.env\` (for example, \`GITHUB_TOKEN=...\`).
620
+
621
+ ## Tool Intent in Frontmatter
622
+
623
+ Declare tool intent directly in \`AGENT.md\` and \`SKILL.md\` frontmatter:
624
+
625
+ \`\`\`yaml
626
+ tools:
627
+ mcp:
628
+ - github/list_issues
629
+ - github/*
630
+ scripts:
631
+ - starter/scripts/*
632
+ \`\`\`
633
+
634
+ How it works:
635
+
636
+ - \`AGENT.md\` provides fallback MCP intent when no skill is active.
637
+ - \`SKILL.md\` intent applies when you activate that skill (\`activate_skill\`).
638
+ - Skill scripts are accessible by default from each skill's \`scripts/\` directory.
639
+ - \`AGENT.md\` \`tools.scripts\` can still be used to narrow script access when active skills do not set script intent.
640
+ - Active skills are unioned, then filtered by policy in \`poncho.config.js\`.
641
+ - Deactivating a skill (\`deactivate_skill\`) removes its MCP tools from runtime registration.
642
+
643
+ Pattern format is strict slash-only:
644
+
645
+ - MCP: \`server/tool\`, \`server/*\`
646
+ - Scripts: \`skill/scripts/file.ts\`, \`skill/scripts/*\`
647
+
648
+ ## Configuration
649
+
650
+ Core files:
651
+
652
+ - \`AGENT.md\`: behavior, model selection, runtime guidance
653
+ - \`poncho.config.js\`: runtime config (storage, auth, telemetry, MCP, tools)
654
+ - \`.env\`: secrets and environment variables
655
+
656
+ Example \`poncho.config.js\`:
657
+
658
+ \`\`\`javascript
659
+ export default {
660
+ storage: {
661
+ provider: "local", // local | memory | redis | upstash | dynamodb
662
+ memory: {
663
+ enabled: true,
664
+ maxRecallConversations: 20,
665
+ },
666
+ },
667
+ auth: {
668
+ required: false,
669
+ },
670
+ telemetry: {
671
+ enabled: true,
672
+ },
673
+ mcp: [
674
+ {
675
+ name: "github",
676
+ url: "https://mcp.example.com/github",
677
+ auth: { type: "bearer", tokenEnv: "GITHUB_TOKEN" },
678
+ tools: {
679
+ mode: "allowlist",
680
+ include: ["github/list_issues", "github/get_issue"],
681
+ },
682
+ },
683
+ ],
684
+ scripts: {
685
+ mode: "allowlist",
686
+ include: ["starter/scripts/*"],
687
+ },
688
+ tools: {
689
+ defaults: {
690
+ list_directory: true,
691
+ read_file: true,
692
+ write_file: true, // still gated by environment/policy
693
+ },
694
+ byEnvironment: {
695
+ production: {
696
+ read_file: false, // example override
697
+ },
698
+ },
699
+ },
700
+ };
701
+ \`\`\`
702
+
703
+ ## Project Structure
704
+
705
+ \`\`\`
706
+ ${name}/
707
+ \u251C\u2500\u2500 AGENT.md # Agent definition and system prompt
708
+ \u251C\u2500\u2500 poncho.config.js # Configuration (MCP servers, auth, etc.)
709
+ \u251C\u2500\u2500 package.json # Dependencies
710
+ \u251C\u2500\u2500 .env.example # Environment variables template
711
+ \u251C\u2500\u2500 tests/
712
+ \u2502 \u2514\u2500\u2500 basic.yaml # Test suite
713
+ \u2514\u2500\u2500 skills/
714
+ \u2514\u2500\u2500 starter/
715
+ \u251C\u2500\u2500 SKILL.md
716
+ \u2514\u2500\u2500 scripts/
717
+ \u2514\u2500\u2500 starter-echo.ts
718
+ \`\`\`
719
+
720
+ ## Deployment
721
+
722
+ \`\`\`bash
723
+ # Build for Vercel
724
+ poncho build vercel
725
+ cd .poncho-build/vercel && vercel deploy --prod
726
+
727
+ # Build for Docker
728
+ poncho build docker
729
+ docker build -t ${name} .
730
+ \`\`\`
731
+
732
+ For full reference:
733
+ https://github.com/cesr/poncho-ai
734
+ `;
735
+ var ENV_TEMPLATE = "ANTHROPIC_API_KEY=sk-ant-...\n";
736
+ var GITIGNORE_TEMPLATE = ".env\nnode_modules\ndist\n.poncho-build\n.poncho/\ninteractive-session.json\n";
737
+ var VERCEL_RUNTIME_DEPENDENCIES = {
738
+ "@anthropic-ai/sdk": "^0.74.0",
739
+ "@aws-sdk/client-dynamodb": "^3.988.0",
740
+ "@latitude-data/telemetry": "^2.0.2",
741
+ commander: "^12.0.0",
742
+ dotenv: "^16.4.0",
743
+ jiti: "^2.6.1",
744
+ mustache: "^4.2.0",
745
+ openai: "^6.3.0",
746
+ redis: "^5.10.0",
747
+ yaml: "^2.8.1"
748
+ };
749
+ var TEST_TEMPLATE = `tests:
750
+ - name: "Basic sanity"
751
+ task: "What is 2 + 2?"
752
+ expect:
753
+ contains: "4"
754
+ `;
755
+ var SKILL_TEMPLATE = `---
756
+ name: starter-skill
757
+ description: Starter local skill template
758
+ ---
759
+
760
+ # Starter Skill
761
+
762
+ This is a starter local skill created by \`poncho init\`.
763
+
764
+ ## Authoring Notes
765
+
766
+ - Put executable JavaScript/TypeScript files in \`scripts/\`.
767
+ - Ask the agent to call \`run_skill_script\` with \`skill\`, \`script\`, and optional \`input\`.
768
+ `;
769
+ var SKILL_TOOL_TEMPLATE = `export default async function run(input) {
770
+ const message = typeof input?.message === "string" ? input.message : "";
771
+ return { echoed: message };
772
+ }
773
+ `;
774
+ var ensureFile = async (path, content) => {
775
+ await mkdir(dirname(path), { recursive: true });
776
+ await writeFile(path, content, { encoding: "utf8", flag: "wx" });
777
+ };
778
+ var copyIfExists = async (sourcePath, destinationPath) => {
779
+ try {
780
+ await access(sourcePath);
781
+ } catch {
782
+ return;
783
+ }
784
+ await mkdir(dirname(destinationPath), { recursive: true });
785
+ await cp(sourcePath, destinationPath, { recursive: true });
786
+ };
787
+ var resolveCliEntrypoint = async () => {
788
+ const sourceEntrypoint = resolve(packageRoot, "src", "index.ts");
789
+ try {
790
+ await access(sourceEntrypoint);
791
+ return sourceEntrypoint;
792
+ } catch {
793
+ return resolve(packageRoot, "dist", "index.js");
794
+ }
795
+ };
796
+ var buildVercelHandlerBundle = async (outDir) => {
797
+ const { build: esbuild } = await import("esbuild");
798
+ const cliEntrypoint = await resolveCliEntrypoint();
799
+ const tempEntry = resolve(outDir, "api", "_entry.js");
800
+ await writeFile(
801
+ tempEntry,
802
+ `import { createRequestHandler } from ${JSON.stringify(cliEntrypoint)};
803
+ let handlerPromise;
804
+ export default async function handler(req, res) {
805
+ try {
806
+ if (!handlerPromise) {
807
+ handlerPromise = createRequestHandler({ workingDir: process.cwd() });
808
+ }
809
+ const requestHandler = await handlerPromise;
810
+ await requestHandler(req, res);
811
+ } catch (error) {
812
+ console.error("Handler error:", error);
813
+ if (!res.headersSent) {
814
+ res.writeHead(500, { "Content-Type": "application/json" });
815
+ res.end(JSON.stringify({ error: "Internal server error", message: error?.message || "Unknown error" }));
816
+ }
817
+ }
818
+ }
819
+ `,
820
+ "utf8"
821
+ );
822
+ await esbuild({
823
+ entryPoints: [tempEntry],
824
+ bundle: true,
825
+ platform: "node",
826
+ format: "esm",
827
+ target: "node20",
828
+ outfile: resolve(outDir, "api", "index.js"),
829
+ sourcemap: false,
830
+ legalComments: "none",
831
+ external: [
832
+ ...Object.keys(VERCEL_RUNTIME_DEPENDENCIES),
833
+ "@anthropic-ai/sdk/*",
834
+ "child_process",
835
+ "fs",
836
+ "fs/promises",
837
+ "http",
838
+ "https",
839
+ "path",
840
+ "module",
841
+ "url",
842
+ "readline",
843
+ "readline/promises",
844
+ "crypto",
845
+ "stream",
846
+ "events",
847
+ "util",
848
+ "os",
849
+ "zlib",
850
+ "net",
851
+ "tls",
852
+ "dns",
853
+ "assert",
854
+ "buffer",
855
+ "timers",
856
+ "timers/promises",
857
+ "node:child_process",
858
+ "node:fs",
859
+ "node:fs/promises",
860
+ "node:http",
861
+ "node:https",
862
+ "node:path",
863
+ "node:module",
864
+ "node:url",
865
+ "node:readline",
866
+ "node:readline/promises",
867
+ "node:crypto",
868
+ "node:stream",
869
+ "node:events",
870
+ "node:util",
871
+ "node:os",
872
+ "node:zlib",
873
+ "node:net",
874
+ "node:tls",
875
+ "node:dns",
876
+ "node:assert",
877
+ "node:buffer",
878
+ "node:timers",
879
+ "node:timers/promises"
880
+ ]
881
+ });
882
+ };
883
+ var renderConfigFile = (config) => `export default ${JSON.stringify(config, null, 2)}
884
+ `;
885
+ var writeConfigFile = async (workingDir, config) => {
886
+ const serialized = renderConfigFile(config);
887
+ await writeFile(resolve(workingDir, "poncho.config.js"), serialized, "utf8");
888
+ };
889
+ var ensureEnvPlaceholder = async (filePath, key) => {
890
+ const normalizedKey = key.trim();
891
+ if (!normalizedKey) {
892
+ return false;
893
+ }
894
+ let content = "";
895
+ try {
896
+ content = await readFile(filePath, "utf8");
897
+ } catch {
898
+ await writeFile(filePath, `${normalizedKey}=
899
+ `, "utf8");
900
+ return true;
901
+ }
902
+ const present = content.split(/\r?\n/).some((line) => line.trimStart().startsWith(`${normalizedKey}=`));
903
+ if (present) {
904
+ return false;
905
+ }
906
+ const withTrailingNewline = content.length === 0 || content.endsWith("\n") ? content : `${content}
907
+ `;
908
+ await writeFile(filePath, `${withTrailingNewline}${normalizedKey}=
909
+ `, "utf8");
910
+ return true;
911
+ };
912
+ var removeEnvPlaceholder = async (filePath, key) => {
913
+ const normalizedKey = key.trim();
914
+ if (!normalizedKey) {
915
+ return false;
916
+ }
917
+ let content = "";
918
+ try {
919
+ content = await readFile(filePath, "utf8");
920
+ } catch {
921
+ return false;
922
+ }
923
+ const lines = content.split(/\r?\n/);
924
+ const filtered = lines.filter((line) => !line.trimStart().startsWith(`${normalizedKey}=`));
925
+ if (filtered.length === lines.length) {
926
+ return false;
927
+ }
928
+ const nextContent = filtered.join("\n").replace(/\n+$/, "");
929
+ await writeFile(filePath, nextContent.length > 0 ? `${nextContent}
930
+ ` : "", "utf8");
931
+ return true;
932
+ };
933
+ var gitInit = (cwd) => new Promise((resolve2) => {
934
+ const child = spawn("git", ["init"], { cwd, stdio: "ignore" });
935
+ child.on("error", () => resolve2(false));
936
+ child.on("close", (code) => resolve2(code === 0));
937
+ });
938
+ var initProject = async (projectName, options) => {
939
+ const baseDir = options?.workingDir ?? process.cwd();
940
+ const projectDir = resolve(baseDir, projectName);
941
+ await mkdir(projectDir, { recursive: true });
942
+ const onboardingOptions = options?.onboarding ?? {
943
+ yes: true,
944
+ interactive: false
945
+ };
946
+ const onboarding = await runInitOnboarding(onboardingOptions);
947
+ const G = "\x1B[32m";
948
+ const D = "\x1B[2m";
949
+ const B = "\x1B[1m";
950
+ const CY = "\x1B[36m";
951
+ const YW = "\x1B[33m";
952
+ const R = "\x1B[0m";
953
+ process.stdout.write("\n");
954
+ const scaffoldFiles = [
955
+ { path: "AGENT.md", content: AGENT_TEMPLATE(projectName, { modelProvider: onboarding.agentModel.provider, modelName: onboarding.agentModel.name }) },
956
+ { path: "poncho.config.js", content: renderConfigFile(onboarding.config) },
957
+ { path: "package.json", content: PACKAGE_TEMPLATE(projectName, projectDir) },
958
+ { path: "README.md", content: README_TEMPLATE(projectName) },
959
+ { path: ".env.example", content: options?.envExampleOverride ?? onboarding.envExample ?? ENV_TEMPLATE },
960
+ { path: ".gitignore", content: GITIGNORE_TEMPLATE },
961
+ { path: "tests/basic.yaml", content: TEST_TEMPLATE },
962
+ { path: "skills/starter/SKILL.md", content: SKILL_TEMPLATE },
963
+ { path: "skills/starter/scripts/starter-echo.ts", content: SKILL_TOOL_TEMPLATE }
964
+ ];
965
+ if (onboarding.envFile) {
966
+ scaffoldFiles.push({ path: ".env", content: onboarding.envFile });
967
+ }
968
+ for (const file of scaffoldFiles) {
969
+ await ensureFile(resolve(projectDir, file.path), file.content);
970
+ process.stdout.write(` ${D}+${R} ${D}${file.path}${R}
971
+ `);
972
+ }
973
+ await initializeOnboardingMarker(projectDir, {
974
+ allowIntro: !(onboardingOptions.yes ?? false)
975
+ });
976
+ process.stdout.write("\n");
977
+ try {
978
+ await runPnpmInstall(projectDir);
979
+ process.stdout.write(` ${G}\u2713${R} ${D}Installed dependencies${R}
980
+ `);
981
+ } catch {
982
+ process.stdout.write(
983
+ ` ${YW}!${R} Could not install dependencies \u2014 run ${D}pnpm install${R} manually
984
+ `
985
+ );
986
+ }
987
+ const gitOk = await gitInit(projectDir);
988
+ if (gitOk) {
989
+ process.stdout.write(` ${G}\u2713${R} ${D}Initialized git${R}
990
+ `);
991
+ }
992
+ process.stdout.write(` ${G}\u2713${R} ${B}${projectName}${R} is ready
993
+ `);
994
+ process.stdout.write("\n");
995
+ process.stdout.write(` ${B}Get started${R}
996
+ `);
997
+ process.stdout.write("\n");
998
+ process.stdout.write(` ${D}$${R} cd ${projectName}
999
+ `);
1000
+ process.stdout.write("\n");
1001
+ process.stdout.write(` ${CY}Web UI${R} ${D}$${R} poncho dev
1002
+ `);
1003
+ process.stdout.write(` ${CY}CLI interactive${R} ${D}$${R} poncho run --interactive
1004
+ `);
1005
+ process.stdout.write("\n");
1006
+ if (onboarding.envNeedsUserInput) {
1007
+ process.stdout.write(
1008
+ ` ${YW}!${R} Make sure you add your keys to the ${B}.env${R} file.
1009
+ `
1010
+ );
1011
+ }
1012
+ process.stdout.write(` ${D}The agent will introduce itself on your first session.${R}
1013
+ `);
1014
+ process.stdout.write("\n");
1015
+ };
1016
+ var updateAgentGuidance = async (workingDir) => {
1017
+ const agentPath = resolve(workingDir, "AGENT.md");
1018
+ const content = await readFile(agentPath, "utf8");
1019
+ const guidanceSectionPattern = /\n## Configuration Assistant Context[\s\S]*?(?=\n## |\n# |$)|\n## Skill Authoring Guidance[\s\S]*?(?=\n## |\n# |$)/g;
1020
+ const normalized = content.replace(/\s+$/g, "");
1021
+ const updated = normalized.replace(guidanceSectionPattern, "").replace(/\n{3,}/g, "\n\n");
1022
+ if (updated === normalized) {
1023
+ process.stdout.write("AGENT.md does not contain deprecated embedded local guidance.\n");
1024
+ return false;
1025
+ }
1026
+ await writeFile(agentPath, `${updated}
1027
+ `, "utf8");
1028
+ process.stdout.write("Removed deprecated embedded local guidance from AGENT.md.\n");
1029
+ return true;
1030
+ };
1031
+ var formatSseEvent = (event) => `event: ${event.type}
1032
+ data: ${JSON.stringify(event)}
1033
+
1034
+ `;
1035
+ var createRequestHandler = async (options) => {
1036
+ const workingDir = options?.workingDir ?? process.cwd();
1037
+ dotenv.config({ path: resolve(workingDir, ".env") });
1038
+ const config = await loadPonchoConfig(workingDir);
1039
+ let agentName = "Agent";
1040
+ let agentModelProvider = "anthropic";
1041
+ let agentModelName = "claude-opus-4-5";
1042
+ try {
1043
+ const agentMd = await readFile(resolve(workingDir, "AGENT.md"), "utf8");
1044
+ const nameMatch = agentMd.match(/^name:\s*(.+)$/m);
1045
+ const providerMatch = agentMd.match(/^\s{2}provider:\s*(.+)$/m);
1046
+ const modelMatch = agentMd.match(/^\s{2}name:\s*(.+)$/m);
1047
+ if (nameMatch?.[1]) {
1048
+ agentName = nameMatch[1].trim().replace(/^["']|["']$/g, "");
1049
+ }
1050
+ if (providerMatch?.[1]) {
1051
+ agentModelProvider = providerMatch[1].trim().replace(/^["']|["']$/g, "");
1052
+ }
1053
+ if (modelMatch?.[1]) {
1054
+ agentModelName = modelMatch[1].trim().replace(/^["']|["']$/g, "");
1055
+ }
1056
+ } catch {
1057
+ }
1058
+ const harness = new AgentHarness({ workingDir });
1059
+ await harness.initialize();
1060
+ const telemetry = new TelemetryEmitter(config?.telemetry);
1061
+ const conversationStore = createConversationStore(resolveStateConfig(config), { workingDir });
1062
+ const sessionStore = new SessionStore();
1063
+ const loginRateLimiter = new LoginRateLimiter();
1064
+ const passphrase = process.env.AGENT_UI_PASSPHRASE ?? "";
1065
+ const isProduction = resolveHarnessEnvironment() === "production";
1066
+ const requireUiAuth = passphrase.length > 0;
1067
+ const secureCookies = isProduction;
1068
+ return async (request, response) => {
1069
+ if (!request.url || !request.method) {
1070
+ writeJson(response, 404, { error: "Not found" });
1071
+ return;
1072
+ }
1073
+ const [pathname] = request.url.split("?");
1074
+ if (request.method === "GET" && (pathname === "/" || pathname.startsWith("/c/"))) {
1075
+ writeHtml(response, 200, renderWebUiHtml({ agentName }));
1076
+ return;
1077
+ }
1078
+ if (pathname === "/manifest.json" && request.method === "GET") {
1079
+ response.writeHead(200, { "Content-Type": "application/manifest+json" });
1080
+ response.end(renderManifest({ agentName }));
1081
+ return;
1082
+ }
1083
+ if (pathname === "/sw.js" && request.method === "GET") {
1084
+ response.writeHead(200, {
1085
+ "Content-Type": "application/javascript",
1086
+ "Service-Worker-Allowed": "/"
1087
+ });
1088
+ response.end(renderServiceWorker());
1089
+ return;
1090
+ }
1091
+ if (pathname === "/icon.svg" && request.method === "GET") {
1092
+ response.writeHead(200, { "Content-Type": "image/svg+xml" });
1093
+ response.end(renderIconSvg({ agentName }));
1094
+ return;
1095
+ }
1096
+ if ((pathname === "/icon-192.png" || pathname === "/icon-512.png") && request.method === "GET") {
1097
+ response.writeHead(302, { Location: "/icon.svg" });
1098
+ response.end();
1099
+ return;
1100
+ }
1101
+ if (pathname === "/health" && request.method === "GET") {
1102
+ writeJson(response, 200, { status: "ok" });
1103
+ return;
1104
+ }
1105
+ const cookies = parseCookies(request);
1106
+ const sessionId = cookies.poncho_session;
1107
+ const session = sessionId ? sessionStore.get(sessionId) : void 0;
1108
+ const ownerId = session?.ownerId ?? "local-owner";
1109
+ const requiresCsrfValidation = request.method !== "GET" && request.method !== "HEAD" && request.method !== "OPTIONS";
1110
+ if (pathname === "/api/auth/session" && request.method === "GET") {
1111
+ if (!requireUiAuth) {
1112
+ writeJson(response, 200, { authenticated: true, csrfToken: "" });
1113
+ return;
1114
+ }
1115
+ if (!session) {
1116
+ writeJson(response, 200, { authenticated: false });
1117
+ return;
1118
+ }
1119
+ writeJson(response, 200, {
1120
+ authenticated: true,
1121
+ sessionId: session.sessionId,
1122
+ ownerId: session.ownerId,
1123
+ csrfToken: session.csrfToken
1124
+ });
1125
+ return;
1126
+ }
1127
+ if (pathname === "/api/auth/login" && request.method === "POST") {
1128
+ if (!requireUiAuth) {
1129
+ writeJson(response, 200, { authenticated: true, csrfToken: "" });
1130
+ return;
1131
+ }
1132
+ const ip = getRequestIp(request);
1133
+ const canAttempt = loginRateLimiter.canAttempt(ip);
1134
+ if (!canAttempt.allowed) {
1135
+ writeJson(response, 429, {
1136
+ code: "AUTH_RATE_LIMIT",
1137
+ message: "Too many failed login attempts. Try again later.",
1138
+ retryAfterSeconds: canAttempt.retryAfterSeconds
1139
+ });
1140
+ return;
1141
+ }
1142
+ const body = await readRequestBody(request);
1143
+ const provided = body.passphrase ?? "";
1144
+ if (!verifyPassphrase(provided, passphrase)) {
1145
+ const failure = loginRateLimiter.registerFailure(ip);
1146
+ writeJson(response, 401, {
1147
+ code: "AUTH_ERROR",
1148
+ message: "Invalid passphrase",
1149
+ retryAfterSeconds: failure.retryAfterSeconds
1150
+ });
1151
+ return;
1152
+ }
1153
+ loginRateLimiter.registerSuccess(ip);
1154
+ const createdSession = sessionStore.create(ownerId);
1155
+ setCookie(response, "poncho_session", createdSession.sessionId, {
1156
+ httpOnly: true,
1157
+ secure: secureCookies,
1158
+ sameSite: "Lax",
1159
+ path: "/",
1160
+ maxAge: 60 * 60 * 8
1161
+ });
1162
+ writeJson(response, 200, {
1163
+ authenticated: true,
1164
+ csrfToken: createdSession.csrfToken
1165
+ });
1166
+ return;
1167
+ }
1168
+ if (pathname === "/api/auth/logout" && request.method === "POST") {
1169
+ if (session?.sessionId) {
1170
+ sessionStore.delete(session.sessionId);
1171
+ }
1172
+ setCookie(response, "poncho_session", "", {
1173
+ httpOnly: true,
1174
+ secure: secureCookies,
1175
+ sameSite: "Lax",
1176
+ path: "/",
1177
+ maxAge: 0
1178
+ });
1179
+ writeJson(response, 200, { ok: true });
1180
+ return;
1181
+ }
1182
+ if (pathname.startsWith("/api/")) {
1183
+ if (requireUiAuth && !session) {
1184
+ writeJson(response, 401, {
1185
+ code: "AUTH_ERROR",
1186
+ message: "Authentication required"
1187
+ });
1188
+ return;
1189
+ }
1190
+ if (requireUiAuth && requiresCsrfValidation && pathname !== "/api/auth/login" && request.headers["x-csrf-token"] !== session?.csrfToken) {
1191
+ writeJson(response, 403, {
1192
+ code: "CSRF_ERROR",
1193
+ message: "Invalid CSRF token"
1194
+ });
1195
+ return;
1196
+ }
1197
+ }
1198
+ if (pathname === "/api/conversations" && request.method === "GET") {
1199
+ const conversations = await conversationStore.list(ownerId);
1200
+ writeJson(response, 200, {
1201
+ conversations: conversations.map((conversation) => ({
1202
+ conversationId: conversation.conversationId,
1203
+ title: conversation.title,
1204
+ runtimeRunId: conversation.runtimeRunId,
1205
+ ownerId: conversation.ownerId,
1206
+ tenantId: conversation.tenantId,
1207
+ createdAt: conversation.createdAt,
1208
+ updatedAt: conversation.updatedAt,
1209
+ messageCount: conversation.messages.length
1210
+ }))
1211
+ });
1212
+ return;
1213
+ }
1214
+ if (pathname === "/api/conversations" && request.method === "POST") {
1215
+ const body = await readRequestBody(request);
1216
+ const conversation = await conversationStore.create(ownerId, body.title);
1217
+ const introMessage = await consumeFirstRunIntro(workingDir, {
1218
+ agentName,
1219
+ provider: agentModelProvider,
1220
+ model: agentModelName,
1221
+ config
1222
+ });
1223
+ if (introMessage) {
1224
+ conversation.messages = [{ role: "assistant", content: introMessage }];
1225
+ await conversationStore.update(conversation);
1226
+ }
1227
+ writeJson(response, 201, { conversation });
1228
+ return;
1229
+ }
1230
+ const conversationPathMatch = pathname.match(/^\/api\/conversations\/([^/]+)$/);
1231
+ if (conversationPathMatch) {
1232
+ const conversationId = decodeURIComponent(conversationPathMatch[1] ?? "");
1233
+ const conversation = await conversationStore.get(conversationId);
1234
+ if (!conversation || conversation.ownerId !== ownerId) {
1235
+ writeJson(response, 404, {
1236
+ code: "CONVERSATION_NOT_FOUND",
1237
+ message: "Conversation not found"
1238
+ });
1239
+ return;
1240
+ }
1241
+ if (request.method === "GET") {
1242
+ writeJson(response, 200, { conversation });
1243
+ return;
1244
+ }
1245
+ if (request.method === "PATCH") {
1246
+ const body = await readRequestBody(request);
1247
+ if (!body.title || body.title.trim().length === 0) {
1248
+ writeJson(response, 400, {
1249
+ code: "VALIDATION_ERROR",
1250
+ message: "title is required"
1251
+ });
1252
+ return;
1253
+ }
1254
+ const updated = await conversationStore.rename(conversationId, body.title);
1255
+ writeJson(response, 200, { conversation: updated });
1256
+ return;
1257
+ }
1258
+ if (request.method === "DELETE") {
1259
+ await conversationStore.delete(conversationId);
1260
+ writeJson(response, 200, { ok: true });
1261
+ return;
1262
+ }
1263
+ }
1264
+ const conversationMessageMatch = pathname.match(/^\/api\/conversations\/([^/]+)\/messages$/);
1265
+ if (conversationMessageMatch && request.method === "POST") {
1266
+ const conversationId = decodeURIComponent(conversationMessageMatch[1] ?? "");
1267
+ const conversation = await conversationStore.get(conversationId);
1268
+ if (!conversation || conversation.ownerId !== ownerId) {
1269
+ writeJson(response, 404, {
1270
+ code: "CONVERSATION_NOT_FOUND",
1271
+ message: "Conversation not found"
1272
+ });
1273
+ return;
1274
+ }
1275
+ const body = await readRequestBody(request);
1276
+ const messageText = body.message?.trim() ?? "";
1277
+ if (!messageText) {
1278
+ writeJson(response, 400, {
1279
+ code: "VALIDATION_ERROR",
1280
+ message: "message is required"
1281
+ });
1282
+ return;
1283
+ }
1284
+ if (conversation.messages.length === 0 && (conversation.title === "New conversation" || conversation.title.trim().length === 0)) {
1285
+ conversation.title = inferConversationTitle(messageText);
1286
+ }
1287
+ response.writeHead(200, {
1288
+ "Content-Type": "text/event-stream",
1289
+ "Cache-Control": "no-cache",
1290
+ Connection: "keep-alive"
1291
+ });
1292
+ let latestRunId = conversation.runtimeRunId ?? "";
1293
+ let assistantResponse = "";
1294
+ const toolTimeline = [];
1295
+ try {
1296
+ const recallCorpus = (await conversationStore.list(ownerId)).filter((item) => item.conversationId !== conversationId).slice(0, 20).map((item) => ({
1297
+ conversationId: item.conversationId,
1298
+ title: item.title,
1299
+ updatedAt: item.updatedAt,
1300
+ content: item.messages.slice(-6).map((message) => `${message.role}: ${message.content}`).join("\n").slice(0, 2e3)
1301
+ })).filter((item) => item.content.length > 0);
1302
+ for await (const event of harness.run({
1303
+ task: messageText,
1304
+ parameters: {
1305
+ ...body.parameters ?? {},
1306
+ __conversationRecallCorpus: recallCorpus,
1307
+ __activeConversationId: conversationId
1308
+ },
1309
+ messages: conversation.messages
1310
+ })) {
1311
+ if (event.type === "run:started") {
1312
+ latestRunId = event.runId;
1313
+ }
1314
+ if (event.type === "model:chunk") {
1315
+ assistantResponse += event.content;
1316
+ }
1317
+ if (event.type === "tool:started") {
1318
+ toolTimeline.push(`- start \`${event.tool}\``);
1319
+ }
1320
+ if (event.type === "tool:completed") {
1321
+ toolTimeline.push(`- done \`${event.tool}\` (${event.duration}ms)`);
1322
+ }
1323
+ if (event.type === "tool:error") {
1324
+ toolTimeline.push(`- error \`${event.tool}\`: ${event.error}`);
1325
+ }
1326
+ if (event.type === "tool:approval:required") {
1327
+ toolTimeline.push(`- approval required \`${event.tool}\``);
1328
+ }
1329
+ if (event.type === "tool:approval:granted") {
1330
+ toolTimeline.push(`- approval granted (${event.approvalId})`);
1331
+ }
1332
+ if (event.type === "tool:approval:denied") {
1333
+ toolTimeline.push(`- approval denied (${event.approvalId})`);
1334
+ }
1335
+ if (event.type === "run:completed" && assistantResponse.length === 0 && event.result.response) {
1336
+ assistantResponse = event.result.response;
1337
+ }
1338
+ await telemetry.emit(event);
1339
+ response.write(formatSseEvent(event));
1340
+ }
1341
+ conversation.messages = [
1342
+ ...conversation.messages,
1343
+ { role: "user", content: messageText },
1344
+ {
1345
+ role: "assistant",
1346
+ content: assistantResponse,
1347
+ metadata: toolTimeline.length > 0 ? { toolActivity: toolTimeline } : void 0
1348
+ }
1349
+ ];
1350
+ conversation.runtimeRunId = latestRunId || conversation.runtimeRunId;
1351
+ conversation.updatedAt = Date.now();
1352
+ await conversationStore.update(conversation);
1353
+ } catch (error) {
1354
+ response.write(
1355
+ formatSseEvent({
1356
+ type: "run:error",
1357
+ runId: latestRunId || "run_unknown",
1358
+ error: {
1359
+ code: "RUN_ERROR",
1360
+ message: error instanceof Error ? error.message : "Unknown error"
1361
+ }
1362
+ })
1363
+ );
1364
+ } finally {
1365
+ response.end();
1366
+ }
1367
+ return;
1368
+ }
1369
+ writeJson(response, 404, { error: "Not found" });
1370
+ };
1371
+ };
1372
+ var startDevServer = async (port, options) => {
1373
+ const handler = await createRequestHandler(options);
1374
+ const server = createServer(handler);
1375
+ const actualPort = await listenOnAvailablePort(server, port);
1376
+ if (actualPort !== port) {
1377
+ process.stdout.write(`Port ${port} is in use, switched to ${actualPort}.
1378
+ `);
1379
+ }
1380
+ process.stdout.write(`Poncho dev server running at http://localhost:${actualPort}
1381
+ `);
1382
+ const shutdown = () => {
1383
+ server.close();
1384
+ server.closeAllConnections?.();
1385
+ process.exit(0);
1386
+ };
1387
+ process.on("SIGINT", shutdown);
1388
+ process.on("SIGTERM", shutdown);
1389
+ return server;
1390
+ };
1391
+ var runOnce = async (task, options) => {
1392
+ const workingDir = options.workingDir ?? process.cwd();
1393
+ dotenv.config({ path: resolve(workingDir, ".env") });
1394
+ const config = await loadPonchoConfig(workingDir);
1395
+ const harness = new AgentHarness({ workingDir });
1396
+ const telemetry = new TelemetryEmitter(config?.telemetry);
1397
+ await harness.initialize();
1398
+ const fileBlobs = await Promise.all(
1399
+ options.filePaths.map(async (path) => {
1400
+ const content = await readFile(resolve(workingDir, path), "utf8");
1401
+ return `# File: ${path}
1402
+ ${content}`;
1403
+ })
1404
+ );
1405
+ const input2 = {
1406
+ task: fileBlobs.length > 0 ? `${task}
1407
+
1408
+ ${fileBlobs.join("\n\n")}` : task,
1409
+ parameters: options.params
1410
+ };
1411
+ if (options.json) {
1412
+ const output = await harness.runToCompletion(input2);
1413
+ for (const event of output.events) {
1414
+ await telemetry.emit(event);
1415
+ }
1416
+ process.stdout.write(`${JSON.stringify(output, null, 2)}
1417
+ `);
1418
+ return;
1419
+ }
1420
+ for await (const event of harness.run(input2)) {
1421
+ await telemetry.emit(event);
1422
+ if (event.type === "model:chunk") {
1423
+ process.stdout.write(event.content);
1424
+ }
1425
+ if (event.type === "run:error") {
1426
+ process.stderr.write(`
1427
+ Error: ${event.error.message}
1428
+ `);
1429
+ }
1430
+ if (event.type === "run:completed") {
1431
+ process.stdout.write("\n");
1432
+ }
1433
+ }
1434
+ };
1435
+ var runInteractive = async (workingDir, params) => {
1436
+ dotenv.config({ path: resolve(workingDir, ".env") });
1437
+ const config = await loadPonchoConfig(workingDir);
1438
+ let pendingApproval = null;
1439
+ let onApprovalRequest = null;
1440
+ const approvalHandler = async (request) => {
1441
+ return new Promise((resolveApproval) => {
1442
+ const req = {
1443
+ tool: request.tool,
1444
+ input: request.input,
1445
+ approvalId: request.approvalId,
1446
+ resolve: resolveApproval
1447
+ };
1448
+ pendingApproval = req;
1449
+ if (onApprovalRequest) {
1450
+ onApprovalRequest(req);
1451
+ }
1452
+ });
1453
+ };
1454
+ const harness = new AgentHarness({
1455
+ workingDir,
1456
+ environment: resolveHarnessEnvironment(),
1457
+ approvalHandler
1458
+ });
1459
+ await harness.initialize();
1460
+ try {
1461
+ const { runInteractiveInk } = await import("./run-interactive-ink-4EKHIHGU.js");
1462
+ await runInteractiveInk({
1463
+ harness,
1464
+ params,
1465
+ workingDir,
1466
+ config,
1467
+ conversationStore: createConversationStore(resolveStateConfig(config), { workingDir }),
1468
+ onSetApprovalCallback: (cb) => {
1469
+ onApprovalRequest = cb;
1470
+ if (pendingApproval) {
1471
+ cb(pendingApproval);
1472
+ }
1473
+ }
1474
+ });
1475
+ } finally {
1476
+ await harness.shutdown();
1477
+ }
1478
+ };
1479
+ var listTools = async (workingDir) => {
1480
+ dotenv.config({ path: resolve(workingDir, ".env") });
1481
+ const harness = new AgentHarness({ workingDir });
1482
+ await harness.initialize();
1483
+ const tools = harness.listTools();
1484
+ if (tools.length === 0) {
1485
+ process.stdout.write("No tools registered.\n");
1486
+ return;
1487
+ }
1488
+ process.stdout.write("Available tools:\n");
1489
+ for (const tool of tools) {
1490
+ process.stdout.write(`- ${tool.name}: ${tool.description}
1491
+ `);
1492
+ }
1493
+ };
1494
+ var runPnpmInstall = async (workingDir) => await new Promise((resolveInstall, rejectInstall) => {
1495
+ const child = spawn("pnpm", ["install"], {
1496
+ cwd: workingDir,
1497
+ stdio: "inherit",
1498
+ env: process.env
1499
+ });
1500
+ child.on("exit", (code) => {
1501
+ if (code === 0) {
1502
+ resolveInstall();
1503
+ return;
1504
+ }
1505
+ rejectInstall(new Error(`pnpm install failed with exit code ${code ?? -1}`));
1506
+ });
1507
+ });
1508
+ var runInstallCommand = async (workingDir, packageNameOrPath) => await new Promise((resolveInstall, rejectInstall) => {
1509
+ const child = spawn("pnpm", ["add", packageNameOrPath], {
1510
+ cwd: workingDir,
1511
+ stdio: "inherit",
1512
+ env: process.env
1513
+ });
1514
+ child.on("exit", (code) => {
1515
+ if (code === 0) {
1516
+ resolveInstall();
1517
+ return;
1518
+ }
1519
+ rejectInstall(new Error(`pnpm add failed with exit code ${code ?? -1}`));
1520
+ });
1521
+ });
1522
+ var resolveInstalledPackageName = (packageNameOrPath) => {
1523
+ if (packageNameOrPath.startsWith(".") || packageNameOrPath.startsWith("/")) {
1524
+ return null;
1525
+ }
1526
+ if (packageNameOrPath.startsWith("@")) {
1527
+ return packageNameOrPath;
1528
+ }
1529
+ if (packageNameOrPath.includes("/")) {
1530
+ return packageNameOrPath.split("/").pop() ?? packageNameOrPath;
1531
+ }
1532
+ return packageNameOrPath;
1533
+ };
1534
+ var resolveSkillRoot = (workingDir, packageNameOrPath) => {
1535
+ if (packageNameOrPath.startsWith(".") || packageNameOrPath.startsWith("/")) {
1536
+ return resolve(workingDir, packageNameOrPath);
1537
+ }
1538
+ const moduleName = resolveInstalledPackageName(packageNameOrPath) ?? packageNameOrPath;
1539
+ try {
1540
+ const packageJsonPath = require2.resolve(`${moduleName}/package.json`, {
1541
+ paths: [workingDir]
1542
+ });
1543
+ return resolve(packageJsonPath, "..");
1544
+ } catch {
1545
+ const candidate = resolve(workingDir, "node_modules", moduleName);
1546
+ if (existsSync(candidate)) {
1547
+ return candidate;
1548
+ }
1549
+ throw new Error(
1550
+ `Could not locate installed package "${moduleName}" in ${workingDir}`
1551
+ );
1552
+ }
1553
+ };
1554
+ var findSkillManifest = async (dir, depth = 2) => {
1555
+ try {
1556
+ await access(resolve(dir, "SKILL.md"));
1557
+ return true;
1558
+ } catch {
1559
+ }
1560
+ if (depth <= 0) return false;
1561
+ try {
1562
+ const { readdir } = await import("fs/promises");
1563
+ const entries = await readdir(dir, { withFileTypes: true });
1564
+ for (const entry of entries) {
1565
+ if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
1566
+ const found = await findSkillManifest(resolve(dir, entry.name), depth - 1);
1567
+ if (found) return true;
1568
+ }
1569
+ }
1570
+ } catch {
1571
+ }
1572
+ return false;
1573
+ };
1574
+ var validateSkillPackage = async (workingDir, packageNameOrPath) => {
1575
+ const skillRoot = resolveSkillRoot(workingDir, packageNameOrPath);
1576
+ const hasSkill = await findSkillManifest(skillRoot);
1577
+ if (!hasSkill) {
1578
+ throw new Error(`Skill validation failed: no SKILL.md found in ${skillRoot}`);
1579
+ }
1580
+ };
1581
+ var addSkill = async (workingDir, packageNameOrPath) => {
1582
+ await runInstallCommand(workingDir, packageNameOrPath);
1583
+ await validateSkillPackage(workingDir, packageNameOrPath);
1584
+ process.stdout.write(`Added skill: ${packageNameOrPath}
1585
+ `);
1586
+ };
1587
+ var runTests = async (workingDir, filePath) => {
1588
+ dotenv.config({ path: resolve(workingDir, ".env") });
1589
+ const testFilePath = filePath ?? resolve(workingDir, "tests", "basic.yaml");
1590
+ const content = await readFile(testFilePath, "utf8");
1591
+ const parsed = YAML.parse(content);
1592
+ const tests = parsed.tests ?? [];
1593
+ const harness = new AgentHarness({ workingDir });
1594
+ await harness.initialize();
1595
+ let passed = 0;
1596
+ let failed = 0;
1597
+ for (const testCase of tests) {
1598
+ try {
1599
+ const output = await harness.runToCompletion({ task: testCase.task });
1600
+ const response = output.result.response ?? "";
1601
+ const events = output.events;
1602
+ const expectation = testCase.expect ?? {};
1603
+ const checks = [];
1604
+ if (expectation.contains) {
1605
+ checks.push(response.includes(expectation.contains));
1606
+ }
1607
+ if (typeof expectation.maxSteps === "number") {
1608
+ checks.push(output.result.steps <= expectation.maxSteps);
1609
+ }
1610
+ if (typeof expectation.maxTokens === "number") {
1611
+ checks.push(
1612
+ output.result.tokens.input + output.result.tokens.output <= expectation.maxTokens
1613
+ );
1614
+ }
1615
+ if (expectation.refusal) {
1616
+ checks.push(
1617
+ response.toLowerCase().includes("can't") || response.toLowerCase().includes("cannot")
1618
+ );
1619
+ }
1620
+ if (expectation.toolCalled) {
1621
+ checks.push(
1622
+ events.some(
1623
+ (event) => event.type === "tool:started" && event.tool === expectation.toolCalled
1624
+ )
1625
+ );
1626
+ }
1627
+ const ok = checks.length === 0 ? output.result.status === "completed" : checks.every(Boolean);
1628
+ if (ok) {
1629
+ passed += 1;
1630
+ process.stdout.write(`PASS ${testCase.name}
1631
+ `);
1632
+ } else {
1633
+ failed += 1;
1634
+ process.stdout.write(`FAIL ${testCase.name}
1635
+ `);
1636
+ }
1637
+ } catch (error) {
1638
+ failed += 1;
1639
+ process.stdout.write(
1640
+ `FAIL ${testCase.name} (${error instanceof Error ? error.message : "Unknown test error"})
1641
+ `
1642
+ );
1643
+ }
1644
+ }
1645
+ process.stdout.write(`
1646
+ Test summary: ${passed} passed, ${failed} failed
1647
+ `);
1648
+ return { passed, failed };
1649
+ };
1650
+ var buildTarget = async (workingDir, target) => {
1651
+ const outDir = resolve(workingDir, ".poncho-build", target);
1652
+ await mkdir(outDir, { recursive: true });
1653
+ const serverEntrypoint = `import { startDevServer } from "@poncho-ai/cli";
1654
+
1655
+ const port = Number.parseInt(process.env.PORT ?? "3000", 10);
1656
+ await startDevServer(Number.isNaN(port) ? 3000 : port, { workingDir: process.cwd() });
1657
+ `;
1658
+ const runtimePackageJson = JSON.stringify(
1659
+ {
1660
+ name: "poncho-runtime-bundle",
1661
+ private: true,
1662
+ type: "module",
1663
+ scripts: {
1664
+ start: "node server.js"
1665
+ },
1666
+ dependencies: {
1667
+ "@poncho-ai/cli": "^0.1.0"
1668
+ }
1669
+ },
1670
+ null,
1671
+ 2
1672
+ );
1673
+ if (target === "vercel") {
1674
+ await mkdir(resolve(outDir, "api"), { recursive: true });
1675
+ await copyIfExists(resolve(workingDir, "AGENT.md"), resolve(outDir, "AGENT.md"));
1676
+ await copyIfExists(
1677
+ resolve(workingDir, "poncho.config.js"),
1678
+ resolve(outDir, "poncho.config.js")
1679
+ );
1680
+ await copyIfExists(resolve(workingDir, "skills"), resolve(outDir, "skills"));
1681
+ await copyIfExists(resolve(workingDir, "tests"), resolve(outDir, "tests"));
1682
+ await writeFile(
1683
+ resolve(outDir, "vercel.json"),
1684
+ JSON.stringify(
1685
+ {
1686
+ version: 2,
1687
+ functions: {
1688
+ "api/index.js": {
1689
+ includeFiles: "{AGENT.md,poncho.config.js,skills/**,tests/**}"
1690
+ }
1691
+ },
1692
+ routes: [{ src: "/(.*)", dest: "/api/index.js" }]
1693
+ },
1694
+ null,
1695
+ 2
1696
+ ),
1697
+ "utf8"
1698
+ );
1699
+ await buildVercelHandlerBundle(outDir);
1700
+ await writeFile(
1701
+ resolve(outDir, "package.json"),
1702
+ JSON.stringify(
1703
+ {
1704
+ private: true,
1705
+ type: "module",
1706
+ engines: {
1707
+ node: "20.x"
1708
+ },
1709
+ dependencies: VERCEL_RUNTIME_DEPENDENCIES
1710
+ },
1711
+ null,
1712
+ 2
1713
+ ),
1714
+ "utf8"
1715
+ );
1716
+ } else if (target === "docker") {
1717
+ await writeFile(
1718
+ resolve(outDir, "Dockerfile"),
1719
+ `FROM node:20-slim
1720
+ WORKDIR /app
1721
+ COPY package.json package.json
1722
+ COPY AGENT.md AGENT.md
1723
+ COPY poncho.config.js poncho.config.js
1724
+ COPY skills skills
1725
+ COPY tests tests
1726
+ COPY .env.example .env.example
1727
+ RUN corepack enable && npm install -g @poncho-ai/cli
1728
+ COPY server.js server.js
1729
+ EXPOSE 3000
1730
+ CMD ["node","server.js"]
1731
+ `,
1732
+ "utf8"
1733
+ );
1734
+ await writeFile(resolve(outDir, "server.js"), serverEntrypoint, "utf8");
1735
+ await writeFile(resolve(outDir, "package.json"), runtimePackageJson, "utf8");
1736
+ } else if (target === "lambda") {
1737
+ await writeFile(
1738
+ resolve(outDir, "lambda-handler.js"),
1739
+ `import { startDevServer } from "@poncho-ai/cli";
1740
+ let serverPromise;
1741
+ export const handler = async (event = {}) => {
1742
+ if (!serverPromise) {
1743
+ serverPromise = startDevServer(0, { workingDir: process.cwd() });
1744
+ }
1745
+ const body = JSON.stringify({
1746
+ status: "ready",
1747
+ route: event.rawPath ?? event.path ?? "/",
1748
+ });
1749
+ return { statusCode: 200, headers: { "content-type": "application/json" }, body };
1750
+ };
1751
+ `,
1752
+ "utf8"
1753
+ );
1754
+ await writeFile(resolve(outDir, "package.json"), runtimePackageJson, "utf8");
1755
+ } else if (target === "fly") {
1756
+ await writeFile(
1757
+ resolve(outDir, "fly.toml"),
1758
+ `app = "poncho-app"
1759
+ [env]
1760
+ PORT = "3000"
1761
+ [http_service]
1762
+ internal_port = 3000
1763
+ force_https = true
1764
+ auto_start_machines = true
1765
+ auto_stop_machines = "stop"
1766
+ min_machines_running = 0
1767
+ `,
1768
+ "utf8"
1769
+ );
1770
+ await writeFile(
1771
+ resolve(outDir, "Dockerfile"),
1772
+ `FROM node:20-slim
1773
+ WORKDIR /app
1774
+ COPY package.json package.json
1775
+ COPY AGENT.md AGENT.md
1776
+ COPY poncho.config.js poncho.config.js
1777
+ COPY skills skills
1778
+ COPY tests tests
1779
+ RUN npm install -g @poncho-ai/cli
1780
+ COPY server.js server.js
1781
+ EXPOSE 3000
1782
+ CMD ["node","server.js"]
1783
+ `,
1784
+ "utf8"
1785
+ );
1786
+ await writeFile(resolve(outDir, "server.js"), serverEntrypoint, "utf8");
1787
+ await writeFile(resolve(outDir, "package.json"), runtimePackageJson, "utf8");
1788
+ } else {
1789
+ throw new Error(`Unsupported build target: ${target}`);
1790
+ }
1791
+ process.stdout.write(`Build artifacts generated at ${outDir}
1792
+ `);
1793
+ };
1794
+ var normalizeMcpName = (entry) => entry.name ?? entry.url ?? `mcp_${Date.now()}`;
1795
+ var mcpAdd = async (workingDir, options) => {
1796
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
1797
+ const mcp = [...config.mcp ?? []];
1798
+ if (!options.url) {
1799
+ throw new Error("Remote MCP only: provide --url for a remote MCP server.");
1800
+ }
1801
+ if (options.url.startsWith("ws://") || options.url.startsWith("wss://")) {
1802
+ throw new Error("WebSocket MCP URLs are no longer supported. Use an HTTP MCP endpoint.");
1803
+ }
1804
+ if (!options.url.startsWith("http://") && !options.url.startsWith("https://")) {
1805
+ throw new Error("Invalid MCP URL. Expected http:// or https://.");
1806
+ }
1807
+ const serverName = options.name ?? normalizeMcpName({ url: options.url });
1808
+ mcp.push({
1809
+ name: serverName,
1810
+ url: options.url,
1811
+ env: options.envVars ?? [],
1812
+ auth: options.authBearerEnv ? {
1813
+ type: "bearer",
1814
+ tokenEnv: options.authBearerEnv
1815
+ } : void 0
1816
+ });
1817
+ await writeConfigFile(workingDir, { ...config, mcp });
1818
+ let envSeedMessage;
1819
+ if (options.authBearerEnv) {
1820
+ const envPath = resolve(workingDir, ".env");
1821
+ const envExamplePath = resolve(workingDir, ".env.example");
1822
+ const addedEnv = await ensureEnvPlaceholder(envPath, options.authBearerEnv);
1823
+ const addedEnvExample = await ensureEnvPlaceholder(envExamplePath, options.authBearerEnv);
1824
+ if (addedEnv || addedEnvExample) {
1825
+ envSeedMessage = `Added ${options.authBearerEnv}= to ${addedEnv ? ".env" : ""}${addedEnv && addedEnvExample ? " and " : ""}${addedEnvExample ? ".env.example" : ""}.`;
1826
+ }
1827
+ }
1828
+ const nextSteps = [];
1829
+ let step = 1;
1830
+ if (options.authBearerEnv) {
1831
+ nextSteps.push(` ${step}) Set token in .env: ${options.authBearerEnv}=...`);
1832
+ step += 1;
1833
+ }
1834
+ nextSteps.push(` ${step}) Discover tools: poncho mcp tools list ${serverName}`);
1835
+ step += 1;
1836
+ nextSteps.push(` ${step}) Select tools: poncho mcp tools select ${serverName}`);
1837
+ step += 1;
1838
+ nextSteps.push(` ${step}) Verify config: poncho mcp list`);
1839
+ process.stdout.write(
1840
+ [
1841
+ `MCP server added: ${serverName}`,
1842
+ ...envSeedMessage ? [envSeedMessage] : [],
1843
+ "Next steps:",
1844
+ ...nextSteps,
1845
+ ""
1846
+ ].join("\n")
1847
+ );
1848
+ };
1849
+ var mcpList = async (workingDir) => {
1850
+ const config = await loadPonchoConfig(workingDir);
1851
+ const mcp = config?.mcp ?? [];
1852
+ if (mcp.length === 0) {
1853
+ process.stdout.write("No MCP servers configured.\n");
1854
+ if (config?.scripts) {
1855
+ process.stdout.write(
1856
+ `Script policy: mode=${config.scripts.mode ?? "all"} include=${config.scripts.include?.length ?? 0} exclude=${config.scripts.exclude?.length ?? 0}
1857
+ `
1858
+ );
1859
+ }
1860
+ return;
1861
+ }
1862
+ process.stdout.write("Configured MCP servers:\n");
1863
+ for (const entry of mcp) {
1864
+ const auth = entry.auth?.type === "bearer" ? `auth=bearer:${entry.auth.tokenEnv}` : "auth=none";
1865
+ const mode = entry.tools?.mode ?? "all";
1866
+ process.stdout.write(
1867
+ `- ${entry.name ?? entry.url} (remote: ${entry.url}, ${auth}, mode=${mode})
1868
+ `
1869
+ );
1870
+ }
1871
+ if (config?.scripts) {
1872
+ process.stdout.write(
1873
+ `Script policy: mode=${config.scripts.mode ?? "all"} include=${config.scripts.include?.length ?? 0} exclude=${config.scripts.exclude?.length ?? 0}
1874
+ `
1875
+ );
1876
+ }
1877
+ };
1878
+ var mcpRemove = async (workingDir, name) => {
1879
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
1880
+ const before = config.mcp ?? [];
1881
+ const removed = before.filter((entry) => normalizeMcpName(entry) === name);
1882
+ const filtered = before.filter((entry) => normalizeMcpName(entry) !== name);
1883
+ await writeConfigFile(workingDir, { ...config, mcp: filtered });
1884
+ const removedTokenEnvNames = new Set(
1885
+ removed.map(
1886
+ (entry) => entry.auth?.type === "bearer" ? entry.auth.tokenEnv?.trim() ?? "" : ""
1887
+ ).filter((value) => value.length > 0)
1888
+ );
1889
+ const stillUsedTokenEnvNames = new Set(
1890
+ filtered.map(
1891
+ (entry) => entry.auth?.type === "bearer" ? entry.auth.tokenEnv?.trim() ?? "" : ""
1892
+ ).filter((value) => value.length > 0)
1893
+ );
1894
+ const removedFromExample = [];
1895
+ for (const tokenEnv of removedTokenEnvNames) {
1896
+ if (stillUsedTokenEnvNames.has(tokenEnv)) {
1897
+ continue;
1898
+ }
1899
+ const changed = await removeEnvPlaceholder(resolve(workingDir, ".env.example"), tokenEnv);
1900
+ if (changed) {
1901
+ removedFromExample.push(tokenEnv);
1902
+ }
1903
+ }
1904
+ process.stdout.write(`Removed MCP server: ${name}
1905
+ `);
1906
+ if (removedFromExample.length > 0) {
1907
+ process.stdout.write(
1908
+ `Removed unused token placeholder(s) from .env.example: ${removedFromExample.join(", ")}
1909
+ `
1910
+ );
1911
+ }
1912
+ };
1913
+ var resolveMcpEntry = async (workingDir, serverName) => {
1914
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
1915
+ const entries = config.mcp ?? [];
1916
+ const index = entries.findIndex((entry) => normalizeMcpName(entry) === serverName);
1917
+ if (index < 0) {
1918
+ throw new Error(`MCP server "${serverName}" is not configured.`);
1919
+ }
1920
+ return { config, index };
1921
+ };
1922
+ var discoverMcpTools = async (workingDir, serverName) => {
1923
+ dotenv.config({ path: resolve(workingDir, ".env") });
1924
+ const { config, index } = await resolveMcpEntry(workingDir, serverName);
1925
+ const entry = (config.mcp ?? [])[index];
1926
+ const bridge = new LocalMcpBridge({ mcp: [entry] });
1927
+ try {
1928
+ await bridge.startLocalServers();
1929
+ await bridge.discoverTools();
1930
+ return bridge.listDiscoveredTools(normalizeMcpName(entry));
1931
+ } finally {
1932
+ await bridge.stopLocalServers();
1933
+ }
1934
+ };
1935
+ var mcpToolsList = async (workingDir, serverName) => {
1936
+ const discovered = await discoverMcpTools(workingDir, serverName);
1937
+ if (discovered.length === 0) {
1938
+ process.stdout.write(`No tools discovered for MCP server "${serverName}".
1939
+ `);
1940
+ return;
1941
+ }
1942
+ process.stdout.write(`Discovered tools for "${serverName}":
1943
+ `);
1944
+ for (const tool of discovered) {
1945
+ process.stdout.write(`- ${tool}
1946
+ `);
1947
+ }
1948
+ };
1949
+ var mcpToolsSelect = async (workingDir, serverName, options) => {
1950
+ const discovered = await discoverMcpTools(workingDir, serverName);
1951
+ if (discovered.length === 0) {
1952
+ process.stdout.write(`No tools discovered for MCP server "${serverName}".
1953
+ `);
1954
+ return;
1955
+ }
1956
+ let selected = [];
1957
+ if (options.all) {
1958
+ selected = [...discovered];
1959
+ } else if (options.toolsCsv && options.toolsCsv.trim().length > 0) {
1960
+ const requested = options.toolsCsv.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
1961
+ selected = discovered.filter((tool) => requested.includes(tool));
1962
+ } else {
1963
+ process.stdout.write(`Discovered tools for "${serverName}":
1964
+ `);
1965
+ discovered.forEach((tool, idx) => {
1966
+ process.stdout.write(`${idx + 1}. ${tool}
1967
+ `);
1968
+ });
1969
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1970
+ const answer = await rl.question(
1971
+ "Enter comma-separated tool numbers/names to allow (or * for all): "
1972
+ );
1973
+ rl.close();
1974
+ const raw = answer.trim();
1975
+ if (raw === "*") {
1976
+ selected = [...discovered];
1977
+ } else {
1978
+ const tokens = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
1979
+ const fromIndex = tokens.map((token) => Number.parseInt(token, 10)).filter((value) => !Number.isNaN(value)).map((index2) => discovered[index2 - 1]).filter((value) => typeof value === "string");
1980
+ const byName = discovered.filter((tool) => tokens.includes(tool));
1981
+ selected = [.../* @__PURE__ */ new Set([...fromIndex, ...byName])];
1982
+ }
1983
+ }
1984
+ if (selected.length === 0) {
1985
+ throw new Error("No valid tools selected.");
1986
+ }
1987
+ const includePatterns = selected.length === discovered.length ? [`${serverName}/*`] : selected.sort();
1988
+ const { config, index } = await resolveMcpEntry(workingDir, serverName);
1989
+ const mcp = [...config.mcp ?? []];
1990
+ const existing = mcp[index];
1991
+ mcp[index] = {
1992
+ ...existing,
1993
+ tools: {
1994
+ ...existing.tools ?? {},
1995
+ mode: "allowlist",
1996
+ include: includePatterns
1997
+ }
1998
+ };
1999
+ await writeConfigFile(workingDir, { ...config, mcp });
2000
+ process.stdout.write(
2001
+ `Updated ${serverName} to allowlist ${includePatterns.join(", ")} in poncho.config.js.
2002
+ `
2003
+ );
2004
+ process.stdout.write(
2005
+ "\nRequired next step: add MCP intent in AGENT.md or SKILL.md. Without this, these MCP tools will not be registered for the model.\n"
2006
+ );
2007
+ process.stdout.write(
2008
+ "\nOption A: AGENT.md (global fallback intent)\nPaste this into AGENT.md frontmatter:\n---\ntools:\n mcp:\n" + includePatterns.map((tool) => ` - ${tool}`).join("\n") + "\n---\n"
2009
+ );
2010
+ process.stdout.write(
2011
+ "\nOption B: SKILL.md (only when that skill is activated)\nPaste this into SKILL.md frontmatter:\n---\ntools:\n mcp:\n" + includePatterns.map((tool) => ` - ${tool}`).join("\n") + "\n---\n"
2012
+ );
2013
+ };
2014
+ var buildCli = () => {
2015
+ const program = new Command();
2016
+ program.name("poncho").description("CLI for building and running Poncho agents").version("0.1.0");
2017
+ 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) => {
2018
+ await initProject(name, {
2019
+ onboarding: {
2020
+ yes: options.yes,
2021
+ interactive: !options.yes && process.stdin.isTTY === true && process.stdout.isTTY === true
2022
+ }
2023
+ });
2024
+ });
2025
+ program.command("dev").description("Run local development server").option("--port <port>", "server port", "3000").action(async (options) => {
2026
+ const port = Number.parseInt(options.port, 10);
2027
+ await startDevServer(Number.isNaN(port) ? 3e3 : port);
2028
+ });
2029
+ program.command("run").argument("[task]", "task to run").description("Execute the agent once").option("--param <keyValue>", "parameter key=value", (value, all) => {
2030
+ all.push(value);
2031
+ return all;
2032
+ }, []).option("--file <path>", "include file contents", (value, all) => {
2033
+ all.push(value);
2034
+ return all;
2035
+ }, []).option("--json", "output json", false).option("--interactive", "run in interactive mode", false).action(
2036
+ async (task, options) => {
2037
+ const params = parseParams(options.param);
2038
+ if (options.interactive) {
2039
+ await runInteractive(process.cwd(), params);
2040
+ return;
2041
+ }
2042
+ if (!task) {
2043
+ throw new Error("Task is required unless --interactive is used.");
2044
+ }
2045
+ await runOnce(task, {
2046
+ params,
2047
+ json: options.json,
2048
+ filePaths: options.file
2049
+ });
2050
+ }
2051
+ );
2052
+ program.command("tools").description("List all tools available to the agent").action(async () => {
2053
+ await listTools(process.cwd());
2054
+ });
2055
+ program.command("add").argument("<packageOrPath>", "skill package name/path").description("Add a skill package and validate SKILL.md").action(async (packageOrPath) => {
2056
+ await addSkill(process.cwd(), packageOrPath);
2057
+ });
2058
+ program.command("update-agent").description("Remove deprecated embedded local guidance from AGENT.md").action(async () => {
2059
+ await updateAgentGuidance(process.cwd());
2060
+ });
2061
+ program.command("test").argument("[file]", "test file path (yaml)").description("Run yaml-defined agent tests").action(async (file) => {
2062
+ const testFile = file ? resolve(process.cwd(), file) : void 0;
2063
+ const result = await runTests(process.cwd(), testFile);
2064
+ if (result.failed > 0) {
2065
+ process.exitCode = 1;
2066
+ }
2067
+ });
2068
+ program.command("build").argument("<target>", "vercel|docker|lambda|fly").description("Generate build artifacts for deployment target").action(async (target) => {
2069
+ await buildTarget(process.cwd(), target);
2070
+ });
2071
+ const mcpCommand = program.command("mcp").description("Manage MCP servers");
2072
+ mcpCommand.command("add").requiredOption("--url <url>", "remote MCP url").option("--name <name>", "server name").option(
2073
+ "--auth-bearer-env <name>",
2074
+ "env var name containing bearer token for this MCP server"
2075
+ ).option("--env <name>", "env variable (repeatable)", (value, all) => {
2076
+ all.push(value);
2077
+ return all;
2078
+ }, []).action(
2079
+ async (options) => {
2080
+ await mcpAdd(process.cwd(), {
2081
+ url: options.url,
2082
+ name: options.name,
2083
+ envVars: options.env,
2084
+ authBearerEnv: options.authBearerEnv
2085
+ });
2086
+ }
2087
+ );
2088
+ mcpCommand.command("list").description("List configured MCP servers").action(async () => {
2089
+ await mcpList(process.cwd());
2090
+ });
2091
+ mcpCommand.command("remove").argument("<name>", "server name").description("Remove an MCP server by name").action(async (name) => {
2092
+ await mcpRemove(process.cwd(), name);
2093
+ });
2094
+ const mcpToolsCommand = mcpCommand.command("tools").description("Discover and curate tools for a configured MCP server");
2095
+ mcpToolsCommand.command("list").argument("<name>", "server name").description("Discover and list tools from a configured MCP server").action(async (name) => {
2096
+ await mcpToolsList(process.cwd(), name);
2097
+ });
2098
+ 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(
2099
+ async (name, options) => {
2100
+ await mcpToolsSelect(process.cwd(), name, {
2101
+ all: options.all,
2102
+ toolsCsv: options.tools
2103
+ });
2104
+ }
2105
+ );
2106
+ return program;
2107
+ };
2108
+ var main = async (argv = process.argv) => {
2109
+ try {
2110
+ await buildCli().parseAsync(argv);
2111
+ } catch (error) {
2112
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EADDRINUSE") {
2113
+ const message = "Port is already in use. Try `poncho dev --port 3001` or stop the process using port 3000.";
2114
+ process.stderr.write(`${message}
2115
+ `);
2116
+ process.exitCode = 1;
2117
+ return;
2118
+ }
2119
+ process.stderr.write(`${error instanceof Error ? error.message : "Unknown CLI error"}
2120
+ `);
2121
+ process.exitCode = 1;
2122
+ }
2123
+ };
2124
+ var packageRoot = resolve(__dirname, "..");
2125
+
2126
+ export {
2127
+ initProject,
2128
+ updateAgentGuidance,
2129
+ createRequestHandler,
2130
+ startDevServer,
2131
+ runOnce,
2132
+ runInteractive,
2133
+ listTools,
2134
+ addSkill,
2135
+ runTests,
2136
+ buildTarget,
2137
+ mcpAdd,
2138
+ mcpList,
2139
+ mcpRemove,
2140
+ mcpToolsList,
2141
+ mcpToolsSelect,
2142
+ buildCli,
2143
+ main,
2144
+ packageRoot
2145
+ };