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