@poncho-ai/cli 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/.turbo/turbo-build.log +5 -5
  2. package/CHANGELOG.md +17 -0
  3. package/dist/chunk-2AZ3Y6R2.js +4121 -0
  4. package/dist/chunk-3273VMA7.js +4182 -0
  5. package/dist/chunk-6REJ5J4T.js +4142 -0
  6. package/dist/chunk-BSW557BB.js +4058 -0
  7. package/dist/chunk-GJYE4S3D.js +4164 -0
  8. package/dist/chunk-HGZTVHBT.js +4089 -0
  9. package/dist/chunk-HNYADV2K.js +4164 -0
  10. package/dist/chunk-IE47LJ33.js +4166 -0
  11. package/dist/chunk-MFVXK3SX.js +4177 -0
  12. package/dist/chunk-N7ZAHMBR.js +4178 -0
  13. package/dist/chunk-TYL4SGJE.js +4177 -0
  14. package/dist/chunk-VIX7Y2YC.js +4169 -0
  15. package/dist/chunk-WCIUVLV3.js +4171 -0
  16. package/dist/chunk-WXFCSFXF.js +4178 -0
  17. package/dist/cli.js +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/run-interactive-ink-4EWW4AJ6.js +463 -0
  20. package/dist/run-interactive-ink-642LZIYZ.js +494 -0
  21. package/dist/run-interactive-ink-72H5IUTC.js +494 -0
  22. package/dist/run-interactive-ink-7P4WWB2Y.js +494 -0
  23. package/dist/run-interactive-ink-EP7GIKLH.js +463 -0
  24. package/dist/run-interactive-ink-FASKW7SN.js +463 -0
  25. package/dist/run-interactive-ink-LLNLDCES.js +494 -0
  26. package/dist/run-interactive-ink-MO6MGLEY.js +494 -0
  27. package/dist/run-interactive-ink-OQZN5DQE.js +463 -0
  28. package/dist/run-interactive-ink-QKB6CG3W.js +494 -0
  29. package/dist/run-interactive-ink-RJCA5IQA.js +494 -0
  30. package/dist/run-interactive-ink-RU2PH6R5.js +494 -0
  31. package/dist/run-interactive-ink-T36C6TJ2.js +463 -0
  32. package/dist/run-interactive-ink-ZL6RAS2O.js +494 -0
  33. package/package.json +3 -2
  34. package/src/index.ts +46 -10
  35. package/src/run-interactive-ink.ts +45 -10
  36. package/src/web-ui.ts +206 -103
@@ -0,0 +1,4169 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/index.ts
9
+ import { spawn } from "child_process";
10
+ import { access as access2, cp, mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
11
+ import { existsSync } from "fs";
12
+ import {
13
+ createServer
14
+ } from "http";
15
+ import { dirname as dirname3, relative, resolve as resolve3 } from "path";
16
+ import { createRequire } from "module";
17
+ import { fileURLToPath } from "url";
18
+ import {
19
+ AgentHarness,
20
+ LocalMcpBridge,
21
+ TelemetryEmitter,
22
+ createConversationStore,
23
+ loadPonchoConfig,
24
+ resolveStateConfig
25
+ } from "@poncho-ai/harness";
26
+ import { Command } from "commander";
27
+ import dotenv from "dotenv";
28
+ import YAML from "yaml";
29
+
30
+ // src/web-ui.ts
31
+ import { createHash, randomUUID, timingSafeEqual } from "crypto";
32
+ import { mkdir, readFile, writeFile } from "fs/promises";
33
+ import { readFileSync } from "fs";
34
+ import { basename, dirname, resolve } from "path";
35
+ import { homedir } from "os";
36
+ var markedSource = readFileSync(__require.resolve("marked/marked.min.js"), "utf-8");
37
+ var DEFAULT_OWNER = "local-owner";
38
+ var SessionStore = class {
39
+ sessions = /* @__PURE__ */ new Map();
40
+ ttlMs;
41
+ constructor(ttlMs = 1e3 * 60 * 60 * 8) {
42
+ this.ttlMs = ttlMs;
43
+ }
44
+ create(ownerId = DEFAULT_OWNER) {
45
+ const now = Date.now();
46
+ const session = {
47
+ sessionId: randomUUID(),
48
+ ownerId,
49
+ csrfToken: randomUUID(),
50
+ createdAt: now,
51
+ expiresAt: now + this.ttlMs,
52
+ lastSeenAt: now
53
+ };
54
+ this.sessions.set(session.sessionId, session);
55
+ return session;
56
+ }
57
+ get(sessionId) {
58
+ const session = this.sessions.get(sessionId);
59
+ if (!session) {
60
+ return void 0;
61
+ }
62
+ if (Date.now() > session.expiresAt) {
63
+ this.sessions.delete(sessionId);
64
+ return void 0;
65
+ }
66
+ session.lastSeenAt = Date.now();
67
+ return session;
68
+ }
69
+ delete(sessionId) {
70
+ this.sessions.delete(sessionId);
71
+ }
72
+ };
73
+ var LoginRateLimiter = class {
74
+ constructor(maxAttempts = 5, windowMs = 1e3 * 60 * 5, lockoutMs = 1e3 * 60 * 10) {
75
+ this.maxAttempts = maxAttempts;
76
+ this.windowMs = windowMs;
77
+ this.lockoutMs = lockoutMs;
78
+ }
79
+ attempts = /* @__PURE__ */ new Map();
80
+ canAttempt(key) {
81
+ const current = this.attempts.get(key);
82
+ if (!current) {
83
+ return { allowed: true };
84
+ }
85
+ if (current.lockedUntil && Date.now() < current.lockedUntil) {
86
+ return {
87
+ allowed: false,
88
+ retryAfterSeconds: Math.ceil((current.lockedUntil - Date.now()) / 1e3)
89
+ };
90
+ }
91
+ return { allowed: true };
92
+ }
93
+ registerFailure(key) {
94
+ const now = Date.now();
95
+ const current = this.attempts.get(key);
96
+ if (!current || now - current.firstFailureAt > this.windowMs) {
97
+ this.attempts.set(key, { count: 1, firstFailureAt: now });
98
+ return { locked: false };
99
+ }
100
+ const count = current.count + 1;
101
+ const next = {
102
+ ...current,
103
+ count
104
+ };
105
+ if (count >= this.maxAttempts) {
106
+ next.lockedUntil = now + this.lockoutMs;
107
+ this.attempts.set(key, next);
108
+ return { locked: true, retryAfterSeconds: Math.ceil(this.lockoutMs / 1e3) };
109
+ }
110
+ this.attempts.set(key, next);
111
+ return { locked: false };
112
+ }
113
+ registerSuccess(key) {
114
+ this.attempts.delete(key);
115
+ }
116
+ };
117
+ var parseCookies = (request) => {
118
+ const cookieHeader = request.headers.cookie ?? "";
119
+ const pairs = cookieHeader.split(";").map((part) => part.trim()).filter(Boolean);
120
+ const cookies = {};
121
+ for (const pair of pairs) {
122
+ const index = pair.indexOf("=");
123
+ if (index <= 0) {
124
+ continue;
125
+ }
126
+ const key = pair.slice(0, index);
127
+ const value = pair.slice(index + 1);
128
+ try {
129
+ cookies[key] = decodeURIComponent(value);
130
+ } catch {
131
+ cookies[key] = value;
132
+ }
133
+ }
134
+ return cookies;
135
+ };
136
+ var setCookie = (response, name, value, options) => {
137
+ const segments = [`${name}=${encodeURIComponent(value)}`];
138
+ segments.push(`Path=${options.path ?? "/"}`);
139
+ if (typeof options.maxAge === "number") {
140
+ segments.push(`Max-Age=${Math.max(0, Math.floor(options.maxAge))}`);
141
+ }
142
+ if (options.httpOnly) {
143
+ segments.push("HttpOnly");
144
+ }
145
+ if (options.secure) {
146
+ segments.push("Secure");
147
+ }
148
+ if (options.sameSite) {
149
+ segments.push(`SameSite=${options.sameSite}`);
150
+ }
151
+ const previous = response.getHeader("Set-Cookie");
152
+ const serialized = segments.join("; ");
153
+ if (!previous) {
154
+ response.setHeader("Set-Cookie", serialized);
155
+ return;
156
+ }
157
+ if (Array.isArray(previous)) {
158
+ response.setHeader("Set-Cookie", [...previous, serialized]);
159
+ return;
160
+ }
161
+ response.setHeader("Set-Cookie", [String(previous), serialized]);
162
+ };
163
+ var verifyPassphrase = (provided, expected) => {
164
+ const providedBuffer = Buffer.from(provided);
165
+ const expectedBuffer = Buffer.from(expected);
166
+ if (providedBuffer.length !== expectedBuffer.length) {
167
+ const zero = Buffer.alloc(expectedBuffer.length);
168
+ return timingSafeEqual(expectedBuffer, zero) && false;
169
+ }
170
+ return timingSafeEqual(providedBuffer, expectedBuffer);
171
+ };
172
+ var getRequestIp = (request) => {
173
+ return request.socket.remoteAddress ?? "unknown";
174
+ };
175
+ var inferConversationTitle = (text) => {
176
+ const normalized = text.trim().replace(/\s+/g, " ");
177
+ if (!normalized) {
178
+ return "New conversation";
179
+ }
180
+ return normalized.length <= 48 ? normalized : `${normalized.slice(0, 48)}...`;
181
+ };
182
+ var renderManifest = (options) => {
183
+ const name = options?.agentName ?? "Agent";
184
+ return JSON.stringify({
185
+ name,
186
+ short_name: name,
187
+ description: `${name} \u2014 AI agent powered by Poncho`,
188
+ start_url: "/",
189
+ display: "standalone",
190
+ background_color: "#000000",
191
+ theme_color: "#000000",
192
+ icons: [
193
+ { src: "/icon.svg", sizes: "any", type: "image/svg+xml" },
194
+ { src: "/icon-192.png", sizes: "192x192", type: "image/png" },
195
+ { src: "/icon-512.png", sizes: "512x512", type: "image/png" }
196
+ ]
197
+ });
198
+ };
199
+ var renderIconSvg = (options) => {
200
+ const letter = (options?.agentName ?? "A").charAt(0).toUpperCase();
201
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
202
+ <rect width="512" height="512" rx="96" fill="#000"/>
203
+ <text x="256" y="256" dy=".35em" text-anchor="middle"
204
+ font-family="-apple-system,BlinkMacSystemFont,sans-serif"
205
+ font-size="280" font-weight="700" fill="#fff">${letter}</text>
206
+ </svg>`;
207
+ };
208
+ var renderServiceWorker = () => `
209
+ const CACHE_NAME = "poncho-shell-v1";
210
+ const SHELL_URLS = ["/"];
211
+
212
+ self.addEventListener("install", (event) => {
213
+ event.waitUntil(
214
+ caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL_URLS))
215
+ );
216
+ self.skipWaiting();
217
+ });
218
+
219
+ self.addEventListener("activate", (event) => {
220
+ event.waitUntil(
221
+ caches.keys().then((keys) =>
222
+ Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
223
+ )
224
+ );
225
+ self.clients.claim();
226
+ });
227
+
228
+ self.addEventListener("fetch", (event) => {
229
+ const url = new URL(event.request.url);
230
+ // Only cache GET requests for the app shell; let API calls pass through
231
+ if (event.request.method !== "GET" || url.pathname.startsWith("/api/")) {
232
+ return;
233
+ }
234
+ event.respondWith(
235
+ fetch(event.request)
236
+ .then((response) => {
237
+ const clone = response.clone();
238
+ caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
239
+ return response;
240
+ })
241
+ .catch(() => caches.match(event.request))
242
+ );
243
+ });
244
+ `;
245
+ var renderWebUiHtml = (options) => {
246
+ const agentInitial = (options?.agentName ?? "A").charAt(0).toUpperCase();
247
+ const agentName = options?.agentName ?? "Agent";
248
+ return `<!doctype html>
249
+ <html lang="en">
250
+ <head>
251
+ <meta charset="utf-8">
252
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
253
+ <meta name="theme-color" content="#000000">
254
+ <meta name="apple-mobile-web-app-capable" content="yes">
255
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
256
+ <meta name="apple-mobile-web-app-title" content="${agentName}">
257
+ <link rel="manifest" href="/manifest.json">
258
+ <link rel="icon" href="/icon.svg" type="image/svg+xml">
259
+ <link rel="apple-touch-icon" href="/icon-192.png">
260
+ <title>${agentName}</title>
261
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inconsolata:400,700">
262
+ <style>
263
+ * { box-sizing: border-box; margin: 0; padding: 0; }
264
+ html, body { height: 100vh; overflow: hidden; overscroll-behavior: none; touch-action: pan-y; }
265
+ body {
266
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Helvetica Neue", sans-serif;
267
+ background: #000;
268
+ color: #ededed;
269
+ font-size: 14px;
270
+ line-height: 1.5;
271
+ -webkit-font-smoothing: antialiased;
272
+ -moz-osx-font-smoothing: grayscale;
273
+ }
274
+ button, input, textarea { font: inherit; color: inherit; }
275
+ .hidden { display: none !important; }
276
+ a { color: #ededed; }
277
+
278
+ /* Auth */
279
+ .auth {
280
+ min-height: 100vh;
281
+ display: grid;
282
+ place-items: center;
283
+ padding: 20px;
284
+ background: #000;
285
+ }
286
+ .auth-card {
287
+ width: min(380px, 90vw);
288
+ background: #0a0a0a;
289
+ border: 1px solid rgba(255,255,255,0.08);
290
+ border-radius: 12px;
291
+ padding: 32px;
292
+ display: grid;
293
+ gap: 20px;
294
+ }
295
+ .auth-brand {
296
+ display: flex;
297
+ align-items: center;
298
+ gap: 8px;
299
+ }
300
+ .auth-brand svg { width: 20px; height: 20px; }
301
+ .auth-title {
302
+ font-size: 16px;
303
+ font-weight: 500;
304
+ letter-spacing: -0.01em;
305
+ }
306
+ .auth-text { color: #666; font-size: 13px; line-height: 1.5; }
307
+ .auth-input {
308
+ width: 100%;
309
+ background: #000;
310
+ border: 1px solid rgba(255,255,255,0.12);
311
+ border-radius: 6px;
312
+ color: #ededed;
313
+ padding: 10px 12px;
314
+ font-size: 14px;
315
+ outline: none;
316
+ transition: border-color 0.15s;
317
+ }
318
+ .auth-input:focus { border-color: rgba(255,255,255,0.3); }
319
+ .auth-input::placeholder { color: #555; }
320
+ .auth-submit {
321
+ background: #ededed;
322
+ color: #000;
323
+ border: 0;
324
+ border-radius: 6px;
325
+ padding: 10px 16px;
326
+ font-size: 14px;
327
+ font-weight: 500;
328
+ cursor: pointer;
329
+ transition: background 0.15s;
330
+ }
331
+ .auth-submit:hover { background: #fff; }
332
+ .error { color: #ff4444; font-size: 13px; min-height: 16px; }
333
+ .message-error {
334
+ background: rgba(255,68,68,0.08);
335
+ border: 1px solid rgba(255,68,68,0.25);
336
+ border-radius: 10px;
337
+ color: #ff6b6b;
338
+ padding: 12px 16px;
339
+ font-size: 13px;
340
+ line-height: 1.5;
341
+ max-width: 600px;
342
+ }
343
+ .message-error strong { color: #ff4444; }
344
+
345
+ /* Layout - use fixed positioning with explicit dimensions */
346
+ .shell {
347
+ position: fixed;
348
+ top: 0;
349
+ left: 0;
350
+ width: 100vw;
351
+ height: 100vh;
352
+ height: 100dvh; /* Dynamic viewport height for normal browsers */
353
+ display: flex;
354
+ overflow: hidden;
355
+ }
356
+ /* PWA standalone mode: use 100vh which works correctly */
357
+ @media (display-mode: standalone) {
358
+ .shell {
359
+ height: 100vh;
360
+ }
361
+ }
362
+
363
+ /* Edge swipe blocker - invisible touch target to intercept right edge gestures */
364
+ .edge-blocker-right {
365
+ position: fixed;
366
+ top: 0;
367
+ bottom: 0;
368
+ right: 0;
369
+ width: 20px;
370
+ z-index: 9999;
371
+ touch-action: none;
372
+ }
373
+ .sidebar {
374
+ width: 260px;
375
+ background: #000;
376
+ border-right: 1px solid rgba(255,255,255,0.06);
377
+ display: flex;
378
+ flex-direction: column;
379
+ padding: 12px 8px;
380
+ }
381
+ .new-chat-btn {
382
+ background: transparent;
383
+ border: 0;
384
+ color: #888;
385
+ border-radius: 12px;
386
+ height: 36px;
387
+ padding: 0 10px;
388
+ display: flex;
389
+ align-items: center;
390
+ gap: 8px;
391
+ font-size: 13px;
392
+ cursor: pointer;
393
+ transition: background 0.15s, color 0.15s;
394
+ }
395
+ .new-chat-btn:hover { color: #ededed; }
396
+ .new-chat-btn svg { width: 16px; height: 16px; }
397
+ .conversation-list {
398
+ flex: 1;
399
+ overflow-y: auto;
400
+ margin-top: 12px;
401
+ display: flex;
402
+ flex-direction: column;
403
+ gap: 2px;
404
+ }
405
+ .conversation-item {
406
+ padding: 7px 28px 7px 10px;
407
+ border-radius: 12px;
408
+ cursor: pointer;
409
+ font-size: 13px;
410
+ color: #555;
411
+ white-space: nowrap;
412
+ overflow: hidden;
413
+ text-overflow: ellipsis;
414
+ position: relative;
415
+ transition: color 0.15s;
416
+ }
417
+ .conversation-item:hover { color: #999; }
418
+ .conversation-item.active {
419
+ color: #ededed;
420
+ }
421
+ .conversation-item .delete-btn {
422
+ position: absolute;
423
+ right: 0;
424
+ top: 0;
425
+ bottom: 0;
426
+ opacity: 0;
427
+ background: #000;
428
+ border: 0;
429
+ color: #444;
430
+ padding: 0 8px;
431
+ border-radius: 0 4px 4px 0;
432
+ cursor: pointer;
433
+ font-size: 16px;
434
+ line-height: 1;
435
+ display: grid;
436
+ place-items: center;
437
+ transition: opacity 0.15s, color 0.15s;
438
+ }
439
+ .conversation-item:hover .delete-btn { opacity: 1; }
440
+ .conversation-item.active .delete-btn { background: rgba(0,0,0,1); }
441
+ .conversation-item .delete-btn::before {
442
+ content: "";
443
+ position: absolute;
444
+ right: 100%;
445
+ top: 0;
446
+ bottom: 0;
447
+ width: 24px;
448
+ background: linear-gradient(to right, transparent, #000);
449
+ pointer-events: none;
450
+ }
451
+ .conversation-item.active .delete-btn::before {
452
+ background: linear-gradient(to right, transparent, rgba(0,0,0,1));
453
+ }
454
+ .conversation-item .delete-btn:hover { color: #888; }
455
+ .conversation-item .delete-btn.confirming {
456
+ opacity: 1;
457
+ width: auto;
458
+ padding: 0 8px;
459
+ font-size: 11px;
460
+ color: #ff4444;
461
+ border-radius: 3px;
462
+ }
463
+ .conversation-item .delete-btn.confirming:hover {
464
+ color: #ff6666;
465
+ }
466
+ .sidebar-footer {
467
+ margin-top: auto;
468
+ padding-top: 8px;
469
+ }
470
+ .logout-btn {
471
+ background: transparent;
472
+ border: 0;
473
+ color: #555;
474
+ width: 100%;
475
+ padding: 8px 10px;
476
+ text-align: left;
477
+ border-radius: 6px;
478
+ cursor: pointer;
479
+ font-size: 13px;
480
+ transition: color 0.15s, background 0.15s;
481
+ }
482
+ .logout-btn:hover { color: #888; }
483
+
484
+ /* Main */
485
+ .main { flex: 1; display: flex; flex-direction: column; min-width: 0; max-width: 100%; background: #000; overflow: hidden; }
486
+ .topbar {
487
+ height: calc(52px + env(safe-area-inset-top, 0px));
488
+ padding-top: env(safe-area-inset-top, 0px);
489
+ display: flex;
490
+ align-items: center;
491
+ justify-content: center;
492
+ font-size: 13px;
493
+ font-weight: 500;
494
+ color: #888;
495
+ border-bottom: 1px solid rgba(255,255,255,0.06);
496
+ position: relative;
497
+ flex-shrink: 0;
498
+ }
499
+ .topbar-title {
500
+ max-width: calc(100% - 100px);
501
+ overflow: hidden;
502
+ text-overflow: ellipsis;
503
+ white-space: nowrap;
504
+ letter-spacing: -0.01em;
505
+ padding: 0 50px;
506
+ }
507
+ .sidebar-toggle {
508
+ display: none;
509
+ position: absolute;
510
+ left: 12px;
511
+ bottom: 4px; /* Position from bottom of topbar content area */
512
+ background: transparent;
513
+ border: 0;
514
+ color: #666;
515
+ width: 44px;
516
+ height: 44px;
517
+ border-radius: 6px;
518
+ cursor: pointer;
519
+ transition: color 0.15s, background 0.15s;
520
+ font-size: 18px;
521
+ z-index: 10;
522
+ -webkit-tap-highlight-color: transparent;
523
+ }
524
+ .sidebar-toggle:hover { color: #ededed; }
525
+ .topbar-new-chat {
526
+ display: none;
527
+ position: absolute;
528
+ right: 12px;
529
+ bottom: 4px;
530
+ background: transparent;
531
+ border: 0;
532
+ color: #666;
533
+ width: 44px;
534
+ height: 44px;
535
+ border-radius: 6px;
536
+ cursor: pointer;
537
+ transition: color 0.15s, background 0.15s;
538
+ z-index: 10;
539
+ -webkit-tap-highlight-color: transparent;
540
+ }
541
+ .topbar-new-chat:hover { color: #ededed; }
542
+ .topbar-new-chat svg { width: 16px; height: 16px; }
543
+
544
+ /* Messages */
545
+ .messages { flex: 1; overflow-y: auto; overflow-x: hidden; padding: 24px 24px; }
546
+ .messages-column { max-width: 680px; margin: 0 auto; }
547
+ .message-row { margin-bottom: 24px; display: flex; max-width: 100%; }
548
+ .message-row.user { justify-content: flex-end; }
549
+ .assistant-wrap { display: flex; gap: 12px; max-width: 100%; min-width: 0; }
550
+ .assistant-avatar {
551
+ width: 24px;
552
+ height: 24px;
553
+ background: #ededed;
554
+ color: #000;
555
+ border-radius: 6px;
556
+ display: grid;
557
+ place-items: center;
558
+ font-size: 11px;
559
+ font-weight: 600;
560
+ flex-shrink: 0;
561
+ margin-top: 2px;
562
+ }
563
+ .assistant-content {
564
+ line-height: 1.65;
565
+ color: #ededed;
566
+ font-size: 14px;
567
+ min-width: 0;
568
+ max-width: 100%;
569
+ overflow-wrap: break-word;
570
+ word-break: break-word;
571
+ margin-top: 2px;
572
+ }
573
+ .assistant-content p { margin: 0 0 12px; }
574
+ .assistant-content p:last-child { margin-bottom: 0; }
575
+ .assistant-content ul, .assistant-content ol { margin: 8px 0; padding-left: 20px; }
576
+ .assistant-content li { margin: 4px 0; }
577
+ .assistant-content strong { font-weight: 600; color: #fff; }
578
+ .assistant-content h2 {
579
+ font-size: 16px;
580
+ font-weight: 600;
581
+ letter-spacing: -0.02em;
582
+ margin: 20px 0 8px;
583
+ color: #fff;
584
+ }
585
+ .assistant-content h3 {
586
+ font-size: 14px;
587
+ font-weight: 600;
588
+ letter-spacing: -0.01em;
589
+ margin: 16px 0 6px;
590
+ color: #fff;
591
+ }
592
+ .assistant-content code {
593
+ background: rgba(255,255,255,0.06);
594
+ border: 1px solid rgba(255,255,255,0.06);
595
+ padding: 2px 5px;
596
+ border-radius: 4px;
597
+ font-family: ui-monospace, "SF Mono", "Fira Code", monospace;
598
+ font-size: 0.88em;
599
+ }
600
+ .assistant-content pre {
601
+ background: #0a0a0a;
602
+ border: 1px solid rgba(255,255,255,0.06);
603
+ padding: 14px 16px;
604
+ border-radius: 8px;
605
+ overflow-x: auto;
606
+ margin: 14px 0;
607
+ }
608
+ .assistant-content pre code {
609
+ background: none;
610
+ border: 0;
611
+ padding: 0;
612
+ font-size: 13px;
613
+ line-height: 1.5;
614
+ }
615
+ .tool-activity-inline {
616
+ margin: 8px 0;
617
+ font-size: 12px;
618
+ line-height: 1.45;
619
+ color: #8a8a8a;
620
+ }
621
+ .tool-activity-inline code {
622
+ font-family: ui-monospace, "SF Mono", "Fira Code", monospace;
623
+ background: rgba(255,255,255,0.04);
624
+ border: 1px solid rgba(255,255,255,0.08);
625
+ padding: 4px 8px;
626
+ border-radius: 6px;
627
+ color: #bcbcbc;
628
+ font-size: 11px;
629
+ }
630
+ .tool-status {
631
+ color: #8a8a8a;
632
+ font-style: italic;
633
+ }
634
+ .tool-done {
635
+ color: #6a9955;
636
+ }
637
+ .tool-error {
638
+ color: #f48771;
639
+ }
640
+ .assistant-content table {
641
+ border-collapse: collapse;
642
+ width: 100%;
643
+ margin: 14px 0;
644
+ font-size: 13px;
645
+ border: 1px solid rgba(255,255,255,0.08);
646
+ border-radius: 8px;
647
+ overflow: hidden;
648
+ }
649
+ .assistant-content th {
650
+ background: rgba(255,255,255,0.06);
651
+ padding: 10px 12px;
652
+ text-align: left;
653
+ font-weight: 600;
654
+ border-bottom: 1px solid rgba(255,255,255,0.12);
655
+ color: #fff;
656
+ }
657
+ .assistant-content td {
658
+ padding: 10px 12px;
659
+ border-bottom: 1px solid rgba(255,255,255,0.06);
660
+ }
661
+ .assistant-content tr:last-child td {
662
+ border-bottom: none;
663
+ }
664
+ .assistant-content tbody tr:hover {
665
+ background: rgba(255,255,255,0.02);
666
+ }
667
+ .tool-activity {
668
+ margin-top: 12px;
669
+ margin-bottom: 12px;
670
+ border: 1px solid rgba(255,255,255,0.08);
671
+ background: rgba(255,255,255,0.03);
672
+ border-radius: 10px;
673
+ font-size: 12px;
674
+ line-height: 1.45;
675
+ color: #bcbcbc;
676
+ max-width: 300px;
677
+ }
678
+ .assistant-content > .tool-activity:first-child {
679
+ margin-top: 0;
680
+ }
681
+ .tool-activity-disclosure {
682
+ display: block;
683
+ }
684
+ .tool-activity-summary {
685
+ list-style: none;
686
+ display: flex;
687
+ align-items: center;
688
+ gap: 8px;
689
+ cursor: pointer;
690
+ padding: 10px 12px;
691
+ user-select: none;
692
+ }
693
+ .tool-activity-summary::-webkit-details-marker {
694
+ display: none;
695
+ }
696
+ .tool-activity-label {
697
+ font-size: 11px;
698
+ text-transform: uppercase;
699
+ letter-spacing: 0.06em;
700
+ color: #8a8a8a;
701
+ font-weight: 600;
702
+ }
703
+ .tool-activity-caret {
704
+ margin-left: auto;
705
+ color: #8a8a8a;
706
+ display: inline-flex;
707
+ align-items: center;
708
+ justify-content: center;
709
+ transition: transform 120ms ease;
710
+ transform: rotate(0deg);
711
+ }
712
+ .tool-activity-caret svg {
713
+ width: 14px;
714
+ height: 14px;
715
+ display: block;
716
+ }
717
+ .tool-activity-disclosure[open] .tool-activity-caret {
718
+ transform: rotate(90deg);
719
+ }
720
+ .tool-activity-list {
721
+ display: grid;
722
+ gap: 6px;
723
+ padding: 0 12px 10px;
724
+ }
725
+ .tool-activity-item {
726
+ font-family: ui-monospace, "SF Mono", "Fira Code", monospace;
727
+ background: rgba(255,255,255,0.04);
728
+ border-radius: 6px;
729
+ padding: 4px 7px;
730
+ color: #d6d6d6;
731
+ }
732
+ .user-bubble {
733
+ background: #111;
734
+ border: 1px solid rgba(255,255,255,0.08);
735
+ padding: 10px 16px;
736
+ border-radius: 18px;
737
+ max-width: 70%;
738
+ font-size: 14px;
739
+ line-height: 1.5;
740
+ overflow-wrap: break-word;
741
+ word-break: break-word;
742
+ }
743
+ .empty-state {
744
+ display: flex;
745
+ flex-direction: column;
746
+ align-items: center;
747
+ justify-content: center;
748
+ height: 100%;
749
+ gap: 16px;
750
+ color: #555;
751
+ }
752
+ .empty-state .assistant-avatar {
753
+ width: 36px;
754
+ height: 36px;
755
+ font-size: 14px;
756
+ border-radius: 8px;
757
+ }
758
+ .empty-state-text {
759
+ font-size: 14px;
760
+ color: #555;
761
+ }
762
+ .thinking-indicator {
763
+ display: inline-block;
764
+ font-family: Inconsolata, monospace;
765
+ font-size: 20px;
766
+ line-height: 1;
767
+ vertical-align: middle;
768
+ color: #ededed;
769
+ opacity: 0.5;
770
+ }
771
+
772
+ /* Composer */
773
+ .composer {
774
+ padding: 12px 24px 24px;
775
+ position: relative;
776
+ }
777
+ /* PWA standalone mode - extra bottom padding */
778
+ @media (display-mode: standalone), (-webkit-touch-callout: none) {
779
+ .composer {
780
+ padding-bottom: 32px;
781
+ }
782
+ }
783
+ @supports (-webkit-touch-callout: none) {
784
+ /* iOS Safari standalone check via JS class */
785
+ .standalone .composer {
786
+ padding-bottom: 32px;
787
+ }
788
+ }
789
+ .composer::before {
790
+ content: "";
791
+ position: absolute;
792
+ left: 0;
793
+ right: 0;
794
+ bottom: 100%;
795
+ height: 48px;
796
+ background: linear-gradient(to top, #000 0%, transparent 100%);
797
+ pointer-events: none;
798
+ }
799
+ .composer-inner { max-width: 680px; margin: 0 auto; }
800
+ .composer-shell {
801
+ background: #0a0a0a;
802
+ border: 1px solid rgba(255,255,255,0.1);
803
+ border-radius: 9999px;
804
+ display: flex;
805
+ align-items: center;
806
+ padding: 4px 6px 4px 18px;
807
+ transition: border-color 0.15s;
808
+ }
809
+ .composer-shell:focus-within { border-color: rgba(255,255,255,0.2); }
810
+ .composer-input {
811
+ flex: 1;
812
+ background: transparent;
813
+ border: 0;
814
+ outline: none;
815
+ color: #ededed;
816
+ min-height: 40px;
817
+ max-height: 200px;
818
+ resize: none;
819
+ padding: 10px 0 8px;
820
+ font-size: 14px;
821
+ line-height: 1.5;
822
+ }
823
+ .composer-input::placeholder { color: #444; }
824
+ .send-btn {
825
+ width: 32px;
826
+ height: 32px;
827
+ background: #ededed;
828
+ border: 0;
829
+ border-radius: 50%;
830
+ color: #000;
831
+ cursor: pointer;
832
+ display: grid;
833
+ place-items: center;
834
+ flex-shrink: 0;
835
+ margin-bottom: 2px;
836
+ transition: background 0.15s, opacity 0.15s;
837
+ }
838
+ .send-btn:hover { background: #fff; }
839
+ .send-btn:disabled { opacity: 0.2; cursor: default; }
840
+ .send-btn:disabled:hover { background: #ededed; }
841
+ .disclaimer {
842
+ text-align: center;
843
+ color: #333;
844
+ font-size: 12px;
845
+ margin-top: 10px;
846
+ }
847
+
848
+ /* Scrollbar */
849
+ ::-webkit-scrollbar { width: 6px; }
850
+ ::-webkit-scrollbar-track { background: transparent; }
851
+ ::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 3px; }
852
+ ::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.16); }
853
+
854
+ /* Mobile */
855
+ @media (max-width: 768px) {
856
+ .sidebar {
857
+ position: fixed;
858
+ inset: 0 auto 0 0;
859
+ z-index: 100;
860
+ transform: translateX(-100%);
861
+ padding-top: calc(env(safe-area-inset-top, 0px) + 12px);
862
+ will-change: transform;
863
+ }
864
+ .sidebar.dragging { transition: none; }
865
+ .sidebar:not(.dragging) { transition: transform 0.25s cubic-bezier(0.4, 0, 0.2, 1); }
866
+ .shell.sidebar-open .sidebar { transform: translateX(0); }
867
+ .sidebar-toggle { display: grid; place-items: center; }
868
+ .topbar-new-chat { display: grid; place-items: center; }
869
+ .sidebar-backdrop {
870
+ position: fixed;
871
+ inset: 0;
872
+ background: rgba(0,0,0,0.6);
873
+ z-index: 50;
874
+ backdrop-filter: blur(2px);
875
+ -webkit-backdrop-filter: blur(2px);
876
+ opacity: 0;
877
+ pointer-events: none;
878
+ will-change: opacity;
879
+ }
880
+ .sidebar-backdrop:not(.dragging) { transition: opacity 0.25s cubic-bezier(0.4, 0, 0.2, 1); }
881
+ .sidebar-backdrop.dragging { transition: none; }
882
+ .shell.sidebar-open .sidebar-backdrop { opacity: 1; pointer-events: auto; }
883
+ .messages { padding: 16px; }
884
+ .composer { padding: 8px 16px 16px; }
885
+ /* Always show delete button on mobile (no hover) */
886
+ .conversation-item .delete-btn { opacity: 1; }
887
+ }
888
+
889
+ /* Reduced motion */
890
+ @media (prefers-reduced-motion: reduce) {
891
+ *, *::before, *::after {
892
+ animation-duration: 0.01ms !important;
893
+ transition-duration: 0.01ms !important;
894
+ }
895
+ }
896
+ </style>
897
+ </head>
898
+ <body data-agent-initial="${agentInitial}" data-agent-name="${agentName}">
899
+ <div class="edge-blocker-right"></div>
900
+ <div id="auth" class="auth hidden">
901
+ <form id="login-form" class="auth-card">
902
+ <div class="auth-brand">
903
+ <svg viewBox="0 0 24 24" fill="none"><path d="M12 2L2 19.5h20L12 2z" fill="currentColor"/></svg>
904
+ <h2 class="auth-title">Poncho</h2>
905
+ </div>
906
+ <p class="auth-text">Enter the passphrase to continue.</p>
907
+ <input id="passphrase" class="auth-input" type="password" placeholder="Passphrase" required>
908
+ <button class="auth-submit" type="submit">Continue</button>
909
+ <div id="login-error" class="error"></div>
910
+ </form>
911
+ </div>
912
+
913
+ <div id="app" class="shell hidden">
914
+ <aside class="sidebar">
915
+ <button id="new-chat" class="new-chat-btn">
916
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>
917
+ </button>
918
+ <div id="conversation-list" class="conversation-list"></div>
919
+ <div class="sidebar-footer">
920
+ <button id="logout" class="logout-btn">Log out</button>
921
+ </div>
922
+ </aside>
923
+ <div id="sidebar-backdrop" class="sidebar-backdrop"></div>
924
+ <main class="main">
925
+ <div class="topbar">
926
+ <button id="sidebar-toggle" class="sidebar-toggle">&#9776;</button>
927
+ <div id="chat-title" class="topbar-title"></div>
928
+ <button id="topbar-new-chat" class="topbar-new-chat">
929
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>
930
+ </button>
931
+ </div>
932
+ <div id="messages" class="messages">
933
+ <div class="empty-state">
934
+ <div class="assistant-avatar">${agentInitial}</div>
935
+ <div class="empty-state-text">How can I help you today?</div>
936
+ </div>
937
+ </div>
938
+ <form id="composer" class="composer">
939
+ <div class="composer-inner">
940
+ <div class="composer-shell">
941
+ <textarea id="prompt" class="composer-input" placeholder="Send a message..." rows="1"></textarea>
942
+ <button id="send" class="send-btn" type="submit">
943
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M8 12V4M4 7l4-4 4 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
944
+ </button>
945
+ </div>
946
+ </div>
947
+ </form>
948
+ </main>
949
+ </div>
950
+
951
+ <script>
952
+ // Marked library (inlined)
953
+ ${markedSource}
954
+
955
+ // Configure marked for GitHub Flavored Markdown (tables, etc.)
956
+ marked.setOptions({
957
+ gfm: true,
958
+ breaks: true
959
+ });
960
+
961
+ const state = {
962
+ csrfToken: "",
963
+ conversations: [],
964
+ activeConversationId: null,
965
+ activeMessages: [],
966
+ isStreaming: false,
967
+ confirmDeleteId: null
968
+ };
969
+
970
+ const agentInitial = document.body.dataset.agentInitial || "A";
971
+ const $ = (id) => document.getElementById(id);
972
+ const elements = {
973
+ auth: $("auth"),
974
+ app: $("app"),
975
+ loginForm: $("login-form"),
976
+ passphrase: $("passphrase"),
977
+ loginError: $("login-error"),
978
+ list: $("conversation-list"),
979
+ newChat: $("new-chat"),
980
+ topbarNewChat: $("topbar-new-chat"),
981
+ messages: $("messages"),
982
+ chatTitle: $("chat-title"),
983
+ logout: $("logout"),
984
+ composer: $("composer"),
985
+ prompt: $("prompt"),
986
+ send: $("send"),
987
+ shell: $("app"),
988
+ sidebarToggle: $("sidebar-toggle"),
989
+ sidebarBackdrop: $("sidebar-backdrop")
990
+ };
991
+
992
+ const pushConversationUrl = (conversationId) => {
993
+ const target = conversationId ? "/c/" + encodeURIComponent(conversationId) : "/";
994
+ if (window.location.pathname !== target) {
995
+ history.pushState({ conversationId: conversationId || null }, "", target);
996
+ }
997
+ };
998
+
999
+ const replaceConversationUrl = (conversationId) => {
1000
+ const target = conversationId ? "/c/" + encodeURIComponent(conversationId) : "/";
1001
+ if (window.location.pathname !== target) {
1002
+ history.replaceState({ conversationId: conversationId || null }, "", target);
1003
+ }
1004
+ };
1005
+
1006
+ const getConversationIdFromUrl = () => {
1007
+ const match = window.location.pathname.match(/^\\/c\\/([^\\/]+)/);
1008
+ return match ? decodeURIComponent(match[1]) : null;
1009
+ };
1010
+
1011
+ const mutatingMethods = new Set(["POST", "PATCH", "PUT", "DELETE"]);
1012
+
1013
+ const api = async (path, options = {}) => {
1014
+ const method = (options.method || "GET").toUpperCase();
1015
+ const headers = { ...(options.headers || {}) };
1016
+ if (mutatingMethods.has(method) && state.csrfToken) {
1017
+ headers["x-csrf-token"] = state.csrfToken;
1018
+ }
1019
+ if (options.body && !headers["Content-Type"]) {
1020
+ headers["Content-Type"] = "application/json";
1021
+ }
1022
+ const response = await fetch(path, { credentials: "include", ...options, method, headers });
1023
+ if (!response.ok) {
1024
+ let payload = {};
1025
+ try { payload = await response.json(); } catch {}
1026
+ const error = new Error(payload.message || ("Request failed: " + response.status));
1027
+ error.status = response.status;
1028
+ error.payload = payload;
1029
+ throw error;
1030
+ }
1031
+ const contentType = response.headers.get("content-type") || "";
1032
+ if (contentType.includes("application/json")) {
1033
+ return await response.json();
1034
+ }
1035
+ return await response.text();
1036
+ };
1037
+
1038
+ const escapeHtml = (value) =>
1039
+ String(value || "")
1040
+ .replace(/&/g, "&amp;")
1041
+ .replace(/</g, "&lt;")
1042
+ .replace(/>/g, "&gt;")
1043
+ .replace(/"/g, "&quot;")
1044
+ .replace(/'/g, "&#39;");
1045
+
1046
+ const renderAssistantMarkdown = (value) => {
1047
+ const source = String(value || "").trim();
1048
+ if (!source) return "<p></p>";
1049
+
1050
+ try {
1051
+ return marked.parse(source);
1052
+ } catch (error) {
1053
+ console.error("Markdown parsing error:", error);
1054
+ // Fallback to escaped text
1055
+ return "<p>" + escapeHtml(source) + "</p>";
1056
+ }
1057
+ };
1058
+
1059
+ const extractToolActivity = (value) => {
1060
+ const source = String(value || "");
1061
+ let markerIndex = source.lastIndexOf("\\n### Tool activity\\n");
1062
+ if (markerIndex < 0 && source.startsWith("### Tool activity\\n")) {
1063
+ markerIndex = 0;
1064
+ }
1065
+ if (markerIndex < 0) {
1066
+ return { content: source, activities: [] };
1067
+ }
1068
+ const content = markerIndex === 0 ? "" : source.slice(0, markerIndex).trimEnd();
1069
+ const rawSection = markerIndex === 0 ? source : source.slice(markerIndex + 1);
1070
+ const afterHeading = rawSection.replace(/^### Tool activity\\s*\\n?/, "");
1071
+ const activities = afterHeading
1072
+ .split("\\n")
1073
+ .map((line) => line.trim())
1074
+ .filter((line) => line.startsWith("- "))
1075
+ .map((line) => line.slice(2).trim())
1076
+ .filter(Boolean);
1077
+ return { content, activities };
1078
+ };
1079
+
1080
+ const renderToolActivity = (items) => {
1081
+ if (!items || !items.length) {
1082
+ return "";
1083
+ }
1084
+ const chips = items
1085
+ .map((item) => '<div class="tool-activity-item">' + escapeHtml(item) + "</div>")
1086
+ .join("");
1087
+ return (
1088
+ '<div class="tool-activity">' +
1089
+ '<details class="tool-activity-disclosure">' +
1090
+ '<summary class="tool-activity-summary">' +
1091
+ '<span class="tool-activity-label">Tool activity</span>' +
1092
+ '<span class="tool-activity-caret" aria-hidden="true"><svg viewBox="0 0 12 12" fill="none"><path d="M4.5 2.75L8 6L4.5 9.25" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></svg></span>' +
1093
+ "</summary>" +
1094
+ '<div class="tool-activity-list">' +
1095
+ chips +
1096
+ "</div>" +
1097
+ "</details>" +
1098
+ "</div>"
1099
+ );
1100
+ };
1101
+
1102
+ const formatDate = (epoch) => {
1103
+ try {
1104
+ const date = new Date(epoch);
1105
+ const now = new Date();
1106
+ const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
1107
+ const startOfDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
1108
+ const dayDiff = Math.floor((startOfToday - startOfDate) / 86400000);
1109
+ if (dayDiff === 0) {
1110
+ return "Today";
1111
+ }
1112
+ if (dayDiff === 1) {
1113
+ return "Yesterday";
1114
+ }
1115
+ if (dayDiff < 7 && dayDiff > 1) {
1116
+ return date.toLocaleDateString(undefined, { weekday: "short" });
1117
+ }
1118
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
1119
+ } catch {
1120
+ return "";
1121
+ }
1122
+ };
1123
+
1124
+ const isMobile = () => window.matchMedia("(max-width: 900px)").matches;
1125
+
1126
+ const setSidebarOpen = (open) => {
1127
+ if (!isMobile()) {
1128
+ elements.shell.classList.remove("sidebar-open");
1129
+ return;
1130
+ }
1131
+ elements.shell.classList.toggle("sidebar-open", open);
1132
+ };
1133
+
1134
+ const renderConversationList = () => {
1135
+ elements.list.innerHTML = "";
1136
+ for (const c of state.conversations) {
1137
+ const item = document.createElement("div");
1138
+ item.className = "conversation-item" + (c.conversationId === state.activeConversationId ? " active" : "");
1139
+ item.textContent = c.title;
1140
+
1141
+ const isConfirming = state.confirmDeleteId === c.conversationId;
1142
+ const deleteBtn = document.createElement("button");
1143
+ deleteBtn.className = "delete-btn" + (isConfirming ? " confirming" : "");
1144
+ deleteBtn.textContent = isConfirming ? "sure?" : "\\u00d7";
1145
+ deleteBtn.onclick = async (e) => {
1146
+ e.stopPropagation();
1147
+ if (!isConfirming) {
1148
+ state.confirmDeleteId = c.conversationId;
1149
+ renderConversationList();
1150
+ return;
1151
+ }
1152
+ await api("/api/conversations/" + c.conversationId, { method: "DELETE" });
1153
+ if (state.activeConversationId === c.conversationId) {
1154
+ state.activeConversationId = null;
1155
+ state.activeMessages = [];
1156
+ pushConversationUrl(null);
1157
+ elements.chatTitle.textContent = "";
1158
+ renderMessages([]);
1159
+ }
1160
+ state.confirmDeleteId = null;
1161
+ await loadConversations();
1162
+ };
1163
+ item.appendChild(deleteBtn);
1164
+
1165
+ item.onclick = async () => {
1166
+ // Clear any delete confirmation, but still navigate
1167
+ if (state.confirmDeleteId) {
1168
+ state.confirmDeleteId = null;
1169
+ }
1170
+ state.activeConversationId = c.conversationId;
1171
+ pushConversationUrl(c.conversationId);
1172
+ renderConversationList();
1173
+ await loadConversation(c.conversationId);
1174
+ if (isMobile()) setSidebarOpen(false);
1175
+ };
1176
+
1177
+ elements.list.appendChild(item);
1178
+ }
1179
+ };
1180
+
1181
+ const renderMessages = (messages, isStreaming = false) => {
1182
+ elements.messages.innerHTML = "";
1183
+ if (!messages || !messages.length) {
1184
+ elements.messages.innerHTML = '<div class="empty-state"><div class="assistant-avatar">' + agentInitial + '</div><div>How can I help you today?</div></div>';
1185
+ return;
1186
+ }
1187
+ const col = document.createElement("div");
1188
+ col.className = "messages-column";
1189
+ messages.forEach((m, i) => {
1190
+ const row = document.createElement("div");
1191
+ row.className = "message-row " + m.role;
1192
+ if (m.role === "assistant") {
1193
+ const wrap = document.createElement("div");
1194
+ wrap.className = "assistant-wrap";
1195
+ wrap.innerHTML = '<div class="assistant-avatar">' + agentInitial + '</div>';
1196
+ const content = document.createElement("div");
1197
+ content.className = "assistant-content";
1198
+ const text = String(m.content || "");
1199
+
1200
+ if (m._error) {
1201
+ const errorEl = document.createElement("div");
1202
+ errorEl.className = "message-error";
1203
+ errorEl.innerHTML = "<strong>Error</strong><br>" + escapeHtml(m._error);
1204
+ content.appendChild(errorEl);
1205
+ } else if (isStreaming && i === messages.length - 1 && !text && (!m._chunks || m._chunks.length === 0)) {
1206
+ const spinner = document.createElement("span");
1207
+ spinner.className = "thinking-indicator";
1208
+ const starFrames = ["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"];
1209
+ let frame = 0;
1210
+ spinner.textContent = starFrames[0];
1211
+ spinner._interval = setInterval(() => { frame = (frame + 1) % starFrames.length; spinner.textContent = starFrames[frame]; }, 70);
1212
+ content.appendChild(spinner);
1213
+ } else {
1214
+ // Check for sections in _sections (streaming) or metadata.sections (stored)
1215
+ const sections = m._sections || (m.metadata && m.metadata.sections);
1216
+
1217
+ if (sections && sections.length > 0) {
1218
+ // Render sections interleaved
1219
+ sections.forEach(section => {
1220
+ if (section.type === "text") {
1221
+ const textDiv = document.createElement("div");
1222
+ textDiv.innerHTML = renderAssistantMarkdown(section.content);
1223
+ content.appendChild(textDiv);
1224
+ } else if (section.type === "tools") {
1225
+ content.insertAdjacentHTML("beforeend", renderToolActivity(section.content));
1226
+ }
1227
+ });
1228
+ // While streaming, show current tools if any
1229
+ if (isStreaming && i === messages.length - 1 && m._currentTools && m._currentTools.length > 0) {
1230
+ content.insertAdjacentHTML("beforeend", renderToolActivity(m._currentTools));
1231
+ }
1232
+ // Show current text being typed
1233
+ if (isStreaming && i === messages.length - 1 && m._currentText) {
1234
+ const textDiv = document.createElement("div");
1235
+ textDiv.innerHTML = renderAssistantMarkdown(m._currentText);
1236
+ content.appendChild(textDiv);
1237
+ }
1238
+ } else {
1239
+ // Fallback: render text and tools the old way (for old messages without sections)
1240
+ if (text) {
1241
+ const parsed = extractToolActivity(text);
1242
+ content.innerHTML = renderAssistantMarkdown(parsed.content);
1243
+ }
1244
+ const metadataToolActivity =
1245
+ m.metadata && Array.isArray(m.metadata.toolActivity)
1246
+ ? m.metadata.toolActivity
1247
+ : [];
1248
+ if (metadataToolActivity.length > 0) {
1249
+ content.insertAdjacentHTML("beforeend", renderToolActivity(metadataToolActivity));
1250
+ }
1251
+ }
1252
+ }
1253
+ wrap.appendChild(content);
1254
+ row.appendChild(wrap);
1255
+ } else {
1256
+ row.innerHTML = '<div class="user-bubble">' + escapeHtml(m.content) + '</div>';
1257
+ }
1258
+ col.appendChild(row);
1259
+ });
1260
+ elements.messages.appendChild(col);
1261
+ elements.messages.scrollTop = elements.messages.scrollHeight;
1262
+ };
1263
+
1264
+ const loadConversations = async () => {
1265
+ const payload = await api("/api/conversations");
1266
+ state.conversations = payload.conversations || [];
1267
+ renderConversationList();
1268
+ };
1269
+
1270
+ const loadConversation = async (conversationId) => {
1271
+ const payload = await api("/api/conversations/" + encodeURIComponent(conversationId));
1272
+ elements.chatTitle.textContent = payload.conversation.title;
1273
+ state.activeMessages = payload.conversation.messages || [];
1274
+ renderMessages(state.activeMessages);
1275
+ elements.prompt.focus();
1276
+ };
1277
+
1278
+ const createConversation = async (title, options = {}) => {
1279
+ const shouldLoadConversation = options.loadConversation !== false;
1280
+ const payload = await api("/api/conversations", {
1281
+ method: "POST",
1282
+ body: JSON.stringify(title ? { title } : {})
1283
+ });
1284
+ state.activeConversationId = payload.conversation.conversationId;
1285
+ state.confirmDeleteId = null;
1286
+ pushConversationUrl(state.activeConversationId);
1287
+ await loadConversations();
1288
+ if (shouldLoadConversation) {
1289
+ await loadConversation(state.activeConversationId);
1290
+ } else {
1291
+ elements.chatTitle.textContent = payload.conversation.title || "New conversation";
1292
+ }
1293
+ return state.activeConversationId;
1294
+ };
1295
+
1296
+ const parseSseChunk = (buffer, onEvent) => {
1297
+ let rest = buffer;
1298
+ while (true) {
1299
+ const index = rest.indexOf("\\n\\n");
1300
+ if (index < 0) {
1301
+ return rest;
1302
+ }
1303
+ const raw = rest.slice(0, index);
1304
+ rest = rest.slice(index + 2);
1305
+ const lines = raw.split("\\n");
1306
+ let eventName = "message";
1307
+ let data = "";
1308
+ for (const line of lines) {
1309
+ if (line.startsWith("event:")) {
1310
+ eventName = line.slice(6).trim();
1311
+ } else if (line.startsWith("data:")) {
1312
+ data += line.slice(5).trim();
1313
+ }
1314
+ }
1315
+ if (data) {
1316
+ try {
1317
+ onEvent(eventName, JSON.parse(data));
1318
+ } catch {}
1319
+ }
1320
+ }
1321
+ };
1322
+
1323
+ const setStreaming = (value) => {
1324
+ state.isStreaming = value;
1325
+ elements.send.disabled = value;
1326
+ };
1327
+
1328
+ const pushToolActivity = (assistantMessage, line) => {
1329
+ if (!line) {
1330
+ return;
1331
+ }
1332
+ if (
1333
+ !assistantMessage.metadata ||
1334
+ !Array.isArray(assistantMessage.metadata.toolActivity)
1335
+ ) {
1336
+ assistantMessage.metadata = {
1337
+ ...(assistantMessage.metadata || {}),
1338
+ toolActivity: [],
1339
+ };
1340
+ }
1341
+ assistantMessage.metadata.toolActivity.push(line);
1342
+ };
1343
+
1344
+ const autoResizePrompt = () => {
1345
+ const el = elements.prompt;
1346
+ el.style.height = "auto";
1347
+ const scrollHeight = el.scrollHeight;
1348
+ const nextHeight = Math.min(scrollHeight, 200);
1349
+ el.style.height = nextHeight + "px";
1350
+ el.style.overflowY = scrollHeight > 200 ? "auto" : "hidden";
1351
+ };
1352
+
1353
+ const sendMessage = async (text) => {
1354
+ const messageText = (text || "").trim();
1355
+ if (!messageText || state.isStreaming) {
1356
+ return;
1357
+ }
1358
+ const localMessages = [...(state.activeMessages || []), { role: "user", content: messageText }];
1359
+ let assistantMessage = {
1360
+ role: "assistant",
1361
+ content: "",
1362
+ _sections: [], // Array of {type: 'text'|'tools', content: string|array}
1363
+ _currentText: "",
1364
+ _currentTools: [],
1365
+ metadata: { toolActivity: [] }
1366
+ };
1367
+ localMessages.push(assistantMessage);
1368
+ state.activeMessages = localMessages;
1369
+ renderMessages(localMessages, true);
1370
+ setStreaming(true);
1371
+ let conversationId = state.activeConversationId;
1372
+ try {
1373
+ if (!conversationId) {
1374
+ conversationId = await createConversation(messageText, { loadConversation: false });
1375
+ }
1376
+ const response = await fetch("/api/conversations/" + encodeURIComponent(conversationId) + "/messages", {
1377
+ method: "POST",
1378
+ credentials: "include",
1379
+ headers: { "Content-Type": "application/json", "x-csrf-token": state.csrfToken },
1380
+ body: JSON.stringify({ message: messageText })
1381
+ });
1382
+ if (!response.ok || !response.body) {
1383
+ throw new Error("Failed to stream response");
1384
+ }
1385
+ const reader = response.body.getReader();
1386
+ const decoder = new TextDecoder();
1387
+ let buffer = "";
1388
+ while (true) {
1389
+ const { value, done } = await reader.read();
1390
+ if (done) {
1391
+ break;
1392
+ }
1393
+ buffer += decoder.decode(value, { stream: true });
1394
+ buffer = parseSseChunk(buffer, (eventName, payload) => {
1395
+ if (eventName === "model:chunk") {
1396
+ const chunk = String(payload.content || "");
1397
+ // If we have tools accumulated and text starts again, push tools as a section
1398
+ if (assistantMessage._currentTools.length > 0 && chunk.length > 0) {
1399
+ assistantMessage._sections.push({ type: "tools", content: assistantMessage._currentTools });
1400
+ assistantMessage._currentTools = [];
1401
+ }
1402
+ assistantMessage.content += chunk;
1403
+ assistantMessage._currentText += chunk;
1404
+ renderMessages(localMessages, true);
1405
+ }
1406
+ if (eventName === "tool:started") {
1407
+ const toolName = payload.tool || "tool";
1408
+ // If we have text accumulated, push it as a text section
1409
+ if (assistantMessage._currentText.length > 0) {
1410
+ assistantMessage._sections.push({ type: "text", content: assistantMessage._currentText });
1411
+ assistantMessage._currentText = "";
1412
+ }
1413
+ const toolText = "- start \\x60" + toolName + "\\x60";
1414
+ assistantMessage._currentTools.push(toolText);
1415
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1416
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1417
+ assistantMessage.metadata.toolActivity.push(toolText);
1418
+ renderMessages(localMessages, true);
1419
+ }
1420
+ if (eventName === "tool:completed") {
1421
+ const toolName = payload.tool || "tool";
1422
+ const duration = typeof payload.duration === "number" ? payload.duration : null;
1423
+ const toolText = "- done \\x60" + toolName + "\\x60" + (duration !== null ? " (" + duration + "ms)" : "");
1424
+ assistantMessage._currentTools.push(toolText);
1425
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1426
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1427
+ assistantMessage.metadata.toolActivity.push(toolText);
1428
+ renderMessages(localMessages, true);
1429
+ }
1430
+ if (eventName === "tool:error") {
1431
+ const toolName = payload.tool || "tool";
1432
+ const errorMsg = payload.error || "unknown error";
1433
+ const toolText = "- error \\x60" + toolName + "\\x60: " + errorMsg;
1434
+ assistantMessage._currentTools.push(toolText);
1435
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1436
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1437
+ assistantMessage.metadata.toolActivity.push(toolText);
1438
+ renderMessages(localMessages, true);
1439
+ }
1440
+ if (eventName === "tool:approval:required") {
1441
+ const toolName = payload.tool || "tool";
1442
+ const toolText = "- approval required \\x60" + toolName + "\\x60";
1443
+ assistantMessage._currentTools.push(toolText);
1444
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1445
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1446
+ assistantMessage.metadata.toolActivity.push(toolText);
1447
+ renderMessages(localMessages, true);
1448
+ }
1449
+ if (eventName === "tool:approval:granted") {
1450
+ const toolText = "- approval granted";
1451
+ assistantMessage._currentTools.push(toolText);
1452
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1453
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1454
+ assistantMessage.metadata.toolActivity.push(toolText);
1455
+ renderMessages(localMessages, true);
1456
+ }
1457
+ if (eventName === "tool:approval:denied") {
1458
+ const toolText = "- approval denied";
1459
+ assistantMessage._currentTools.push(toolText);
1460
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1461
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1462
+ assistantMessage.metadata.toolActivity.push(toolText);
1463
+ renderMessages(localMessages, true);
1464
+ }
1465
+ if (eventName === "run:completed") {
1466
+ if (!assistantMessage.content || assistantMessage.content.length === 0) {
1467
+ assistantMessage.content = String(payload.result?.response || "");
1468
+ }
1469
+ // Finalize sections: push any remaining tools and text
1470
+ if (assistantMessage._currentTools.length > 0) {
1471
+ assistantMessage._sections.push({ type: "tools", content: assistantMessage._currentTools });
1472
+ assistantMessage._currentTools = [];
1473
+ }
1474
+ if (assistantMessage._currentText.length > 0) {
1475
+ assistantMessage._sections.push({ type: "text", content: assistantMessage._currentText });
1476
+ assistantMessage._currentText = "";
1477
+ }
1478
+ renderMessages(localMessages, false);
1479
+ }
1480
+ if (eventName === "run:error") {
1481
+ const errMsg = payload.error?.message || "Something went wrong";
1482
+ assistantMessage.content = "";
1483
+ assistantMessage._error = errMsg;
1484
+ renderMessages(localMessages, false);
1485
+ }
1486
+ });
1487
+ }
1488
+ // Update the state with our local messages (don't reload and lose tool chips)
1489
+ state.activeMessages = localMessages;
1490
+ await loadConversations();
1491
+ // Don't reload the conversation - we already have the latest state with tool chips
1492
+ } finally {
1493
+ setStreaming(false);
1494
+ elements.prompt.focus();
1495
+ }
1496
+ };
1497
+
1498
+ const requireAuth = async () => {
1499
+ try {
1500
+ const session = await api("/api/auth/session");
1501
+ if (!session.authenticated) {
1502
+ elements.auth.classList.remove("hidden");
1503
+ elements.app.classList.add("hidden");
1504
+ return false;
1505
+ }
1506
+ state.csrfToken = session.csrfToken || "";
1507
+ elements.auth.classList.add("hidden");
1508
+ elements.app.classList.remove("hidden");
1509
+ return true;
1510
+ } catch {
1511
+ elements.auth.classList.remove("hidden");
1512
+ elements.app.classList.add("hidden");
1513
+ return false;
1514
+ }
1515
+ };
1516
+
1517
+ elements.loginForm.addEventListener("submit", async (event) => {
1518
+ event.preventDefault();
1519
+ elements.loginError.textContent = "";
1520
+ try {
1521
+ const result = await api("/api/auth/login", {
1522
+ method: "POST",
1523
+ body: JSON.stringify({ passphrase: elements.passphrase.value || "" })
1524
+ });
1525
+ state.csrfToken = result.csrfToken || "";
1526
+ elements.passphrase.value = "";
1527
+ elements.auth.classList.add("hidden");
1528
+ elements.app.classList.remove("hidden");
1529
+ await loadConversations();
1530
+ const urlConversationId = getConversationIdFromUrl();
1531
+ if (urlConversationId) {
1532
+ state.activeConversationId = urlConversationId;
1533
+ renderConversationList();
1534
+ try {
1535
+ await loadConversation(urlConversationId);
1536
+ } catch {
1537
+ state.activeConversationId = null;
1538
+ state.activeMessages = [];
1539
+ replaceConversationUrl(null);
1540
+ renderMessages([]);
1541
+ renderConversationList();
1542
+ }
1543
+ }
1544
+ } catch (error) {
1545
+ elements.loginError.textContent = error.message || "Login failed";
1546
+ }
1547
+ });
1548
+
1549
+ const startNewChat = () => {
1550
+ state.activeConversationId = null;
1551
+ state.activeMessages = [];
1552
+ state.confirmDeleteId = null;
1553
+ pushConversationUrl(null);
1554
+ elements.chatTitle.textContent = "";
1555
+ renderMessages([]);
1556
+ renderConversationList();
1557
+ elements.prompt.focus();
1558
+ if (isMobile()) {
1559
+ setSidebarOpen(false);
1560
+ }
1561
+ };
1562
+
1563
+ elements.newChat.addEventListener("click", startNewChat);
1564
+ elements.topbarNewChat.addEventListener("click", startNewChat);
1565
+
1566
+ elements.prompt.addEventListener("input", () => {
1567
+ autoResizePrompt();
1568
+ });
1569
+
1570
+ elements.prompt.addEventListener("keydown", (event) => {
1571
+ if (event.key === "Enter" && !event.shiftKey) {
1572
+ event.preventDefault();
1573
+ elements.composer.requestSubmit();
1574
+ }
1575
+ });
1576
+
1577
+ elements.sidebarToggle.addEventListener("click", () => {
1578
+ if (isMobile()) setSidebarOpen(!elements.shell.classList.contains("sidebar-open"));
1579
+ });
1580
+
1581
+ elements.sidebarBackdrop.addEventListener("click", () => setSidebarOpen(false));
1582
+
1583
+ elements.logout.addEventListener("click", async () => {
1584
+ await api("/api/auth/logout", { method: "POST" });
1585
+ state.activeConversationId = null;
1586
+ state.activeMessages = [];
1587
+ state.confirmDeleteId = null;
1588
+ state.conversations = [];
1589
+ state.csrfToken = "";
1590
+ await requireAuth();
1591
+ });
1592
+
1593
+ elements.composer.addEventListener("submit", async (event) => {
1594
+ event.preventDefault();
1595
+ const value = elements.prompt.value;
1596
+ elements.prompt.value = "";
1597
+ autoResizePrompt();
1598
+ await sendMessage(value);
1599
+ });
1600
+
1601
+ document.addEventListener("click", (event) => {
1602
+ if (!(event.target instanceof Node)) {
1603
+ return;
1604
+ }
1605
+ if (!event.target.closest(".conversation-item") && state.confirmDeleteId) {
1606
+ state.confirmDeleteId = null;
1607
+ renderConversationList();
1608
+ }
1609
+ });
1610
+
1611
+ window.addEventListener("resize", () => {
1612
+ setSidebarOpen(false);
1613
+ });
1614
+
1615
+ const navigateToConversation = async (conversationId) => {
1616
+ if (conversationId) {
1617
+ state.activeConversationId = conversationId;
1618
+ renderConversationList();
1619
+ try {
1620
+ await loadConversation(conversationId);
1621
+ } catch {
1622
+ // Conversation not found \u2013 fall back to empty state
1623
+ state.activeConversationId = null;
1624
+ state.activeMessages = [];
1625
+ replaceConversationUrl(null);
1626
+ elements.chatTitle.textContent = "";
1627
+ renderMessages([]);
1628
+ renderConversationList();
1629
+ }
1630
+ } else {
1631
+ state.activeConversationId = null;
1632
+ state.activeMessages = [];
1633
+ elements.chatTitle.textContent = "";
1634
+ renderMessages([]);
1635
+ renderConversationList();
1636
+ }
1637
+ };
1638
+
1639
+ window.addEventListener("popstate", async () => {
1640
+ if (state.isStreaming) return;
1641
+ const conversationId = getConversationIdFromUrl();
1642
+ await navigateToConversation(conversationId);
1643
+ });
1644
+
1645
+ (async () => {
1646
+ const authenticated = await requireAuth();
1647
+ if (!authenticated) {
1648
+ return;
1649
+ }
1650
+ await loadConversations();
1651
+ const urlConversationId = getConversationIdFromUrl();
1652
+ if (urlConversationId) {
1653
+ state.activeConversationId = urlConversationId;
1654
+ replaceConversationUrl(urlConversationId);
1655
+ renderConversationList();
1656
+ try {
1657
+ await loadConversation(urlConversationId);
1658
+ } catch {
1659
+ // URL pointed to a conversation that no longer exists
1660
+ state.activeConversationId = null;
1661
+ state.activeMessages = [];
1662
+ replaceConversationUrl(null);
1663
+ elements.chatTitle.textContent = "";
1664
+ renderMessages([]);
1665
+ renderConversationList();
1666
+ if (state.conversations.length === 0) {
1667
+ await createConversation();
1668
+ }
1669
+ }
1670
+ } else if (state.conversations.length === 0) {
1671
+ await createConversation();
1672
+ }
1673
+ autoResizePrompt();
1674
+ elements.prompt.focus();
1675
+ })();
1676
+
1677
+ if ("serviceWorker" in navigator) {
1678
+ navigator.serviceWorker.register("/sw.js").catch(() => {});
1679
+ }
1680
+
1681
+ // Detect iOS standalone mode and add class for CSS targeting
1682
+ if (window.navigator.standalone === true || window.matchMedia("(display-mode: standalone)").matches) {
1683
+ document.documentElement.classList.add("standalone");
1684
+ }
1685
+
1686
+ // iOS viewport and keyboard handling
1687
+ (function() {
1688
+ var shell = document.querySelector(".shell");
1689
+ var pinScroll = function() { if (window.scrollY !== 0) window.scrollTo(0, 0); };
1690
+
1691
+ // Track the "full" height when keyboard is not open
1692
+ var fullHeight = window.innerHeight;
1693
+
1694
+ // Resize shell when iOS keyboard opens/closes
1695
+ var resizeForKeyboard = function() {
1696
+ if (!shell || !window.visualViewport) return;
1697
+ var vvHeight = window.visualViewport.height;
1698
+
1699
+ // Update fullHeight if viewport grew (keyboard closed)
1700
+ if (vvHeight > fullHeight) {
1701
+ fullHeight = vvHeight;
1702
+ }
1703
+
1704
+ // Only apply height override if keyboard appears to be open
1705
+ // (viewport significantly smaller than full height)
1706
+ if (vvHeight < fullHeight - 100) {
1707
+ shell.style.height = vvHeight + "px";
1708
+ } else {
1709
+ // Keyboard closed - remove override, let CSS handle it
1710
+ shell.style.height = "";
1711
+ }
1712
+ pinScroll();
1713
+ };
1714
+
1715
+ if (window.visualViewport) {
1716
+ window.visualViewport.addEventListener("scroll", pinScroll);
1717
+ window.visualViewport.addEventListener("resize", resizeForKeyboard);
1718
+ }
1719
+ document.addEventListener("scroll", pinScroll);
1720
+
1721
+ // Draggable sidebar from left edge (mobile only)
1722
+ (function() {
1723
+ var sidebar = document.querySelector(".sidebar");
1724
+ var backdrop = document.querySelector(".sidebar-backdrop");
1725
+ var shell = document.querySelector(".shell");
1726
+ if (!sidebar || !backdrop || !shell) return;
1727
+
1728
+ var sidebarWidth = 260;
1729
+ var edgeThreshold = 50; // px from left edge to start drag
1730
+ var velocityThreshold = 0.3; // px/ms to trigger open/close
1731
+
1732
+ var dragging = false;
1733
+ var startX = 0;
1734
+ var startY = 0;
1735
+ var currentX = 0;
1736
+ var startTime = 0;
1737
+ var isOpen = false;
1738
+ var directionLocked = false;
1739
+ var isHorizontal = false;
1740
+
1741
+ function getProgress() {
1742
+ // Returns 0 (closed) to 1 (open)
1743
+ if (isOpen) {
1744
+ return Math.max(0, Math.min(1, 1 + currentX / sidebarWidth));
1745
+ } else {
1746
+ return Math.max(0, Math.min(1, currentX / sidebarWidth));
1747
+ }
1748
+ }
1749
+
1750
+ function updatePosition(progress) {
1751
+ var offset = (progress - 1) * sidebarWidth;
1752
+ sidebar.style.transform = "translateX(" + offset + "px)";
1753
+ backdrop.style.opacity = progress;
1754
+ if (progress > 0) {
1755
+ backdrop.style.pointerEvents = "auto";
1756
+ } else {
1757
+ backdrop.style.pointerEvents = "none";
1758
+ }
1759
+ }
1760
+
1761
+ function onTouchStart(e) {
1762
+ if (window.innerWidth > 768) return;
1763
+
1764
+ // Don't intercept touches on interactive elements
1765
+ var target = e.target;
1766
+ if (target.closest("button") || target.closest("a") || target.closest("input") || target.closest("textarea")) {
1767
+ return;
1768
+ }
1769
+
1770
+ var touch = e.touches[0];
1771
+ isOpen = shell.classList.contains("sidebar-open");
1772
+
1773
+ // When sidebar is closed: only respond to edge swipes
1774
+ // When sidebar is open: only respond to backdrop touches (not sidebar content)
1775
+ var fromEdge = touch.clientX < edgeThreshold;
1776
+ var onBackdrop = e.target === backdrop;
1777
+
1778
+ if (!isOpen && !fromEdge) return;
1779
+ if (isOpen && !onBackdrop) return;
1780
+
1781
+ // Prevent Safari back gesture when starting from edge
1782
+ if (fromEdge) {
1783
+ e.preventDefault();
1784
+ }
1785
+
1786
+ startX = touch.clientX;
1787
+ startY = touch.clientY;
1788
+ currentX = 0;
1789
+ startTime = Date.now();
1790
+ directionLocked = false;
1791
+ isHorizontal = false;
1792
+ dragging = true;
1793
+ sidebar.classList.add("dragging");
1794
+ backdrop.classList.add("dragging");
1795
+ }
1796
+
1797
+ function onTouchMove(e) {
1798
+ if (!dragging) return;
1799
+ var touch = e.touches[0];
1800
+ var dx = touch.clientX - startX;
1801
+ var dy = touch.clientY - startY;
1802
+
1803
+ // Lock direction after some movement
1804
+ if (!directionLocked && (Math.abs(dx) > 10 || Math.abs(dy) > 10)) {
1805
+ directionLocked = true;
1806
+ isHorizontal = Math.abs(dx) > Math.abs(dy);
1807
+ if (!isHorizontal) {
1808
+ // Vertical scroll, cancel drag
1809
+ dragging = false;
1810
+ sidebar.classList.remove("dragging");
1811
+ backdrop.classList.remove("dragging");
1812
+ return;
1813
+ }
1814
+ }
1815
+
1816
+ if (!directionLocked) return;
1817
+
1818
+ // Prevent scrolling while dragging sidebar
1819
+ e.preventDefault();
1820
+
1821
+ currentX = dx;
1822
+ updatePosition(getProgress());
1823
+ }
1824
+
1825
+ function onTouchEnd(e) {
1826
+ if (!dragging) return;
1827
+ dragging = false;
1828
+ sidebar.classList.remove("dragging");
1829
+ backdrop.classList.remove("dragging");
1830
+
1831
+ var touch = e.changedTouches[0];
1832
+ var dx = touch.clientX - startX;
1833
+ var dt = Date.now() - startTime;
1834
+ var velocity = dx / dt; // px/ms
1835
+
1836
+ var progress = getProgress();
1837
+ var shouldOpen;
1838
+
1839
+ // Use velocity if fast enough, otherwise use position threshold
1840
+ if (Math.abs(velocity) > velocityThreshold) {
1841
+ shouldOpen = velocity > 0;
1842
+ } else {
1843
+ shouldOpen = progress > 0.5;
1844
+ }
1845
+
1846
+ // Reset inline styles and let CSS handle the animation
1847
+ sidebar.style.transform = "";
1848
+ backdrop.style.opacity = "";
1849
+ backdrop.style.pointerEvents = "";
1850
+
1851
+ if (shouldOpen) {
1852
+ shell.classList.add("sidebar-open");
1853
+ } else {
1854
+ shell.classList.remove("sidebar-open");
1855
+ }
1856
+ }
1857
+
1858
+ document.addEventListener("touchstart", onTouchStart, { passive: false });
1859
+ document.addEventListener("touchmove", onTouchMove, { passive: false });
1860
+ document.addEventListener("touchend", onTouchEnd, { passive: true });
1861
+ document.addEventListener("touchcancel", onTouchEnd, { passive: true });
1862
+ })();
1863
+
1864
+ // Prevent Safari back/forward navigation by manipulating history
1865
+ // This doesn't stop the gesture animation but prevents actual navigation
1866
+ if (window.navigator.standalone || window.matchMedia("(display-mode: standalone)").matches) {
1867
+ history.pushState(null, "", location.href);
1868
+ window.addEventListener("popstate", function() {
1869
+ history.pushState(null, "", location.href);
1870
+ });
1871
+ }
1872
+
1873
+ // Right edge blocker - intercept touch events to prevent forward navigation
1874
+ var rightBlocker = document.querySelector(".edge-blocker-right");
1875
+ if (rightBlocker) {
1876
+ rightBlocker.addEventListener("touchstart", function(e) {
1877
+ e.preventDefault();
1878
+ }, { passive: false });
1879
+ rightBlocker.addEventListener("touchmove", function(e) {
1880
+ e.preventDefault();
1881
+ }, { passive: false });
1882
+ }
1883
+ })();
1884
+
1885
+ </script>
1886
+ </body>
1887
+ </html>`;
1888
+ };
1889
+
1890
+ // src/index.ts
1891
+ import { createInterface } from "readline/promises";
1892
+
1893
+ // src/init-onboarding.ts
1894
+ import { stdin, stdout } from "process";
1895
+ import { input, password, select } from "@inquirer/prompts";
1896
+ import {
1897
+ fieldsForScope
1898
+ } from "@poncho-ai/sdk";
1899
+ var C = {
1900
+ reset: "\x1B[0m",
1901
+ bold: "\x1B[1m",
1902
+ dim: "\x1B[2m",
1903
+ cyan: "\x1B[36m"
1904
+ };
1905
+ var dim = (s) => `${C.dim}${s}${C.reset}`;
1906
+ var bold = (s) => `${C.bold}${s}${C.reset}`;
1907
+ var INPUT_CARET = "\xBB";
1908
+ var shouldAskField = (field, answers) => {
1909
+ if (!field.dependsOn) {
1910
+ return true;
1911
+ }
1912
+ const value = answers[field.dependsOn.fieldId];
1913
+ if (typeof field.dependsOn.equals !== "undefined") {
1914
+ return value === field.dependsOn.equals;
1915
+ }
1916
+ if (field.dependsOn.oneOf) {
1917
+ return field.dependsOn.oneOf.includes(value);
1918
+ }
1919
+ return true;
1920
+ };
1921
+ var parsePromptValue = (field, answer) => {
1922
+ if (field.kind === "boolean") {
1923
+ const normalized = answer.trim().toLowerCase();
1924
+ if (normalized === "y" || normalized === "yes" || normalized === "true") {
1925
+ return true;
1926
+ }
1927
+ if (normalized === "n" || normalized === "no" || normalized === "false") {
1928
+ return false;
1929
+ }
1930
+ return Boolean(field.defaultValue);
1931
+ }
1932
+ if (field.kind === "number") {
1933
+ const parsed = Number.parseInt(answer.trim(), 10);
1934
+ if (Number.isFinite(parsed)) {
1935
+ return parsed;
1936
+ }
1937
+ return Number(field.defaultValue);
1938
+ }
1939
+ if (field.kind === "select") {
1940
+ const trimmed2 = answer.trim();
1941
+ if (field.options && field.options.some((option) => option.value === trimmed2)) {
1942
+ return trimmed2;
1943
+ }
1944
+ const asNumber = Number.parseInt(trimmed2, 10);
1945
+ if (Number.isFinite(asNumber) && field.options && asNumber >= 1 && asNumber <= field.options.length) {
1946
+ return field.options[asNumber - 1]?.value ?? String(field.defaultValue);
1947
+ }
1948
+ return String(field.defaultValue);
1949
+ }
1950
+ const trimmed = answer.trim();
1951
+ if (trimmed.length === 0) {
1952
+ return String(field.defaultValue);
1953
+ }
1954
+ return trimmed;
1955
+ };
1956
+ var askSecret = async (field) => {
1957
+ if (!stdin.isTTY) {
1958
+ return void 0;
1959
+ }
1960
+ const hint = field.placeholder ? dim(` (${field.placeholder})`) : "";
1961
+ const message = `${field.prompt}${hint}`;
1962
+ const value = await password(
1963
+ {
1964
+ message,
1965
+ // true invisible input while typing/pasting
1966
+ mask: false,
1967
+ theme: {
1968
+ prefix: {
1969
+ idle: dim(INPUT_CARET),
1970
+ done: dim("\u2713")
1971
+ },
1972
+ style: {
1973
+ help: () => ""
1974
+ }
1975
+ }
1976
+ },
1977
+ { input: stdin, output: stdout }
1978
+ );
1979
+ return value ?? "";
1980
+ };
1981
+ var askSelectWithArrowKeys = async (field) => {
1982
+ if (!field.options || field.options.length === 0) {
1983
+ return void 0;
1984
+ }
1985
+ if (!stdin.isTTY) {
1986
+ return void 0;
1987
+ }
1988
+ const selected = await select(
1989
+ {
1990
+ message: field.prompt,
1991
+ choices: field.options.map((option) => ({
1992
+ name: option.label,
1993
+ value: option.value
1994
+ })),
1995
+ default: String(field.defaultValue),
1996
+ theme: {
1997
+ prefix: {
1998
+ idle: dim(INPUT_CARET),
1999
+ done: dim("\u2713")
2000
+ }
2001
+ }
2002
+ },
2003
+ { input: stdin, output: stdout }
2004
+ );
2005
+ return selected;
2006
+ };
2007
+ var askBooleanWithArrowKeys = async (field) => {
2008
+ if (!stdin.isTTY) {
2009
+ return void 0;
2010
+ }
2011
+ const selected = await select(
2012
+ {
2013
+ message: field.prompt,
2014
+ choices: [
2015
+ { name: "Yes", value: "true" },
2016
+ { name: "No", value: "false" }
2017
+ ],
2018
+ default: field.defaultValue ? "true" : "false",
2019
+ theme: {
2020
+ prefix: {
2021
+ idle: dim(INPUT_CARET),
2022
+ done: dim("\u2713")
2023
+ }
2024
+ }
2025
+ },
2026
+ { input: stdin, output: stdout }
2027
+ );
2028
+ return selected;
2029
+ };
2030
+ var askTextInput = async (field) => {
2031
+ if (!stdin.isTTY) {
2032
+ return void 0;
2033
+ }
2034
+ const answer = await input(
2035
+ {
2036
+ message: field.prompt,
2037
+ default: String(field.defaultValue ?? ""),
2038
+ theme: {
2039
+ prefix: {
2040
+ idle: dim(INPUT_CARET),
2041
+ done: dim("\u2713")
2042
+ }
2043
+ }
2044
+ },
2045
+ { input: stdin, output: stdout }
2046
+ );
2047
+ return answer;
2048
+ };
2049
+ var buildDefaultAnswers = () => {
2050
+ const answers = {};
2051
+ for (const field of fieldsForScope("light")) {
2052
+ answers[field.id] = field.defaultValue;
2053
+ }
2054
+ return answers;
2055
+ };
2056
+ var askOnboardingQuestions = async (options) => {
2057
+ const answers = buildDefaultAnswers();
2058
+ const interactive = options.yes === true ? false : options.interactive ?? (stdin.isTTY === true && stdout.isTTY === true);
2059
+ if (!interactive) {
2060
+ return answers;
2061
+ }
2062
+ stdout.write("\n");
2063
+ stdout.write(` ${bold("Poncho")} ${dim("\xB7 quick setup")}
2064
+ `);
2065
+ stdout.write("\n");
2066
+ const fields = fieldsForScope("light");
2067
+ for (const field of fields) {
2068
+ if (!shouldAskField(field, answers)) {
2069
+ continue;
2070
+ }
2071
+ stdout.write("\n");
2072
+ let value;
2073
+ if (field.secret) {
2074
+ value = await askSecret(field);
2075
+ } else if (field.kind === "select") {
2076
+ value = await askSelectWithArrowKeys(field);
2077
+ } else if (field.kind === "boolean") {
2078
+ value = await askBooleanWithArrowKeys(field);
2079
+ } else {
2080
+ value = await askTextInput(field);
2081
+ }
2082
+ if (!value || value.trim().length === 0) {
2083
+ continue;
2084
+ }
2085
+ answers[field.id] = parsePromptValue(field, value);
2086
+ }
2087
+ return answers;
2088
+ };
2089
+ var getProviderModelName = (provider) => provider === "openai" ? "gpt-4.1" : "claude-opus-4-5";
2090
+ var maybeSet = (target, key, value) => {
2091
+ if (typeof value === "string" && value.trim().length === 0) {
2092
+ return;
2093
+ }
2094
+ if (typeof value === "undefined") {
2095
+ return;
2096
+ }
2097
+ target[key] = value;
2098
+ };
2099
+ var buildConfigFromOnboardingAnswers = (answers) => {
2100
+ const storageProvider = String(answers["storage.provider"] ?? "local");
2101
+ const memoryEnabled = Boolean(answers["storage.memory.enabled"] ?? true);
2102
+ const maxRecallConversations = Number(
2103
+ answers["storage.memory.maxRecallConversations"] ?? 20
2104
+ );
2105
+ const storage = {
2106
+ provider: storageProvider,
2107
+ memory: {
2108
+ enabled: memoryEnabled,
2109
+ maxRecallConversations
2110
+ }
2111
+ };
2112
+ maybeSet(storage, "url", answers["storage.url"]);
2113
+ maybeSet(storage, "token", answers["storage.token"]);
2114
+ maybeSet(storage, "table", answers["storage.table"]);
2115
+ maybeSet(storage, "region", answers["storage.region"]);
2116
+ const authRequired = Boolean(answers["auth.required"] ?? false);
2117
+ const authType = answers["auth.type"] ?? "bearer";
2118
+ const auth = {
2119
+ required: authRequired,
2120
+ type: authType
2121
+ };
2122
+ if (authType === "header") {
2123
+ maybeSet(auth, "headerName", answers["auth.headerName"]);
2124
+ }
2125
+ const telemetryEnabled = Boolean(answers["telemetry.enabled"] ?? true);
2126
+ const telemetry = {
2127
+ enabled: telemetryEnabled
2128
+ };
2129
+ maybeSet(telemetry, "otlp", answers["telemetry.otlp"]);
2130
+ return {
2131
+ mcp: [],
2132
+ auth,
2133
+ storage,
2134
+ telemetry
2135
+ };
2136
+ };
2137
+ var collectEnvVars = (answers) => {
2138
+ const envVars = /* @__PURE__ */ new Set();
2139
+ const provider = String(answers["model.provider"] ?? "anthropic");
2140
+ if (provider === "openai") {
2141
+ envVars.add("OPENAI_API_KEY=sk-...");
2142
+ } else {
2143
+ envVars.add("ANTHROPIC_API_KEY=sk-ant-...");
2144
+ }
2145
+ const storageProvider = String(answers["storage.provider"] ?? "local");
2146
+ if (storageProvider === "redis") {
2147
+ envVars.add("REDIS_URL=redis://localhost:6379");
2148
+ }
2149
+ if (storageProvider === "upstash") {
2150
+ envVars.add("UPSTASH_REDIS_REST_URL=https://...");
2151
+ envVars.add("UPSTASH_REDIS_REST_TOKEN=...");
2152
+ }
2153
+ if (storageProvider === "dynamodb") {
2154
+ envVars.add("PONCHO_DYNAMODB_TABLE=poncho-conversations");
2155
+ envVars.add("AWS_REGION=us-east-1");
2156
+ }
2157
+ const authRequired = Boolean(answers["auth.required"] ?? false);
2158
+ if (authRequired) {
2159
+ envVars.add("PONCHO_AUTH_TOKEN=...");
2160
+ }
2161
+ return Array.from(envVars);
2162
+ };
2163
+ var collectEnvFileLines = (answers) => {
2164
+ const lines = [
2165
+ "# Poncho environment configuration",
2166
+ "# Fill in empty values before running `poncho dev` or `poncho run --interactive`.",
2167
+ "# Tip: keep secrets in `.env` only (never commit them).",
2168
+ ""
2169
+ ];
2170
+ const modelProvider = String(answers["model.provider"] ?? "anthropic");
2171
+ const modelEnvKey = modelProvider === "openai" ? "env.OPENAI_API_KEY" : "env.ANTHROPIC_API_KEY";
2172
+ const modelEnvVar = modelProvider === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY";
2173
+ const modelEnvValue = String(answers[modelEnvKey] ?? "");
2174
+ lines.push("# Model");
2175
+ if (modelEnvValue.length === 0) {
2176
+ lines.push(
2177
+ 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"
2178
+ );
2179
+ }
2180
+ lines.push(`${modelEnvVar}=${modelEnvValue}`);
2181
+ lines.push("");
2182
+ const authRequired = Boolean(answers["auth.required"] ?? false);
2183
+ const authType = answers["auth.type"] ?? "bearer";
2184
+ const authHeaderName = String(answers["auth.headerName"] ?? "x-poncho-key");
2185
+ if (authRequired) {
2186
+ lines.push("# Auth (API request authentication)");
2187
+ if (authType === "bearer") {
2188
+ lines.push("# Requests should include: Authorization: Bearer <token>");
2189
+ } else if (authType === "header") {
2190
+ lines.push(`# Requests should include: ${authHeaderName}: <token>`);
2191
+ } else {
2192
+ lines.push("# Custom auth mode: read this token in your auth.validate function.");
2193
+ }
2194
+ lines.push("PONCHO_AUTH_TOKEN=");
2195
+ lines.push("");
2196
+ }
2197
+ const storageProvider = String(answers["storage.provider"] ?? "local");
2198
+ if (storageProvider === "redis") {
2199
+ lines.push("# Storage (Redis)");
2200
+ lines.push("# Run local Redis: docker run -p 6379:6379 redis:7");
2201
+ lines.push("# Or use a managed Redis URL from your cloud provider.");
2202
+ lines.push("REDIS_URL=");
2203
+ lines.push("");
2204
+ } else if (storageProvider === "upstash") {
2205
+ lines.push("# Storage (Upstash)");
2206
+ lines.push("# Create a Redis database at https://console.upstash.com/");
2207
+ lines.push("# Copy REST URL + REST TOKEN from the Upstash dashboard.");
2208
+ lines.push("UPSTASH_REDIS_REST_URL=");
2209
+ lines.push("UPSTASH_REDIS_REST_TOKEN=");
2210
+ lines.push("");
2211
+ } else if (storageProvider === "dynamodb") {
2212
+ lines.push("# Storage (DynamoDB)");
2213
+ lines.push("# Create a DynamoDB table for Poncho conversation/state storage.");
2214
+ lines.push("# Ensure AWS credentials are configured (AWS_PROFILE or access keys).");
2215
+ lines.push("PONCHO_DYNAMODB_TABLE=");
2216
+ lines.push("AWS_REGION=");
2217
+ lines.push("");
2218
+ } else if (storageProvider === "local" || storageProvider === "memory") {
2219
+ lines.push(
2220
+ storageProvider === "local" ? "# Storage (Local file): no extra env vars required." : "# Storage (In-memory): no extra env vars required, data resets on restart."
2221
+ );
2222
+ lines.push("");
2223
+ }
2224
+ const telemetryEnabled = Boolean(answers["telemetry.enabled"] ?? true);
2225
+ if (telemetryEnabled) {
2226
+ lines.push("# Telemetry (optional)");
2227
+ lines.push("# Latitude telemetry setup: https://docs.latitude.so/");
2228
+ lines.push("# If not using Latitude yet, you can leave these empty.");
2229
+ lines.push("LATITUDE_API_KEY=");
2230
+ lines.push("LATITUDE_PROJECT_ID=");
2231
+ lines.push("LATITUDE_PATH=");
2232
+ lines.push("");
2233
+ }
2234
+ while (lines.length > 0 && lines[lines.length - 1] === "") {
2235
+ lines.pop();
2236
+ }
2237
+ return lines;
2238
+ };
2239
+ var runInitOnboarding = async (options) => {
2240
+ const answers = await askOnboardingQuestions(options);
2241
+ const provider = String(answers["model.provider"] ?? "anthropic");
2242
+ const config = buildConfigFromOnboardingAnswers(answers);
2243
+ const envExampleLines = collectEnvVars(answers);
2244
+ const envFileLines = collectEnvFileLines(answers);
2245
+ const envNeedsUserInput = envFileLines.some(
2246
+ (line) => line.includes("=") && !line.startsWith("#") && line.endsWith("=")
2247
+ );
2248
+ return {
2249
+ answers,
2250
+ config,
2251
+ envExample: `${envExampleLines.join("\n")}
2252
+ `,
2253
+ envFile: envFileLines.length > 0 ? `${envFileLines.join("\n")}
2254
+ ` : "",
2255
+ envNeedsUserInput,
2256
+ agentModel: {
2257
+ provider: provider === "openai" ? "openai" : "anthropic",
2258
+ name: getProviderModelName(provider)
2259
+ }
2260
+ };
2261
+ };
2262
+
2263
+ // src/init-feature-context.ts
2264
+ import { createHash as createHash2 } from "crypto";
2265
+ import { access, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
2266
+ import { basename as basename2, dirname as dirname2, resolve as resolve2 } from "path";
2267
+ import { homedir as homedir2 } from "os";
2268
+ var ONBOARDING_VERSION = 1;
2269
+ var getStateDirectory = () => {
2270
+ const cwd = process.cwd();
2271
+ const home = homedir2();
2272
+ const isServerless = process.env.VERCEL === "1" || process.env.VERCEL_ENV !== void 0 || process.env.VERCEL_URL !== void 0 || process.env.AWS_LAMBDA_FUNCTION_NAME !== void 0 || process.env.AWS_EXECUTION_ENV?.includes("AWS_Lambda") === true || process.env.LAMBDA_TASK_ROOT !== void 0 || process.env.NOW_REGION !== void 0 || cwd.startsWith("/var/task") || home.startsWith("/var/task") || process.env.SERVERLESS === "1";
2273
+ if (isServerless) {
2274
+ return "/tmp/.poncho/state";
2275
+ }
2276
+ return resolve2(homedir2(), ".poncho", "state");
2277
+ };
2278
+ var summarizeConfig = (config) => {
2279
+ const provider = config?.storage?.provider ?? config?.state?.provider ?? "local";
2280
+ const memoryEnabled = config?.storage?.memory?.enabled ?? config?.memory?.enabled ?? false;
2281
+ const authRequired = config?.auth?.required ?? false;
2282
+ const telemetryEnabled = config?.telemetry?.enabled ?? true;
2283
+ return [
2284
+ `storage: ${provider}`,
2285
+ `memory tools: ${memoryEnabled ? "enabled" : "disabled"}`,
2286
+ `auth: ${authRequired ? "required" : "not required"}`,
2287
+ `telemetry: ${telemetryEnabled ? "enabled" : "disabled"}`
2288
+ ];
2289
+ };
2290
+ var getOnboardingMarkerPath = (workingDir) => resolve2(
2291
+ getStateDirectory(),
2292
+ `${basename2(workingDir).replace(/[^a-zA-Z0-9_-]+/g, "-") || "project"}-${createHash2("sha256").update(workingDir).digest("hex").slice(0, 12)}-onboarding.json`
2293
+ );
2294
+ var readMarker = async (workingDir) => {
2295
+ const markerPath = getOnboardingMarkerPath(workingDir);
2296
+ try {
2297
+ await access(markerPath);
2298
+ } catch {
2299
+ return void 0;
2300
+ }
2301
+ try {
2302
+ const raw = await readFile2(markerPath, "utf8");
2303
+ return JSON.parse(raw);
2304
+ } catch {
2305
+ return void 0;
2306
+ }
2307
+ };
2308
+ var writeMarker = async (workingDir, state) => {
2309
+ const markerPath = getOnboardingMarkerPath(workingDir);
2310
+ await mkdir2(dirname2(markerPath), { recursive: true });
2311
+ await writeFile2(markerPath, JSON.stringify(state, null, 2), "utf8");
2312
+ };
2313
+ var initializeOnboardingMarker = async (workingDir, options) => {
2314
+ const current = await readMarker(workingDir);
2315
+ if (current) {
2316
+ return;
2317
+ }
2318
+ const allowIntro = options?.allowIntro ?? true;
2319
+ await writeMarker(workingDir, {
2320
+ introduced: allowIntro ? false : true,
2321
+ allowIntro,
2322
+ onboardingVersion: ONBOARDING_VERSION,
2323
+ createdAt: Date.now()
2324
+ });
2325
+ };
2326
+ var consumeFirstRunIntro = async (workingDir, input2) => {
2327
+ const runtimeEnv = resolveHarnessEnvironment();
2328
+ if (runtimeEnv === "production") {
2329
+ return void 0;
2330
+ }
2331
+ const marker = await readMarker(workingDir);
2332
+ if (marker?.allowIntro === false) {
2333
+ return void 0;
2334
+ }
2335
+ const shouldShow = !marker || marker.introduced === false;
2336
+ if (!shouldShow) {
2337
+ return void 0;
2338
+ }
2339
+ await writeMarker(workingDir, {
2340
+ introduced: true,
2341
+ allowIntro: true,
2342
+ onboardingVersion: ONBOARDING_VERSION,
2343
+ createdAt: marker?.createdAt ?? Date.now(),
2344
+ introducedAt: Date.now()
2345
+ });
2346
+ const summary = summarizeConfig(input2.config);
2347
+ return [
2348
+ `Hi! I'm **${input2.agentName}**. I can configure myself directly by chat.
2349
+ `,
2350
+ `**Current config**`,
2351
+ ` Model: ${input2.provider}/${input2.model}`,
2352
+ ` \`\`\`${summary.join(" \xB7 ")}\`\`\``,
2353
+ "",
2354
+ "Feel free to ask me anything when you're ready. I can help you:",
2355
+ "",
2356
+ "- **Build skills**: Create custom tools and capabilities for this agent",
2357
+ "- **Configure the model**: Switch providers (OpenAI, Anthropic, etc.) or models",
2358
+ "- **Set up storage**: Use local files, Upstash, or other backends",
2359
+ "- **Enable auth**: Add bearer tokens or custom authentication",
2360
+ "- **Turn on telemetry**: Track usage with OpenTelemetry/OTLP",
2361
+ "- **Add MCP servers**: Connect external tool servers",
2362
+ "",
2363
+ "Just let me know what you'd like to work on!\n"
2364
+ ].join("\n");
2365
+ };
2366
+
2367
+ // src/index.ts
2368
+ var __dirname = dirname3(fileURLToPath(import.meta.url));
2369
+ var require2 = createRequire(import.meta.url);
2370
+ var writeJson = (response, statusCode, payload) => {
2371
+ response.writeHead(statusCode, { "Content-Type": "application/json" });
2372
+ response.end(JSON.stringify(payload));
2373
+ };
2374
+ var writeHtml = (response, statusCode, payload) => {
2375
+ response.writeHead(statusCode, { "Content-Type": "text/html; charset=utf-8" });
2376
+ response.end(payload);
2377
+ };
2378
+ var readRequestBody = async (request) => {
2379
+ const chunks = [];
2380
+ for await (const chunk of request) {
2381
+ chunks.push(Buffer.from(chunk));
2382
+ }
2383
+ const body = Buffer.concat(chunks).toString("utf8");
2384
+ return body.length > 0 ? JSON.parse(body) : {};
2385
+ };
2386
+ var resolveHarnessEnvironment = () => {
2387
+ if (process.env.PONCHO_ENV) {
2388
+ const value = process.env.PONCHO_ENV.toLowerCase();
2389
+ if (value === "production" || value === "staging") {
2390
+ return value;
2391
+ }
2392
+ return "development";
2393
+ }
2394
+ if (process.env.VERCEL_ENV) {
2395
+ const vercelEnv = process.env.VERCEL_ENV.toLowerCase();
2396
+ if (vercelEnv === "production") return "production";
2397
+ if (vercelEnv === "preview") return "staging";
2398
+ return "development";
2399
+ }
2400
+ if (process.env.RAILWAY_ENVIRONMENT) {
2401
+ const railwayEnv = process.env.RAILWAY_ENVIRONMENT.toLowerCase();
2402
+ if (railwayEnv === "production") return "production";
2403
+ return "staging";
2404
+ }
2405
+ if (process.env.RENDER) {
2406
+ if (process.env.IS_PULL_REQUEST === "true") return "staging";
2407
+ return "production";
2408
+ }
2409
+ if (process.env.AWS_EXECUTION_ENV || process.env.AWS_LAMBDA_FUNCTION_NAME) {
2410
+ return "production";
2411
+ }
2412
+ if (process.env.FLY_APP_NAME) {
2413
+ return "production";
2414
+ }
2415
+ if (process.env.NODE_ENV) {
2416
+ const value = process.env.NODE_ENV.toLowerCase();
2417
+ if (value === "production" || value === "staging") {
2418
+ return value;
2419
+ }
2420
+ return "development";
2421
+ }
2422
+ return "development";
2423
+ };
2424
+ var listenOnAvailablePort = async (server, preferredPort) => await new Promise((resolveListen, rejectListen) => {
2425
+ let currentPort = preferredPort;
2426
+ const tryListen = () => {
2427
+ const onListening = () => {
2428
+ server.off("error", onError);
2429
+ const address = server.address();
2430
+ if (address && typeof address === "object" && typeof address.port === "number") {
2431
+ resolveListen(address.port);
2432
+ return;
2433
+ }
2434
+ resolveListen(currentPort);
2435
+ };
2436
+ const onError = (error) => {
2437
+ server.off("listening", onListening);
2438
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EADDRINUSE") {
2439
+ currentPort += 1;
2440
+ if (currentPort > 65535) {
2441
+ rejectListen(
2442
+ new Error(
2443
+ "No available ports found from the requested port up to 65535."
2444
+ )
2445
+ );
2446
+ return;
2447
+ }
2448
+ setImmediate(tryListen);
2449
+ return;
2450
+ }
2451
+ rejectListen(error);
2452
+ };
2453
+ server.once("listening", onListening);
2454
+ server.once("error", onError);
2455
+ server.listen(currentPort);
2456
+ };
2457
+ tryListen();
2458
+ });
2459
+ var parseParams = (values) => {
2460
+ const params = {};
2461
+ for (const value of values) {
2462
+ const [key, ...rest] = value.split("=");
2463
+ if (!key) {
2464
+ continue;
2465
+ }
2466
+ params[key] = rest.join("=");
2467
+ }
2468
+ return params;
2469
+ };
2470
+ var AGENT_TEMPLATE = (name, options) => `---
2471
+ name: ${name}
2472
+ description: A helpful Poncho assistant
2473
+ model:
2474
+ provider: ${options.modelProvider}
2475
+ name: ${options.modelName}
2476
+ temperature: 0.2
2477
+ limits:
2478
+ maxSteps: 50
2479
+ timeout: 300
2480
+ ---
2481
+
2482
+ # {{name}}
2483
+
2484
+ You are **{{name}}**, a helpful assistant built with Poncho.
2485
+
2486
+ Working directory: {{runtime.workingDir}}
2487
+ Environment: {{runtime.environment}}
2488
+
2489
+ ## Task Guidance
2490
+
2491
+ - Use tools when needed
2492
+ - Explain your reasoning clearly
2493
+ - Ask clarifying questions when requirements are ambiguous
2494
+ - Never claim a file/tool change unless the corresponding tool call actually succeeded
2495
+ `;
2496
+ var resolveLocalPackagesRoot = () => {
2497
+ const candidate = resolve3(__dirname, "..", "..", "harness", "package.json");
2498
+ if (existsSync(candidate)) {
2499
+ return resolve3(__dirname, "..", "..");
2500
+ }
2501
+ return null;
2502
+ };
2503
+ var resolveCoreDeps = (projectDir) => {
2504
+ const packagesRoot = resolveLocalPackagesRoot();
2505
+ if (packagesRoot) {
2506
+ const harnessAbs = resolve3(packagesRoot, "harness");
2507
+ const sdkAbs = resolve3(packagesRoot, "sdk");
2508
+ return {
2509
+ harness: `link:${relative(projectDir, harnessAbs)}`,
2510
+ sdk: `link:${relative(projectDir, sdkAbs)}`
2511
+ };
2512
+ }
2513
+ return { harness: "^0.1.0", sdk: "^0.1.0" };
2514
+ };
2515
+ var PACKAGE_TEMPLATE = (name, projectDir) => {
2516
+ const deps = resolveCoreDeps(projectDir);
2517
+ return JSON.stringify(
2518
+ {
2519
+ name,
2520
+ private: true,
2521
+ type: "module",
2522
+ dependencies: {
2523
+ "@poncho-ai/harness": deps.harness,
2524
+ "@poncho-ai/sdk": deps.sdk
2525
+ }
2526
+ },
2527
+ null,
2528
+ 2
2529
+ );
2530
+ };
2531
+ var README_TEMPLATE = (name) => `# ${name}
2532
+
2533
+ An AI agent built with [Poncho](https://github.com/cesr/poncho-ai).
2534
+
2535
+ ## Prerequisites
2536
+
2537
+ - Node.js 20+
2538
+ - npm (or pnpm/yarn)
2539
+ - Anthropic or OpenAI API key
2540
+
2541
+ ## Quick Start
2542
+
2543
+ \`\`\`bash
2544
+ npm install
2545
+ # If you didn't enter an API key during init:
2546
+ cp .env.example .env
2547
+ # Then edit .env and add your API key
2548
+ poncho dev
2549
+ \`\`\`
2550
+
2551
+ Open \`http://localhost:3000\` for the web UI.
2552
+
2553
+ On your first interactive session, the agent introduces its configurable capabilities.
2554
+
2555
+ ## Common Commands
2556
+
2557
+ \`\`\`bash
2558
+ # Local web UI + API server
2559
+ poncho dev
2560
+
2561
+ # Local interactive CLI
2562
+ poncho run --interactive
2563
+
2564
+ # One-off run
2565
+ poncho run "Your task here"
2566
+
2567
+ # Run tests
2568
+ poncho test
2569
+
2570
+ # List available tools
2571
+ poncho tools
2572
+ \`\`\`
2573
+
2574
+ ## Add Skills
2575
+
2576
+ Install skills from a local path or remote repository, then verify discovery:
2577
+
2578
+ \`\`\`bash
2579
+ # Install skills into ./skills
2580
+ poncho add <repo-or-path>
2581
+
2582
+ # Verify loaded tools
2583
+ poncho tools
2584
+ \`\`\`
2585
+
2586
+ After adding skills, run \`poncho dev\` or \`poncho run --interactive\` and ask the agent to use them.
2587
+
2588
+ ## Configure MCP Servers (Remote)
2589
+
2590
+ Connect remote MCP servers and expose their tools to the agent:
2591
+
2592
+ \`\`\`bash
2593
+ # Add remote MCP server
2594
+ poncho mcp add --url https://mcp.example.com/github --name github --auth-bearer-env GITHUB_TOKEN
2595
+
2596
+ # List configured servers
2597
+ poncho mcp list
2598
+
2599
+ # Discover and select MCP tools into config allowlist
2600
+ poncho mcp tools list github
2601
+ poncho mcp tools select github
2602
+
2603
+ # Remove a server
2604
+ poncho mcp remove github
2605
+ \`\`\`
2606
+
2607
+ Set required secrets in \`.env\` (for example, \`GITHUB_TOKEN=...\`).
2608
+
2609
+ ## Tool Intent in Frontmatter
2610
+
2611
+ Declare tool intent directly in \`AGENT.md\` and \`SKILL.md\` frontmatter:
2612
+
2613
+ \`\`\`yaml
2614
+ tools:
2615
+ mcp:
2616
+ - github/list_issues
2617
+ - github/*
2618
+ scripts:
2619
+ - starter/scripts/*
2620
+ \`\`\`
2621
+
2622
+ How it works:
2623
+
2624
+ - \`AGENT.md\` provides fallback MCP intent when no skill is active.
2625
+ - \`SKILL.md\` intent applies when you activate that skill (\`activate_skill\`).
2626
+ - Skill scripts are accessible by default from each skill's \`scripts/\` directory.
2627
+ - \`AGENT.md\` \`tools.scripts\` can still be used to narrow script access when active skills do not set script intent.
2628
+ - Active skills are unioned, then filtered by policy in \`poncho.config.js\`.
2629
+ - Deactivating a skill (\`deactivate_skill\`) removes its MCP tools from runtime registration.
2630
+
2631
+ Pattern format is strict slash-only:
2632
+
2633
+ - MCP: \`server/tool\`, \`server/*\`
2634
+ - Scripts: \`skill/scripts/file.ts\`, \`skill/scripts/*\`
2635
+
2636
+ ## Configuration
2637
+
2638
+ Core files:
2639
+
2640
+ - \`AGENT.md\`: behavior, model selection, runtime guidance
2641
+ - \`poncho.config.js\`: runtime config (storage, auth, telemetry, MCP, tools)
2642
+ - \`.env\`: secrets and environment variables
2643
+
2644
+ Example \`poncho.config.js\`:
2645
+
2646
+ \`\`\`javascript
2647
+ export default {
2648
+ storage: {
2649
+ provider: "local", // local | memory | redis | upstash | dynamodb
2650
+ memory: {
2651
+ enabled: true,
2652
+ maxRecallConversations: 20,
2653
+ },
2654
+ },
2655
+ auth: {
2656
+ required: false,
2657
+ },
2658
+ telemetry: {
2659
+ enabled: true,
2660
+ },
2661
+ mcp: [
2662
+ {
2663
+ name: "github",
2664
+ url: "https://mcp.example.com/github",
2665
+ auth: { type: "bearer", tokenEnv: "GITHUB_TOKEN" },
2666
+ tools: {
2667
+ mode: "allowlist",
2668
+ include: ["github/list_issues", "github/get_issue"],
2669
+ },
2670
+ },
2671
+ ],
2672
+ scripts: {
2673
+ mode: "allowlist",
2674
+ include: ["starter/scripts/*"],
2675
+ },
2676
+ tools: {
2677
+ defaults: {
2678
+ list_directory: true,
2679
+ read_file: true,
2680
+ write_file: true, // still gated by environment/policy
2681
+ },
2682
+ byEnvironment: {
2683
+ production: {
2684
+ read_file: false, // example override
2685
+ },
2686
+ },
2687
+ },
2688
+ };
2689
+ \`\`\`
2690
+
2691
+ ## Project Structure
2692
+
2693
+ \`\`\`
2694
+ ${name}/
2695
+ \u251C\u2500\u2500 AGENT.md # Agent definition and system prompt
2696
+ \u251C\u2500\u2500 poncho.config.js # Configuration (MCP servers, auth, etc.)
2697
+ \u251C\u2500\u2500 package.json # Dependencies
2698
+ \u251C\u2500\u2500 .env.example # Environment variables template
2699
+ \u251C\u2500\u2500 tests/
2700
+ \u2502 \u2514\u2500\u2500 basic.yaml # Test suite
2701
+ \u2514\u2500\u2500 skills/
2702
+ \u2514\u2500\u2500 starter/
2703
+ \u251C\u2500\u2500 SKILL.md
2704
+ \u2514\u2500\u2500 scripts/
2705
+ \u2514\u2500\u2500 starter-echo.ts
2706
+ \`\`\`
2707
+
2708
+ ## Deployment
2709
+
2710
+ \`\`\`bash
2711
+ # Build for Vercel
2712
+ poncho build vercel
2713
+ cd .poncho-build/vercel && vercel deploy --prod
2714
+
2715
+ # Build for Docker
2716
+ poncho build docker
2717
+ docker build -t ${name} .
2718
+ \`\`\`
2719
+
2720
+ For full reference:
2721
+ https://github.com/cesr/poncho-ai
2722
+ `;
2723
+ var ENV_TEMPLATE = "ANTHROPIC_API_KEY=sk-ant-...\n";
2724
+ var GITIGNORE_TEMPLATE = ".env\nnode_modules\ndist\n.poncho-build\n.poncho/\ninteractive-session.json\n";
2725
+ var VERCEL_RUNTIME_DEPENDENCIES = {
2726
+ "@anthropic-ai/sdk": "^0.74.0",
2727
+ "@aws-sdk/client-dynamodb": "^3.988.0",
2728
+ "@latitude-data/telemetry": "^2.0.2",
2729
+ commander: "^12.0.0",
2730
+ dotenv: "^16.4.0",
2731
+ jiti: "^2.6.1",
2732
+ mustache: "^4.2.0",
2733
+ openai: "^6.3.0",
2734
+ redis: "^5.10.0",
2735
+ yaml: "^2.8.1"
2736
+ };
2737
+ var TEST_TEMPLATE = `tests:
2738
+ - name: "Basic sanity"
2739
+ task: "What is 2 + 2?"
2740
+ expect:
2741
+ contains: "4"
2742
+ `;
2743
+ var SKILL_TEMPLATE = `---
2744
+ name: starter-skill
2745
+ description: Starter local skill template
2746
+ ---
2747
+
2748
+ # Starter Skill
2749
+
2750
+ This is a starter local skill created by \`poncho init\`.
2751
+
2752
+ ## Authoring Notes
2753
+
2754
+ - Put executable JavaScript/TypeScript files in \`scripts/\`.
2755
+ - Ask the agent to call \`run_skill_script\` with \`skill\`, \`script\`, and optional \`input\`.
2756
+ `;
2757
+ var SKILL_TOOL_TEMPLATE = `export default async function run(input) {
2758
+ const message = typeof input?.message === "string" ? input.message : "";
2759
+ return { echoed: message };
2760
+ }
2761
+ `;
2762
+ var ensureFile = async (path, content) => {
2763
+ await mkdir3(dirname3(path), { recursive: true });
2764
+ await writeFile3(path, content, { encoding: "utf8", flag: "wx" });
2765
+ };
2766
+ var copyIfExists = async (sourcePath, destinationPath) => {
2767
+ try {
2768
+ await access2(sourcePath);
2769
+ } catch {
2770
+ return;
2771
+ }
2772
+ await mkdir3(dirname3(destinationPath), { recursive: true });
2773
+ await cp(sourcePath, destinationPath, { recursive: true });
2774
+ };
2775
+ var resolveCliEntrypoint = async () => {
2776
+ const sourceEntrypoint = resolve3(packageRoot, "src", "index.ts");
2777
+ try {
2778
+ await access2(sourceEntrypoint);
2779
+ return sourceEntrypoint;
2780
+ } catch {
2781
+ return resolve3(packageRoot, "dist", "index.js");
2782
+ }
2783
+ };
2784
+ var buildVercelHandlerBundle = async (outDir) => {
2785
+ const { build: esbuild } = await import("esbuild");
2786
+ const cliEntrypoint = await resolveCliEntrypoint();
2787
+ const tempEntry = resolve3(outDir, "api", "_entry.js");
2788
+ await writeFile3(
2789
+ tempEntry,
2790
+ `import { createRequestHandler } from ${JSON.stringify(cliEntrypoint)};
2791
+ let handlerPromise;
2792
+ export default async function handler(req, res) {
2793
+ try {
2794
+ if (!handlerPromise) {
2795
+ handlerPromise = createRequestHandler({ workingDir: process.cwd() });
2796
+ }
2797
+ const requestHandler = await handlerPromise;
2798
+ await requestHandler(req, res);
2799
+ } catch (error) {
2800
+ console.error("Handler error:", error);
2801
+ if (!res.headersSent) {
2802
+ res.writeHead(500, { "Content-Type": "application/json" });
2803
+ res.end(JSON.stringify({ error: "Internal server error", message: error?.message || "Unknown error" }));
2804
+ }
2805
+ }
2806
+ }
2807
+ `,
2808
+ "utf8"
2809
+ );
2810
+ await esbuild({
2811
+ entryPoints: [tempEntry],
2812
+ bundle: true,
2813
+ platform: "node",
2814
+ format: "esm",
2815
+ target: "node20",
2816
+ outfile: resolve3(outDir, "api", "index.js"),
2817
+ sourcemap: false,
2818
+ legalComments: "none",
2819
+ external: [
2820
+ ...Object.keys(VERCEL_RUNTIME_DEPENDENCIES),
2821
+ "@anthropic-ai/sdk/*",
2822
+ "child_process",
2823
+ "fs",
2824
+ "fs/promises",
2825
+ "http",
2826
+ "https",
2827
+ "path",
2828
+ "module",
2829
+ "url",
2830
+ "readline",
2831
+ "readline/promises",
2832
+ "crypto",
2833
+ "stream",
2834
+ "events",
2835
+ "util",
2836
+ "os",
2837
+ "zlib",
2838
+ "net",
2839
+ "tls",
2840
+ "dns",
2841
+ "assert",
2842
+ "buffer",
2843
+ "timers",
2844
+ "timers/promises",
2845
+ "node:child_process",
2846
+ "node:fs",
2847
+ "node:fs/promises",
2848
+ "node:http",
2849
+ "node:https",
2850
+ "node:path",
2851
+ "node:module",
2852
+ "node:url",
2853
+ "node:readline",
2854
+ "node:readline/promises",
2855
+ "node:crypto",
2856
+ "node:stream",
2857
+ "node:events",
2858
+ "node:util",
2859
+ "node:os",
2860
+ "node:zlib",
2861
+ "node:net",
2862
+ "node:tls",
2863
+ "node:dns",
2864
+ "node:assert",
2865
+ "node:buffer",
2866
+ "node:timers",
2867
+ "node:timers/promises"
2868
+ ]
2869
+ });
2870
+ };
2871
+ var renderConfigFile = (config) => `export default ${JSON.stringify(config, null, 2)}
2872
+ `;
2873
+ var writeConfigFile = async (workingDir, config) => {
2874
+ const serialized = renderConfigFile(config);
2875
+ await writeFile3(resolve3(workingDir, "poncho.config.js"), serialized, "utf8");
2876
+ };
2877
+ var ensureEnvPlaceholder = async (filePath, key) => {
2878
+ const normalizedKey = key.trim();
2879
+ if (!normalizedKey) {
2880
+ return false;
2881
+ }
2882
+ let content = "";
2883
+ try {
2884
+ content = await readFile3(filePath, "utf8");
2885
+ } catch {
2886
+ await writeFile3(filePath, `${normalizedKey}=
2887
+ `, "utf8");
2888
+ return true;
2889
+ }
2890
+ const present = content.split(/\r?\n/).some((line) => line.trimStart().startsWith(`${normalizedKey}=`));
2891
+ if (present) {
2892
+ return false;
2893
+ }
2894
+ const withTrailingNewline = content.length === 0 || content.endsWith("\n") ? content : `${content}
2895
+ `;
2896
+ await writeFile3(filePath, `${withTrailingNewline}${normalizedKey}=
2897
+ `, "utf8");
2898
+ return true;
2899
+ };
2900
+ var removeEnvPlaceholder = async (filePath, key) => {
2901
+ const normalizedKey = key.trim();
2902
+ if (!normalizedKey) {
2903
+ return false;
2904
+ }
2905
+ let content = "";
2906
+ try {
2907
+ content = await readFile3(filePath, "utf8");
2908
+ } catch {
2909
+ return false;
2910
+ }
2911
+ const lines = content.split(/\r?\n/);
2912
+ const filtered = lines.filter((line) => !line.trimStart().startsWith(`${normalizedKey}=`));
2913
+ if (filtered.length === lines.length) {
2914
+ return false;
2915
+ }
2916
+ const nextContent = filtered.join("\n").replace(/\n+$/, "");
2917
+ await writeFile3(filePath, nextContent.length > 0 ? `${nextContent}
2918
+ ` : "", "utf8");
2919
+ return true;
2920
+ };
2921
+ var gitInit = (cwd) => new Promise((resolve4) => {
2922
+ const child = spawn("git", ["init"], { cwd, stdio: "ignore" });
2923
+ child.on("error", () => resolve4(false));
2924
+ child.on("close", (code) => resolve4(code === 0));
2925
+ });
2926
+ var initProject = async (projectName, options) => {
2927
+ const baseDir = options?.workingDir ?? process.cwd();
2928
+ const projectDir = resolve3(baseDir, projectName);
2929
+ await mkdir3(projectDir, { recursive: true });
2930
+ const onboardingOptions = options?.onboarding ?? {
2931
+ yes: true,
2932
+ interactive: false
2933
+ };
2934
+ const onboarding = await runInitOnboarding(onboardingOptions);
2935
+ const G = "\x1B[32m";
2936
+ const D = "\x1B[2m";
2937
+ const B = "\x1B[1m";
2938
+ const CY = "\x1B[36m";
2939
+ const YW = "\x1B[33m";
2940
+ const R = "\x1B[0m";
2941
+ process.stdout.write("\n");
2942
+ const scaffoldFiles = [
2943
+ { path: "AGENT.md", content: AGENT_TEMPLATE(projectName, { modelProvider: onboarding.agentModel.provider, modelName: onboarding.agentModel.name }) },
2944
+ { path: "poncho.config.js", content: renderConfigFile(onboarding.config) },
2945
+ { path: "package.json", content: PACKAGE_TEMPLATE(projectName, projectDir) },
2946
+ { path: "README.md", content: README_TEMPLATE(projectName) },
2947
+ { path: ".env.example", content: options?.envExampleOverride ?? onboarding.envExample ?? ENV_TEMPLATE },
2948
+ { path: ".gitignore", content: GITIGNORE_TEMPLATE },
2949
+ { path: "tests/basic.yaml", content: TEST_TEMPLATE },
2950
+ { path: "skills/starter/SKILL.md", content: SKILL_TEMPLATE },
2951
+ { path: "skills/starter/scripts/starter-echo.ts", content: SKILL_TOOL_TEMPLATE }
2952
+ ];
2953
+ if (onboarding.envFile) {
2954
+ scaffoldFiles.push({ path: ".env", content: onboarding.envFile });
2955
+ }
2956
+ for (const file of scaffoldFiles) {
2957
+ await ensureFile(resolve3(projectDir, file.path), file.content);
2958
+ process.stdout.write(` ${D}+${R} ${D}${file.path}${R}
2959
+ `);
2960
+ }
2961
+ await initializeOnboardingMarker(projectDir, {
2962
+ allowIntro: !(onboardingOptions.yes ?? false)
2963
+ });
2964
+ process.stdout.write("\n");
2965
+ try {
2966
+ await runPnpmInstall(projectDir);
2967
+ process.stdout.write(` ${G}\u2713${R} ${D}Installed dependencies${R}
2968
+ `);
2969
+ } catch {
2970
+ process.stdout.write(
2971
+ ` ${YW}!${R} Could not install dependencies \u2014 run ${D}pnpm install${R} manually
2972
+ `
2973
+ );
2974
+ }
2975
+ const gitOk = await gitInit(projectDir);
2976
+ if (gitOk) {
2977
+ process.stdout.write(` ${G}\u2713${R} ${D}Initialized git${R}
2978
+ `);
2979
+ }
2980
+ process.stdout.write(` ${G}\u2713${R} ${B}${projectName}${R} is ready
2981
+ `);
2982
+ process.stdout.write("\n");
2983
+ process.stdout.write(` ${B}Get started${R}
2984
+ `);
2985
+ process.stdout.write("\n");
2986
+ process.stdout.write(` ${D}$${R} cd ${projectName}
2987
+ `);
2988
+ process.stdout.write("\n");
2989
+ process.stdout.write(` ${CY}Web UI${R} ${D}$${R} poncho dev
2990
+ `);
2991
+ process.stdout.write(` ${CY}CLI interactive${R} ${D}$${R} poncho run --interactive
2992
+ `);
2993
+ process.stdout.write("\n");
2994
+ if (onboarding.envNeedsUserInput) {
2995
+ process.stdout.write(
2996
+ ` ${YW}!${R} Make sure you add your keys to the ${B}.env${R} file.
2997
+ `
2998
+ );
2999
+ }
3000
+ process.stdout.write(` ${D}The agent will introduce itself on your first session.${R}
3001
+ `);
3002
+ process.stdout.write("\n");
3003
+ };
3004
+ var updateAgentGuidance = async (workingDir) => {
3005
+ const agentPath = resolve3(workingDir, "AGENT.md");
3006
+ const content = await readFile3(agentPath, "utf8");
3007
+ const guidanceSectionPattern = /\n## Configuration Assistant Context[\s\S]*?(?=\n## |\n# |$)|\n## Skill Authoring Guidance[\s\S]*?(?=\n## |\n# |$)/g;
3008
+ const normalized = content.replace(/\s+$/g, "");
3009
+ const updated = normalized.replace(guidanceSectionPattern, "").replace(/\n{3,}/g, "\n\n");
3010
+ if (updated === normalized) {
3011
+ process.stdout.write("AGENT.md does not contain deprecated embedded local guidance.\n");
3012
+ return false;
3013
+ }
3014
+ await writeFile3(agentPath, `${updated}
3015
+ `, "utf8");
3016
+ process.stdout.write("Removed deprecated embedded local guidance from AGENT.md.\n");
3017
+ return true;
3018
+ };
3019
+ var formatSseEvent = (event) => `event: ${event.type}
3020
+ data: ${JSON.stringify(event)}
3021
+
3022
+ `;
3023
+ var createRequestHandler = async (options) => {
3024
+ const workingDir = options?.workingDir ?? process.cwd();
3025
+ dotenv.config({ path: resolve3(workingDir, ".env") });
3026
+ const config = await loadPonchoConfig(workingDir);
3027
+ let agentName = "Agent";
3028
+ let agentModelProvider = "anthropic";
3029
+ let agentModelName = "claude-opus-4-5";
3030
+ try {
3031
+ const agentMd = await readFile3(resolve3(workingDir, "AGENT.md"), "utf8");
3032
+ const nameMatch = agentMd.match(/^name:\s*(.+)$/m);
3033
+ const providerMatch = agentMd.match(/^\s{2}provider:\s*(.+)$/m);
3034
+ const modelMatch = agentMd.match(/^\s{2}name:\s*(.+)$/m);
3035
+ if (nameMatch?.[1]) {
3036
+ agentName = nameMatch[1].trim().replace(/^["']|["']$/g, "");
3037
+ }
3038
+ if (providerMatch?.[1]) {
3039
+ agentModelProvider = providerMatch[1].trim().replace(/^["']|["']$/g, "");
3040
+ }
3041
+ if (modelMatch?.[1]) {
3042
+ agentModelName = modelMatch[1].trim().replace(/^["']|["']$/g, "");
3043
+ }
3044
+ } catch {
3045
+ }
3046
+ const harness = new AgentHarness({ workingDir, environment: resolveHarnessEnvironment() });
3047
+ await harness.initialize();
3048
+ const telemetry = new TelemetryEmitter(config?.telemetry);
3049
+ const conversationStore = createConversationStore(resolveStateConfig(config), { workingDir });
3050
+ const sessionStore = new SessionStore();
3051
+ const loginRateLimiter = new LoginRateLimiter();
3052
+ const passphrase = process.env.AGENT_UI_PASSPHRASE ?? "";
3053
+ const isProduction = resolveHarnessEnvironment() === "production";
3054
+ const requireUiAuth = passphrase.length > 0;
3055
+ const secureCookies = isProduction;
3056
+ return async (request, response) => {
3057
+ if (!request.url || !request.method) {
3058
+ writeJson(response, 404, { error: "Not found" });
3059
+ return;
3060
+ }
3061
+ const [pathname] = request.url.split("?");
3062
+ if (request.method === "GET" && (pathname === "/" || pathname.startsWith("/c/"))) {
3063
+ writeHtml(response, 200, renderWebUiHtml({ agentName }));
3064
+ return;
3065
+ }
3066
+ if (pathname === "/manifest.json" && request.method === "GET") {
3067
+ response.writeHead(200, { "Content-Type": "application/manifest+json" });
3068
+ response.end(renderManifest({ agentName }));
3069
+ return;
3070
+ }
3071
+ if (pathname === "/sw.js" && request.method === "GET") {
3072
+ response.writeHead(200, {
3073
+ "Content-Type": "application/javascript",
3074
+ "Service-Worker-Allowed": "/"
3075
+ });
3076
+ response.end(renderServiceWorker());
3077
+ return;
3078
+ }
3079
+ if (pathname === "/icon.svg" && request.method === "GET") {
3080
+ response.writeHead(200, { "Content-Type": "image/svg+xml" });
3081
+ response.end(renderIconSvg({ agentName }));
3082
+ return;
3083
+ }
3084
+ if ((pathname === "/icon-192.png" || pathname === "/icon-512.png") && request.method === "GET") {
3085
+ response.writeHead(302, { Location: "/icon.svg" });
3086
+ response.end();
3087
+ return;
3088
+ }
3089
+ if (pathname === "/health" && request.method === "GET") {
3090
+ writeJson(response, 200, { status: "ok" });
3091
+ return;
3092
+ }
3093
+ const cookies = parseCookies(request);
3094
+ const sessionId = cookies.poncho_session;
3095
+ const session = sessionId ? sessionStore.get(sessionId) : void 0;
3096
+ const ownerId = session?.ownerId ?? "local-owner";
3097
+ const requiresCsrfValidation = request.method !== "GET" && request.method !== "HEAD" && request.method !== "OPTIONS";
3098
+ if (pathname === "/api/auth/session" && request.method === "GET") {
3099
+ if (!requireUiAuth) {
3100
+ writeJson(response, 200, { authenticated: true, csrfToken: "" });
3101
+ return;
3102
+ }
3103
+ if (!session) {
3104
+ writeJson(response, 200, { authenticated: false });
3105
+ return;
3106
+ }
3107
+ writeJson(response, 200, {
3108
+ authenticated: true,
3109
+ sessionId: session.sessionId,
3110
+ ownerId: session.ownerId,
3111
+ csrfToken: session.csrfToken
3112
+ });
3113
+ return;
3114
+ }
3115
+ if (pathname === "/api/auth/login" && request.method === "POST") {
3116
+ if (!requireUiAuth) {
3117
+ writeJson(response, 200, { authenticated: true, csrfToken: "" });
3118
+ return;
3119
+ }
3120
+ const ip = getRequestIp(request);
3121
+ const canAttempt = loginRateLimiter.canAttempt(ip);
3122
+ if (!canAttempt.allowed) {
3123
+ writeJson(response, 429, {
3124
+ code: "AUTH_RATE_LIMIT",
3125
+ message: "Too many failed login attempts. Try again later.",
3126
+ retryAfterSeconds: canAttempt.retryAfterSeconds
3127
+ });
3128
+ return;
3129
+ }
3130
+ const body = await readRequestBody(request);
3131
+ const provided = body.passphrase ?? "";
3132
+ if (!verifyPassphrase(provided, passphrase)) {
3133
+ const failure = loginRateLimiter.registerFailure(ip);
3134
+ writeJson(response, 401, {
3135
+ code: "AUTH_ERROR",
3136
+ message: "Invalid passphrase",
3137
+ retryAfterSeconds: failure.retryAfterSeconds
3138
+ });
3139
+ return;
3140
+ }
3141
+ loginRateLimiter.registerSuccess(ip);
3142
+ const createdSession = sessionStore.create(ownerId);
3143
+ setCookie(response, "poncho_session", createdSession.sessionId, {
3144
+ httpOnly: true,
3145
+ secure: secureCookies,
3146
+ sameSite: "Lax",
3147
+ path: "/",
3148
+ maxAge: 60 * 60 * 8
3149
+ });
3150
+ writeJson(response, 200, {
3151
+ authenticated: true,
3152
+ csrfToken: createdSession.csrfToken
3153
+ });
3154
+ return;
3155
+ }
3156
+ if (pathname === "/api/auth/logout" && request.method === "POST") {
3157
+ if (session?.sessionId) {
3158
+ sessionStore.delete(session.sessionId);
3159
+ }
3160
+ setCookie(response, "poncho_session", "", {
3161
+ httpOnly: true,
3162
+ secure: secureCookies,
3163
+ sameSite: "Lax",
3164
+ path: "/",
3165
+ maxAge: 0
3166
+ });
3167
+ writeJson(response, 200, { ok: true });
3168
+ return;
3169
+ }
3170
+ if (pathname.startsWith("/api/")) {
3171
+ if (requireUiAuth && !session) {
3172
+ writeJson(response, 401, {
3173
+ code: "AUTH_ERROR",
3174
+ message: "Authentication required"
3175
+ });
3176
+ return;
3177
+ }
3178
+ if (requireUiAuth && requiresCsrfValidation && pathname !== "/api/auth/login" && request.headers["x-csrf-token"] !== session?.csrfToken) {
3179
+ writeJson(response, 403, {
3180
+ code: "CSRF_ERROR",
3181
+ message: "Invalid CSRF token"
3182
+ });
3183
+ return;
3184
+ }
3185
+ }
3186
+ if (pathname === "/api/conversations" && request.method === "GET") {
3187
+ const conversations = await conversationStore.list(ownerId);
3188
+ writeJson(response, 200, {
3189
+ conversations: conversations.map((conversation) => ({
3190
+ conversationId: conversation.conversationId,
3191
+ title: conversation.title,
3192
+ runtimeRunId: conversation.runtimeRunId,
3193
+ ownerId: conversation.ownerId,
3194
+ tenantId: conversation.tenantId,
3195
+ createdAt: conversation.createdAt,
3196
+ updatedAt: conversation.updatedAt,
3197
+ messageCount: conversation.messages.length
3198
+ }))
3199
+ });
3200
+ return;
3201
+ }
3202
+ if (pathname === "/api/conversations" && request.method === "POST") {
3203
+ const body = await readRequestBody(request);
3204
+ const conversation = await conversationStore.create(ownerId, body.title);
3205
+ const introMessage = await consumeFirstRunIntro(workingDir, {
3206
+ agentName,
3207
+ provider: agentModelProvider,
3208
+ model: agentModelName,
3209
+ config
3210
+ });
3211
+ if (introMessage) {
3212
+ conversation.messages = [{ role: "assistant", content: introMessage }];
3213
+ await conversationStore.update(conversation);
3214
+ }
3215
+ writeJson(response, 201, { conversation });
3216
+ return;
3217
+ }
3218
+ const conversationPathMatch = pathname.match(/^\/api\/conversations\/([^/]+)$/);
3219
+ if (conversationPathMatch) {
3220
+ const conversationId = decodeURIComponent(conversationPathMatch[1] ?? "");
3221
+ const conversation = await conversationStore.get(conversationId);
3222
+ if (!conversation || conversation.ownerId !== ownerId) {
3223
+ writeJson(response, 404, {
3224
+ code: "CONVERSATION_NOT_FOUND",
3225
+ message: "Conversation not found"
3226
+ });
3227
+ return;
3228
+ }
3229
+ if (request.method === "GET") {
3230
+ writeJson(response, 200, { conversation });
3231
+ return;
3232
+ }
3233
+ if (request.method === "PATCH") {
3234
+ const body = await readRequestBody(request);
3235
+ if (!body.title || body.title.trim().length === 0) {
3236
+ writeJson(response, 400, {
3237
+ code: "VALIDATION_ERROR",
3238
+ message: "title is required"
3239
+ });
3240
+ return;
3241
+ }
3242
+ const updated = await conversationStore.rename(conversationId, body.title);
3243
+ writeJson(response, 200, { conversation: updated });
3244
+ return;
3245
+ }
3246
+ if (request.method === "DELETE") {
3247
+ await conversationStore.delete(conversationId);
3248
+ writeJson(response, 200, { ok: true });
3249
+ return;
3250
+ }
3251
+ }
3252
+ const conversationMessageMatch = pathname.match(/^\/api\/conversations\/([^/]+)\/messages$/);
3253
+ if (conversationMessageMatch && request.method === "POST") {
3254
+ const conversationId = decodeURIComponent(conversationMessageMatch[1] ?? "");
3255
+ const conversation = await conversationStore.get(conversationId);
3256
+ if (!conversation || conversation.ownerId !== ownerId) {
3257
+ writeJson(response, 404, {
3258
+ code: "CONVERSATION_NOT_FOUND",
3259
+ message: "Conversation not found"
3260
+ });
3261
+ return;
3262
+ }
3263
+ const body = await readRequestBody(request);
3264
+ const messageText = body.message?.trim() ?? "";
3265
+ if (!messageText) {
3266
+ writeJson(response, 400, {
3267
+ code: "VALIDATION_ERROR",
3268
+ message: "message is required"
3269
+ });
3270
+ return;
3271
+ }
3272
+ if (conversation.messages.length === 0 && (conversation.title === "New conversation" || conversation.title.trim().length === 0)) {
3273
+ conversation.title = inferConversationTitle(messageText);
3274
+ }
3275
+ response.writeHead(200, {
3276
+ "Content-Type": "text/event-stream",
3277
+ "Cache-Control": "no-cache",
3278
+ Connection: "keep-alive"
3279
+ });
3280
+ let latestRunId = conversation.runtimeRunId ?? "";
3281
+ let assistantResponse = "";
3282
+ const toolTimeline = [];
3283
+ const sections = [];
3284
+ let currentText = "";
3285
+ let currentTools = [];
3286
+ try {
3287
+ const recallCorpus = (await conversationStore.list(ownerId)).filter((item) => item.conversationId !== conversationId).slice(0, 20).map((item) => ({
3288
+ conversationId: item.conversationId,
3289
+ title: item.title,
3290
+ updatedAt: item.updatedAt,
3291
+ content: item.messages.slice(-6).map((message) => `${message.role}: ${message.content}`).join("\n").slice(0, 2e3)
3292
+ })).filter((item) => item.content.length > 0);
3293
+ for await (const event of harness.run({
3294
+ task: messageText,
3295
+ parameters: {
3296
+ ...body.parameters ?? {},
3297
+ __conversationRecallCorpus: recallCorpus,
3298
+ __activeConversationId: conversationId
3299
+ },
3300
+ messages: conversation.messages
3301
+ })) {
3302
+ if (event.type === "run:started") {
3303
+ latestRunId = event.runId;
3304
+ }
3305
+ if (event.type === "model:chunk") {
3306
+ if (currentTools.length > 0) {
3307
+ sections.push({ type: "tools", content: currentTools });
3308
+ currentTools = [];
3309
+ }
3310
+ assistantResponse += event.content;
3311
+ currentText += event.content;
3312
+ }
3313
+ if (event.type === "tool:started") {
3314
+ if (currentText.length > 0) {
3315
+ sections.push({ type: "text", content: currentText });
3316
+ currentText = "";
3317
+ }
3318
+ const toolText = `- start \`${event.tool}\``;
3319
+ toolTimeline.push(toolText);
3320
+ currentTools.push(toolText);
3321
+ }
3322
+ if (event.type === "tool:completed") {
3323
+ const toolText = `- done \`${event.tool}\` (${event.duration}ms)`;
3324
+ toolTimeline.push(toolText);
3325
+ currentTools.push(toolText);
3326
+ }
3327
+ if (event.type === "tool:error") {
3328
+ const toolText = `- error \`${event.tool}\`: ${event.error}`;
3329
+ toolTimeline.push(toolText);
3330
+ currentTools.push(toolText);
3331
+ }
3332
+ if (event.type === "tool:approval:required") {
3333
+ const toolText = `- approval required \`${event.tool}\``;
3334
+ toolTimeline.push(toolText);
3335
+ currentTools.push(toolText);
3336
+ }
3337
+ if (event.type === "tool:approval:granted") {
3338
+ const toolText = `- approval granted (${event.approvalId})`;
3339
+ toolTimeline.push(toolText);
3340
+ currentTools.push(toolText);
3341
+ }
3342
+ if (event.type === "tool:approval:denied") {
3343
+ const toolText = `- approval denied (${event.approvalId})`;
3344
+ toolTimeline.push(toolText);
3345
+ currentTools.push(toolText);
3346
+ }
3347
+ if (event.type === "run:completed" && assistantResponse.length === 0 && event.result.response) {
3348
+ assistantResponse = event.result.response;
3349
+ }
3350
+ await telemetry.emit(event);
3351
+ response.write(formatSseEvent(event));
3352
+ }
3353
+ if (currentTools.length > 0) {
3354
+ sections.push({ type: "tools", content: currentTools });
3355
+ }
3356
+ if (currentText.length > 0) {
3357
+ sections.push({ type: "text", content: currentText });
3358
+ }
3359
+ conversation.messages = [
3360
+ ...conversation.messages,
3361
+ { role: "user", content: messageText },
3362
+ {
3363
+ role: "assistant",
3364
+ content: assistantResponse,
3365
+ metadata: toolTimeline.length > 0 || sections.length > 0 ? {
3366
+ toolActivity: toolTimeline,
3367
+ sections: sections.length > 0 ? sections : void 0
3368
+ } : void 0
3369
+ }
3370
+ ];
3371
+ conversation.runtimeRunId = latestRunId || conversation.runtimeRunId;
3372
+ conversation.updatedAt = Date.now();
3373
+ await conversationStore.update(conversation);
3374
+ } catch (error) {
3375
+ response.write(
3376
+ formatSseEvent({
3377
+ type: "run:error",
3378
+ runId: latestRunId || "run_unknown",
3379
+ error: {
3380
+ code: "RUN_ERROR",
3381
+ message: error instanceof Error ? error.message : "Unknown error"
3382
+ }
3383
+ })
3384
+ );
3385
+ } finally {
3386
+ response.end();
3387
+ }
3388
+ return;
3389
+ }
3390
+ writeJson(response, 404, { error: "Not found" });
3391
+ };
3392
+ };
3393
+ var startDevServer = async (port, options) => {
3394
+ const handler = await createRequestHandler(options);
3395
+ const server = createServer(handler);
3396
+ const actualPort = await listenOnAvailablePort(server, port);
3397
+ if (actualPort !== port) {
3398
+ process.stdout.write(`Port ${port} is in use, switched to ${actualPort}.
3399
+ `);
3400
+ }
3401
+ process.stdout.write(`Poncho dev server running at http://localhost:${actualPort}
3402
+ `);
3403
+ const shutdown = () => {
3404
+ server.close();
3405
+ server.closeAllConnections?.();
3406
+ process.exit(0);
3407
+ };
3408
+ process.on("SIGINT", shutdown);
3409
+ process.on("SIGTERM", shutdown);
3410
+ return server;
3411
+ };
3412
+ var runOnce = async (task, options) => {
3413
+ const workingDir = options.workingDir ?? process.cwd();
3414
+ dotenv.config({ path: resolve3(workingDir, ".env") });
3415
+ const config = await loadPonchoConfig(workingDir);
3416
+ const harness = new AgentHarness({ workingDir });
3417
+ const telemetry = new TelemetryEmitter(config?.telemetry);
3418
+ await harness.initialize();
3419
+ const fileBlobs = await Promise.all(
3420
+ options.filePaths.map(async (path) => {
3421
+ const content = await readFile3(resolve3(workingDir, path), "utf8");
3422
+ return `# File: ${path}
3423
+ ${content}`;
3424
+ })
3425
+ );
3426
+ const input2 = {
3427
+ task: fileBlobs.length > 0 ? `${task}
3428
+
3429
+ ${fileBlobs.join("\n\n")}` : task,
3430
+ parameters: options.params
3431
+ };
3432
+ if (options.json) {
3433
+ const output = await harness.runToCompletion(input2);
3434
+ for (const event of output.events) {
3435
+ await telemetry.emit(event);
3436
+ }
3437
+ process.stdout.write(`${JSON.stringify(output, null, 2)}
3438
+ `);
3439
+ return;
3440
+ }
3441
+ for await (const event of harness.run(input2)) {
3442
+ await telemetry.emit(event);
3443
+ if (event.type === "model:chunk") {
3444
+ process.stdout.write(event.content);
3445
+ }
3446
+ if (event.type === "run:error") {
3447
+ process.stderr.write(`
3448
+ Error: ${event.error.message}
3449
+ `);
3450
+ }
3451
+ if (event.type === "run:completed") {
3452
+ process.stdout.write("\n");
3453
+ }
3454
+ }
3455
+ };
3456
+ var runInteractive = async (workingDir, params) => {
3457
+ dotenv.config({ path: resolve3(workingDir, ".env") });
3458
+ const config = await loadPonchoConfig(workingDir);
3459
+ let pendingApproval = null;
3460
+ let onApprovalRequest = null;
3461
+ const approvalHandler = async (request) => {
3462
+ return new Promise((resolveApproval) => {
3463
+ const req = {
3464
+ tool: request.tool,
3465
+ input: request.input,
3466
+ approvalId: request.approvalId,
3467
+ resolve: resolveApproval
3468
+ };
3469
+ pendingApproval = req;
3470
+ if (onApprovalRequest) {
3471
+ onApprovalRequest(req);
3472
+ }
3473
+ });
3474
+ };
3475
+ const harness = new AgentHarness({
3476
+ workingDir,
3477
+ environment: resolveHarnessEnvironment(),
3478
+ approvalHandler
3479
+ });
3480
+ await harness.initialize();
3481
+ try {
3482
+ const { runInteractiveInk } = await import("./run-interactive-ink-642LZIYZ.js");
3483
+ await runInteractiveInk({
3484
+ harness,
3485
+ params,
3486
+ workingDir,
3487
+ config,
3488
+ conversationStore: createConversationStore(resolveStateConfig(config), { workingDir }),
3489
+ onSetApprovalCallback: (cb) => {
3490
+ onApprovalRequest = cb;
3491
+ if (pendingApproval) {
3492
+ cb(pendingApproval);
3493
+ }
3494
+ }
3495
+ });
3496
+ } finally {
3497
+ await harness.shutdown();
3498
+ }
3499
+ };
3500
+ var listTools = async (workingDir) => {
3501
+ dotenv.config({ path: resolve3(workingDir, ".env") });
3502
+ const harness = new AgentHarness({ workingDir });
3503
+ await harness.initialize();
3504
+ const tools = harness.listTools();
3505
+ if (tools.length === 0) {
3506
+ process.stdout.write("No tools registered.\n");
3507
+ return;
3508
+ }
3509
+ process.stdout.write("Available tools:\n");
3510
+ for (const tool of tools) {
3511
+ process.stdout.write(`- ${tool.name}: ${tool.description}
3512
+ `);
3513
+ }
3514
+ };
3515
+ var runPnpmInstall = async (workingDir) => await new Promise((resolveInstall, rejectInstall) => {
3516
+ const child = spawn("pnpm", ["install"], {
3517
+ cwd: workingDir,
3518
+ stdio: "inherit",
3519
+ env: process.env
3520
+ });
3521
+ child.on("exit", (code) => {
3522
+ if (code === 0) {
3523
+ resolveInstall();
3524
+ return;
3525
+ }
3526
+ rejectInstall(new Error(`pnpm install failed with exit code ${code ?? -1}`));
3527
+ });
3528
+ });
3529
+ var runInstallCommand = async (workingDir, packageNameOrPath) => await new Promise((resolveInstall, rejectInstall) => {
3530
+ const child = spawn("pnpm", ["add", packageNameOrPath], {
3531
+ cwd: workingDir,
3532
+ stdio: "inherit",
3533
+ env: process.env
3534
+ });
3535
+ child.on("exit", (code) => {
3536
+ if (code === 0) {
3537
+ resolveInstall();
3538
+ return;
3539
+ }
3540
+ rejectInstall(new Error(`pnpm add failed with exit code ${code ?? -1}`));
3541
+ });
3542
+ });
3543
+ var resolveInstalledPackageName = (packageNameOrPath) => {
3544
+ if (packageNameOrPath.startsWith(".") || packageNameOrPath.startsWith("/")) {
3545
+ return null;
3546
+ }
3547
+ if (packageNameOrPath.startsWith("@")) {
3548
+ return packageNameOrPath;
3549
+ }
3550
+ if (packageNameOrPath.includes("/")) {
3551
+ return packageNameOrPath.split("/").pop() ?? packageNameOrPath;
3552
+ }
3553
+ return packageNameOrPath;
3554
+ };
3555
+ var resolveSkillRoot = (workingDir, packageNameOrPath) => {
3556
+ if (packageNameOrPath.startsWith(".") || packageNameOrPath.startsWith("/")) {
3557
+ return resolve3(workingDir, packageNameOrPath);
3558
+ }
3559
+ const moduleName = resolveInstalledPackageName(packageNameOrPath) ?? packageNameOrPath;
3560
+ try {
3561
+ const packageJsonPath = require2.resolve(`${moduleName}/package.json`, {
3562
+ paths: [workingDir]
3563
+ });
3564
+ return resolve3(packageJsonPath, "..");
3565
+ } catch {
3566
+ const candidate = resolve3(workingDir, "node_modules", moduleName);
3567
+ if (existsSync(candidate)) {
3568
+ return candidate;
3569
+ }
3570
+ throw new Error(
3571
+ `Could not locate installed package "${moduleName}" in ${workingDir}`
3572
+ );
3573
+ }
3574
+ };
3575
+ var findSkillManifest = async (dir, depth = 2) => {
3576
+ try {
3577
+ await access2(resolve3(dir, "SKILL.md"));
3578
+ return true;
3579
+ } catch {
3580
+ }
3581
+ if (depth <= 0) return false;
3582
+ try {
3583
+ const { readdir } = await import("fs/promises");
3584
+ const entries = await readdir(dir, { withFileTypes: true });
3585
+ for (const entry of entries) {
3586
+ if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
3587
+ const found = await findSkillManifest(resolve3(dir, entry.name), depth - 1);
3588
+ if (found) return true;
3589
+ }
3590
+ }
3591
+ } catch {
3592
+ }
3593
+ return false;
3594
+ };
3595
+ var validateSkillPackage = async (workingDir, packageNameOrPath) => {
3596
+ const skillRoot = resolveSkillRoot(workingDir, packageNameOrPath);
3597
+ const hasSkill = await findSkillManifest(skillRoot);
3598
+ if (!hasSkill) {
3599
+ throw new Error(`Skill validation failed: no SKILL.md found in ${skillRoot}`);
3600
+ }
3601
+ };
3602
+ var addSkill = async (workingDir, packageNameOrPath) => {
3603
+ await runInstallCommand(workingDir, packageNameOrPath);
3604
+ await validateSkillPackage(workingDir, packageNameOrPath);
3605
+ process.stdout.write(`Added skill: ${packageNameOrPath}
3606
+ `);
3607
+ };
3608
+ var runTests = async (workingDir, filePath) => {
3609
+ dotenv.config({ path: resolve3(workingDir, ".env") });
3610
+ const testFilePath = filePath ?? resolve3(workingDir, "tests", "basic.yaml");
3611
+ const content = await readFile3(testFilePath, "utf8");
3612
+ const parsed = YAML.parse(content);
3613
+ const tests = parsed.tests ?? [];
3614
+ const harness = new AgentHarness({ workingDir });
3615
+ await harness.initialize();
3616
+ let passed = 0;
3617
+ let failed = 0;
3618
+ for (const testCase of tests) {
3619
+ try {
3620
+ const output = await harness.runToCompletion({ task: testCase.task });
3621
+ const response = output.result.response ?? "";
3622
+ const events = output.events;
3623
+ const expectation = testCase.expect ?? {};
3624
+ const checks = [];
3625
+ if (expectation.contains) {
3626
+ checks.push(response.includes(expectation.contains));
3627
+ }
3628
+ if (typeof expectation.maxSteps === "number") {
3629
+ checks.push(output.result.steps <= expectation.maxSteps);
3630
+ }
3631
+ if (typeof expectation.maxTokens === "number") {
3632
+ checks.push(
3633
+ output.result.tokens.input + output.result.tokens.output <= expectation.maxTokens
3634
+ );
3635
+ }
3636
+ if (expectation.refusal) {
3637
+ checks.push(
3638
+ response.toLowerCase().includes("can't") || response.toLowerCase().includes("cannot")
3639
+ );
3640
+ }
3641
+ if (expectation.toolCalled) {
3642
+ checks.push(
3643
+ events.some(
3644
+ (event) => event.type === "tool:started" && event.tool === expectation.toolCalled
3645
+ )
3646
+ );
3647
+ }
3648
+ const ok = checks.length === 0 ? output.result.status === "completed" : checks.every(Boolean);
3649
+ if (ok) {
3650
+ passed += 1;
3651
+ process.stdout.write(`PASS ${testCase.name}
3652
+ `);
3653
+ } else {
3654
+ failed += 1;
3655
+ process.stdout.write(`FAIL ${testCase.name}
3656
+ `);
3657
+ }
3658
+ } catch (error) {
3659
+ failed += 1;
3660
+ process.stdout.write(
3661
+ `FAIL ${testCase.name} (${error instanceof Error ? error.message : "Unknown test error"})
3662
+ `
3663
+ );
3664
+ }
3665
+ }
3666
+ process.stdout.write(`
3667
+ Test summary: ${passed} passed, ${failed} failed
3668
+ `);
3669
+ return { passed, failed };
3670
+ };
3671
+ var buildTarget = async (workingDir, target) => {
3672
+ const outDir = resolve3(workingDir, ".poncho-build", target);
3673
+ await mkdir3(outDir, { recursive: true });
3674
+ const serverEntrypoint = `import { startDevServer } from "@poncho-ai/cli";
3675
+
3676
+ const port = Number.parseInt(process.env.PORT ?? "3000", 10);
3677
+ await startDevServer(Number.isNaN(port) ? 3000 : port, { workingDir: process.cwd() });
3678
+ `;
3679
+ const runtimePackageJson = JSON.stringify(
3680
+ {
3681
+ name: "poncho-runtime-bundle",
3682
+ private: true,
3683
+ type: "module",
3684
+ scripts: {
3685
+ start: "node server.js"
3686
+ },
3687
+ dependencies: {
3688
+ "@poncho-ai/cli": "^0.1.0"
3689
+ }
3690
+ },
3691
+ null,
3692
+ 2
3693
+ );
3694
+ if (target === "vercel") {
3695
+ await mkdir3(resolve3(outDir, "api"), { recursive: true });
3696
+ await copyIfExists(resolve3(workingDir, "AGENT.md"), resolve3(outDir, "AGENT.md"));
3697
+ await copyIfExists(
3698
+ resolve3(workingDir, "poncho.config.js"),
3699
+ resolve3(outDir, "poncho.config.js")
3700
+ );
3701
+ await copyIfExists(resolve3(workingDir, "skills"), resolve3(outDir, "skills"));
3702
+ await copyIfExists(resolve3(workingDir, "tests"), resolve3(outDir, "tests"));
3703
+ await writeFile3(
3704
+ resolve3(outDir, "vercel.json"),
3705
+ JSON.stringify(
3706
+ {
3707
+ version: 2,
3708
+ functions: {
3709
+ "api/index.js": {
3710
+ includeFiles: "{AGENT.md,poncho.config.js,skills/**,tests/**}"
3711
+ }
3712
+ },
3713
+ routes: [{ src: "/(.*)", dest: "/api/index.js" }]
3714
+ },
3715
+ null,
3716
+ 2
3717
+ ),
3718
+ "utf8"
3719
+ );
3720
+ await buildVercelHandlerBundle(outDir);
3721
+ await writeFile3(
3722
+ resolve3(outDir, "package.json"),
3723
+ JSON.stringify(
3724
+ {
3725
+ private: true,
3726
+ type: "module",
3727
+ engines: {
3728
+ node: "20.x"
3729
+ },
3730
+ dependencies: VERCEL_RUNTIME_DEPENDENCIES
3731
+ },
3732
+ null,
3733
+ 2
3734
+ ),
3735
+ "utf8"
3736
+ );
3737
+ } else if (target === "docker") {
3738
+ await writeFile3(
3739
+ resolve3(outDir, "Dockerfile"),
3740
+ `FROM node:20-slim
3741
+ WORKDIR /app
3742
+ COPY package.json package.json
3743
+ COPY AGENT.md AGENT.md
3744
+ COPY poncho.config.js poncho.config.js
3745
+ COPY skills skills
3746
+ COPY tests tests
3747
+ COPY .env.example .env.example
3748
+ RUN corepack enable && npm install -g @poncho-ai/cli
3749
+ COPY server.js server.js
3750
+ EXPOSE 3000
3751
+ CMD ["node","server.js"]
3752
+ `,
3753
+ "utf8"
3754
+ );
3755
+ await writeFile3(resolve3(outDir, "server.js"), serverEntrypoint, "utf8");
3756
+ await writeFile3(resolve3(outDir, "package.json"), runtimePackageJson, "utf8");
3757
+ } else if (target === "lambda") {
3758
+ await writeFile3(
3759
+ resolve3(outDir, "lambda-handler.js"),
3760
+ `import { startDevServer } from "@poncho-ai/cli";
3761
+ let serverPromise;
3762
+ export const handler = async (event = {}) => {
3763
+ if (!serverPromise) {
3764
+ serverPromise = startDevServer(0, { workingDir: process.cwd() });
3765
+ }
3766
+ const body = JSON.stringify({
3767
+ status: "ready",
3768
+ route: event.rawPath ?? event.path ?? "/",
3769
+ });
3770
+ return { statusCode: 200, headers: { "content-type": "application/json" }, body };
3771
+ };
3772
+ `,
3773
+ "utf8"
3774
+ );
3775
+ await writeFile3(resolve3(outDir, "package.json"), runtimePackageJson, "utf8");
3776
+ } else if (target === "fly") {
3777
+ await writeFile3(
3778
+ resolve3(outDir, "fly.toml"),
3779
+ `app = "poncho-app"
3780
+ [env]
3781
+ PORT = "3000"
3782
+ [http_service]
3783
+ internal_port = 3000
3784
+ force_https = true
3785
+ auto_start_machines = true
3786
+ auto_stop_machines = "stop"
3787
+ min_machines_running = 0
3788
+ `,
3789
+ "utf8"
3790
+ );
3791
+ await writeFile3(
3792
+ resolve3(outDir, "Dockerfile"),
3793
+ `FROM node:20-slim
3794
+ WORKDIR /app
3795
+ COPY package.json package.json
3796
+ COPY AGENT.md AGENT.md
3797
+ COPY poncho.config.js poncho.config.js
3798
+ COPY skills skills
3799
+ COPY tests tests
3800
+ RUN npm install -g @poncho-ai/cli
3801
+ COPY server.js server.js
3802
+ EXPOSE 3000
3803
+ CMD ["node","server.js"]
3804
+ `,
3805
+ "utf8"
3806
+ );
3807
+ await writeFile3(resolve3(outDir, "server.js"), serverEntrypoint, "utf8");
3808
+ await writeFile3(resolve3(outDir, "package.json"), runtimePackageJson, "utf8");
3809
+ } else {
3810
+ throw new Error(`Unsupported build target: ${target}`);
3811
+ }
3812
+ process.stdout.write(`Build artifacts generated at ${outDir}
3813
+ `);
3814
+ };
3815
+ var normalizeMcpName = (entry) => entry.name ?? entry.url ?? `mcp_${Date.now()}`;
3816
+ var mcpAdd = async (workingDir, options) => {
3817
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
3818
+ const mcp = [...config.mcp ?? []];
3819
+ if (!options.url) {
3820
+ throw new Error("Remote MCP only: provide --url for a remote MCP server.");
3821
+ }
3822
+ if (options.url.startsWith("ws://") || options.url.startsWith("wss://")) {
3823
+ throw new Error("WebSocket MCP URLs are no longer supported. Use an HTTP MCP endpoint.");
3824
+ }
3825
+ if (!options.url.startsWith("http://") && !options.url.startsWith("https://")) {
3826
+ throw new Error("Invalid MCP URL. Expected http:// or https://.");
3827
+ }
3828
+ const serverName = options.name ?? normalizeMcpName({ url: options.url });
3829
+ mcp.push({
3830
+ name: serverName,
3831
+ url: options.url,
3832
+ env: options.envVars ?? [],
3833
+ auth: options.authBearerEnv ? {
3834
+ type: "bearer",
3835
+ tokenEnv: options.authBearerEnv
3836
+ } : void 0
3837
+ });
3838
+ await writeConfigFile(workingDir, { ...config, mcp });
3839
+ let envSeedMessage;
3840
+ if (options.authBearerEnv) {
3841
+ const envPath = resolve3(workingDir, ".env");
3842
+ const envExamplePath = resolve3(workingDir, ".env.example");
3843
+ const addedEnv = await ensureEnvPlaceholder(envPath, options.authBearerEnv);
3844
+ const addedEnvExample = await ensureEnvPlaceholder(envExamplePath, options.authBearerEnv);
3845
+ if (addedEnv || addedEnvExample) {
3846
+ envSeedMessage = `Added ${options.authBearerEnv}= to ${addedEnv ? ".env" : ""}${addedEnv && addedEnvExample ? " and " : ""}${addedEnvExample ? ".env.example" : ""}.`;
3847
+ }
3848
+ }
3849
+ const nextSteps = [];
3850
+ let step = 1;
3851
+ if (options.authBearerEnv) {
3852
+ nextSteps.push(` ${step}) Set token in .env: ${options.authBearerEnv}=...`);
3853
+ step += 1;
3854
+ }
3855
+ nextSteps.push(` ${step}) Discover tools: poncho mcp tools list ${serverName}`);
3856
+ step += 1;
3857
+ nextSteps.push(` ${step}) Select tools: poncho mcp tools select ${serverName}`);
3858
+ step += 1;
3859
+ nextSteps.push(` ${step}) Verify config: poncho mcp list`);
3860
+ process.stdout.write(
3861
+ [
3862
+ `MCP server added: ${serverName}`,
3863
+ ...envSeedMessage ? [envSeedMessage] : [],
3864
+ "Next steps:",
3865
+ ...nextSteps,
3866
+ ""
3867
+ ].join("\n")
3868
+ );
3869
+ };
3870
+ var mcpList = async (workingDir) => {
3871
+ const config = await loadPonchoConfig(workingDir);
3872
+ const mcp = config?.mcp ?? [];
3873
+ if (mcp.length === 0) {
3874
+ process.stdout.write("No MCP servers configured.\n");
3875
+ if (config?.scripts) {
3876
+ process.stdout.write(
3877
+ `Script policy: mode=${config.scripts.mode ?? "all"} include=${config.scripts.include?.length ?? 0} exclude=${config.scripts.exclude?.length ?? 0}
3878
+ `
3879
+ );
3880
+ }
3881
+ return;
3882
+ }
3883
+ process.stdout.write("Configured MCP servers:\n");
3884
+ for (const entry of mcp) {
3885
+ const auth = entry.auth?.type === "bearer" ? `auth=bearer:${entry.auth.tokenEnv}` : "auth=none";
3886
+ const mode = entry.tools?.mode ?? "all";
3887
+ process.stdout.write(
3888
+ `- ${entry.name ?? entry.url} (remote: ${entry.url}, ${auth}, mode=${mode})
3889
+ `
3890
+ );
3891
+ }
3892
+ if (config?.scripts) {
3893
+ process.stdout.write(
3894
+ `Script policy: mode=${config.scripts.mode ?? "all"} include=${config.scripts.include?.length ?? 0} exclude=${config.scripts.exclude?.length ?? 0}
3895
+ `
3896
+ );
3897
+ }
3898
+ };
3899
+ var mcpRemove = async (workingDir, name) => {
3900
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
3901
+ const before = config.mcp ?? [];
3902
+ const removed = before.filter((entry) => normalizeMcpName(entry) === name);
3903
+ const filtered = before.filter((entry) => normalizeMcpName(entry) !== name);
3904
+ await writeConfigFile(workingDir, { ...config, mcp: filtered });
3905
+ const removedTokenEnvNames = new Set(
3906
+ removed.map(
3907
+ (entry) => entry.auth?.type === "bearer" ? entry.auth.tokenEnv?.trim() ?? "" : ""
3908
+ ).filter((value) => value.length > 0)
3909
+ );
3910
+ const stillUsedTokenEnvNames = new Set(
3911
+ filtered.map(
3912
+ (entry) => entry.auth?.type === "bearer" ? entry.auth.tokenEnv?.trim() ?? "" : ""
3913
+ ).filter((value) => value.length > 0)
3914
+ );
3915
+ const removedFromExample = [];
3916
+ for (const tokenEnv of removedTokenEnvNames) {
3917
+ if (stillUsedTokenEnvNames.has(tokenEnv)) {
3918
+ continue;
3919
+ }
3920
+ const changed = await removeEnvPlaceholder(resolve3(workingDir, ".env.example"), tokenEnv);
3921
+ if (changed) {
3922
+ removedFromExample.push(tokenEnv);
3923
+ }
3924
+ }
3925
+ process.stdout.write(`Removed MCP server: ${name}
3926
+ `);
3927
+ if (removedFromExample.length > 0) {
3928
+ process.stdout.write(
3929
+ `Removed unused token placeholder(s) from .env.example: ${removedFromExample.join(", ")}
3930
+ `
3931
+ );
3932
+ }
3933
+ };
3934
+ var resolveMcpEntry = async (workingDir, serverName) => {
3935
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
3936
+ const entries = config.mcp ?? [];
3937
+ const index = entries.findIndex((entry) => normalizeMcpName(entry) === serverName);
3938
+ if (index < 0) {
3939
+ throw new Error(`MCP server "${serverName}" is not configured.`);
3940
+ }
3941
+ return { config, index };
3942
+ };
3943
+ var discoverMcpTools = async (workingDir, serverName) => {
3944
+ dotenv.config({ path: resolve3(workingDir, ".env") });
3945
+ const { config, index } = await resolveMcpEntry(workingDir, serverName);
3946
+ const entry = (config.mcp ?? [])[index];
3947
+ const bridge = new LocalMcpBridge({ mcp: [entry] });
3948
+ try {
3949
+ await bridge.startLocalServers();
3950
+ await bridge.discoverTools();
3951
+ return bridge.listDiscoveredTools(normalizeMcpName(entry));
3952
+ } finally {
3953
+ await bridge.stopLocalServers();
3954
+ }
3955
+ };
3956
+ var mcpToolsList = async (workingDir, serverName) => {
3957
+ const discovered = await discoverMcpTools(workingDir, serverName);
3958
+ if (discovered.length === 0) {
3959
+ process.stdout.write(`No tools discovered for MCP server "${serverName}".
3960
+ `);
3961
+ return;
3962
+ }
3963
+ process.stdout.write(`Discovered tools for "${serverName}":
3964
+ `);
3965
+ for (const tool of discovered) {
3966
+ process.stdout.write(`- ${tool}
3967
+ `);
3968
+ }
3969
+ };
3970
+ var mcpToolsSelect = async (workingDir, serverName, options) => {
3971
+ const discovered = await discoverMcpTools(workingDir, serverName);
3972
+ if (discovered.length === 0) {
3973
+ process.stdout.write(`No tools discovered for MCP server "${serverName}".
3974
+ `);
3975
+ return;
3976
+ }
3977
+ let selected = [];
3978
+ if (options.all) {
3979
+ selected = [...discovered];
3980
+ } else if (options.toolsCsv && options.toolsCsv.trim().length > 0) {
3981
+ const requested = options.toolsCsv.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
3982
+ selected = discovered.filter((tool) => requested.includes(tool));
3983
+ } else {
3984
+ process.stdout.write(`Discovered tools for "${serverName}":
3985
+ `);
3986
+ discovered.forEach((tool, idx) => {
3987
+ process.stdout.write(`${idx + 1}. ${tool}
3988
+ `);
3989
+ });
3990
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3991
+ const answer = await rl.question(
3992
+ "Enter comma-separated tool numbers/names to allow (or * for all): "
3993
+ );
3994
+ rl.close();
3995
+ const raw = answer.trim();
3996
+ if (raw === "*") {
3997
+ selected = [...discovered];
3998
+ } else {
3999
+ const tokens = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
4000
+ const fromIndex = tokens.map((token) => Number.parseInt(token, 10)).filter((value) => !Number.isNaN(value)).map((index2) => discovered[index2 - 1]).filter((value) => typeof value === "string");
4001
+ const byName = discovered.filter((tool) => tokens.includes(tool));
4002
+ selected = [.../* @__PURE__ */ new Set([...fromIndex, ...byName])];
4003
+ }
4004
+ }
4005
+ if (selected.length === 0) {
4006
+ throw new Error("No valid tools selected.");
4007
+ }
4008
+ const includePatterns = selected.length === discovered.length ? [`${serverName}/*`] : selected.sort();
4009
+ const { config, index } = await resolveMcpEntry(workingDir, serverName);
4010
+ const mcp = [...config.mcp ?? []];
4011
+ const existing = mcp[index];
4012
+ mcp[index] = {
4013
+ ...existing,
4014
+ tools: {
4015
+ ...existing.tools ?? {},
4016
+ mode: "allowlist",
4017
+ include: includePatterns
4018
+ }
4019
+ };
4020
+ await writeConfigFile(workingDir, { ...config, mcp });
4021
+ process.stdout.write(
4022
+ `Updated ${serverName} to allowlist ${includePatterns.join(", ")} in poncho.config.js.
4023
+ `
4024
+ );
4025
+ process.stdout.write(
4026
+ "\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"
4027
+ );
4028
+ process.stdout.write(
4029
+ "\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"
4030
+ );
4031
+ process.stdout.write(
4032
+ "\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"
4033
+ );
4034
+ };
4035
+ var buildCli = () => {
4036
+ const program = new Command();
4037
+ program.name("poncho").description("CLI for building and running Poncho agents").version("0.1.0");
4038
+ 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) => {
4039
+ await initProject(name, {
4040
+ onboarding: {
4041
+ yes: options.yes,
4042
+ interactive: !options.yes && process.stdin.isTTY === true && process.stdout.isTTY === true
4043
+ }
4044
+ });
4045
+ });
4046
+ program.command("dev").description("Run local development server").option("--port <port>", "server port", "3000").action(async (options) => {
4047
+ const port = Number.parseInt(options.port, 10);
4048
+ await startDevServer(Number.isNaN(port) ? 3e3 : port);
4049
+ });
4050
+ program.command("run").argument("[task]", "task to run").description("Execute the agent once").option("--param <keyValue>", "parameter key=value", (value, all) => {
4051
+ all.push(value);
4052
+ return all;
4053
+ }, []).option("--file <path>", "include file contents", (value, all) => {
4054
+ all.push(value);
4055
+ return all;
4056
+ }, []).option("--json", "output json", false).option("--interactive", "run in interactive mode", false).action(
4057
+ async (task, options) => {
4058
+ const params = parseParams(options.param);
4059
+ if (options.interactive) {
4060
+ await runInteractive(process.cwd(), params);
4061
+ return;
4062
+ }
4063
+ if (!task) {
4064
+ throw new Error("Task is required unless --interactive is used.");
4065
+ }
4066
+ await runOnce(task, {
4067
+ params,
4068
+ json: options.json,
4069
+ filePaths: options.file
4070
+ });
4071
+ }
4072
+ );
4073
+ program.command("tools").description("List all tools available to the agent").action(async () => {
4074
+ await listTools(process.cwd());
4075
+ });
4076
+ program.command("add").argument("<packageOrPath>", "skill package name/path").description("Add a skill package and validate SKILL.md").action(async (packageOrPath) => {
4077
+ await addSkill(process.cwd(), packageOrPath);
4078
+ });
4079
+ program.command("update-agent").description("Remove deprecated embedded local guidance from AGENT.md").action(async () => {
4080
+ await updateAgentGuidance(process.cwd());
4081
+ });
4082
+ program.command("test").argument("[file]", "test file path (yaml)").description("Run yaml-defined agent tests").action(async (file) => {
4083
+ const testFile = file ? resolve3(process.cwd(), file) : void 0;
4084
+ const result = await runTests(process.cwd(), testFile);
4085
+ if (result.failed > 0) {
4086
+ process.exitCode = 1;
4087
+ }
4088
+ });
4089
+ program.command("build").argument("<target>", "vercel|docker|lambda|fly").description("Generate build artifacts for deployment target").action(async (target) => {
4090
+ await buildTarget(process.cwd(), target);
4091
+ });
4092
+ const mcpCommand = program.command("mcp").description("Manage MCP servers");
4093
+ mcpCommand.command("add").requiredOption("--url <url>", "remote MCP url").option("--name <name>", "server name").option(
4094
+ "--auth-bearer-env <name>",
4095
+ "env var name containing bearer token for this MCP server"
4096
+ ).option("--env <name>", "env variable (repeatable)", (value, all) => {
4097
+ all.push(value);
4098
+ return all;
4099
+ }, []).action(
4100
+ async (options) => {
4101
+ await mcpAdd(process.cwd(), {
4102
+ url: options.url,
4103
+ name: options.name,
4104
+ envVars: options.env,
4105
+ authBearerEnv: options.authBearerEnv
4106
+ });
4107
+ }
4108
+ );
4109
+ mcpCommand.command("list").description("List configured MCP servers").action(async () => {
4110
+ await mcpList(process.cwd());
4111
+ });
4112
+ mcpCommand.command("remove").argument("<name>", "server name").description("Remove an MCP server by name").action(async (name) => {
4113
+ await mcpRemove(process.cwd(), name);
4114
+ });
4115
+ const mcpToolsCommand = mcpCommand.command("tools").description("Discover and curate tools for a configured MCP server");
4116
+ mcpToolsCommand.command("list").argument("<name>", "server name").description("Discover and list tools from a configured MCP server").action(async (name) => {
4117
+ await mcpToolsList(process.cwd(), name);
4118
+ });
4119
+ 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(
4120
+ async (name, options) => {
4121
+ await mcpToolsSelect(process.cwd(), name, {
4122
+ all: options.all,
4123
+ toolsCsv: options.tools
4124
+ });
4125
+ }
4126
+ );
4127
+ return program;
4128
+ };
4129
+ var main = async (argv = process.argv) => {
4130
+ try {
4131
+ await buildCli().parseAsync(argv);
4132
+ } catch (error) {
4133
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EADDRINUSE") {
4134
+ const message = "Port is already in use. Try `poncho dev --port 3001` or stop the process using port 3000.";
4135
+ process.stderr.write(`${message}
4136
+ `);
4137
+ process.exitCode = 1;
4138
+ return;
4139
+ }
4140
+ process.stderr.write(`${error instanceof Error ? error.message : "Unknown CLI error"}
4141
+ `);
4142
+ process.exitCode = 1;
4143
+ }
4144
+ };
4145
+ var packageRoot = resolve3(__dirname, "..");
4146
+
4147
+ export {
4148
+ inferConversationTitle,
4149
+ consumeFirstRunIntro,
4150
+ resolveHarnessEnvironment,
4151
+ initProject,
4152
+ updateAgentGuidance,
4153
+ createRequestHandler,
4154
+ startDevServer,
4155
+ runOnce,
4156
+ runInteractive,
4157
+ listTools,
4158
+ addSkill,
4159
+ runTests,
4160
+ buildTarget,
4161
+ mcpAdd,
4162
+ mcpList,
4163
+ mcpRemove,
4164
+ mcpToolsList,
4165
+ mcpToolsSelect,
4166
+ buildCli,
4167
+ main,
4168
+ packageRoot
4169
+ };