@poncho-ai/cli 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.turbo/turbo-build.log +7 -7
  2. package/dist/chunk-2TLKQG7R.js +5360 -0
  3. package/dist/chunk-3FY4LP2E.js +4981 -0
  4. package/dist/chunk-3WQANPEG.js +5086 -0
  5. package/dist/chunk-44DXWF6D.js +5450 -0
  6. package/dist/chunk-62G3MI43.js +5316 -0
  7. package/dist/chunk-6J2JICGH.js +5135 -0
  8. package/dist/chunk-6KLC6MWK.js +5357 -0
  9. package/dist/chunk-6LG2DUWF.js +5181 -0
  10. package/dist/chunk-ASAXSYEZ.js +5179 -0
  11. package/dist/chunk-B5B5LAR2.js +5181 -0
  12. package/dist/chunk-C7T4EJNQ.js +4934 -0
  13. package/dist/chunk-EPG7ZYDE.js +5452 -0
  14. package/dist/chunk-FMRRGTJX.js +5041 -0
  15. package/dist/chunk-HHMFEU26.js +5451 -0
  16. package/dist/chunk-JRJY6LUC.js +5178 -0
  17. package/dist/chunk-O7SJY7YQ.js +5177 -0
  18. package/dist/chunk-PYP4SKOI.js +5125 -0
  19. package/dist/chunk-VECWMU7E.js +5276 -0
  20. package/dist/chunk-XEBDWQI6.js +5178 -0
  21. package/dist/chunk-YW2D7Z22.js +5360 -0
  22. package/dist/chunk-YZXMEO2T.js +5177 -0
  23. package/dist/cli.js +1 -1
  24. package/dist/index.d.ts +18 -2
  25. package/dist/index.js +11 -1
  26. package/dist/run-interactive-ink-6EJ6Z5HE.js +494 -0
  27. package/dist/run-interactive-ink-72BHZB7Q.js +494 -0
  28. package/dist/run-interactive-ink-BNRIM52Y.js +494 -0
  29. package/dist/run-interactive-ink-BZNBOELJ.js +494 -0
  30. package/dist/run-interactive-ink-GODBXZF3.js +494 -0
  31. package/dist/run-interactive-ink-J4AISGNQ.js +494 -0
  32. package/dist/run-interactive-ink-K75SE2J2.js +494 -0
  33. package/dist/run-interactive-ink-M2XKKPIJ.js +494 -0
  34. package/dist/run-interactive-ink-MITWAF7L.js +494 -0
  35. package/dist/run-interactive-ink-NR5BRFUF.js +494 -0
  36. package/dist/run-interactive-ink-OGNG6UYE.js +494 -0
  37. package/dist/run-interactive-ink-P3VNJEXK.js +494 -0
  38. package/dist/run-interactive-ink-PHLW5YWV.js +494 -0
  39. package/dist/run-interactive-ink-PVU3XABN.js +494 -0
  40. package/dist/run-interactive-ink-SLSK7BY5.js +494 -0
  41. package/dist/run-interactive-ink-TRPYQYHG.js +494 -0
  42. package/dist/run-interactive-ink-U2RPRBIR.js +494 -0
  43. package/dist/run-interactive-ink-U2WTGZJ3.js +494 -0
  44. package/dist/run-interactive-ink-UHBFYNNB.js +494 -0
  45. package/dist/run-interactive-ink-XQDUN6OS.js +494 -0
  46. package/dist/run-interactive-ink-XUHSJCGH.js +494 -0
  47. package/package.json +1 -1
  48. package/src/index.ts +322 -27
  49. package/src/web-ui.ts +350 -33
  50. package/test/cli.test.ts +232 -1
@@ -0,0 +1,4981 @@
1
+ // src/index.ts
2
+ import { spawn } from "child_process";
3
+ import { access as access2, cp, mkdir as mkdir3, readFile as readFile3, readdir, stat, writeFile as writeFile3 } from "fs/promises";
4
+ import { existsSync } from "fs";
5
+ import {
6
+ createServer
7
+ } from "http";
8
+ import { basename as basename3, 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
+ 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 safeJsonPreview = (value) => {
1236
+ try {
1237
+ return JSON.stringify(value, (_, nestedValue) =>
1238
+ typeof nestedValue === "bigint" ? String(nestedValue) : nestedValue,
1239
+ );
1240
+ } catch {
1241
+ return "[unserializable input]";
1242
+ }
1243
+ };
1244
+
1245
+ const updatePendingApproval = (approvalId, updater) => {
1246
+ if (!approvalId || typeof updater !== "function") {
1247
+ return false;
1248
+ }
1249
+ const messages = state.activeMessages || [];
1250
+ for (const message of messages) {
1251
+ if (!message || !Array.isArray(message._pendingApprovals)) {
1252
+ continue;
1253
+ }
1254
+ const idx = message._pendingApprovals.findIndex((req) => req.approvalId === approvalId);
1255
+ if (idx < 0) {
1256
+ continue;
1257
+ }
1258
+ const next = updater(message._pendingApprovals[idx], message._pendingApprovals);
1259
+ if (next === null) {
1260
+ message._pendingApprovals.splice(idx, 1);
1261
+ } else if (next && typeof next === "object") {
1262
+ message._pendingApprovals[idx] = next;
1263
+ }
1264
+ return true;
1265
+ }
1266
+ return false;
1267
+ };
1268
+
1269
+ const toUiPendingApprovals = (pendingApprovals) => {
1270
+ if (!Array.isArray(pendingApprovals)) {
1271
+ return [];
1272
+ }
1273
+ return pendingApprovals
1274
+ .map((item) => {
1275
+ const approvalId =
1276
+ item && typeof item.approvalId === "string" ? item.approvalId : "";
1277
+ if (!approvalId) {
1278
+ return null;
1279
+ }
1280
+ const toolName = item && typeof item.tool === "string" ? item.tool : "tool";
1281
+ const preview = safeJsonPreview(item?.input ?? {});
1282
+ const inputPreview = preview.length > 600 ? preview.slice(0, 600) + "..." : preview;
1283
+ return {
1284
+ approvalId,
1285
+ tool: toolName,
1286
+ inputPreview,
1287
+ state: "pending",
1288
+ };
1289
+ })
1290
+ .filter(Boolean);
1291
+ };
1292
+
1293
+ const hydratePendingApprovals = (messages, pendingApprovals) => {
1294
+ const nextMessages = Array.isArray(messages) ? [...messages] : [];
1295
+ const pending = toUiPendingApprovals(pendingApprovals);
1296
+ if (pending.length === 0) {
1297
+ return nextMessages;
1298
+ }
1299
+ const toolLines = pending.map((request) => "- approval required \\x60" + request.tool + "\\x60");
1300
+ for (let idx = nextMessages.length - 1; idx >= 0; idx -= 1) {
1301
+ const message = nextMessages[idx];
1302
+ if (!message || message.role !== "assistant") {
1303
+ continue;
1304
+ }
1305
+ const metadata = message.metadata && typeof message.metadata === "object" ? message.metadata : {};
1306
+ const existingTimeline = Array.isArray(metadata.toolActivity) ? metadata.toolActivity : [];
1307
+ const mergedTimeline = [...existingTimeline];
1308
+ toolLines.forEach((line) => {
1309
+ if (!mergedTimeline.includes(line)) {
1310
+ mergedTimeline.push(line);
1311
+ }
1312
+ });
1313
+ nextMessages[idx] = {
1314
+ ...message,
1315
+ metadata: {
1316
+ ...metadata,
1317
+ toolActivity: mergedTimeline,
1318
+ },
1319
+ _pendingApprovals: pending,
1320
+ };
1321
+ return nextMessages;
1322
+ }
1323
+ nextMessages.push({
1324
+ role: "assistant",
1325
+ content: "",
1326
+ metadata: { toolActivity: toolLines },
1327
+ _pendingApprovals: pending,
1328
+ });
1329
+ return nextMessages;
1330
+ };
1331
+
1332
+ const formatDate = (epoch) => {
1333
+ try {
1334
+ const date = new Date(epoch);
1335
+ const now = new Date();
1336
+ const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
1337
+ const startOfDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
1338
+ const dayDiff = Math.floor((startOfToday - startOfDate) / 86400000);
1339
+ if (dayDiff === 0) {
1340
+ return "Today";
1341
+ }
1342
+ if (dayDiff === 1) {
1343
+ return "Yesterday";
1344
+ }
1345
+ if (dayDiff < 7 && dayDiff > 1) {
1346
+ return date.toLocaleDateString(undefined, { weekday: "short" });
1347
+ }
1348
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
1349
+ } catch {
1350
+ return "";
1351
+ }
1352
+ };
1353
+
1354
+ const isMobile = () => window.matchMedia("(max-width: 900px)").matches;
1355
+
1356
+ const setSidebarOpen = (open) => {
1357
+ if (!isMobile()) {
1358
+ elements.shell.classList.remove("sidebar-open");
1359
+ return;
1360
+ }
1361
+ elements.shell.classList.toggle("sidebar-open", open);
1362
+ };
1363
+
1364
+ const renderConversationList = () => {
1365
+ elements.list.innerHTML = "";
1366
+ for (const c of state.conversations) {
1367
+ const item = document.createElement("div");
1368
+ item.className = "conversation-item" + (c.conversationId === state.activeConversationId ? " active" : "");
1369
+ item.textContent = c.title;
1370
+
1371
+ const isConfirming = state.confirmDeleteId === c.conversationId;
1372
+ const deleteBtn = document.createElement("button");
1373
+ deleteBtn.className = "delete-btn" + (isConfirming ? " confirming" : "");
1374
+ deleteBtn.textContent = isConfirming ? "sure?" : "\\u00d7";
1375
+ deleteBtn.onclick = async (e) => {
1376
+ e.stopPropagation();
1377
+ if (!isConfirming) {
1378
+ state.confirmDeleteId = c.conversationId;
1379
+ renderConversationList();
1380
+ return;
1381
+ }
1382
+ await api("/api/conversations/" + c.conversationId, { method: "DELETE" });
1383
+ if (state.activeConversationId === c.conversationId) {
1384
+ state.activeConversationId = null;
1385
+ state.activeMessages = [];
1386
+ pushConversationUrl(null);
1387
+ elements.chatTitle.textContent = "";
1388
+ renderMessages([]);
1389
+ }
1390
+ state.confirmDeleteId = null;
1391
+ await loadConversations();
1392
+ };
1393
+ item.appendChild(deleteBtn);
1394
+
1395
+ item.onclick = async () => {
1396
+ // Clear any delete confirmation, but still navigate
1397
+ if (state.confirmDeleteId) {
1398
+ state.confirmDeleteId = null;
1399
+ }
1400
+ state.activeConversationId = c.conversationId;
1401
+ pushConversationUrl(c.conversationId);
1402
+ renderConversationList();
1403
+ await loadConversation(c.conversationId);
1404
+ if (isMobile()) setSidebarOpen(false);
1405
+ };
1406
+
1407
+ elements.list.appendChild(item);
1408
+ }
1409
+ };
1410
+
1411
+ const renderMessages = (messages, isStreaming = false) => {
1412
+ const createThinkingIndicator = () => {
1413
+ const spinner = document.createElement("span");
1414
+ spinner.className = "thinking-indicator";
1415
+ const starFrames = ["\u2736", "\u2738", "\u2739", "\u273A", "\u2739", "\u2737"];
1416
+ let frame = 0;
1417
+ spinner.textContent = starFrames[0];
1418
+ spinner._interval = setInterval(() => {
1419
+ frame = (frame + 1) % starFrames.length;
1420
+ spinner.textContent = starFrames[frame];
1421
+ }, 70);
1422
+ return spinner;
1423
+ };
1424
+
1425
+ elements.messages.innerHTML = "";
1426
+ if (!messages || !messages.length) {
1427
+ elements.messages.innerHTML = '<div class="empty-state"><div class="assistant-avatar">' + agentInitial + '</div><div>How can I help you today?</div></div>';
1428
+ return;
1429
+ }
1430
+ const col = document.createElement("div");
1431
+ col.className = "messages-column";
1432
+ messages.forEach((m, i) => {
1433
+ const row = document.createElement("div");
1434
+ row.className = "message-row " + m.role;
1435
+ if (m.role === "assistant") {
1436
+ const wrap = document.createElement("div");
1437
+ wrap.className = "assistant-wrap";
1438
+ wrap.innerHTML = '<div class="assistant-avatar">' + agentInitial + '</div>';
1439
+ const content = document.createElement("div");
1440
+ content.className = "assistant-content";
1441
+ const text = String(m.content || "");
1442
+ const isLastAssistant = i === messages.length - 1;
1443
+ const hasPendingApprovals =
1444
+ Array.isArray(m._pendingApprovals) && m._pendingApprovals.length > 0;
1445
+ const shouldRenderEmptyStreamingIndicator =
1446
+ isStreaming &&
1447
+ isLastAssistant &&
1448
+ !text &&
1449
+ (!Array.isArray(m._sections) || m._sections.length === 0) &&
1450
+ (!Array.isArray(m._currentTools) || m._currentTools.length === 0) &&
1451
+ !hasPendingApprovals;
1452
+
1453
+ if (m._error) {
1454
+ const errorEl = document.createElement("div");
1455
+ errorEl.className = "message-error";
1456
+ errorEl.innerHTML = "<strong>Error</strong><br>" + escapeHtml(m._error);
1457
+ content.appendChild(errorEl);
1458
+ } else if (shouldRenderEmptyStreamingIndicator) {
1459
+ content.appendChild(createThinkingIndicator());
1460
+ } else {
1461
+ // Check for sections in _sections (streaming) or metadata.sections (stored)
1462
+ const sections = m._sections || (m.metadata && m.metadata.sections);
1463
+ const pendingApprovals = Array.isArray(m._pendingApprovals) ? m._pendingApprovals : [];
1464
+
1465
+ if (sections && sections.length > 0) {
1466
+ let lastToolsSectionIndex = -1;
1467
+ for (let sectionIdx = sections.length - 1; sectionIdx >= 0; sectionIdx -= 1) {
1468
+ if (sections[sectionIdx] && sections[sectionIdx].type === "tools") {
1469
+ lastToolsSectionIndex = sectionIdx;
1470
+ break;
1471
+ }
1472
+ }
1473
+ // Render sections interleaved
1474
+ sections.forEach((section, sectionIdx) => {
1475
+ if (section.type === "text") {
1476
+ const textDiv = document.createElement("div");
1477
+ textDiv.innerHTML = renderAssistantMarkdown(section.content);
1478
+ content.appendChild(textDiv);
1479
+ } else if (section.type === "tools") {
1480
+ const sectionApprovals =
1481
+ !isStreaming &&
1482
+ pendingApprovals.length > 0 &&
1483
+ sectionIdx === lastToolsSectionIndex
1484
+ ? pendingApprovals
1485
+ : [];
1486
+ content.insertAdjacentHTML(
1487
+ "beforeend",
1488
+ renderToolActivity(section.content, sectionApprovals),
1489
+ );
1490
+ }
1491
+ });
1492
+ // While streaming, show current tools if any
1493
+ if (isStreaming && i === messages.length - 1 && m._currentTools && m._currentTools.length > 0) {
1494
+ content.insertAdjacentHTML(
1495
+ "beforeend",
1496
+ renderToolActivity(m._currentTools, m._pendingApprovals || []),
1497
+ );
1498
+ }
1499
+ // When reloading with unresolved approvals, show them even when not streaming
1500
+ if (!isStreaming && pendingApprovals.length > 0 && lastToolsSectionIndex < 0) {
1501
+ content.insertAdjacentHTML("beforeend", renderToolActivity([], m._pendingApprovals));
1502
+ }
1503
+ // Show current text being typed
1504
+ if (isStreaming && i === messages.length - 1 && m._currentText) {
1505
+ const textDiv = document.createElement("div");
1506
+ textDiv.innerHTML = renderAssistantMarkdown(m._currentText);
1507
+ content.appendChild(textDiv);
1508
+ }
1509
+ } else {
1510
+ // Fallback: render text and tools the old way (for old messages without sections)
1511
+ if (text) {
1512
+ const parsed = extractToolActivity(text);
1513
+ content.innerHTML = renderAssistantMarkdown(parsed.content);
1514
+ }
1515
+ const metadataToolActivity =
1516
+ m.metadata && Array.isArray(m.metadata.toolActivity)
1517
+ ? m.metadata.toolActivity
1518
+ : [];
1519
+ if (metadataToolActivity.length > 0 || pendingApprovals.length > 0) {
1520
+ content.insertAdjacentHTML(
1521
+ "beforeend",
1522
+ renderToolActivity(metadataToolActivity, pendingApprovals),
1523
+ );
1524
+ }
1525
+ }
1526
+ if (
1527
+ isStreaming &&
1528
+ isLastAssistant &&
1529
+ !hasPendingApprovals &&
1530
+ (!m._currentText || m._currentText.length === 0)
1531
+ ) {
1532
+ const waitIndicator = document.createElement("div");
1533
+ waitIndicator.appendChild(createThinkingIndicator());
1534
+ content.appendChild(waitIndicator);
1535
+ }
1536
+ }
1537
+ wrap.appendChild(content);
1538
+ row.appendChild(wrap);
1539
+ } else {
1540
+ row.innerHTML = '<div class="user-bubble">' + escapeHtml(m.content) + '</div>';
1541
+ }
1542
+ col.appendChild(row);
1543
+ });
1544
+ elements.messages.appendChild(col);
1545
+ elements.messages.scrollTop = elements.messages.scrollHeight;
1546
+ };
1547
+
1548
+ const loadConversations = async () => {
1549
+ const payload = await api("/api/conversations");
1550
+ state.conversations = payload.conversations || [];
1551
+ renderConversationList();
1552
+ };
1553
+
1554
+ const loadConversation = async (conversationId) => {
1555
+ const payload = await api("/api/conversations/" + encodeURIComponent(conversationId));
1556
+ elements.chatTitle.textContent = payload.conversation.title;
1557
+ state.activeMessages = hydratePendingApprovals(
1558
+ payload.conversation.messages || [],
1559
+ payload.conversation.pendingApprovals || payload.pendingApprovals || [],
1560
+ );
1561
+ renderMessages(state.activeMessages);
1562
+ elements.prompt.focus();
1563
+ };
1564
+
1565
+ const streamConversationEvents = (conversationId) => {
1566
+ return new Promise((resolve) => {
1567
+ const localMessages = state.activeMessages || [];
1568
+ let assistantMessage = localMessages[localMessages.length - 1];
1569
+ if (!assistantMessage || assistantMessage.role !== "assistant") {
1570
+ assistantMessage = {
1571
+ role: "assistant",
1572
+ content: "",
1573
+ _sections: [],
1574
+ _currentText: "",
1575
+ _currentTools: [],
1576
+ _pendingApprovals: [],
1577
+ metadata: { toolActivity: [] },
1578
+ };
1579
+ localMessages.push(assistantMessage);
1580
+ state.activeMessages = localMessages;
1581
+ }
1582
+ if (!assistantMessage._sections) assistantMessage._sections = [];
1583
+ if (!assistantMessage._currentText) assistantMessage._currentText = "";
1584
+ if (!assistantMessage._currentTools) assistantMessage._currentTools = [];
1585
+ if (!assistantMessage._pendingApprovals) assistantMessage._pendingApprovals = [];
1586
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1587
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1588
+
1589
+ const url = "/api/conversations/" + encodeURIComponent(conversationId) + "/events";
1590
+ fetch(url, { credentials: "include" }).then((response) => {
1591
+ if (!response.ok || !response.body) {
1592
+ resolve(undefined);
1593
+ return;
1594
+ }
1595
+ const reader = response.body.getReader();
1596
+ const decoder = new TextDecoder();
1597
+ let buffer = "";
1598
+ const processChunks = async () => {
1599
+ while (true) {
1600
+ const { value, done } = await reader.read();
1601
+ if (done) {
1602
+ break;
1603
+ }
1604
+ buffer += decoder.decode(value, { stream: true });
1605
+ buffer = parseSseChunk(buffer, (eventName, payload) => {
1606
+ try {
1607
+ if (eventName === "stream:end") {
1608
+ return;
1609
+ }
1610
+ if (eventName === "model:chunk") {
1611
+ const chunk = String(payload.content || "");
1612
+ if (assistantMessage._currentTools.length > 0 && chunk.length > 0) {
1613
+ assistantMessage._sections.push({
1614
+ type: "tools",
1615
+ content: assistantMessage._currentTools,
1616
+ });
1617
+ assistantMessage._currentTools = [];
1618
+ }
1619
+ assistantMessage.content += chunk;
1620
+ assistantMessage._currentText += chunk;
1621
+ renderMessages(localMessages, true);
1622
+ }
1623
+ if (eventName === "tool:started") {
1624
+ const toolName = payload.tool || "tool";
1625
+ if (assistantMessage._currentText.length > 0) {
1626
+ assistantMessage._sections.push({
1627
+ type: "text",
1628
+ content: assistantMessage._currentText,
1629
+ });
1630
+ assistantMessage._currentText = "";
1631
+ }
1632
+ const toolText = "- start \\x60" + toolName + "\\x60";
1633
+ assistantMessage._currentTools.push(toolText);
1634
+ assistantMessage.metadata.toolActivity.push(toolText);
1635
+ renderMessages(localMessages, true);
1636
+ }
1637
+ if (eventName === "tool:completed") {
1638
+ const toolName = payload.tool || "tool";
1639
+ const duration =
1640
+ typeof payload.duration === "number" ? payload.duration : null;
1641
+ const toolText =
1642
+ "- done \\x60" +
1643
+ toolName +
1644
+ "\\x60" +
1645
+ (duration !== null ? " (" + duration + "ms)" : "");
1646
+ assistantMessage._currentTools.push(toolText);
1647
+ assistantMessage.metadata.toolActivity.push(toolText);
1648
+ renderMessages(localMessages, true);
1649
+ }
1650
+ if (eventName === "tool:error") {
1651
+ const toolName = payload.tool || "tool";
1652
+ const errorMsg = payload.error || "unknown error";
1653
+ const toolText = "- error \\x60" + toolName + "\\x60: " + errorMsg;
1654
+ assistantMessage._currentTools.push(toolText);
1655
+ assistantMessage.metadata.toolActivity.push(toolText);
1656
+ renderMessages(localMessages, true);
1657
+ }
1658
+ if (eventName === "run:completed") {
1659
+ if (
1660
+ !assistantMessage.content ||
1661
+ assistantMessage.content.length === 0
1662
+ ) {
1663
+ assistantMessage.content = String(
1664
+ payload.result?.response || "",
1665
+ );
1666
+ }
1667
+ if (assistantMessage._currentTools.length > 0) {
1668
+ assistantMessage._sections.push({
1669
+ type: "tools",
1670
+ content: assistantMessage._currentTools,
1671
+ });
1672
+ assistantMessage._currentTools = [];
1673
+ }
1674
+ if (assistantMessage._currentText.length > 0) {
1675
+ assistantMessage._sections.push({
1676
+ type: "text",
1677
+ content: assistantMessage._currentText,
1678
+ });
1679
+ assistantMessage._currentText = "";
1680
+ }
1681
+ renderMessages(localMessages, false);
1682
+ }
1683
+ if (eventName === "run:error") {
1684
+ const errMsg =
1685
+ payload.error?.message || "Something went wrong";
1686
+ assistantMessage.content = "";
1687
+ assistantMessage._error = errMsg;
1688
+ renderMessages(localMessages, false);
1689
+ }
1690
+ } catch (error) {
1691
+ console.error("SSE reconnect event error:", eventName, error);
1692
+ }
1693
+ });
1694
+ }
1695
+ };
1696
+ processChunks().finally(() => {
1697
+ state.activeMessages = localMessages;
1698
+ resolve(undefined);
1699
+ });
1700
+ }).catch(() => {
1701
+ resolve(undefined);
1702
+ });
1703
+ });
1704
+ };
1705
+
1706
+ const createConversation = async (title, options = {}) => {
1707
+ const shouldLoadConversation = options.loadConversation !== false;
1708
+ const payload = await api("/api/conversations", {
1709
+ method: "POST",
1710
+ body: JSON.stringify(title ? { title } : {})
1711
+ });
1712
+ state.activeConversationId = payload.conversation.conversationId;
1713
+ state.confirmDeleteId = null;
1714
+ pushConversationUrl(state.activeConversationId);
1715
+ await loadConversations();
1716
+ if (shouldLoadConversation) {
1717
+ await loadConversation(state.activeConversationId);
1718
+ } else {
1719
+ elements.chatTitle.textContent = payload.conversation.title || "New conversation";
1720
+ }
1721
+ return state.activeConversationId;
1722
+ };
1723
+
1724
+ const parseSseChunk = (buffer, onEvent) => {
1725
+ let rest = buffer;
1726
+ while (true) {
1727
+ const index = rest.indexOf("\\n\\n");
1728
+ if (index < 0) {
1729
+ return rest;
1730
+ }
1731
+ const raw = rest.slice(0, index);
1732
+ rest = rest.slice(index + 2);
1733
+ const lines = raw.split("\\n");
1734
+ let eventName = "message";
1735
+ let data = "";
1736
+ for (const line of lines) {
1737
+ if (line.startsWith("event:")) {
1738
+ eventName = line.slice(6).trim();
1739
+ } else if (line.startsWith("data:")) {
1740
+ data += line.slice(5).trim();
1741
+ }
1742
+ }
1743
+ if (data) {
1744
+ try {
1745
+ onEvent(eventName, JSON.parse(data));
1746
+ } catch {}
1747
+ }
1748
+ }
1749
+ };
1750
+
1751
+ const setStreaming = (value) => {
1752
+ state.isStreaming = value;
1753
+ elements.send.disabled = value;
1754
+ };
1755
+
1756
+ const pushToolActivity = (assistantMessage, line) => {
1757
+ if (!line) {
1758
+ return;
1759
+ }
1760
+ if (
1761
+ !assistantMessage.metadata ||
1762
+ !Array.isArray(assistantMessage.metadata.toolActivity)
1763
+ ) {
1764
+ assistantMessage.metadata = {
1765
+ ...(assistantMessage.metadata || {}),
1766
+ toolActivity: [],
1767
+ };
1768
+ }
1769
+ assistantMessage.metadata.toolActivity.push(line);
1770
+ };
1771
+
1772
+ const autoResizePrompt = () => {
1773
+ const el = elements.prompt;
1774
+ el.style.height = "auto";
1775
+ const scrollHeight = el.scrollHeight;
1776
+ const nextHeight = Math.min(scrollHeight, 200);
1777
+ el.style.height = nextHeight + "px";
1778
+ el.style.overflowY = scrollHeight > 200 ? "auto" : "hidden";
1779
+ };
1780
+
1781
+ const sendMessage = async (text) => {
1782
+ const messageText = (text || "").trim();
1783
+ if (!messageText || state.isStreaming) {
1784
+ return;
1785
+ }
1786
+ const localMessages = [...(state.activeMessages || []), { role: "user", content: messageText }];
1787
+ let assistantMessage = {
1788
+ role: "assistant",
1789
+ content: "",
1790
+ _sections: [], // Array of {type: 'text'|'tools', content: string|array}
1791
+ _currentText: "",
1792
+ _currentTools: [],
1793
+ _pendingApprovals: [],
1794
+ metadata: { toolActivity: [] }
1795
+ };
1796
+ localMessages.push(assistantMessage);
1797
+ state.activeMessages = localMessages;
1798
+ renderMessages(localMessages, true);
1799
+ setStreaming(true);
1800
+ let conversationId = state.activeConversationId;
1801
+ try {
1802
+ if (!conversationId) {
1803
+ conversationId = await createConversation(messageText, { loadConversation: false });
1804
+ }
1805
+ const response = await fetch("/api/conversations/" + encodeURIComponent(conversationId) + "/messages", {
1806
+ method: "POST",
1807
+ credentials: "include",
1808
+ headers: { "Content-Type": "application/json", "x-csrf-token": state.csrfToken },
1809
+ body: JSON.stringify({ message: messageText })
1810
+ });
1811
+ if (!response.ok || !response.body) {
1812
+ throw new Error("Failed to stream response");
1813
+ }
1814
+ const reader = response.body.getReader();
1815
+ const decoder = new TextDecoder();
1816
+ let buffer = "";
1817
+ while (true) {
1818
+ const { value, done } = await reader.read();
1819
+ if (done) {
1820
+ break;
1821
+ }
1822
+ buffer += decoder.decode(value, { stream: true });
1823
+ buffer = parseSseChunk(buffer, (eventName, payload) => {
1824
+ try {
1825
+ if (eventName === "model:chunk") {
1826
+ const chunk = String(payload.content || "");
1827
+ // If we have tools accumulated and text starts again, push tools as a section
1828
+ if (assistantMessage._currentTools.length > 0 && chunk.length > 0) {
1829
+ assistantMessage._sections.push({ type: "tools", content: assistantMessage._currentTools });
1830
+ assistantMessage._currentTools = [];
1831
+ }
1832
+ assistantMessage.content += chunk;
1833
+ assistantMessage._currentText += chunk;
1834
+ renderMessages(localMessages, true);
1835
+ }
1836
+ if (eventName === "tool:started") {
1837
+ const toolName = payload.tool || "tool";
1838
+ // If we have text accumulated, push it as a text section
1839
+ if (assistantMessage._currentText.length > 0) {
1840
+ assistantMessage._sections.push({ type: "text", content: assistantMessage._currentText });
1841
+ assistantMessage._currentText = "";
1842
+ }
1843
+ const toolText = "- start \\x60" + toolName + "\\x60";
1844
+ assistantMessage._currentTools.push(toolText);
1845
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1846
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1847
+ assistantMessage.metadata.toolActivity.push(toolText);
1848
+ renderMessages(localMessages, true);
1849
+ }
1850
+ if (eventName === "tool:completed") {
1851
+ const toolName = payload.tool || "tool";
1852
+ const duration = typeof payload.duration === "number" ? payload.duration : null;
1853
+ const toolText = "- done \\x60" + toolName + "\\x60" + (duration !== null ? " (" + duration + "ms)" : "");
1854
+ assistantMessage._currentTools.push(toolText);
1855
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1856
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1857
+ assistantMessage.metadata.toolActivity.push(toolText);
1858
+ renderMessages(localMessages, true);
1859
+ }
1860
+ if (eventName === "tool:error") {
1861
+ const toolName = payload.tool || "tool";
1862
+ const errorMsg = payload.error || "unknown error";
1863
+ const toolText = "- error \\x60" + toolName + "\\x60: " + errorMsg;
1864
+ assistantMessage._currentTools.push(toolText);
1865
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1866
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1867
+ assistantMessage.metadata.toolActivity.push(toolText);
1868
+ renderMessages(localMessages, true);
1869
+ }
1870
+ if (eventName === "tool:approval:required") {
1871
+ const toolName = payload.tool || "tool";
1872
+ const toolText = "- approval required \\x60" + toolName + "\\x60";
1873
+ assistantMessage._currentTools.push(toolText);
1874
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1875
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1876
+ assistantMessage.metadata.toolActivity.push(toolText);
1877
+ const approvalId =
1878
+ typeof payload.approvalId === "string" ? payload.approvalId : "";
1879
+ if (approvalId) {
1880
+ const preview = safeJsonPreview(payload.input ?? {});
1881
+ const inputPreview = preview.length > 600 ? preview.slice(0, 600) + "..." : preview;
1882
+ if (!Array.isArray(assistantMessage._pendingApprovals)) {
1883
+ assistantMessage._pendingApprovals = [];
1884
+ }
1885
+ const exists = assistantMessage._pendingApprovals.some(
1886
+ (req) => req.approvalId === approvalId,
1887
+ );
1888
+ if (!exists) {
1889
+ assistantMessage._pendingApprovals.push({
1890
+ approvalId,
1891
+ tool: toolName,
1892
+ inputPreview,
1893
+ state: "pending",
1894
+ });
1895
+ }
1896
+ }
1897
+ renderMessages(localMessages, true);
1898
+ }
1899
+ if (eventName === "tool:approval:granted") {
1900
+ const toolText = "- approval granted";
1901
+ assistantMessage._currentTools.push(toolText);
1902
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1903
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1904
+ assistantMessage.metadata.toolActivity.push(toolText);
1905
+ const approvalId =
1906
+ typeof payload.approvalId === "string" ? payload.approvalId : "";
1907
+ if (approvalId && Array.isArray(assistantMessage._pendingApprovals)) {
1908
+ assistantMessage._pendingApprovals = assistantMessage._pendingApprovals.filter(
1909
+ (req) => req.approvalId !== approvalId,
1910
+ );
1911
+ }
1912
+ renderMessages(localMessages, true);
1913
+ }
1914
+ if (eventName === "tool:approval:denied") {
1915
+ const toolText = "- approval denied";
1916
+ assistantMessage._currentTools.push(toolText);
1917
+ if (!assistantMessage.metadata) assistantMessage.metadata = {};
1918
+ if (!assistantMessage.metadata.toolActivity) assistantMessage.metadata.toolActivity = [];
1919
+ assistantMessage.metadata.toolActivity.push(toolText);
1920
+ const approvalId =
1921
+ typeof payload.approvalId === "string" ? payload.approvalId : "";
1922
+ if (approvalId && Array.isArray(assistantMessage._pendingApprovals)) {
1923
+ assistantMessage._pendingApprovals = assistantMessage._pendingApprovals.filter(
1924
+ (req) => req.approvalId !== approvalId,
1925
+ );
1926
+ }
1927
+ renderMessages(localMessages, true);
1928
+ }
1929
+ if (eventName === "run:completed") {
1930
+ if (!assistantMessage.content || assistantMessage.content.length === 0) {
1931
+ assistantMessage.content = String(payload.result?.response || "");
1932
+ }
1933
+ // Finalize sections: push any remaining tools and text
1934
+ if (assistantMessage._currentTools.length > 0) {
1935
+ assistantMessage._sections.push({ type: "tools", content: assistantMessage._currentTools });
1936
+ assistantMessage._currentTools = [];
1937
+ }
1938
+ if (assistantMessage._currentText.length > 0) {
1939
+ assistantMessage._sections.push({ type: "text", content: assistantMessage._currentText });
1940
+ assistantMessage._currentText = "";
1941
+ }
1942
+ renderMessages(localMessages, false);
1943
+ }
1944
+ if (eventName === "run:error") {
1945
+ const errMsg = payload.error?.message || "Something went wrong";
1946
+ assistantMessage.content = "";
1947
+ assistantMessage._error = errMsg;
1948
+ renderMessages(localMessages, false);
1949
+ }
1950
+ } catch (error) {
1951
+ console.error("SSE event handling error:", eventName, error);
1952
+ }
1953
+ });
1954
+ }
1955
+ // Update the state with our local messages (don't reload and lose tool chips)
1956
+ state.activeMessages = localMessages;
1957
+ await loadConversations();
1958
+ // Don't reload the conversation - we already have the latest state with tool chips
1959
+ } finally {
1960
+ setStreaming(false);
1961
+ elements.prompt.focus();
1962
+ }
1963
+ };
1964
+
1965
+ const requireAuth = async () => {
1966
+ try {
1967
+ const session = await api("/api/auth/session");
1968
+ if (!session.authenticated) {
1969
+ elements.auth.classList.remove("hidden");
1970
+ elements.app.classList.add("hidden");
1971
+ return false;
1972
+ }
1973
+ state.csrfToken = session.csrfToken || "";
1974
+ elements.auth.classList.add("hidden");
1975
+ elements.app.classList.remove("hidden");
1976
+ return true;
1977
+ } catch {
1978
+ elements.auth.classList.remove("hidden");
1979
+ elements.app.classList.add("hidden");
1980
+ return false;
1981
+ }
1982
+ };
1983
+
1984
+ elements.loginForm.addEventListener("submit", async (event) => {
1985
+ event.preventDefault();
1986
+ elements.loginError.textContent = "";
1987
+ try {
1988
+ const result = await api("/api/auth/login", {
1989
+ method: "POST",
1990
+ body: JSON.stringify({ passphrase: elements.passphrase.value || "" })
1991
+ });
1992
+ state.csrfToken = result.csrfToken || "";
1993
+ elements.passphrase.value = "";
1994
+ elements.auth.classList.add("hidden");
1995
+ elements.app.classList.remove("hidden");
1996
+ await loadConversations();
1997
+ const urlConversationId = getConversationIdFromUrl();
1998
+ if (urlConversationId) {
1999
+ state.activeConversationId = urlConversationId;
2000
+ renderConversationList();
2001
+ try {
2002
+ await loadConversation(urlConversationId);
2003
+ } catch {
2004
+ state.activeConversationId = null;
2005
+ state.activeMessages = [];
2006
+ replaceConversationUrl(null);
2007
+ renderMessages([]);
2008
+ renderConversationList();
2009
+ }
2010
+ }
2011
+ } catch (error) {
2012
+ elements.loginError.textContent = error.message || "Login failed";
2013
+ }
2014
+ });
2015
+
2016
+ const startNewChat = () => {
2017
+ state.activeConversationId = null;
2018
+ state.activeMessages = [];
2019
+ state.confirmDeleteId = null;
2020
+ pushConversationUrl(null);
2021
+ elements.chatTitle.textContent = "";
2022
+ renderMessages([]);
2023
+ renderConversationList();
2024
+ elements.prompt.focus();
2025
+ if (isMobile()) {
2026
+ setSidebarOpen(false);
2027
+ }
2028
+ };
2029
+
2030
+ elements.newChat.addEventListener("click", startNewChat);
2031
+ elements.topbarNewChat.addEventListener("click", startNewChat);
2032
+
2033
+ elements.prompt.addEventListener("input", () => {
2034
+ autoResizePrompt();
2035
+ });
2036
+
2037
+ elements.prompt.addEventListener("keydown", (event) => {
2038
+ if (event.key === "Enter" && !event.shiftKey) {
2039
+ event.preventDefault();
2040
+ elements.composer.requestSubmit();
2041
+ }
2042
+ });
2043
+
2044
+ elements.sidebarToggle.addEventListener("click", () => {
2045
+ if (isMobile()) setSidebarOpen(!elements.shell.classList.contains("sidebar-open"));
2046
+ });
2047
+
2048
+ elements.sidebarBackdrop.addEventListener("click", () => setSidebarOpen(false));
2049
+
2050
+ elements.logout.addEventListener("click", async () => {
2051
+ await api("/api/auth/logout", { method: "POST" });
2052
+ state.activeConversationId = null;
2053
+ state.activeMessages = [];
2054
+ state.confirmDeleteId = null;
2055
+ state.conversations = [];
2056
+ state.csrfToken = "";
2057
+ await requireAuth();
2058
+ });
2059
+
2060
+ elements.composer.addEventListener("submit", async (event) => {
2061
+ event.preventDefault();
2062
+ const value = elements.prompt.value;
2063
+ elements.prompt.value = "";
2064
+ autoResizePrompt();
2065
+ await sendMessage(value);
2066
+ });
2067
+
2068
+ elements.messages.addEventListener("click", async (event) => {
2069
+ const target = event.target;
2070
+ if (!(target instanceof Element)) {
2071
+ return;
2072
+ }
2073
+ const button = target.closest(".approval-action-btn");
2074
+ if (!button) {
2075
+ return;
2076
+ }
2077
+ const approvalId = button.getAttribute("data-approval-id") || "";
2078
+ const decision = button.getAttribute("data-approval-decision") || "";
2079
+ if (!approvalId || (decision !== "approve" && decision !== "deny")) {
2080
+ return;
2081
+ }
2082
+ if (state.approvalRequestsInFlight[approvalId]) {
2083
+ return;
2084
+ }
2085
+ state.approvalRequestsInFlight[approvalId] = true;
2086
+ const wasStreaming = state.isStreaming;
2087
+ if (!wasStreaming) {
2088
+ setStreaming(true);
2089
+ }
2090
+ updatePendingApproval(approvalId, (request) => ({
2091
+ ...request,
2092
+ state: "submitting",
2093
+ pendingDecision: decision,
2094
+ }));
2095
+ renderMessages(state.activeMessages, state.isStreaming);
2096
+ try {
2097
+ await api("/api/approvals/" + encodeURIComponent(approvalId), {
2098
+ method: "POST",
2099
+ body: JSON.stringify({ approved: decision === "approve" }),
2100
+ });
2101
+ updatePendingApproval(approvalId, () => null);
2102
+ renderMessages(state.activeMessages, state.isStreaming);
2103
+ if (!wasStreaming && state.activeConversationId) {
2104
+ await streamConversationEvents(state.activeConversationId);
2105
+ }
2106
+ } catch (error) {
2107
+ const errMsg = error instanceof Error ? error.message : String(error);
2108
+ updatePendingApproval(approvalId, (request) => ({
2109
+ ...request,
2110
+ state: "pending",
2111
+ pendingDecision: null,
2112
+ inputPreview: String(request.inputPreview || "") + " (submit failed: " + errMsg + ")",
2113
+ }));
2114
+ renderMessages(state.activeMessages, state.isStreaming);
2115
+ } finally {
2116
+ if (!wasStreaming) {
2117
+ setStreaming(false);
2118
+ renderMessages(state.activeMessages, false);
2119
+ }
2120
+ delete state.approvalRequestsInFlight[approvalId];
2121
+ }
2122
+ });
2123
+
2124
+ document.addEventListener("click", (event) => {
2125
+ if (!(event.target instanceof Node)) {
2126
+ return;
2127
+ }
2128
+ if (!event.target.closest(".conversation-item") && state.confirmDeleteId) {
2129
+ state.confirmDeleteId = null;
2130
+ renderConversationList();
2131
+ }
2132
+ });
2133
+
2134
+ window.addEventListener("resize", () => {
2135
+ setSidebarOpen(false);
2136
+ });
2137
+
2138
+ const navigateToConversation = async (conversationId) => {
2139
+ if (conversationId) {
2140
+ state.activeConversationId = conversationId;
2141
+ renderConversationList();
2142
+ try {
2143
+ await loadConversation(conversationId);
2144
+ } catch {
2145
+ // Conversation not found \u2013 fall back to empty state
2146
+ state.activeConversationId = null;
2147
+ state.activeMessages = [];
2148
+ replaceConversationUrl(null);
2149
+ elements.chatTitle.textContent = "";
2150
+ renderMessages([]);
2151
+ renderConversationList();
2152
+ }
2153
+ } else {
2154
+ state.activeConversationId = null;
2155
+ state.activeMessages = [];
2156
+ elements.chatTitle.textContent = "";
2157
+ renderMessages([]);
2158
+ renderConversationList();
2159
+ }
2160
+ };
2161
+
2162
+ window.addEventListener("popstate", async () => {
2163
+ if (state.isStreaming) return;
2164
+ const conversationId = getConversationIdFromUrl();
2165
+ await navigateToConversation(conversationId);
2166
+ });
2167
+
2168
+ (async () => {
2169
+ const authenticated = await requireAuth();
2170
+ if (!authenticated) {
2171
+ return;
2172
+ }
2173
+ await loadConversations();
2174
+ const urlConversationId = getConversationIdFromUrl();
2175
+ if (urlConversationId) {
2176
+ state.activeConversationId = urlConversationId;
2177
+ replaceConversationUrl(urlConversationId);
2178
+ renderConversationList();
2179
+ try {
2180
+ await loadConversation(urlConversationId);
2181
+ } catch {
2182
+ // URL pointed to a conversation that no longer exists
2183
+ state.activeConversationId = null;
2184
+ state.activeMessages = [];
2185
+ replaceConversationUrl(null);
2186
+ elements.chatTitle.textContent = "";
2187
+ renderMessages([]);
2188
+ renderConversationList();
2189
+ if (state.conversations.length === 0) {
2190
+ await createConversation();
2191
+ }
2192
+ }
2193
+ } else if (state.conversations.length === 0) {
2194
+ await createConversation();
2195
+ }
2196
+ autoResizePrompt();
2197
+ elements.prompt.focus();
2198
+ })();
2199
+
2200
+ if ("serviceWorker" in navigator) {
2201
+ navigator.serviceWorker.register("/sw.js").catch(() => {});
2202
+ }
2203
+
2204
+ // Detect iOS standalone mode and add class for CSS targeting
2205
+ if (window.navigator.standalone === true || window.matchMedia("(display-mode: standalone)").matches) {
2206
+ document.documentElement.classList.add("standalone");
2207
+ }
2208
+
2209
+ // iOS viewport and keyboard handling
2210
+ (function() {
2211
+ var shell = document.querySelector(".shell");
2212
+ var pinScroll = function() { if (window.scrollY !== 0) window.scrollTo(0, 0); };
2213
+
2214
+ // Track the "full" height when keyboard is not open
2215
+ var fullHeight = window.innerHeight;
2216
+
2217
+ // Resize shell when iOS keyboard opens/closes
2218
+ var resizeForKeyboard = function() {
2219
+ if (!shell || !window.visualViewport) return;
2220
+ var vvHeight = window.visualViewport.height;
2221
+
2222
+ // Update fullHeight if viewport grew (keyboard closed)
2223
+ if (vvHeight > fullHeight) {
2224
+ fullHeight = vvHeight;
2225
+ }
2226
+
2227
+ // Only apply height override if keyboard appears to be open
2228
+ // (viewport significantly smaller than full height)
2229
+ if (vvHeight < fullHeight - 100) {
2230
+ shell.style.height = vvHeight + "px";
2231
+ } else {
2232
+ // Keyboard closed - remove override, let CSS handle it
2233
+ shell.style.height = "";
2234
+ }
2235
+ pinScroll();
2236
+ };
2237
+
2238
+ if (window.visualViewport) {
2239
+ window.visualViewport.addEventListener("scroll", pinScroll);
2240
+ window.visualViewport.addEventListener("resize", resizeForKeyboard);
2241
+ }
2242
+ document.addEventListener("scroll", pinScroll);
2243
+
2244
+ // Draggable sidebar from left edge (mobile only)
2245
+ (function() {
2246
+ var sidebar = document.querySelector(".sidebar");
2247
+ var backdrop = document.querySelector(".sidebar-backdrop");
2248
+ var shell = document.querySelector(".shell");
2249
+ if (!sidebar || !backdrop || !shell) return;
2250
+
2251
+ var sidebarWidth = 260;
2252
+ var edgeThreshold = 50; // px from left edge to start drag
2253
+ var velocityThreshold = 0.3; // px/ms to trigger open/close
2254
+
2255
+ var dragging = false;
2256
+ var startX = 0;
2257
+ var startY = 0;
2258
+ var currentX = 0;
2259
+ var startTime = 0;
2260
+ var isOpen = false;
2261
+ var directionLocked = false;
2262
+ var isHorizontal = false;
2263
+
2264
+ function getProgress() {
2265
+ // Returns 0 (closed) to 1 (open)
2266
+ if (isOpen) {
2267
+ return Math.max(0, Math.min(1, 1 + currentX / sidebarWidth));
2268
+ } else {
2269
+ return Math.max(0, Math.min(1, currentX / sidebarWidth));
2270
+ }
2271
+ }
2272
+
2273
+ function updatePosition(progress) {
2274
+ var offset = (progress - 1) * sidebarWidth;
2275
+ sidebar.style.transform = "translateX(" + offset + "px)";
2276
+ backdrop.style.opacity = progress;
2277
+ if (progress > 0) {
2278
+ backdrop.style.pointerEvents = "auto";
2279
+ } else {
2280
+ backdrop.style.pointerEvents = "none";
2281
+ }
2282
+ }
2283
+
2284
+ function onTouchStart(e) {
2285
+ if (window.innerWidth > 768) return;
2286
+
2287
+ // Don't intercept touches on interactive elements
2288
+ var target = e.target;
2289
+ if (target.closest("button") || target.closest("a") || target.closest("input") || target.closest("textarea")) {
2290
+ return;
2291
+ }
2292
+
2293
+ var touch = e.touches[0];
2294
+ isOpen = shell.classList.contains("sidebar-open");
2295
+
2296
+ // When sidebar is closed: only respond to edge swipes
2297
+ // When sidebar is open: only respond to backdrop touches (not sidebar content)
2298
+ var fromEdge = touch.clientX < edgeThreshold;
2299
+ var onBackdrop = e.target === backdrop;
2300
+
2301
+ if (!isOpen && !fromEdge) return;
2302
+ if (isOpen && !onBackdrop) return;
2303
+
2304
+ // Prevent Safari back gesture when starting from edge
2305
+ if (fromEdge) {
2306
+ e.preventDefault();
2307
+ }
2308
+
2309
+ startX = touch.clientX;
2310
+ startY = touch.clientY;
2311
+ currentX = 0;
2312
+ startTime = Date.now();
2313
+ directionLocked = false;
2314
+ isHorizontal = false;
2315
+ dragging = true;
2316
+ sidebar.classList.add("dragging");
2317
+ backdrop.classList.add("dragging");
2318
+ }
2319
+
2320
+ function onTouchMove(e) {
2321
+ if (!dragging) return;
2322
+ var touch = e.touches[0];
2323
+ var dx = touch.clientX - startX;
2324
+ var dy = touch.clientY - startY;
2325
+
2326
+ // Lock direction after some movement
2327
+ if (!directionLocked && (Math.abs(dx) > 10 || Math.abs(dy) > 10)) {
2328
+ directionLocked = true;
2329
+ isHorizontal = Math.abs(dx) > Math.abs(dy);
2330
+ if (!isHorizontal) {
2331
+ // Vertical scroll, cancel drag
2332
+ dragging = false;
2333
+ sidebar.classList.remove("dragging");
2334
+ backdrop.classList.remove("dragging");
2335
+ return;
2336
+ }
2337
+ }
2338
+
2339
+ if (!directionLocked) return;
2340
+
2341
+ // Prevent scrolling while dragging sidebar
2342
+ e.preventDefault();
2343
+
2344
+ currentX = dx;
2345
+ updatePosition(getProgress());
2346
+ }
2347
+
2348
+ function onTouchEnd(e) {
2349
+ if (!dragging) return;
2350
+ dragging = false;
2351
+ sidebar.classList.remove("dragging");
2352
+ backdrop.classList.remove("dragging");
2353
+
2354
+ var touch = e.changedTouches[0];
2355
+ var dx = touch.clientX - startX;
2356
+ var dt = Date.now() - startTime;
2357
+ var velocity = dx / dt; // px/ms
2358
+
2359
+ var progress = getProgress();
2360
+ var shouldOpen;
2361
+
2362
+ // Use velocity if fast enough, otherwise use position threshold
2363
+ if (Math.abs(velocity) > velocityThreshold) {
2364
+ shouldOpen = velocity > 0;
2365
+ } else {
2366
+ shouldOpen = progress > 0.5;
2367
+ }
2368
+
2369
+ // Reset inline styles and let CSS handle the animation
2370
+ sidebar.style.transform = "";
2371
+ backdrop.style.opacity = "";
2372
+ backdrop.style.pointerEvents = "";
2373
+
2374
+ if (shouldOpen) {
2375
+ shell.classList.add("sidebar-open");
2376
+ } else {
2377
+ shell.classList.remove("sidebar-open");
2378
+ }
2379
+ }
2380
+
2381
+ document.addEventListener("touchstart", onTouchStart, { passive: false });
2382
+ document.addEventListener("touchmove", onTouchMove, { passive: false });
2383
+ document.addEventListener("touchend", onTouchEnd, { passive: true });
2384
+ document.addEventListener("touchcancel", onTouchEnd, { passive: true });
2385
+ })();
2386
+
2387
+ // Prevent Safari back/forward navigation by manipulating history
2388
+ // This doesn't stop the gesture animation but prevents actual navigation
2389
+ if (window.navigator.standalone || window.matchMedia("(display-mode: standalone)").matches) {
2390
+ history.pushState(null, "", location.href);
2391
+ window.addEventListener("popstate", function() {
2392
+ history.pushState(null, "", location.href);
2393
+ });
2394
+ }
2395
+
2396
+ // Right edge blocker - intercept touch events to prevent forward navigation
2397
+ var rightBlocker = document.querySelector(".edge-blocker-right");
2398
+ if (rightBlocker) {
2399
+ rightBlocker.addEventListener("touchstart", function(e) {
2400
+ e.preventDefault();
2401
+ }, { passive: false });
2402
+ rightBlocker.addEventListener("touchmove", function(e) {
2403
+ e.preventDefault();
2404
+ }, { passive: false });
2405
+ }
2406
+ })();
2407
+
2408
+ </script>
2409
+ </body>
2410
+ </html>`;
2411
+ };
2412
+
2413
+ // src/index.ts
2414
+ import { createInterface } from "readline/promises";
2415
+
2416
+ // src/init-onboarding.ts
2417
+ import { stdin, stdout } from "process";
2418
+ import { input, password, select } from "@inquirer/prompts";
2419
+ import {
2420
+ fieldsForScope
2421
+ } from "@poncho-ai/sdk";
2422
+ var C = {
2423
+ reset: "\x1B[0m",
2424
+ bold: "\x1B[1m",
2425
+ dim: "\x1B[2m",
2426
+ cyan: "\x1B[36m"
2427
+ };
2428
+ var dim = (s) => `${C.dim}${s}${C.reset}`;
2429
+ var bold = (s) => `${C.bold}${s}${C.reset}`;
2430
+ var INPUT_CARET = "\xBB";
2431
+ var shouldAskField = (field, answers) => {
2432
+ if (!field.dependsOn) {
2433
+ return true;
2434
+ }
2435
+ const value = answers[field.dependsOn.fieldId];
2436
+ if (typeof field.dependsOn.equals !== "undefined") {
2437
+ return value === field.dependsOn.equals;
2438
+ }
2439
+ if (field.dependsOn.oneOf) {
2440
+ return field.dependsOn.oneOf.includes(value);
2441
+ }
2442
+ return true;
2443
+ };
2444
+ var parsePromptValue = (field, answer) => {
2445
+ if (field.kind === "boolean") {
2446
+ const normalized = answer.trim().toLowerCase();
2447
+ if (normalized === "y" || normalized === "yes" || normalized === "true") {
2448
+ return true;
2449
+ }
2450
+ if (normalized === "n" || normalized === "no" || normalized === "false") {
2451
+ return false;
2452
+ }
2453
+ return Boolean(field.defaultValue);
2454
+ }
2455
+ if (field.kind === "number") {
2456
+ const parsed = Number.parseInt(answer.trim(), 10);
2457
+ if (Number.isFinite(parsed)) {
2458
+ return parsed;
2459
+ }
2460
+ return Number(field.defaultValue);
2461
+ }
2462
+ if (field.kind === "select") {
2463
+ const trimmed2 = answer.trim();
2464
+ if (field.options && field.options.some((option) => option.value === trimmed2)) {
2465
+ return trimmed2;
2466
+ }
2467
+ const asNumber = Number.parseInt(trimmed2, 10);
2468
+ if (Number.isFinite(asNumber) && field.options && asNumber >= 1 && asNumber <= field.options.length) {
2469
+ return field.options[asNumber - 1]?.value ?? String(field.defaultValue);
2470
+ }
2471
+ return String(field.defaultValue);
2472
+ }
2473
+ const trimmed = answer.trim();
2474
+ if (trimmed.length === 0) {
2475
+ return String(field.defaultValue);
2476
+ }
2477
+ return trimmed;
2478
+ };
2479
+ var askSecret = async (field) => {
2480
+ if (!stdin.isTTY) {
2481
+ return void 0;
2482
+ }
2483
+ const hint = field.placeholder ? dim(` (${field.placeholder})`) : "";
2484
+ const message = `${field.prompt}${hint}`;
2485
+ const value = await password(
2486
+ {
2487
+ message,
2488
+ // true invisible input while typing/pasting
2489
+ mask: false,
2490
+ theme: {
2491
+ prefix: {
2492
+ idle: dim(INPUT_CARET),
2493
+ done: dim("\u2713")
2494
+ },
2495
+ style: {
2496
+ help: () => ""
2497
+ }
2498
+ }
2499
+ },
2500
+ { input: stdin, output: stdout }
2501
+ );
2502
+ return value ?? "";
2503
+ };
2504
+ var askSelectWithArrowKeys = async (field) => {
2505
+ if (!field.options || field.options.length === 0) {
2506
+ return void 0;
2507
+ }
2508
+ if (!stdin.isTTY) {
2509
+ return void 0;
2510
+ }
2511
+ const selected = await select(
2512
+ {
2513
+ message: field.prompt,
2514
+ choices: field.options.map((option) => ({
2515
+ name: option.label,
2516
+ value: option.value
2517
+ })),
2518
+ default: String(field.defaultValue),
2519
+ theme: {
2520
+ prefix: {
2521
+ idle: dim(INPUT_CARET),
2522
+ done: dim("\u2713")
2523
+ }
2524
+ }
2525
+ },
2526
+ { input: stdin, output: stdout }
2527
+ );
2528
+ return selected;
2529
+ };
2530
+ var askBooleanWithArrowKeys = async (field) => {
2531
+ if (!stdin.isTTY) {
2532
+ return void 0;
2533
+ }
2534
+ const selected = await select(
2535
+ {
2536
+ message: field.prompt,
2537
+ choices: [
2538
+ { name: "Yes", value: "true" },
2539
+ { name: "No", value: "false" }
2540
+ ],
2541
+ default: field.defaultValue ? "true" : "false",
2542
+ theme: {
2543
+ prefix: {
2544
+ idle: dim(INPUT_CARET),
2545
+ done: dim("\u2713")
2546
+ }
2547
+ }
2548
+ },
2549
+ { input: stdin, output: stdout }
2550
+ );
2551
+ return selected;
2552
+ };
2553
+ var askTextInput = async (field) => {
2554
+ if (!stdin.isTTY) {
2555
+ return void 0;
2556
+ }
2557
+ const answer = await input(
2558
+ {
2559
+ message: field.prompt,
2560
+ default: String(field.defaultValue ?? ""),
2561
+ theme: {
2562
+ prefix: {
2563
+ idle: dim(INPUT_CARET),
2564
+ done: dim("\u2713")
2565
+ }
2566
+ }
2567
+ },
2568
+ { input: stdin, output: stdout }
2569
+ );
2570
+ return answer;
2571
+ };
2572
+ var buildDefaultAnswers = () => {
2573
+ const answers = {};
2574
+ for (const field of fieldsForScope("light")) {
2575
+ answers[field.id] = field.defaultValue;
2576
+ }
2577
+ return answers;
2578
+ };
2579
+ var askOnboardingQuestions = async (options) => {
2580
+ const answers = buildDefaultAnswers();
2581
+ const interactive = options.yes === true ? false : options.interactive ?? (stdin.isTTY === true && stdout.isTTY === true);
2582
+ if (!interactive) {
2583
+ return answers;
2584
+ }
2585
+ stdout.write("\n");
2586
+ stdout.write(` ${bold("Poncho")} ${dim("\xB7 quick setup")}
2587
+ `);
2588
+ stdout.write("\n");
2589
+ const fields = fieldsForScope("light");
2590
+ for (const field of fields) {
2591
+ if (!shouldAskField(field, answers)) {
2592
+ continue;
2593
+ }
2594
+ stdout.write("\n");
2595
+ let value;
2596
+ if (field.secret) {
2597
+ value = await askSecret(field);
2598
+ } else if (field.kind === "select") {
2599
+ value = await askSelectWithArrowKeys(field);
2600
+ } else if (field.kind === "boolean") {
2601
+ value = await askBooleanWithArrowKeys(field);
2602
+ } else {
2603
+ value = await askTextInput(field);
2604
+ }
2605
+ if (!value || value.trim().length === 0) {
2606
+ continue;
2607
+ }
2608
+ answers[field.id] = parsePromptValue(field, value);
2609
+ }
2610
+ return answers;
2611
+ };
2612
+ var getProviderModelName = (provider) => provider === "openai" ? "gpt-4.1" : "claude-opus-4-5";
2613
+ var maybeSet = (target, key, value) => {
2614
+ if (typeof value === "string" && value.trim().length === 0) {
2615
+ return;
2616
+ }
2617
+ if (typeof value === "undefined") {
2618
+ return;
2619
+ }
2620
+ target[key] = value;
2621
+ };
2622
+ var buildConfigFromOnboardingAnswers = (answers) => {
2623
+ const storageProvider = String(answers["storage.provider"] ?? "local");
2624
+ const memoryEnabled = Boolean(answers["storage.memory.enabled"] ?? true);
2625
+ const maxRecallConversations = Number(
2626
+ answers["storage.memory.maxRecallConversations"] ?? 20
2627
+ );
2628
+ const storage = {
2629
+ provider: storageProvider,
2630
+ memory: {
2631
+ enabled: memoryEnabled,
2632
+ maxRecallConversations
2633
+ }
2634
+ };
2635
+ maybeSet(storage, "url", answers["storage.url"]);
2636
+ maybeSet(storage, "token", answers["storage.token"]);
2637
+ maybeSet(storage, "table", answers["storage.table"]);
2638
+ maybeSet(storage, "region", answers["storage.region"]);
2639
+ const authRequired = Boolean(answers["auth.required"] ?? false);
2640
+ const authType = answers["auth.type"] ?? "bearer";
2641
+ const auth = {
2642
+ required: authRequired,
2643
+ type: authType
2644
+ };
2645
+ if (authType === "header") {
2646
+ maybeSet(auth, "headerName", answers["auth.headerName"]);
2647
+ }
2648
+ const telemetryEnabled = Boolean(answers["telemetry.enabled"] ?? true);
2649
+ const telemetry = {
2650
+ enabled: telemetryEnabled
2651
+ };
2652
+ maybeSet(telemetry, "otlp", answers["telemetry.otlp"]);
2653
+ return {
2654
+ mcp: [],
2655
+ auth,
2656
+ storage,
2657
+ telemetry
2658
+ };
2659
+ };
2660
+ var collectEnvVars = (answers) => {
2661
+ const envVars = /* @__PURE__ */ new Set();
2662
+ const provider = String(answers["model.provider"] ?? "anthropic");
2663
+ if (provider === "openai") {
2664
+ envVars.add("OPENAI_API_KEY=sk-...");
2665
+ } else {
2666
+ envVars.add("ANTHROPIC_API_KEY=sk-ant-...");
2667
+ }
2668
+ const storageProvider = String(answers["storage.provider"] ?? "local");
2669
+ if (storageProvider === "redis") {
2670
+ envVars.add("REDIS_URL=redis://localhost:6379");
2671
+ }
2672
+ if (storageProvider === "upstash") {
2673
+ envVars.add("UPSTASH_REDIS_REST_URL=https://...");
2674
+ envVars.add("UPSTASH_REDIS_REST_TOKEN=...");
2675
+ }
2676
+ if (storageProvider === "dynamodb") {
2677
+ envVars.add("PONCHO_DYNAMODB_TABLE=poncho-conversations");
2678
+ envVars.add("AWS_REGION=us-east-1");
2679
+ }
2680
+ const authRequired = Boolean(answers["auth.required"] ?? false);
2681
+ if (authRequired) {
2682
+ envVars.add("PONCHO_AUTH_TOKEN=...");
2683
+ }
2684
+ return Array.from(envVars);
2685
+ };
2686
+ var collectEnvFileLines = (answers) => {
2687
+ const lines = [
2688
+ "# Poncho environment configuration",
2689
+ "# Fill in empty values before running `poncho dev` or `poncho run --interactive`.",
2690
+ "# Tip: keep secrets in `.env` only (never commit them).",
2691
+ ""
2692
+ ];
2693
+ const modelProvider = String(answers["model.provider"] ?? "anthropic");
2694
+ const modelEnvKey = modelProvider === "openai" ? "env.OPENAI_API_KEY" : "env.ANTHROPIC_API_KEY";
2695
+ const modelEnvVar = modelProvider === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY";
2696
+ const modelEnvValue = String(answers[modelEnvKey] ?? "");
2697
+ lines.push("# Model");
2698
+ if (modelEnvValue.length === 0) {
2699
+ lines.push(
2700
+ 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"
2701
+ );
2702
+ }
2703
+ lines.push(`${modelEnvVar}=${modelEnvValue}`);
2704
+ lines.push("");
2705
+ const authRequired = Boolean(answers["auth.required"] ?? false);
2706
+ const authType = answers["auth.type"] ?? "bearer";
2707
+ const authHeaderName = String(answers["auth.headerName"] ?? "x-poncho-key");
2708
+ if (authRequired) {
2709
+ lines.push("# Auth (protects both Web UI and API)");
2710
+ lines.push("# Web UI: enter this token as the passphrase");
2711
+ if (authType === "bearer") {
2712
+ lines.push("# API: include Authorization: Bearer <token> header");
2713
+ } else if (authType === "header") {
2714
+ lines.push(`# API: include ${authHeaderName}: <token> header`);
2715
+ } else {
2716
+ lines.push("# Custom auth mode: read this token in your auth.validate function.");
2717
+ }
2718
+ lines.push("PONCHO_AUTH_TOKEN=");
2719
+ lines.push("");
2720
+ }
2721
+ const storageProvider = String(answers["storage.provider"] ?? "local");
2722
+ if (storageProvider === "redis") {
2723
+ lines.push("# Storage (Redis)");
2724
+ lines.push("# Run local Redis: docker run -p 6379:6379 redis:7");
2725
+ lines.push("# Or use a managed Redis URL from your cloud provider.");
2726
+ lines.push("REDIS_URL=");
2727
+ lines.push("");
2728
+ } else if (storageProvider === "upstash") {
2729
+ lines.push("# Storage (Upstash)");
2730
+ lines.push("# Create a Redis database at https://console.upstash.com/");
2731
+ lines.push("# Copy REST URL + REST TOKEN from the Upstash dashboard.");
2732
+ lines.push("UPSTASH_REDIS_REST_URL=");
2733
+ lines.push("UPSTASH_REDIS_REST_TOKEN=");
2734
+ lines.push("");
2735
+ } else if (storageProvider === "dynamodb") {
2736
+ lines.push("# Storage (DynamoDB)");
2737
+ lines.push("# Create a DynamoDB table for Poncho conversation/state storage.");
2738
+ lines.push("# Ensure AWS credentials are configured (AWS_PROFILE or access keys).");
2739
+ lines.push("PONCHO_DYNAMODB_TABLE=");
2740
+ lines.push("AWS_REGION=");
2741
+ lines.push("");
2742
+ } else if (storageProvider === "local" || storageProvider === "memory") {
2743
+ lines.push(
2744
+ storageProvider === "local" ? "# Storage (Local file): no extra env vars required." : "# Storage (In-memory): no extra env vars required, data resets on restart."
2745
+ );
2746
+ lines.push("");
2747
+ }
2748
+ const telemetryEnabled = Boolean(answers["telemetry.enabled"] ?? true);
2749
+ if (telemetryEnabled) {
2750
+ lines.push("# Telemetry (optional)");
2751
+ lines.push("# Latitude telemetry setup: https://docs.latitude.so/");
2752
+ lines.push("# If not using Latitude yet, you can leave these empty.");
2753
+ lines.push("LATITUDE_API_KEY=");
2754
+ lines.push("LATITUDE_PROJECT_ID=");
2755
+ lines.push("LATITUDE_PATH=");
2756
+ lines.push("");
2757
+ }
2758
+ while (lines.length > 0 && lines[lines.length - 1] === "") {
2759
+ lines.pop();
2760
+ }
2761
+ return lines;
2762
+ };
2763
+ var runInitOnboarding = async (options) => {
2764
+ const answers = await askOnboardingQuestions(options);
2765
+ const provider = String(answers["model.provider"] ?? "anthropic");
2766
+ const config = buildConfigFromOnboardingAnswers(answers);
2767
+ const envExampleLines = collectEnvVars(answers);
2768
+ const envFileLines = collectEnvFileLines(answers);
2769
+ const envNeedsUserInput = envFileLines.some(
2770
+ (line) => line.includes("=") && !line.startsWith("#") && line.endsWith("=")
2771
+ );
2772
+ return {
2773
+ answers,
2774
+ config,
2775
+ envExample: `${envExampleLines.join("\n")}
2776
+ `,
2777
+ envFile: envFileLines.length > 0 ? `${envFileLines.join("\n")}
2778
+ ` : "",
2779
+ envNeedsUserInput,
2780
+ agentModel: {
2781
+ provider: provider === "openai" ? "openai" : "anthropic",
2782
+ name: getProviderModelName(provider)
2783
+ }
2784
+ };
2785
+ };
2786
+
2787
+ // src/init-feature-context.ts
2788
+ import { createHash as createHash2 } from "crypto";
2789
+ import { access, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
2790
+ import { basename as basename2, dirname as dirname2, resolve as resolve2 } from "path";
2791
+ import { homedir as homedir2 } from "os";
2792
+ var ONBOARDING_VERSION = 1;
2793
+ var getStateDirectory = () => {
2794
+ const cwd = process.cwd();
2795
+ const home = homedir2();
2796
+ 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";
2797
+ if (isServerless) {
2798
+ return "/tmp/.poncho/state";
2799
+ }
2800
+ return resolve2(homedir2(), ".poncho", "state");
2801
+ };
2802
+ var summarizeConfig = (config) => {
2803
+ const provider = config?.storage?.provider ?? config?.state?.provider ?? "local";
2804
+ const memoryEnabled = config?.storage?.memory?.enabled ?? config?.memory?.enabled ?? false;
2805
+ const authRequired = config?.auth?.required ?? false;
2806
+ const telemetryEnabled = config?.telemetry?.enabled ?? true;
2807
+ return [
2808
+ `storage: ${provider}`,
2809
+ `memory tools: ${memoryEnabled ? "enabled" : "disabled"}`,
2810
+ `auth: ${authRequired ? "required" : "not required"}`,
2811
+ `telemetry: ${telemetryEnabled ? "enabled" : "disabled"}`
2812
+ ];
2813
+ };
2814
+ var getOnboardingMarkerPath = (workingDir) => resolve2(
2815
+ getStateDirectory(),
2816
+ `${basename2(workingDir).replace(/[^a-zA-Z0-9_-]+/g, "-") || "project"}-${createHash2("sha256").update(workingDir).digest("hex").slice(0, 12)}-onboarding.json`
2817
+ );
2818
+ var readMarker = async (workingDir) => {
2819
+ const markerPath = getOnboardingMarkerPath(workingDir);
2820
+ try {
2821
+ await access(markerPath);
2822
+ } catch {
2823
+ return void 0;
2824
+ }
2825
+ try {
2826
+ const raw = await readFile2(markerPath, "utf8");
2827
+ return JSON.parse(raw);
2828
+ } catch {
2829
+ return void 0;
2830
+ }
2831
+ };
2832
+ var writeMarker = async (workingDir, state) => {
2833
+ const markerPath = getOnboardingMarkerPath(workingDir);
2834
+ await mkdir2(dirname2(markerPath), { recursive: true });
2835
+ await writeFile2(markerPath, JSON.stringify(state, null, 2), "utf8");
2836
+ };
2837
+ var initializeOnboardingMarker = async (workingDir, options) => {
2838
+ const current = await readMarker(workingDir);
2839
+ if (current) {
2840
+ return;
2841
+ }
2842
+ const allowIntro = options?.allowIntro ?? true;
2843
+ await writeMarker(workingDir, {
2844
+ introduced: allowIntro ? false : true,
2845
+ allowIntro,
2846
+ onboardingVersion: ONBOARDING_VERSION,
2847
+ createdAt: Date.now()
2848
+ });
2849
+ };
2850
+ var consumeFirstRunIntro = async (workingDir, input2) => {
2851
+ const runtimeEnv = resolveHarnessEnvironment();
2852
+ if (runtimeEnv === "production") {
2853
+ return void 0;
2854
+ }
2855
+ const marker = await readMarker(workingDir);
2856
+ if (marker?.allowIntro === false) {
2857
+ return void 0;
2858
+ }
2859
+ const shouldShow = !marker || marker.introduced === false;
2860
+ if (!shouldShow) {
2861
+ return void 0;
2862
+ }
2863
+ await writeMarker(workingDir, {
2864
+ introduced: true,
2865
+ allowIntro: true,
2866
+ onboardingVersion: ONBOARDING_VERSION,
2867
+ createdAt: marker?.createdAt ?? Date.now(),
2868
+ introducedAt: Date.now()
2869
+ });
2870
+ const summary = summarizeConfig(input2.config);
2871
+ return [
2872
+ `Hi! I'm **${input2.agentName}**. I can configure myself directly by chat.
2873
+ `,
2874
+ `**Current config**`,
2875
+ ` Model: ${input2.provider}/${input2.model}`,
2876
+ ` \`\`\`${summary.join(" \xB7 ")}\`\`\``,
2877
+ "",
2878
+ "Feel free to ask me anything when you're ready. I can help you:",
2879
+ "",
2880
+ "- **Build skills**: Create custom tools and capabilities for this agent",
2881
+ "- **Configure the model**: Switch providers (OpenAI, Anthropic, etc.) or models",
2882
+ "- **Set up storage**: Use local files, Upstash, or other backends",
2883
+ "- **Enable auth**: Add bearer tokens or custom authentication",
2884
+ "- **Turn on telemetry**: Track usage with OpenTelemetry/OTLP",
2885
+ "- **Add MCP servers**: Connect external tool servers",
2886
+ "",
2887
+ "Just let me know what you'd like to work on!\n"
2888
+ ].join("\n");
2889
+ };
2890
+
2891
+ // src/index.ts
2892
+ var __dirname = dirname3(fileURLToPath(import.meta.url));
2893
+ var require3 = createRequire2(import.meta.url);
2894
+ var writeJson = (response, statusCode, payload) => {
2895
+ response.writeHead(statusCode, { "Content-Type": "application/json" });
2896
+ response.end(JSON.stringify(payload));
2897
+ };
2898
+ var writeHtml = (response, statusCode, payload) => {
2899
+ response.writeHead(statusCode, { "Content-Type": "text/html; charset=utf-8" });
2900
+ response.end(payload);
2901
+ };
2902
+ var readRequestBody = async (request) => {
2903
+ const chunks = [];
2904
+ for await (const chunk of request) {
2905
+ chunks.push(Buffer.from(chunk));
2906
+ }
2907
+ const body = Buffer.concat(chunks).toString("utf8");
2908
+ return body.length > 0 ? JSON.parse(body) : {};
2909
+ };
2910
+ var resolveHarnessEnvironment = () => {
2911
+ if (process.env.PONCHO_ENV) {
2912
+ const value = process.env.PONCHO_ENV.toLowerCase();
2913
+ if (value === "production" || value === "staging") {
2914
+ return value;
2915
+ }
2916
+ return "development";
2917
+ }
2918
+ if (process.env.VERCEL_ENV) {
2919
+ const vercelEnv = process.env.VERCEL_ENV.toLowerCase();
2920
+ if (vercelEnv === "production") return "production";
2921
+ if (vercelEnv === "preview") return "staging";
2922
+ return "development";
2923
+ }
2924
+ if (process.env.RAILWAY_ENVIRONMENT) {
2925
+ const railwayEnv = process.env.RAILWAY_ENVIRONMENT.toLowerCase();
2926
+ if (railwayEnv === "production") return "production";
2927
+ return "staging";
2928
+ }
2929
+ if (process.env.RENDER) {
2930
+ if (process.env.IS_PULL_REQUEST === "true") return "staging";
2931
+ return "production";
2932
+ }
2933
+ if (process.env.AWS_EXECUTION_ENV || process.env.AWS_LAMBDA_FUNCTION_NAME) {
2934
+ return "production";
2935
+ }
2936
+ if (process.env.FLY_APP_NAME) {
2937
+ return "production";
2938
+ }
2939
+ if (process.env.NODE_ENV) {
2940
+ const value = process.env.NODE_ENV.toLowerCase();
2941
+ if (value === "production" || value === "staging") {
2942
+ return value;
2943
+ }
2944
+ return "development";
2945
+ }
2946
+ return "development";
2947
+ };
2948
+ var listenOnAvailablePort = async (server, preferredPort) => await new Promise((resolveListen, rejectListen) => {
2949
+ let currentPort = preferredPort;
2950
+ const tryListen = () => {
2951
+ const onListening = () => {
2952
+ server.off("error", onError);
2953
+ const address = server.address();
2954
+ if (address && typeof address === "object" && typeof address.port === "number") {
2955
+ resolveListen(address.port);
2956
+ return;
2957
+ }
2958
+ resolveListen(currentPort);
2959
+ };
2960
+ const onError = (error) => {
2961
+ server.off("listening", onListening);
2962
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EADDRINUSE") {
2963
+ currentPort += 1;
2964
+ if (currentPort > 65535) {
2965
+ rejectListen(
2966
+ new Error(
2967
+ "No available ports found from the requested port up to 65535."
2968
+ )
2969
+ );
2970
+ return;
2971
+ }
2972
+ setImmediate(tryListen);
2973
+ return;
2974
+ }
2975
+ rejectListen(error);
2976
+ };
2977
+ server.once("listening", onListening);
2978
+ server.once("error", onError);
2979
+ server.listen(currentPort);
2980
+ };
2981
+ tryListen();
2982
+ });
2983
+ var parseParams = (values) => {
2984
+ const params = {};
2985
+ for (const value of values) {
2986
+ const [key, ...rest] = value.split("=");
2987
+ if (!key) {
2988
+ continue;
2989
+ }
2990
+ params[key] = rest.join("=");
2991
+ }
2992
+ return params;
2993
+ };
2994
+ var AGENT_TEMPLATE = (name, options) => `---
2995
+ name: ${name}
2996
+ description: A helpful Poncho assistant
2997
+ model:
2998
+ provider: ${options.modelProvider}
2999
+ name: ${options.modelName}
3000
+ temperature: 0.2
3001
+ limits:
3002
+ maxSteps: 50
3003
+ timeout: 300
3004
+ ---
3005
+
3006
+ # {{name}}
3007
+
3008
+ You are **{{name}}**, a helpful assistant built with Poncho.
3009
+
3010
+ Working directory: {{runtime.workingDir}}
3011
+ Environment: {{runtime.environment}}
3012
+
3013
+ ## Task Guidance
3014
+
3015
+ - Use tools when needed
3016
+ - Explain your reasoning clearly
3017
+ - Ask clarifying questions when requirements are ambiguous
3018
+ - Never claim a file/tool change unless the corresponding tool call actually succeeded
3019
+ `;
3020
+ var resolveLocalPackagesRoot = () => {
3021
+ const candidate = resolve3(__dirname, "..", "..", "harness", "package.json");
3022
+ if (existsSync(candidate)) {
3023
+ return resolve3(__dirname, "..", "..");
3024
+ }
3025
+ return null;
3026
+ };
3027
+ var resolveCoreDeps = (projectDir) => {
3028
+ const packagesRoot = resolveLocalPackagesRoot();
3029
+ if (packagesRoot) {
3030
+ const harnessAbs = resolve3(packagesRoot, "harness");
3031
+ const sdkAbs = resolve3(packagesRoot, "sdk");
3032
+ return {
3033
+ harness: `link:${relative(projectDir, harnessAbs)}`,
3034
+ sdk: `link:${relative(projectDir, sdkAbs)}`
3035
+ };
3036
+ }
3037
+ return { harness: "^0.1.0", sdk: "^0.1.0" };
3038
+ };
3039
+ var PACKAGE_TEMPLATE = (name, projectDir) => {
3040
+ const deps = resolveCoreDeps(projectDir);
3041
+ return JSON.stringify(
3042
+ {
3043
+ name,
3044
+ private: true,
3045
+ type: "module",
3046
+ dependencies: {
3047
+ "@poncho-ai/harness": deps.harness,
3048
+ "@poncho-ai/sdk": deps.sdk
3049
+ }
3050
+ },
3051
+ null,
3052
+ 2
3053
+ );
3054
+ };
3055
+ var README_TEMPLATE = (name) => `# ${name}
3056
+
3057
+ An AI agent built with [Poncho](https://github.com/cesr/poncho-ai).
3058
+
3059
+ ## Prerequisites
3060
+
3061
+ - Node.js 20+
3062
+ - npm (or pnpm/yarn)
3063
+ - Anthropic or OpenAI API key
3064
+
3065
+ ## Quick Start
3066
+
3067
+ \`\`\`bash
3068
+ npm install
3069
+ # If you didn't enter an API key during init:
3070
+ cp .env.example .env
3071
+ # Then edit .env and add your API key
3072
+ poncho dev
3073
+ \`\`\`
3074
+
3075
+ Open \`http://localhost:3000\` for the web UI.
3076
+
3077
+ On your first interactive session, the agent introduces its configurable capabilities.
3078
+
3079
+ ## Common Commands
3080
+
3081
+ \`\`\`bash
3082
+ # Local web UI + API server
3083
+ poncho dev
3084
+
3085
+ # Local interactive CLI
3086
+ poncho run --interactive
3087
+
3088
+ # One-off run
3089
+ poncho run "Your task here"
3090
+
3091
+ # Run tests
3092
+ poncho test
3093
+
3094
+ # List available tools
3095
+ poncho tools
3096
+ \`\`\`
3097
+
3098
+ ## Add Skills
3099
+
3100
+ Install skills from a local path or remote repository, then verify discovery:
3101
+
3102
+ \`\`\`bash
3103
+ # Install skills into ./skills
3104
+ poncho add <repo-or-path>
3105
+
3106
+ # Verify loaded tools
3107
+ poncho tools
3108
+ \`\`\`
3109
+
3110
+ \`poncho add\` copies discovered skill directories (folders that contain \`SKILL.md\`) into local \`skills/\`.
3111
+ If a destination folder already exists in \`skills/\`, the command fails instead of overwriting files.
3112
+
3113
+ After adding skills, run \`poncho dev\` or \`poncho run --interactive\` and ask the agent to use them.
3114
+
3115
+ ## Configure MCP Servers (Remote)
3116
+
3117
+ Connect remote MCP servers and expose their tools to the agent:
3118
+
3119
+ \`\`\`bash
3120
+ # Add remote MCP server
3121
+ poncho mcp add --url https://mcp.example.com/github --name github --auth-bearer-env GITHUB_TOKEN
3122
+
3123
+ # List configured servers
3124
+ poncho mcp list
3125
+
3126
+ # Discover MCP tools and print frontmatter intent snippets
3127
+ poncho mcp tools list github
3128
+ poncho mcp tools select github
3129
+
3130
+ # Remove a server
3131
+ poncho mcp remove github
3132
+ \`\`\`
3133
+
3134
+ Set required secrets in \`.env\` (for example, \`GITHUB_TOKEN=...\`).
3135
+
3136
+ ## Tool Intent and Approvals in Frontmatter
3137
+
3138
+ Declare tool intent directly in \`AGENT.md\` and \`SKILL.md\` frontmatter:
3139
+
3140
+ \`\`\`yaml
3141
+ allowed-tools:
3142
+ - mcp:github/list_issues
3143
+ - mcp:github/*
3144
+ approval-required:
3145
+ - mcp:github/create_issue
3146
+ - ./scripts/deploy.ts
3147
+ \`\`\`
3148
+
3149
+ How it works:
3150
+
3151
+ - \`AGENT.md\` provides fallback MCP intent when no skill is active.
3152
+ - \`SKILL.md\` intent applies when you activate that skill (\`activate_skill\`).
3153
+ - Scripts in a sibling \`scripts/\` directory are available by convention.
3154
+ - For non-standard script folders (for example \`tools/\`), add explicit relative entries in \`allowed-tools\`.
3155
+ - Use \`approval-required\` to require human approval for specific MCP calls or script files.
3156
+ - Deactivating a skill (\`deactivate_skill\`) removes its MCP tools from runtime registration.
3157
+
3158
+ Pattern format is strict slash-only:
3159
+
3160
+ - MCP: \`server/tool\`, \`server/*\`
3161
+ - Scripts: relative paths such as \`./scripts/file.ts\`, \`./scripts/*\`, \`./tools/deploy.ts\`
3162
+
3163
+ ## Configuration
3164
+
3165
+ Core files:
3166
+
3167
+ - \`AGENT.md\`: behavior, model selection, runtime guidance
3168
+ - \`poncho.config.js\`: runtime config (storage, auth, telemetry, MCP, tools)
3169
+ - \`.env\`: secrets and environment variables
3170
+
3171
+ Example \`poncho.config.js\`:
3172
+
3173
+ \`\`\`javascript
3174
+ export default {
3175
+ storage: {
3176
+ provider: "local", // local | memory | redis | upstash | dynamodb
3177
+ memory: {
3178
+ enabled: true,
3179
+ maxRecallConversations: 20,
3180
+ },
3181
+ },
3182
+ auth: {
3183
+ required: false,
3184
+ },
3185
+ telemetry: {
3186
+ enabled: true,
3187
+ },
3188
+ mcp: [
3189
+ {
3190
+ name: "github",
3191
+ url: "https://mcp.example.com/github",
3192
+ auth: { type: "bearer", tokenEnv: "GITHUB_TOKEN" },
3193
+ },
3194
+ ],
3195
+ tools: {
3196
+ defaults: {
3197
+ list_directory: true,
3198
+ read_file: true,
3199
+ write_file: true, // still gated by environment/policy
3200
+ },
3201
+ byEnvironment: {
3202
+ production: {
3203
+ read_file: false, // example override
3204
+ },
3205
+ },
3206
+ },
3207
+ };
3208
+ \`\`\`
3209
+
3210
+ ## Project Structure
3211
+
3212
+ \`\`\`
3213
+ ${name}/
3214
+ \u251C\u2500\u2500 AGENT.md # Agent definition and system prompt
3215
+ \u251C\u2500\u2500 poncho.config.js # Configuration (MCP servers, auth, etc.)
3216
+ \u251C\u2500\u2500 package.json # Dependencies
3217
+ \u251C\u2500\u2500 .env.example # Environment variables template
3218
+ \u251C\u2500\u2500 tests/
3219
+ \u2502 \u2514\u2500\u2500 basic.yaml # Test suite
3220
+ \u2514\u2500\u2500 skills/
3221
+ \u2514\u2500\u2500 starter/
3222
+ \u251C\u2500\u2500 SKILL.md
3223
+ \u2514\u2500\u2500 scripts/
3224
+ \u2514\u2500\u2500 starter-echo.ts
3225
+ \`\`\`
3226
+
3227
+ ## Deployment
3228
+
3229
+ \`\`\`bash
3230
+ # Build for Vercel
3231
+ poncho build vercel
3232
+ cd .poncho-build/vercel && vercel deploy --prod
3233
+
3234
+ # Build for Docker
3235
+ poncho build docker
3236
+ docker build -t ${name} .
3237
+ \`\`\`
3238
+
3239
+ For full reference:
3240
+ https://github.com/cesr/poncho-ai
3241
+ `;
3242
+ var ENV_TEMPLATE = "ANTHROPIC_API_KEY=sk-ant-...\n";
3243
+ var GITIGNORE_TEMPLATE = ".env\nnode_modules\ndist\n.poncho-build\n.poncho/\ninteractive-session.json\n";
3244
+ var VERCEL_RUNTIME_DEPENDENCIES = {
3245
+ "@anthropic-ai/sdk": "^0.74.0",
3246
+ "@aws-sdk/client-dynamodb": "^3.988.0",
3247
+ "@latitude-data/telemetry": "^2.0.2",
3248
+ commander: "^12.0.0",
3249
+ dotenv: "^16.4.0",
3250
+ jiti: "^2.6.1",
3251
+ mustache: "^4.2.0",
3252
+ openai: "^6.3.0",
3253
+ redis: "^5.10.0",
3254
+ yaml: "^2.8.1"
3255
+ };
3256
+ var TEST_TEMPLATE = `tests:
3257
+ - name: "Basic sanity"
3258
+ task: "What is 2 + 2?"
3259
+ expect:
3260
+ contains: "4"
3261
+ `;
3262
+ var SKILL_TEMPLATE = `---
3263
+ name: starter-skill
3264
+ description: Starter local skill template
3265
+ ---
3266
+
3267
+ # Starter Skill
3268
+
3269
+ This is a starter local skill created by \`poncho init\`.
3270
+
3271
+ ## Authoring Notes
3272
+
3273
+ - Put executable JavaScript/TypeScript files in \`scripts/\`.
3274
+ - Ask the agent to call \`run_skill_script\` with \`skill\`, \`script\`, and optional \`input\`.
3275
+ `;
3276
+ var SKILL_TOOL_TEMPLATE = `export default async function run(input) {
3277
+ const message = typeof input?.message === "string" ? input.message : "";
3278
+ return { echoed: message };
3279
+ }
3280
+ `;
3281
+ var ensureFile = async (path, content) => {
3282
+ await mkdir3(dirname3(path), { recursive: true });
3283
+ await writeFile3(path, content, { encoding: "utf8", flag: "wx" });
3284
+ };
3285
+ var copyIfExists = async (sourcePath, destinationPath) => {
3286
+ try {
3287
+ await access2(sourcePath);
3288
+ } catch {
3289
+ return;
3290
+ }
3291
+ await mkdir3(dirname3(destinationPath), { recursive: true });
3292
+ await cp(sourcePath, destinationPath, { recursive: true, dereference: true });
3293
+ };
3294
+ var resolveCliEntrypoint = async () => {
3295
+ const sourceEntrypoint = resolve3(packageRoot, "src", "index.ts");
3296
+ try {
3297
+ await access2(sourceEntrypoint);
3298
+ return sourceEntrypoint;
3299
+ } catch {
3300
+ return resolve3(packageRoot, "dist", "index.js");
3301
+ }
3302
+ };
3303
+ var buildVercelHandlerBundle = async (outDir) => {
3304
+ const { build: esbuild } = await import("esbuild");
3305
+ const cliEntrypoint = await resolveCliEntrypoint();
3306
+ const tempEntry = resolve3(outDir, "api", "_entry.js");
3307
+ await writeFile3(
3308
+ tempEntry,
3309
+ `import { createRequestHandler } from ${JSON.stringify(cliEntrypoint)};
3310
+ let handlerPromise;
3311
+ export default async function handler(req, res) {
3312
+ try {
3313
+ if (!handlerPromise) {
3314
+ handlerPromise = createRequestHandler({ workingDir: process.cwd() });
3315
+ }
3316
+ const requestHandler = await handlerPromise;
3317
+ await requestHandler(req, res);
3318
+ } catch (error) {
3319
+ console.error("Handler error:", error);
3320
+ if (!res.headersSent) {
3321
+ res.writeHead(500, { "Content-Type": "application/json" });
3322
+ res.end(JSON.stringify({ error: "Internal server error", message: error?.message || "Unknown error" }));
3323
+ }
3324
+ }
3325
+ }
3326
+ `,
3327
+ "utf8"
3328
+ );
3329
+ await esbuild({
3330
+ entryPoints: [tempEntry],
3331
+ bundle: true,
3332
+ platform: "node",
3333
+ format: "esm",
3334
+ target: "node20",
3335
+ outfile: resolve3(outDir, "api", "index.js"),
3336
+ sourcemap: false,
3337
+ legalComments: "none",
3338
+ external: [
3339
+ ...Object.keys(VERCEL_RUNTIME_DEPENDENCIES),
3340
+ "@anthropic-ai/sdk/*",
3341
+ "child_process",
3342
+ "fs",
3343
+ "fs/promises",
3344
+ "http",
3345
+ "https",
3346
+ "path",
3347
+ "module",
3348
+ "url",
3349
+ "readline",
3350
+ "readline/promises",
3351
+ "crypto",
3352
+ "stream",
3353
+ "events",
3354
+ "util",
3355
+ "os",
3356
+ "zlib",
3357
+ "net",
3358
+ "tls",
3359
+ "dns",
3360
+ "assert",
3361
+ "buffer",
3362
+ "timers",
3363
+ "timers/promises",
3364
+ "node:child_process",
3365
+ "node:fs",
3366
+ "node:fs/promises",
3367
+ "node:http",
3368
+ "node:https",
3369
+ "node:path",
3370
+ "node:module",
3371
+ "node:url",
3372
+ "node:readline",
3373
+ "node:readline/promises",
3374
+ "node:crypto",
3375
+ "node:stream",
3376
+ "node:events",
3377
+ "node:util",
3378
+ "node:os",
3379
+ "node:zlib",
3380
+ "node:net",
3381
+ "node:tls",
3382
+ "node:dns",
3383
+ "node:assert",
3384
+ "node:buffer",
3385
+ "node:timers",
3386
+ "node:timers/promises"
3387
+ ]
3388
+ });
3389
+ };
3390
+ var renderConfigFile = (config) => `export default ${JSON.stringify(config, null, 2)}
3391
+ `;
3392
+ var writeConfigFile = async (workingDir, config) => {
3393
+ const serialized = renderConfigFile(config);
3394
+ await writeFile3(resolve3(workingDir, "poncho.config.js"), serialized, "utf8");
3395
+ };
3396
+ var ensureEnvPlaceholder = async (filePath, key) => {
3397
+ const normalizedKey = key.trim();
3398
+ if (!normalizedKey) {
3399
+ return false;
3400
+ }
3401
+ let content = "";
3402
+ try {
3403
+ content = await readFile3(filePath, "utf8");
3404
+ } catch {
3405
+ await writeFile3(filePath, `${normalizedKey}=
3406
+ `, "utf8");
3407
+ return true;
3408
+ }
3409
+ const present = content.split(/\r?\n/).some((line) => line.trimStart().startsWith(`${normalizedKey}=`));
3410
+ if (present) {
3411
+ return false;
3412
+ }
3413
+ const withTrailingNewline = content.length === 0 || content.endsWith("\n") ? content : `${content}
3414
+ `;
3415
+ await writeFile3(filePath, `${withTrailingNewline}${normalizedKey}=
3416
+ `, "utf8");
3417
+ return true;
3418
+ };
3419
+ var removeEnvPlaceholder = async (filePath, key) => {
3420
+ const normalizedKey = key.trim();
3421
+ if (!normalizedKey) {
3422
+ return false;
3423
+ }
3424
+ let content = "";
3425
+ try {
3426
+ content = await readFile3(filePath, "utf8");
3427
+ } catch {
3428
+ return false;
3429
+ }
3430
+ const lines = content.split(/\r?\n/);
3431
+ const filtered = lines.filter((line) => !line.trimStart().startsWith(`${normalizedKey}=`));
3432
+ if (filtered.length === lines.length) {
3433
+ return false;
3434
+ }
3435
+ const nextContent = filtered.join("\n").replace(/\n+$/, "");
3436
+ await writeFile3(filePath, nextContent.length > 0 ? `${nextContent}
3437
+ ` : "", "utf8");
3438
+ return true;
3439
+ };
3440
+ var gitInit = (cwd) => new Promise((resolve4) => {
3441
+ const child = spawn("git", ["init"], { cwd, stdio: "ignore" });
3442
+ child.on("error", () => resolve4(false));
3443
+ child.on("close", (code) => resolve4(code === 0));
3444
+ });
3445
+ var initProject = async (projectName, options) => {
3446
+ const baseDir = options?.workingDir ?? process.cwd();
3447
+ const projectDir = resolve3(baseDir, projectName);
3448
+ await mkdir3(projectDir, { recursive: true });
3449
+ const onboardingOptions = options?.onboarding ?? {
3450
+ yes: true,
3451
+ interactive: false
3452
+ };
3453
+ const onboarding = await runInitOnboarding(onboardingOptions);
3454
+ const G = "\x1B[32m";
3455
+ const D = "\x1B[2m";
3456
+ const B = "\x1B[1m";
3457
+ const CY = "\x1B[36m";
3458
+ const YW = "\x1B[33m";
3459
+ const R = "\x1B[0m";
3460
+ process.stdout.write("\n");
3461
+ const scaffoldFiles = [
3462
+ { path: "AGENT.md", content: AGENT_TEMPLATE(projectName, { modelProvider: onboarding.agentModel.provider, modelName: onboarding.agentModel.name }) },
3463
+ { path: "poncho.config.js", content: renderConfigFile(onboarding.config) },
3464
+ { path: "package.json", content: PACKAGE_TEMPLATE(projectName, projectDir) },
3465
+ { path: "README.md", content: README_TEMPLATE(projectName) },
3466
+ { path: ".env.example", content: options?.envExampleOverride ?? onboarding.envExample ?? ENV_TEMPLATE },
3467
+ { path: ".gitignore", content: GITIGNORE_TEMPLATE },
3468
+ { path: "tests/basic.yaml", content: TEST_TEMPLATE },
3469
+ { path: "skills/starter/SKILL.md", content: SKILL_TEMPLATE },
3470
+ { path: "skills/starter/scripts/starter-echo.ts", content: SKILL_TOOL_TEMPLATE }
3471
+ ];
3472
+ if (onboarding.envFile) {
3473
+ scaffoldFiles.push({ path: ".env", content: onboarding.envFile });
3474
+ }
3475
+ for (const file of scaffoldFiles) {
3476
+ await ensureFile(resolve3(projectDir, file.path), file.content);
3477
+ process.stdout.write(` ${D}+${R} ${D}${file.path}${R}
3478
+ `);
3479
+ }
3480
+ await initializeOnboardingMarker(projectDir, {
3481
+ allowIntro: !(onboardingOptions.yes ?? false)
3482
+ });
3483
+ process.stdout.write("\n");
3484
+ try {
3485
+ await runPnpmInstall(projectDir);
3486
+ process.stdout.write(` ${G}\u2713${R} ${D}Installed dependencies${R}
3487
+ `);
3488
+ } catch {
3489
+ process.stdout.write(
3490
+ ` ${YW}!${R} Could not install dependencies \u2014 run ${D}pnpm install${R} manually
3491
+ `
3492
+ );
3493
+ }
3494
+ const gitOk = await gitInit(projectDir);
3495
+ if (gitOk) {
3496
+ process.stdout.write(` ${G}\u2713${R} ${D}Initialized git${R}
3497
+ `);
3498
+ }
3499
+ process.stdout.write(` ${G}\u2713${R} ${B}${projectName}${R} is ready
3500
+ `);
3501
+ process.stdout.write("\n");
3502
+ process.stdout.write(` ${B}Get started${R}
3503
+ `);
3504
+ process.stdout.write("\n");
3505
+ process.stdout.write(` ${D}$${R} cd ${projectName}
3506
+ `);
3507
+ process.stdout.write("\n");
3508
+ process.stdout.write(` ${CY}Web UI${R} ${D}$${R} poncho dev
3509
+ `);
3510
+ process.stdout.write(` ${CY}CLI interactive${R} ${D}$${R} poncho run --interactive
3511
+ `);
3512
+ process.stdout.write("\n");
3513
+ if (onboarding.envNeedsUserInput) {
3514
+ process.stdout.write(
3515
+ ` ${YW}!${R} Make sure you add your keys to the ${B}.env${R} file.
3516
+ `
3517
+ );
3518
+ }
3519
+ process.stdout.write(` ${D}The agent will introduce itself on your first session.${R}
3520
+ `);
3521
+ process.stdout.write("\n");
3522
+ };
3523
+ var updateAgentGuidance = async (workingDir) => {
3524
+ const agentPath = resolve3(workingDir, "AGENT.md");
3525
+ const content = await readFile3(agentPath, "utf8");
3526
+ const guidanceSectionPattern = /\n## Configuration Assistant Context[\s\S]*?(?=\n## |\n# |$)|\n## Skill Authoring Guidance[\s\S]*?(?=\n## |\n# |$)/g;
3527
+ const normalized = content.replace(/\s+$/g, "");
3528
+ const updated = normalized.replace(guidanceSectionPattern, "").replace(/\n{3,}/g, "\n\n");
3529
+ if (updated === normalized) {
3530
+ process.stdout.write("AGENT.md does not contain deprecated embedded local guidance.\n");
3531
+ return false;
3532
+ }
3533
+ await writeFile3(agentPath, `${updated}
3534
+ `, "utf8");
3535
+ process.stdout.write("Removed deprecated embedded local guidance from AGENT.md.\n");
3536
+ return true;
3537
+ };
3538
+ var formatSseEvent = (event) => `event: ${event.type}
3539
+ data: ${JSON.stringify(event)}
3540
+
3541
+ `;
3542
+ var createRequestHandler = async (options) => {
3543
+ const workingDir = options?.workingDir ?? process.cwd();
3544
+ dotenv.config({ path: resolve3(workingDir, ".env") });
3545
+ const config = await loadPonchoConfig(workingDir);
3546
+ let agentName = "Agent";
3547
+ let agentModelProvider = "anthropic";
3548
+ let agentModelName = "claude-opus-4-5";
3549
+ try {
3550
+ const agentMd = await readFile3(resolve3(workingDir, "AGENT.md"), "utf8");
3551
+ const nameMatch = agentMd.match(/^name:\s*(.+)$/m);
3552
+ const providerMatch = agentMd.match(/^\s{2}provider:\s*(.+)$/m);
3553
+ const modelMatch = agentMd.match(/^\s{2}name:\s*(.+)$/m);
3554
+ if (nameMatch?.[1]) {
3555
+ agentName = nameMatch[1].trim().replace(/^["']|["']$/g, "");
3556
+ }
3557
+ if (providerMatch?.[1]) {
3558
+ agentModelProvider = providerMatch[1].trim().replace(/^["']|["']$/g, "");
3559
+ }
3560
+ if (modelMatch?.[1]) {
3561
+ agentModelName = modelMatch[1].trim().replace(/^["']|["']$/g, "");
3562
+ }
3563
+ } catch {
3564
+ }
3565
+ const runOwners = /* @__PURE__ */ new Map();
3566
+ const runConversations = /* @__PURE__ */ new Map();
3567
+ const pendingApprovals = /* @__PURE__ */ new Map();
3568
+ const conversationEventStreams = /* @__PURE__ */ new Map();
3569
+ const broadcastEvent = (conversationId, event) => {
3570
+ let stream = conversationEventStreams.get(conversationId);
3571
+ if (!stream) {
3572
+ stream = { buffer: [], subscribers: /* @__PURE__ */ new Set(), finished: false };
3573
+ conversationEventStreams.set(conversationId, stream);
3574
+ }
3575
+ stream.buffer.push(event);
3576
+ for (const subscriber of stream.subscribers) {
3577
+ try {
3578
+ subscriber.write(formatSseEvent(event));
3579
+ } catch {
3580
+ stream.subscribers.delete(subscriber);
3581
+ }
3582
+ }
3583
+ };
3584
+ const finishConversationStream = (conversationId) => {
3585
+ const stream = conversationEventStreams.get(conversationId);
3586
+ if (stream) {
3587
+ stream.finished = true;
3588
+ for (const subscriber of stream.subscribers) {
3589
+ try {
3590
+ subscriber.write("event: stream:end\ndata: {}\n\n");
3591
+ subscriber.end();
3592
+ } catch {
3593
+ }
3594
+ }
3595
+ stream.subscribers.clear();
3596
+ setTimeout(() => conversationEventStreams.delete(conversationId), 3e4);
3597
+ }
3598
+ };
3599
+ const persistConversationPendingApprovals = async (conversationId) => {
3600
+ const conversation = await conversationStore.get(conversationId);
3601
+ if (!conversation) {
3602
+ return;
3603
+ }
3604
+ conversation.pendingApprovals = Array.from(pendingApprovals.entries()).filter(
3605
+ ([, pending]) => pending.ownerId === conversation.ownerId && pending.conversationId === conversationId
3606
+ ).map(([approvalId, pending]) => ({
3607
+ approvalId,
3608
+ runId: pending.runId,
3609
+ tool: pending.tool,
3610
+ input: pending.input
3611
+ }));
3612
+ await conversationStore.update(conversation);
3613
+ };
3614
+ const harness = new AgentHarness({
3615
+ workingDir,
3616
+ environment: resolveHarnessEnvironment(),
3617
+ approvalHandler: async (request) => new Promise((resolveApproval) => {
3618
+ const ownerIdForRun = runOwners.get(request.runId) ?? "local-owner";
3619
+ const conversationIdForRun = runConversations.get(request.runId) ?? null;
3620
+ pendingApprovals.set(request.approvalId, {
3621
+ ownerId: ownerIdForRun,
3622
+ runId: request.runId,
3623
+ conversationId: conversationIdForRun,
3624
+ tool: request.tool,
3625
+ input: request.input,
3626
+ resolve: resolveApproval
3627
+ });
3628
+ if (conversationIdForRun) {
3629
+ void persistConversationPendingApprovals(conversationIdForRun);
3630
+ }
3631
+ })
3632
+ });
3633
+ await harness.initialize();
3634
+ const telemetry = new TelemetryEmitter(config?.telemetry);
3635
+ const conversationStore = createConversationStore(resolveStateConfig(config), { workingDir });
3636
+ const sessionStore = new SessionStore();
3637
+ const loginRateLimiter = new LoginRateLimiter();
3638
+ const authToken = process.env.PONCHO_AUTH_TOKEN ?? "";
3639
+ const authRequired = config?.auth?.required ?? false;
3640
+ const requireAuth = authRequired && authToken.length > 0;
3641
+ const isProduction = resolveHarnessEnvironment() === "production";
3642
+ const secureCookies = isProduction;
3643
+ const validateBearerToken = (authHeader) => {
3644
+ if (!requireAuth || !authToken) {
3645
+ return true;
3646
+ }
3647
+ if (!authHeader || typeof authHeader !== "string") {
3648
+ return false;
3649
+ }
3650
+ const match = authHeader.match(/^Bearer\s+(.+)$/i);
3651
+ if (!match || !match[1]) {
3652
+ return false;
3653
+ }
3654
+ return verifyPassphrase(match[1], authToken);
3655
+ };
3656
+ return async (request, response) => {
3657
+ if (!request.url || !request.method) {
3658
+ writeJson(response, 404, { error: "Not found" });
3659
+ return;
3660
+ }
3661
+ const [pathname] = request.url.split("?");
3662
+ if (request.method === "GET" && (pathname === "/" || pathname.startsWith("/c/"))) {
3663
+ writeHtml(response, 200, renderWebUiHtml({ agentName }));
3664
+ return;
3665
+ }
3666
+ if (pathname === "/manifest.json" && request.method === "GET") {
3667
+ response.writeHead(200, { "Content-Type": "application/manifest+json" });
3668
+ response.end(renderManifest({ agentName }));
3669
+ return;
3670
+ }
3671
+ if (pathname === "/sw.js" && request.method === "GET") {
3672
+ response.writeHead(200, {
3673
+ "Content-Type": "application/javascript",
3674
+ "Service-Worker-Allowed": "/"
3675
+ });
3676
+ response.end(renderServiceWorker());
3677
+ return;
3678
+ }
3679
+ if (pathname === "/icon.svg" && request.method === "GET") {
3680
+ response.writeHead(200, { "Content-Type": "image/svg+xml" });
3681
+ response.end(renderIconSvg({ agentName }));
3682
+ return;
3683
+ }
3684
+ if ((pathname === "/icon-192.png" || pathname === "/icon-512.png") && request.method === "GET") {
3685
+ response.writeHead(302, { Location: "/icon.svg" });
3686
+ response.end();
3687
+ return;
3688
+ }
3689
+ if (pathname === "/health" && request.method === "GET") {
3690
+ writeJson(response, 200, { status: "ok" });
3691
+ return;
3692
+ }
3693
+ const cookies = parseCookies(request);
3694
+ const sessionId = cookies.poncho_session;
3695
+ const session = sessionId ? sessionStore.get(sessionId) : void 0;
3696
+ const ownerId = session?.ownerId ?? "local-owner";
3697
+ const requiresCsrfValidation = request.method !== "GET" && request.method !== "HEAD" && request.method !== "OPTIONS";
3698
+ if (pathname === "/api/auth/session" && request.method === "GET") {
3699
+ if (!requireAuth) {
3700
+ writeJson(response, 200, { authenticated: true, csrfToken: "" });
3701
+ return;
3702
+ }
3703
+ if (!session) {
3704
+ writeJson(response, 200, { authenticated: false });
3705
+ return;
3706
+ }
3707
+ writeJson(response, 200, {
3708
+ authenticated: true,
3709
+ sessionId: session.sessionId,
3710
+ ownerId: session.ownerId,
3711
+ csrfToken: session.csrfToken
3712
+ });
3713
+ return;
3714
+ }
3715
+ if (pathname === "/api/auth/login" && request.method === "POST") {
3716
+ if (!requireAuth) {
3717
+ writeJson(response, 200, { authenticated: true, csrfToken: "" });
3718
+ return;
3719
+ }
3720
+ const ip = getRequestIp(request);
3721
+ const canAttempt = loginRateLimiter.canAttempt(ip);
3722
+ if (!canAttempt.allowed) {
3723
+ writeJson(response, 429, {
3724
+ code: "AUTH_RATE_LIMIT",
3725
+ message: "Too many failed login attempts. Try again later.",
3726
+ retryAfterSeconds: canAttempt.retryAfterSeconds
3727
+ });
3728
+ return;
3729
+ }
3730
+ const body = await readRequestBody(request);
3731
+ const provided = body.passphrase ?? "";
3732
+ if (!verifyPassphrase(provided, authToken)) {
3733
+ const failure = loginRateLimiter.registerFailure(ip);
3734
+ writeJson(response, 401, {
3735
+ code: "AUTH_ERROR",
3736
+ message: "Invalid passphrase",
3737
+ retryAfterSeconds: failure.retryAfterSeconds
3738
+ });
3739
+ return;
3740
+ }
3741
+ loginRateLimiter.registerSuccess(ip);
3742
+ const createdSession = sessionStore.create(ownerId);
3743
+ setCookie(response, "poncho_session", createdSession.sessionId, {
3744
+ httpOnly: true,
3745
+ secure: secureCookies,
3746
+ sameSite: "Lax",
3747
+ path: "/",
3748
+ maxAge: 60 * 60 * 8
3749
+ });
3750
+ writeJson(response, 200, {
3751
+ authenticated: true,
3752
+ csrfToken: createdSession.csrfToken
3753
+ });
3754
+ return;
3755
+ }
3756
+ if (pathname === "/api/auth/logout" && request.method === "POST") {
3757
+ if (session?.sessionId) {
3758
+ sessionStore.delete(session.sessionId);
3759
+ }
3760
+ setCookie(response, "poncho_session", "", {
3761
+ httpOnly: true,
3762
+ secure: secureCookies,
3763
+ sameSite: "Lax",
3764
+ path: "/",
3765
+ maxAge: 0
3766
+ });
3767
+ writeJson(response, 200, { ok: true });
3768
+ return;
3769
+ }
3770
+ if (pathname.startsWith("/api/")) {
3771
+ const hasBearerToken = request.headers.authorization?.startsWith("Bearer ");
3772
+ const isAuthenticated = !requireAuth || session || validateBearerToken(request.headers.authorization);
3773
+ if (!isAuthenticated) {
3774
+ writeJson(response, 401, {
3775
+ code: "AUTH_ERROR",
3776
+ message: "Authentication required"
3777
+ });
3778
+ return;
3779
+ }
3780
+ if (requireAuth && session && !hasBearerToken && requiresCsrfValidation && pathname !== "/api/auth/login" && request.headers["x-csrf-token"] !== session?.csrfToken) {
3781
+ writeJson(response, 403, {
3782
+ code: "CSRF_ERROR",
3783
+ message: "Invalid CSRF token"
3784
+ });
3785
+ return;
3786
+ }
3787
+ }
3788
+ if (pathname === "/api/conversations" && request.method === "GET") {
3789
+ const conversations = await conversationStore.list(ownerId);
3790
+ writeJson(response, 200, {
3791
+ conversations: conversations.map((conversation) => ({
3792
+ conversationId: conversation.conversationId,
3793
+ title: conversation.title,
3794
+ runtimeRunId: conversation.runtimeRunId,
3795
+ ownerId: conversation.ownerId,
3796
+ tenantId: conversation.tenantId,
3797
+ createdAt: conversation.createdAt,
3798
+ updatedAt: conversation.updatedAt,
3799
+ messageCount: conversation.messages.length
3800
+ }))
3801
+ });
3802
+ return;
3803
+ }
3804
+ if (pathname === "/api/conversations" && request.method === "POST") {
3805
+ const body = await readRequestBody(request);
3806
+ const conversation = await conversationStore.create(ownerId, body.title);
3807
+ const introMessage = await consumeFirstRunIntro(workingDir, {
3808
+ agentName,
3809
+ provider: agentModelProvider,
3810
+ model: agentModelName,
3811
+ config
3812
+ });
3813
+ if (introMessage) {
3814
+ conversation.messages = [{ role: "assistant", content: introMessage }];
3815
+ await conversationStore.update(conversation);
3816
+ }
3817
+ writeJson(response, 201, { conversation });
3818
+ return;
3819
+ }
3820
+ const approvalMatch = pathname.match(/^\/api\/approvals\/([^/]+)$/);
3821
+ if (approvalMatch && request.method === "POST") {
3822
+ const approvalId = decodeURIComponent(approvalMatch[1] ?? "");
3823
+ const pending = pendingApprovals.get(approvalId);
3824
+ if (!pending || pending.ownerId !== ownerId) {
3825
+ const conversations = await conversationStore.list(ownerId);
3826
+ let prunedStale = false;
3827
+ for (const conversation of conversations) {
3828
+ if (!Array.isArray(conversation.pendingApprovals)) {
3829
+ continue;
3830
+ }
3831
+ const next = conversation.pendingApprovals.filter(
3832
+ (approval) => approval.approvalId !== approvalId
3833
+ );
3834
+ if (next.length !== conversation.pendingApprovals.length) {
3835
+ conversation.pendingApprovals = next;
3836
+ await conversationStore.update(conversation);
3837
+ prunedStale = true;
3838
+ }
3839
+ }
3840
+ writeJson(response, 404, {
3841
+ code: "APPROVAL_NOT_FOUND",
3842
+ message: prunedStale ? "Approval request is no longer active" : "Approval request not found"
3843
+ });
3844
+ return;
3845
+ }
3846
+ const body = await readRequestBody(request);
3847
+ const approved = body.approved === true;
3848
+ pendingApprovals.delete(approvalId);
3849
+ if (pending.conversationId) {
3850
+ await persistConversationPendingApprovals(pending.conversationId);
3851
+ }
3852
+ pending.resolve(approved);
3853
+ writeJson(response, 200, { ok: true, approvalId, approved });
3854
+ return;
3855
+ }
3856
+ const conversationEventsMatch = pathname.match(
3857
+ /^\/api\/conversations\/([^/]+)\/events$/
3858
+ );
3859
+ if (conversationEventsMatch && request.method === "GET") {
3860
+ const conversationId = decodeURIComponent(conversationEventsMatch[1] ?? "");
3861
+ const conversation = await conversationStore.get(conversationId);
3862
+ if (!conversation || conversation.ownerId !== ownerId) {
3863
+ writeJson(response, 404, {
3864
+ code: "CONVERSATION_NOT_FOUND",
3865
+ message: "Conversation not found"
3866
+ });
3867
+ return;
3868
+ }
3869
+ response.writeHead(200, {
3870
+ "Content-Type": "text/event-stream",
3871
+ "Cache-Control": "no-cache",
3872
+ Connection: "keep-alive"
3873
+ });
3874
+ const stream = conversationEventStreams.get(conversationId);
3875
+ if (!stream) {
3876
+ response.write("event: stream:end\ndata: {}\n\n");
3877
+ response.end();
3878
+ return;
3879
+ }
3880
+ for (const bufferedEvent of stream.buffer) {
3881
+ try {
3882
+ response.write(formatSseEvent(bufferedEvent));
3883
+ } catch {
3884
+ response.end();
3885
+ return;
3886
+ }
3887
+ }
3888
+ if (stream.finished) {
3889
+ response.write("event: stream:end\ndata: {}\n\n");
3890
+ response.end();
3891
+ return;
3892
+ }
3893
+ stream.subscribers.add(response);
3894
+ request.on("close", () => {
3895
+ stream.subscribers.delete(response);
3896
+ });
3897
+ return;
3898
+ }
3899
+ const conversationPathMatch = pathname.match(/^\/api\/conversations\/([^/]+)$/);
3900
+ if (conversationPathMatch) {
3901
+ const conversationId = decodeURIComponent(conversationPathMatch[1] ?? "");
3902
+ const conversation = await conversationStore.get(conversationId);
3903
+ if (!conversation || conversation.ownerId !== ownerId) {
3904
+ writeJson(response, 404, {
3905
+ code: "CONVERSATION_NOT_FOUND",
3906
+ message: "Conversation not found"
3907
+ });
3908
+ return;
3909
+ }
3910
+ if (request.method === "GET") {
3911
+ const storedPending = Array.isArray(conversation.pendingApprovals) ? conversation.pendingApprovals : [];
3912
+ const livePending = Array.from(pendingApprovals.entries()).filter(
3913
+ ([, pending]) => pending.ownerId === ownerId && pending.conversationId === conversationId
3914
+ ).map(([approvalId, pending]) => ({
3915
+ approvalId,
3916
+ runId: pending.runId,
3917
+ tool: pending.tool,
3918
+ input: pending.input
3919
+ }));
3920
+ const mergedPendingById = /* @__PURE__ */ new Map();
3921
+ for (const approval of storedPending) {
3922
+ if (approval && typeof approval.approvalId === "string") {
3923
+ mergedPendingById.set(approval.approvalId, approval);
3924
+ }
3925
+ }
3926
+ for (const approval of livePending) {
3927
+ mergedPendingById.set(approval.approvalId, approval);
3928
+ }
3929
+ writeJson(response, 200, {
3930
+ conversation: {
3931
+ ...conversation,
3932
+ pendingApprovals: Array.from(mergedPendingById.values())
3933
+ }
3934
+ });
3935
+ return;
3936
+ }
3937
+ if (request.method === "PATCH") {
3938
+ const body = await readRequestBody(request);
3939
+ if (!body.title || body.title.trim().length === 0) {
3940
+ writeJson(response, 400, {
3941
+ code: "VALIDATION_ERROR",
3942
+ message: "title is required"
3943
+ });
3944
+ return;
3945
+ }
3946
+ const updated = await conversationStore.rename(conversationId, body.title);
3947
+ writeJson(response, 200, { conversation: updated });
3948
+ return;
3949
+ }
3950
+ if (request.method === "DELETE") {
3951
+ await conversationStore.delete(conversationId);
3952
+ writeJson(response, 200, { ok: true });
3953
+ return;
3954
+ }
3955
+ }
3956
+ const conversationMessageMatch = pathname.match(/^\/api\/conversations\/([^/]+)\/messages$/);
3957
+ if (conversationMessageMatch && request.method === "POST") {
3958
+ const conversationId = decodeURIComponent(conversationMessageMatch[1] ?? "");
3959
+ const conversation = await conversationStore.get(conversationId);
3960
+ if (!conversation || conversation.ownerId !== ownerId) {
3961
+ writeJson(response, 404, {
3962
+ code: "CONVERSATION_NOT_FOUND",
3963
+ message: "Conversation not found"
3964
+ });
3965
+ return;
3966
+ }
3967
+ const body = await readRequestBody(request);
3968
+ const messageText = body.message?.trim() ?? "";
3969
+ if (!messageText) {
3970
+ writeJson(response, 400, {
3971
+ code: "VALIDATION_ERROR",
3972
+ message: "message is required"
3973
+ });
3974
+ return;
3975
+ }
3976
+ if (conversation.messages.length === 0 && (conversation.title === "New conversation" || conversation.title.trim().length === 0)) {
3977
+ conversation.title = inferConversationTitle(messageText);
3978
+ }
3979
+ response.writeHead(200, {
3980
+ "Content-Type": "text/event-stream",
3981
+ "Cache-Control": "no-cache",
3982
+ Connection: "keep-alive"
3983
+ });
3984
+ const historyMessages = [...conversation.messages];
3985
+ let latestRunId = conversation.runtimeRunId ?? "";
3986
+ let assistantResponse = "";
3987
+ const toolTimeline = [];
3988
+ const sections = [];
3989
+ let currentText = "";
3990
+ let currentTools = [];
3991
+ try {
3992
+ conversation.messages = [...historyMessages, { role: "user", content: messageText }];
3993
+ conversation.updatedAt = Date.now();
3994
+ await conversationStore.update(conversation);
3995
+ const persistDraftAssistantTurn = async () => {
3996
+ const draftSections = [
3997
+ ...sections.map((section) => ({
3998
+ type: section.type,
3999
+ content: Array.isArray(section.content) ? [...section.content] : section.content
4000
+ }))
4001
+ ];
4002
+ if (currentTools.length > 0) {
4003
+ draftSections.push({ type: "tools", content: [...currentTools] });
4004
+ }
4005
+ if (currentText.length > 0) {
4006
+ draftSections.push({ type: "text", content: currentText });
4007
+ }
4008
+ const hasDraftContent = assistantResponse.length > 0 || toolTimeline.length > 0 || draftSections.length > 0;
4009
+ if (!hasDraftContent) {
4010
+ return;
4011
+ }
4012
+ conversation.messages = [
4013
+ ...historyMessages,
4014
+ { role: "user", content: messageText },
4015
+ {
4016
+ role: "assistant",
4017
+ content: assistantResponse,
4018
+ metadata: toolTimeline.length > 0 || draftSections.length > 0 ? {
4019
+ toolActivity: [...toolTimeline],
4020
+ sections: draftSections.length > 0 ? draftSections : void 0
4021
+ } : void 0
4022
+ }
4023
+ ];
4024
+ conversation.updatedAt = Date.now();
4025
+ await conversationStore.update(conversation);
4026
+ };
4027
+ const recallCorpus = (await conversationStore.list(ownerId)).filter((item) => item.conversationId !== conversationId).slice(0, 20).map((item) => ({
4028
+ conversationId: item.conversationId,
4029
+ title: item.title,
4030
+ updatedAt: item.updatedAt,
4031
+ content: item.messages.slice(-6).map((message) => `${message.role}: ${message.content}`).join("\n").slice(0, 2e3)
4032
+ })).filter((item) => item.content.length > 0);
4033
+ for await (const event of harness.runWithTelemetry({
4034
+ task: messageText,
4035
+ parameters: {
4036
+ ...body.parameters ?? {},
4037
+ __conversationRecallCorpus: recallCorpus,
4038
+ __activeConversationId: conversationId
4039
+ },
4040
+ messages: historyMessages
4041
+ })) {
4042
+ if (event.type === "run:started") {
4043
+ latestRunId = event.runId;
4044
+ runOwners.set(event.runId, ownerId);
4045
+ runConversations.set(event.runId, conversationId);
4046
+ }
4047
+ if (event.type === "model:chunk") {
4048
+ if (currentTools.length > 0) {
4049
+ sections.push({ type: "tools", content: currentTools });
4050
+ currentTools = [];
4051
+ }
4052
+ assistantResponse += event.content;
4053
+ currentText += event.content;
4054
+ }
4055
+ if (event.type === "tool:started") {
4056
+ if (currentText.length > 0) {
4057
+ sections.push({ type: "text", content: currentText });
4058
+ currentText = "";
4059
+ }
4060
+ const toolText = `- start \`${event.tool}\``;
4061
+ toolTimeline.push(toolText);
4062
+ currentTools.push(toolText);
4063
+ }
4064
+ if (event.type === "tool:completed") {
4065
+ const toolText = `- done \`${event.tool}\` (${event.duration}ms)`;
4066
+ toolTimeline.push(toolText);
4067
+ currentTools.push(toolText);
4068
+ }
4069
+ if (event.type === "tool:error") {
4070
+ const toolText = `- error \`${event.tool}\`: ${event.error}`;
4071
+ toolTimeline.push(toolText);
4072
+ currentTools.push(toolText);
4073
+ }
4074
+ if (event.type === "tool:approval:required") {
4075
+ const toolText = `- approval required \`${event.tool}\``;
4076
+ toolTimeline.push(toolText);
4077
+ currentTools.push(toolText);
4078
+ await persistDraftAssistantTurn();
4079
+ }
4080
+ if (event.type === "tool:approval:granted") {
4081
+ const toolText = `- approval granted (${event.approvalId})`;
4082
+ toolTimeline.push(toolText);
4083
+ currentTools.push(toolText);
4084
+ await persistDraftAssistantTurn();
4085
+ }
4086
+ if (event.type === "tool:approval:denied") {
4087
+ const toolText = `- approval denied (${event.approvalId})`;
4088
+ toolTimeline.push(toolText);
4089
+ currentTools.push(toolText);
4090
+ await persistDraftAssistantTurn();
4091
+ }
4092
+ if (event.type === "run:completed" && assistantResponse.length === 0 && event.result.response) {
4093
+ assistantResponse = event.result.response;
4094
+ }
4095
+ await telemetry.emit(event);
4096
+ broadcastEvent(conversationId, event);
4097
+ try {
4098
+ response.write(formatSseEvent(event));
4099
+ } catch {
4100
+ }
4101
+ }
4102
+ if (currentTools.length > 0) {
4103
+ sections.push({ type: "tools", content: currentTools });
4104
+ }
4105
+ if (currentText.length > 0) {
4106
+ sections.push({ type: "text", content: currentText });
4107
+ }
4108
+ conversation.messages = [
4109
+ ...historyMessages,
4110
+ { role: "user", content: messageText },
4111
+ {
4112
+ role: "assistant",
4113
+ content: assistantResponse,
4114
+ metadata: toolTimeline.length > 0 || sections.length > 0 ? {
4115
+ toolActivity: toolTimeline,
4116
+ sections: sections.length > 0 ? sections : void 0
4117
+ } : void 0
4118
+ }
4119
+ ];
4120
+ conversation.runtimeRunId = latestRunId || conversation.runtimeRunId;
4121
+ conversation.pendingApprovals = [];
4122
+ conversation.updatedAt = Date.now();
4123
+ await conversationStore.update(conversation);
4124
+ } catch (error) {
4125
+ try {
4126
+ response.write(
4127
+ formatSseEvent({
4128
+ type: "run:error",
4129
+ runId: latestRunId || "run_unknown",
4130
+ error: {
4131
+ code: "RUN_ERROR",
4132
+ message: error instanceof Error ? error.message : "Unknown error"
4133
+ }
4134
+ })
4135
+ );
4136
+ } catch {
4137
+ const fallbackSections = [...sections];
4138
+ if (currentTools.length > 0) {
4139
+ fallbackSections.push({ type: "tools", content: [...currentTools] });
4140
+ }
4141
+ if (currentText.length > 0) {
4142
+ fallbackSections.push({ type: "text", content: currentText });
4143
+ }
4144
+ if (assistantResponse.length > 0 || toolTimeline.length > 0 || fallbackSections.length > 0) {
4145
+ conversation.messages = [
4146
+ ...historyMessages,
4147
+ { role: "user", content: messageText },
4148
+ {
4149
+ role: "assistant",
4150
+ content: assistantResponse,
4151
+ metadata: toolTimeline.length > 0 || fallbackSections.length > 0 ? {
4152
+ toolActivity: [...toolTimeline],
4153
+ sections: fallbackSections.length > 0 ? fallbackSections : void 0
4154
+ } : void 0
4155
+ }
4156
+ ];
4157
+ conversation.updatedAt = Date.now();
4158
+ await conversationStore.update(conversation);
4159
+ }
4160
+ }
4161
+ } finally {
4162
+ finishConversationStream(conversationId);
4163
+ await persistConversationPendingApprovals(conversationId);
4164
+ if (latestRunId) {
4165
+ runOwners.delete(latestRunId);
4166
+ runConversations.delete(latestRunId);
4167
+ }
4168
+ try {
4169
+ response.end();
4170
+ } catch {
4171
+ }
4172
+ }
4173
+ return;
4174
+ }
4175
+ writeJson(response, 404, { error: "Not found" });
4176
+ };
4177
+ };
4178
+ var startDevServer = async (port, options) => {
4179
+ const handler = await createRequestHandler(options);
4180
+ const server = createServer(handler);
4181
+ const actualPort = await listenOnAvailablePort(server, port);
4182
+ if (actualPort !== port) {
4183
+ process.stdout.write(`Port ${port} is in use, switched to ${actualPort}.
4184
+ `);
4185
+ }
4186
+ process.stdout.write(`Poncho dev server running at http://localhost:${actualPort}
4187
+ `);
4188
+ const shutdown = () => {
4189
+ server.close();
4190
+ server.closeAllConnections?.();
4191
+ process.exit(0);
4192
+ };
4193
+ process.on("SIGINT", shutdown);
4194
+ process.on("SIGTERM", shutdown);
4195
+ return server;
4196
+ };
4197
+ var runOnce = async (task, options) => {
4198
+ const workingDir = options.workingDir ?? process.cwd();
4199
+ dotenv.config({ path: resolve3(workingDir, ".env") });
4200
+ const config = await loadPonchoConfig(workingDir);
4201
+ const harness = new AgentHarness({ workingDir });
4202
+ const telemetry = new TelemetryEmitter(config?.telemetry);
4203
+ await harness.initialize();
4204
+ const fileBlobs = await Promise.all(
4205
+ options.filePaths.map(async (path) => {
4206
+ const content = await readFile3(resolve3(workingDir, path), "utf8");
4207
+ return `# File: ${path}
4208
+ ${content}`;
4209
+ })
4210
+ );
4211
+ const input2 = {
4212
+ task: fileBlobs.length > 0 ? `${task}
4213
+
4214
+ ${fileBlobs.join("\n\n")}` : task,
4215
+ parameters: options.params
4216
+ };
4217
+ if (options.json) {
4218
+ const output = await harness.runToCompletion(input2);
4219
+ for (const event of output.events) {
4220
+ await telemetry.emit(event);
4221
+ }
4222
+ process.stdout.write(`${JSON.stringify(output, null, 2)}
4223
+ `);
4224
+ return;
4225
+ }
4226
+ for await (const event of harness.runWithTelemetry(input2)) {
4227
+ await telemetry.emit(event);
4228
+ if (event.type === "model:chunk") {
4229
+ process.stdout.write(event.content);
4230
+ }
4231
+ if (event.type === "run:error") {
4232
+ process.stderr.write(`
4233
+ Error: ${event.error.message}
4234
+ `);
4235
+ }
4236
+ if (event.type === "run:completed") {
4237
+ process.stdout.write("\n");
4238
+ }
4239
+ }
4240
+ };
4241
+ var runInteractive = async (workingDir, params) => {
4242
+ dotenv.config({ path: resolve3(workingDir, ".env") });
4243
+ const config = await loadPonchoConfig(workingDir);
4244
+ let pendingApproval = null;
4245
+ let onApprovalRequest = null;
4246
+ const approvalHandler = async (request) => {
4247
+ return new Promise((resolveApproval) => {
4248
+ const req = {
4249
+ tool: request.tool,
4250
+ input: request.input,
4251
+ approvalId: request.approvalId,
4252
+ resolve: resolveApproval
4253
+ };
4254
+ pendingApproval = req;
4255
+ if (onApprovalRequest) {
4256
+ onApprovalRequest(req);
4257
+ }
4258
+ });
4259
+ };
4260
+ const harness = new AgentHarness({
4261
+ workingDir,
4262
+ environment: resolveHarnessEnvironment(),
4263
+ approvalHandler
4264
+ });
4265
+ await harness.initialize();
4266
+ try {
4267
+ const { runInteractiveInk } = await import("./run-interactive-ink-OGNG6UYE.js");
4268
+ await runInteractiveInk({
4269
+ harness,
4270
+ params,
4271
+ workingDir,
4272
+ config,
4273
+ conversationStore: createConversationStore(resolveStateConfig(config), { workingDir }),
4274
+ onSetApprovalCallback: (cb) => {
4275
+ onApprovalRequest = cb;
4276
+ if (pendingApproval) {
4277
+ cb(pendingApproval);
4278
+ }
4279
+ }
4280
+ });
4281
+ } finally {
4282
+ await harness.shutdown();
4283
+ }
4284
+ };
4285
+ var listTools = async (workingDir) => {
4286
+ dotenv.config({ path: resolve3(workingDir, ".env") });
4287
+ const harness = new AgentHarness({ workingDir });
4288
+ await harness.initialize();
4289
+ const tools = harness.listTools();
4290
+ if (tools.length === 0) {
4291
+ process.stdout.write("No tools registered.\n");
4292
+ return;
4293
+ }
4294
+ process.stdout.write("Available tools:\n");
4295
+ for (const tool of tools) {
4296
+ process.stdout.write(`- ${tool.name}: ${tool.description}
4297
+ `);
4298
+ }
4299
+ };
4300
+ var runPnpmInstall = async (workingDir) => await new Promise((resolveInstall, rejectInstall) => {
4301
+ const child = spawn("pnpm", ["install"], {
4302
+ cwd: workingDir,
4303
+ stdio: "inherit",
4304
+ env: process.env
4305
+ });
4306
+ child.on("exit", (code) => {
4307
+ if (code === 0) {
4308
+ resolveInstall();
4309
+ return;
4310
+ }
4311
+ rejectInstall(new Error(`pnpm install failed with exit code ${code ?? -1}`));
4312
+ });
4313
+ });
4314
+ var runInstallCommand = async (workingDir, packageNameOrPath) => await new Promise((resolveInstall, rejectInstall) => {
4315
+ const child = spawn("pnpm", ["add", packageNameOrPath], {
4316
+ cwd: workingDir,
4317
+ stdio: "inherit",
4318
+ env: process.env
4319
+ });
4320
+ child.on("exit", (code) => {
4321
+ if (code === 0) {
4322
+ resolveInstall();
4323
+ return;
4324
+ }
4325
+ rejectInstall(new Error(`pnpm add failed with exit code ${code ?? -1}`));
4326
+ });
4327
+ });
4328
+ var resolveInstalledPackageName = (packageNameOrPath) => {
4329
+ if (packageNameOrPath.startsWith(".") || packageNameOrPath.startsWith("/")) {
4330
+ return null;
4331
+ }
4332
+ if (packageNameOrPath.startsWith("@")) {
4333
+ return packageNameOrPath;
4334
+ }
4335
+ if (packageNameOrPath.includes("/")) {
4336
+ return packageNameOrPath.split("/").pop() ?? packageNameOrPath;
4337
+ }
4338
+ return packageNameOrPath;
4339
+ };
4340
+ var resolveSkillRoot = (workingDir, packageNameOrPath) => {
4341
+ if (packageNameOrPath.startsWith(".") || packageNameOrPath.startsWith("/")) {
4342
+ return resolve3(workingDir, packageNameOrPath);
4343
+ }
4344
+ const moduleName = resolveInstalledPackageName(packageNameOrPath) ?? packageNameOrPath;
4345
+ try {
4346
+ const packageJsonPath = require3.resolve(`${moduleName}/package.json`, {
4347
+ paths: [workingDir]
4348
+ });
4349
+ return resolve3(packageJsonPath, "..");
4350
+ } catch {
4351
+ const candidate = resolve3(workingDir, "node_modules", moduleName);
4352
+ if (existsSync(candidate)) {
4353
+ return candidate;
4354
+ }
4355
+ throw new Error(
4356
+ `Could not locate installed package "${moduleName}" in ${workingDir}`
4357
+ );
4358
+ }
4359
+ };
4360
+ var collectSkillManifests = async (dir, depth = 2) => {
4361
+ const manifests = [];
4362
+ const localManifest = resolve3(dir, "SKILL.md");
4363
+ try {
4364
+ await access2(localManifest);
4365
+ manifests.push(localManifest);
4366
+ } catch {
4367
+ }
4368
+ if (depth <= 0) return manifests;
4369
+ try {
4370
+ const entries = await readdir(dir, { withFileTypes: true });
4371
+ for (const entry of entries) {
4372
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
4373
+ let isDir = entry.isDirectory();
4374
+ if (!isDir && entry.isSymbolicLink()) {
4375
+ try {
4376
+ const s = await stat(resolve3(dir, entry.name));
4377
+ isDir = s.isDirectory();
4378
+ } catch {
4379
+ continue;
4380
+ }
4381
+ }
4382
+ if (isDir) {
4383
+ manifests.push(...await collectSkillManifests(resolve3(dir, entry.name), depth - 1));
4384
+ }
4385
+ }
4386
+ } catch {
4387
+ }
4388
+ return manifests;
4389
+ };
4390
+ var validateSkillPackage = async (workingDir, packageNameOrPath) => {
4391
+ const skillRoot = resolveSkillRoot(workingDir, packageNameOrPath);
4392
+ const manifests = await collectSkillManifests(skillRoot);
4393
+ if (manifests.length === 0) {
4394
+ throw new Error(`Skill validation failed: no SKILL.md found in ${skillRoot}`);
4395
+ }
4396
+ return { skillRoot, manifests };
4397
+ };
4398
+ var copySkillsIntoProject = async (workingDir, manifests) => {
4399
+ const skillsDir = resolve3(workingDir, "skills");
4400
+ await mkdir3(skillsDir, { recursive: true });
4401
+ const destinations = /* @__PURE__ */ new Map();
4402
+ for (const manifest of manifests) {
4403
+ const sourceSkillDir = dirname3(manifest);
4404
+ const skillFolderName = basename3(sourceSkillDir);
4405
+ if (destinations.has(skillFolderName)) {
4406
+ throw new Error(
4407
+ `Skill copy failed: multiple skill directories map to "skills/${skillFolderName}" (${destinations.get(skillFolderName)} and ${sourceSkillDir}).`
4408
+ );
4409
+ }
4410
+ destinations.set(skillFolderName, sourceSkillDir);
4411
+ }
4412
+ const copied = [];
4413
+ for (const [skillFolderName, sourceSkillDir] of destinations.entries()) {
4414
+ const destinationSkillDir = resolve3(skillsDir, skillFolderName);
4415
+ if (existsSync(destinationSkillDir)) {
4416
+ throw new Error(
4417
+ `Skill copy failed: destination already exists at ${destinationSkillDir}. Remove or rename it and try again.`
4418
+ );
4419
+ }
4420
+ await cp(sourceSkillDir, destinationSkillDir, {
4421
+ recursive: true,
4422
+ dereference: true,
4423
+ force: false,
4424
+ errorOnExist: true
4425
+ });
4426
+ copied.push(relative(workingDir, destinationSkillDir).split("\\").join("/"));
4427
+ }
4428
+ return copied.sort();
4429
+ };
4430
+ var copySkillsFromPackage = async (workingDir, packageNameOrPath) => {
4431
+ const { manifests } = await validateSkillPackage(workingDir, packageNameOrPath);
4432
+ return await copySkillsIntoProject(workingDir, manifests);
4433
+ };
4434
+ var addSkill = async (workingDir, packageNameOrPath) => {
4435
+ await runInstallCommand(workingDir, packageNameOrPath);
4436
+ const copiedSkills = await copySkillsFromPackage(workingDir, packageNameOrPath);
4437
+ process.stdout.write(
4438
+ `Added ${copiedSkills.length} skill${copiedSkills.length === 1 ? "" : "s"} from ${packageNameOrPath}:
4439
+ `
4440
+ );
4441
+ for (const copied of copiedSkills) {
4442
+ process.stdout.write(`- ${copied}
4443
+ `);
4444
+ }
4445
+ };
4446
+ var runTests = async (workingDir, filePath) => {
4447
+ dotenv.config({ path: resolve3(workingDir, ".env") });
4448
+ const testFilePath = filePath ?? resolve3(workingDir, "tests", "basic.yaml");
4449
+ const content = await readFile3(testFilePath, "utf8");
4450
+ const parsed = YAML.parse(content);
4451
+ const tests = parsed.tests ?? [];
4452
+ const harness = new AgentHarness({ workingDir });
4453
+ await harness.initialize();
4454
+ let passed = 0;
4455
+ let failed = 0;
4456
+ for (const testCase of tests) {
4457
+ try {
4458
+ const output = await harness.runToCompletion({ task: testCase.task });
4459
+ const response = output.result.response ?? "";
4460
+ const events = output.events;
4461
+ const expectation = testCase.expect ?? {};
4462
+ const checks = [];
4463
+ if (expectation.contains) {
4464
+ checks.push(response.includes(expectation.contains));
4465
+ }
4466
+ if (typeof expectation.maxSteps === "number") {
4467
+ checks.push(output.result.steps <= expectation.maxSteps);
4468
+ }
4469
+ if (typeof expectation.maxTokens === "number") {
4470
+ checks.push(
4471
+ output.result.tokens.input + output.result.tokens.output <= expectation.maxTokens
4472
+ );
4473
+ }
4474
+ if (expectation.refusal) {
4475
+ checks.push(
4476
+ response.toLowerCase().includes("can't") || response.toLowerCase().includes("cannot")
4477
+ );
4478
+ }
4479
+ if (expectation.toolCalled) {
4480
+ checks.push(
4481
+ events.some(
4482
+ (event) => event.type === "tool:started" && event.tool === expectation.toolCalled
4483
+ )
4484
+ );
4485
+ }
4486
+ const ok = checks.length === 0 ? output.result.status === "completed" : checks.every(Boolean);
4487
+ if (ok) {
4488
+ passed += 1;
4489
+ process.stdout.write(`PASS ${testCase.name}
4490
+ `);
4491
+ } else {
4492
+ failed += 1;
4493
+ process.stdout.write(`FAIL ${testCase.name}
4494
+ `);
4495
+ }
4496
+ } catch (error) {
4497
+ failed += 1;
4498
+ process.stdout.write(
4499
+ `FAIL ${testCase.name} (${error instanceof Error ? error.message : "Unknown test error"})
4500
+ `
4501
+ );
4502
+ }
4503
+ }
4504
+ process.stdout.write(`
4505
+ Test summary: ${passed} passed, ${failed} failed
4506
+ `);
4507
+ return { passed, failed };
4508
+ };
4509
+ var buildTarget = async (workingDir, target) => {
4510
+ const outDir = resolve3(workingDir, ".poncho-build", target);
4511
+ await mkdir3(outDir, { recursive: true });
4512
+ const serverEntrypoint = `import { startDevServer } from "@poncho-ai/cli";
4513
+
4514
+ const port = Number.parseInt(process.env.PORT ?? "3000", 10);
4515
+ await startDevServer(Number.isNaN(port) ? 3000 : port, { workingDir: process.cwd() });
4516
+ `;
4517
+ const runtimePackageJson = JSON.stringify(
4518
+ {
4519
+ name: "poncho-runtime-bundle",
4520
+ private: true,
4521
+ type: "module",
4522
+ scripts: {
4523
+ start: "node server.js"
4524
+ },
4525
+ dependencies: {
4526
+ "@poncho-ai/cli": "^0.1.0"
4527
+ }
4528
+ },
4529
+ null,
4530
+ 2
4531
+ );
4532
+ if (target === "vercel") {
4533
+ await mkdir3(resolve3(outDir, "api"), { recursive: true });
4534
+ await copyIfExists(resolve3(workingDir, "AGENT.md"), resolve3(outDir, "AGENT.md"));
4535
+ await copyIfExists(
4536
+ resolve3(workingDir, "poncho.config.js"),
4537
+ resolve3(outDir, "poncho.config.js")
4538
+ );
4539
+ await copyIfExists(resolve3(workingDir, "skills"), resolve3(outDir, "skills"));
4540
+ await copyIfExists(resolve3(workingDir, "tests"), resolve3(outDir, "tests"));
4541
+ await writeFile3(
4542
+ resolve3(outDir, "vercel.json"),
4543
+ JSON.stringify(
4544
+ {
4545
+ version: 2,
4546
+ functions: {
4547
+ "api/index.js": {
4548
+ includeFiles: "{AGENT.md,poncho.config.js,skills/**,tests/**}"
4549
+ }
4550
+ },
4551
+ routes: [{ src: "/(.*)", dest: "/api/index.js" }]
4552
+ },
4553
+ null,
4554
+ 2
4555
+ ),
4556
+ "utf8"
4557
+ );
4558
+ await buildVercelHandlerBundle(outDir);
4559
+ await writeFile3(
4560
+ resolve3(outDir, "package.json"),
4561
+ JSON.stringify(
4562
+ {
4563
+ private: true,
4564
+ type: "module",
4565
+ engines: {
4566
+ node: "20.x"
4567
+ },
4568
+ dependencies: VERCEL_RUNTIME_DEPENDENCIES
4569
+ },
4570
+ null,
4571
+ 2
4572
+ ),
4573
+ "utf8"
4574
+ );
4575
+ } else if (target === "docker") {
4576
+ await writeFile3(
4577
+ resolve3(outDir, "Dockerfile"),
4578
+ `FROM node:20-slim
4579
+ WORKDIR /app
4580
+ COPY package.json package.json
4581
+ COPY AGENT.md AGENT.md
4582
+ COPY poncho.config.js poncho.config.js
4583
+ COPY skills skills
4584
+ COPY tests tests
4585
+ COPY .env.example .env.example
4586
+ RUN corepack enable && npm install -g @poncho-ai/cli
4587
+ COPY server.js server.js
4588
+ EXPOSE 3000
4589
+ CMD ["node","server.js"]
4590
+ `,
4591
+ "utf8"
4592
+ );
4593
+ await writeFile3(resolve3(outDir, "server.js"), serverEntrypoint, "utf8");
4594
+ await writeFile3(resolve3(outDir, "package.json"), runtimePackageJson, "utf8");
4595
+ } else if (target === "lambda") {
4596
+ await writeFile3(
4597
+ resolve3(outDir, "lambda-handler.js"),
4598
+ `import { startDevServer } from "@poncho-ai/cli";
4599
+ let serverPromise;
4600
+ export const handler = async (event = {}) => {
4601
+ if (!serverPromise) {
4602
+ serverPromise = startDevServer(0, { workingDir: process.cwd() });
4603
+ }
4604
+ const body = JSON.stringify({
4605
+ status: "ready",
4606
+ route: event.rawPath ?? event.path ?? "/",
4607
+ });
4608
+ return { statusCode: 200, headers: { "content-type": "application/json" }, body };
4609
+ };
4610
+ `,
4611
+ "utf8"
4612
+ );
4613
+ await writeFile3(resolve3(outDir, "package.json"), runtimePackageJson, "utf8");
4614
+ } else if (target === "fly") {
4615
+ await writeFile3(
4616
+ resolve3(outDir, "fly.toml"),
4617
+ `app = "poncho-app"
4618
+ [env]
4619
+ PORT = "3000"
4620
+ [http_service]
4621
+ internal_port = 3000
4622
+ force_https = true
4623
+ auto_start_machines = true
4624
+ auto_stop_machines = "stop"
4625
+ min_machines_running = 0
4626
+ `,
4627
+ "utf8"
4628
+ );
4629
+ await writeFile3(
4630
+ resolve3(outDir, "Dockerfile"),
4631
+ `FROM node:20-slim
4632
+ WORKDIR /app
4633
+ COPY package.json package.json
4634
+ COPY AGENT.md AGENT.md
4635
+ COPY poncho.config.js poncho.config.js
4636
+ COPY skills skills
4637
+ COPY tests tests
4638
+ RUN npm install -g @poncho-ai/cli
4639
+ COPY server.js server.js
4640
+ EXPOSE 3000
4641
+ CMD ["node","server.js"]
4642
+ `,
4643
+ "utf8"
4644
+ );
4645
+ await writeFile3(resolve3(outDir, "server.js"), serverEntrypoint, "utf8");
4646
+ await writeFile3(resolve3(outDir, "package.json"), runtimePackageJson, "utf8");
4647
+ } else {
4648
+ throw new Error(`Unsupported build target: ${target}`);
4649
+ }
4650
+ process.stdout.write(`Build artifacts generated at ${outDir}
4651
+ `);
4652
+ };
4653
+ var normalizeMcpName = (entry) => entry.name ?? entry.url ?? `mcp_${Date.now()}`;
4654
+ var mcpAdd = async (workingDir, options) => {
4655
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
4656
+ const mcp = [...config.mcp ?? []];
4657
+ if (!options.url) {
4658
+ throw new Error("Remote MCP only: provide --url for a remote MCP server.");
4659
+ }
4660
+ if (options.url.startsWith("ws://") || options.url.startsWith("wss://")) {
4661
+ throw new Error("WebSocket MCP URLs are no longer supported. Use an HTTP MCP endpoint.");
4662
+ }
4663
+ if (!options.url.startsWith("http://") && !options.url.startsWith("https://")) {
4664
+ throw new Error("Invalid MCP URL. Expected http:// or https://.");
4665
+ }
4666
+ const serverName = options.name ?? normalizeMcpName({ url: options.url });
4667
+ mcp.push({
4668
+ name: serverName,
4669
+ url: options.url,
4670
+ env: options.envVars ?? [],
4671
+ auth: options.authBearerEnv ? {
4672
+ type: "bearer",
4673
+ tokenEnv: options.authBearerEnv
4674
+ } : void 0
4675
+ });
4676
+ await writeConfigFile(workingDir, { ...config, mcp });
4677
+ let envSeedMessage;
4678
+ if (options.authBearerEnv) {
4679
+ const envPath = resolve3(workingDir, ".env");
4680
+ const envExamplePath = resolve3(workingDir, ".env.example");
4681
+ const addedEnv = await ensureEnvPlaceholder(envPath, options.authBearerEnv);
4682
+ const addedEnvExample = await ensureEnvPlaceholder(envExamplePath, options.authBearerEnv);
4683
+ if (addedEnv || addedEnvExample) {
4684
+ envSeedMessage = `Added ${options.authBearerEnv}= to ${addedEnv ? ".env" : ""}${addedEnv && addedEnvExample ? " and " : ""}${addedEnvExample ? ".env.example" : ""}.`;
4685
+ }
4686
+ }
4687
+ const nextSteps = [];
4688
+ let step = 1;
4689
+ if (options.authBearerEnv) {
4690
+ nextSteps.push(` ${step}) Set token in .env: ${options.authBearerEnv}=...`);
4691
+ step += 1;
4692
+ }
4693
+ nextSteps.push(` ${step}) Discover tools: poncho mcp tools list ${serverName}`);
4694
+ step += 1;
4695
+ nextSteps.push(` ${step}) Select tools: poncho mcp tools select ${serverName}`);
4696
+ step += 1;
4697
+ nextSteps.push(` ${step}) Verify config: poncho mcp list`);
4698
+ process.stdout.write(
4699
+ [
4700
+ `MCP server added: ${serverName}`,
4701
+ ...envSeedMessage ? [envSeedMessage] : [],
4702
+ "Next steps:",
4703
+ ...nextSteps,
4704
+ ""
4705
+ ].join("\n")
4706
+ );
4707
+ };
4708
+ var mcpList = async (workingDir) => {
4709
+ const config = await loadPonchoConfig(workingDir);
4710
+ const mcp = config?.mcp ?? [];
4711
+ if (mcp.length === 0) {
4712
+ process.stdout.write("No MCP servers configured.\n");
4713
+ return;
4714
+ }
4715
+ process.stdout.write("Configured MCP servers:\n");
4716
+ for (const entry of mcp) {
4717
+ const auth = entry.auth?.type === "bearer" ? `auth=bearer:${entry.auth.tokenEnv}` : "auth=none";
4718
+ process.stdout.write(
4719
+ `- ${entry.name ?? entry.url} (remote: ${entry.url}, ${auth})
4720
+ `
4721
+ );
4722
+ }
4723
+ };
4724
+ var mcpRemove = async (workingDir, name) => {
4725
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
4726
+ const before = config.mcp ?? [];
4727
+ const removed = before.filter((entry) => normalizeMcpName(entry) === name);
4728
+ const filtered = before.filter((entry) => normalizeMcpName(entry) !== name);
4729
+ await writeConfigFile(workingDir, { ...config, mcp: filtered });
4730
+ const removedTokenEnvNames = new Set(
4731
+ removed.map(
4732
+ (entry) => entry.auth?.type === "bearer" ? entry.auth.tokenEnv?.trim() ?? "" : ""
4733
+ ).filter((value) => value.length > 0)
4734
+ );
4735
+ const stillUsedTokenEnvNames = new Set(
4736
+ filtered.map(
4737
+ (entry) => entry.auth?.type === "bearer" ? entry.auth.tokenEnv?.trim() ?? "" : ""
4738
+ ).filter((value) => value.length > 0)
4739
+ );
4740
+ const removedFromExample = [];
4741
+ for (const tokenEnv of removedTokenEnvNames) {
4742
+ if (stillUsedTokenEnvNames.has(tokenEnv)) {
4743
+ continue;
4744
+ }
4745
+ const changed = await removeEnvPlaceholder(resolve3(workingDir, ".env.example"), tokenEnv);
4746
+ if (changed) {
4747
+ removedFromExample.push(tokenEnv);
4748
+ }
4749
+ }
4750
+ process.stdout.write(`Removed MCP server: ${name}
4751
+ `);
4752
+ if (removedFromExample.length > 0) {
4753
+ process.stdout.write(
4754
+ `Removed unused token placeholder(s) from .env.example: ${removedFromExample.join(", ")}
4755
+ `
4756
+ );
4757
+ }
4758
+ };
4759
+ var resolveMcpEntry = async (workingDir, serverName) => {
4760
+ const config = await loadPonchoConfig(workingDir) ?? { mcp: [] };
4761
+ const entries = config.mcp ?? [];
4762
+ const index = entries.findIndex((entry) => normalizeMcpName(entry) === serverName);
4763
+ if (index < 0) {
4764
+ throw new Error(`MCP server "${serverName}" is not configured.`);
4765
+ }
4766
+ return { config, index };
4767
+ };
4768
+ var discoverMcpTools = async (workingDir, serverName) => {
4769
+ dotenv.config({ path: resolve3(workingDir, ".env") });
4770
+ const { config, index } = await resolveMcpEntry(workingDir, serverName);
4771
+ const entry = (config.mcp ?? [])[index];
4772
+ const bridge = new LocalMcpBridge({ mcp: [entry] });
4773
+ try {
4774
+ await bridge.startLocalServers();
4775
+ await bridge.discoverTools();
4776
+ return bridge.listDiscoveredTools(normalizeMcpName(entry));
4777
+ } finally {
4778
+ await bridge.stopLocalServers();
4779
+ }
4780
+ };
4781
+ var mcpToolsList = async (workingDir, serverName) => {
4782
+ const discovered = await discoverMcpTools(workingDir, serverName);
4783
+ if (discovered.length === 0) {
4784
+ process.stdout.write(`No tools discovered for MCP server "${serverName}".
4785
+ `);
4786
+ return;
4787
+ }
4788
+ process.stdout.write(`Discovered tools for "${serverName}":
4789
+ `);
4790
+ for (const tool of discovered) {
4791
+ process.stdout.write(`- ${tool}
4792
+ `);
4793
+ }
4794
+ };
4795
+ var mcpToolsSelect = async (workingDir, serverName, options) => {
4796
+ const discovered = await discoverMcpTools(workingDir, serverName);
4797
+ if (discovered.length === 0) {
4798
+ process.stdout.write(`No tools discovered for MCP server "${serverName}".
4799
+ `);
4800
+ return;
4801
+ }
4802
+ let selected = [];
4803
+ if (options.all) {
4804
+ selected = [...discovered];
4805
+ } else if (options.toolsCsv && options.toolsCsv.trim().length > 0) {
4806
+ const requested = options.toolsCsv.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
4807
+ selected = discovered.filter((tool) => requested.includes(tool));
4808
+ } else {
4809
+ process.stdout.write(`Discovered tools for "${serverName}":
4810
+ `);
4811
+ discovered.forEach((tool, idx) => {
4812
+ process.stdout.write(`${idx + 1}. ${tool}
4813
+ `);
4814
+ });
4815
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
4816
+ const answer = await rl.question(
4817
+ "Enter comma-separated tool numbers/names to allow (or * for all): "
4818
+ );
4819
+ rl.close();
4820
+ const raw = answer.trim();
4821
+ if (raw === "*") {
4822
+ selected = [...discovered];
4823
+ } else {
4824
+ const tokens = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
4825
+ const fromIndex = tokens.map((token) => Number.parseInt(token, 10)).filter((value) => !Number.isNaN(value)).map((index) => discovered[index - 1]).filter((value) => typeof value === "string");
4826
+ const byName = discovered.filter((tool) => tokens.includes(tool));
4827
+ selected = [.../* @__PURE__ */ new Set([...fromIndex, ...byName])];
4828
+ }
4829
+ }
4830
+ if (selected.length === 0) {
4831
+ throw new Error("No valid tools selected.");
4832
+ }
4833
+ const includePatterns = selected.length === discovered.length ? [`${serverName}/*`] : selected.sort();
4834
+ process.stdout.write(`Selected MCP tools: ${includePatterns.join(", ")}
4835
+ `);
4836
+ process.stdout.write(
4837
+ "\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"
4838
+ );
4839
+ process.stdout.write(
4840
+ "\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"
4841
+ );
4842
+ process.stdout.write(
4843
+ "\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"
4844
+ );
4845
+ };
4846
+ var buildCli = () => {
4847
+ const program = new Command();
4848
+ program.name("poncho").description("CLI for building and running Poncho agents").version("0.1.0");
4849
+ 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) => {
4850
+ await initProject(name, {
4851
+ onboarding: {
4852
+ yes: options.yes,
4853
+ interactive: !options.yes && process.stdin.isTTY === true && process.stdout.isTTY === true
4854
+ }
4855
+ });
4856
+ });
4857
+ program.command("dev").description("Run local development server").option("--port <port>", "server port", "3000").action(async (options) => {
4858
+ const port = Number.parseInt(options.port, 10);
4859
+ await startDevServer(Number.isNaN(port) ? 3e3 : port);
4860
+ });
4861
+ program.command("run").argument("[task]", "task to run").description("Execute the agent once").option("--param <keyValue>", "parameter key=value", (value, all) => {
4862
+ all.push(value);
4863
+ return all;
4864
+ }, []).option("--file <path>", "include file contents", (value, all) => {
4865
+ all.push(value);
4866
+ return all;
4867
+ }, []).option("--json", "output json", false).option("--interactive", "run in interactive mode", false).action(
4868
+ async (task, options) => {
4869
+ const params = parseParams(options.param);
4870
+ if (options.interactive) {
4871
+ await runInteractive(process.cwd(), params);
4872
+ return;
4873
+ }
4874
+ if (!task) {
4875
+ throw new Error("Task is required unless --interactive is used.");
4876
+ }
4877
+ await runOnce(task, {
4878
+ params,
4879
+ json: options.json,
4880
+ filePaths: options.file
4881
+ });
4882
+ }
4883
+ );
4884
+ program.command("tools").description("List all tools available to the agent").action(async () => {
4885
+ await listTools(process.cwd());
4886
+ });
4887
+ program.command("add").argument("<packageOrPath>", "skill package name/path").description("Add a skill package, validate SKILL.md, and copy skills into ./skills").action(async (packageOrPath) => {
4888
+ await addSkill(process.cwd(), packageOrPath);
4889
+ });
4890
+ program.command("update-agent").description("Remove deprecated embedded local guidance from AGENT.md").action(async () => {
4891
+ await updateAgentGuidance(process.cwd());
4892
+ });
4893
+ program.command("test").argument("[file]", "test file path (yaml)").description("Run yaml-defined agent tests").action(async (file) => {
4894
+ const testFile = file ? resolve3(process.cwd(), file) : void 0;
4895
+ const result = await runTests(process.cwd(), testFile);
4896
+ if (result.failed > 0) {
4897
+ process.exitCode = 1;
4898
+ }
4899
+ });
4900
+ program.command("build").argument("<target>", "vercel|docker|lambda|fly").description("Generate build artifacts for deployment target").action(async (target) => {
4901
+ await buildTarget(process.cwd(), target);
4902
+ });
4903
+ const mcpCommand = program.command("mcp").description("Manage MCP servers");
4904
+ mcpCommand.command("add").requiredOption("--url <url>", "remote MCP url").option("--name <name>", "server name").option(
4905
+ "--auth-bearer-env <name>",
4906
+ "env var name containing bearer token for this MCP server"
4907
+ ).option("--env <name>", "env variable (repeatable)", (value, all) => {
4908
+ all.push(value);
4909
+ return all;
4910
+ }, []).action(
4911
+ async (options) => {
4912
+ await mcpAdd(process.cwd(), {
4913
+ url: options.url,
4914
+ name: options.name,
4915
+ envVars: options.env,
4916
+ authBearerEnv: options.authBearerEnv
4917
+ });
4918
+ }
4919
+ );
4920
+ mcpCommand.command("list").description("List configured MCP servers").action(async () => {
4921
+ await mcpList(process.cwd());
4922
+ });
4923
+ mcpCommand.command("remove").argument("<name>", "server name").description("Remove an MCP server by name").action(async (name) => {
4924
+ await mcpRemove(process.cwd(), name);
4925
+ });
4926
+ const mcpToolsCommand = mcpCommand.command("tools").description("Discover and curate tools for a configured MCP server");
4927
+ mcpToolsCommand.command("list").argument("<name>", "server name").description("Discover and list tools from a configured MCP server").action(async (name) => {
4928
+ await mcpToolsList(process.cwd(), name);
4929
+ });
4930
+ 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(
4931
+ async (name, options) => {
4932
+ await mcpToolsSelect(process.cwd(), name, {
4933
+ all: options.all,
4934
+ toolsCsv: options.tools
4935
+ });
4936
+ }
4937
+ );
4938
+ return program;
4939
+ };
4940
+ var main = async (argv = process.argv) => {
4941
+ try {
4942
+ await buildCli().parseAsync(argv);
4943
+ } catch (error) {
4944
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EADDRINUSE") {
4945
+ const message = "Port is already in use. Try `poncho dev --port 3001` or stop the process using port 3000.";
4946
+ process.stderr.write(`${message}
4947
+ `);
4948
+ process.exitCode = 1;
4949
+ return;
4950
+ }
4951
+ process.stderr.write(`${error instanceof Error ? error.message : "Unknown CLI error"}
4952
+ `);
4953
+ process.exitCode = 1;
4954
+ }
4955
+ };
4956
+ var packageRoot = resolve3(__dirname, "..");
4957
+
4958
+ export {
4959
+ inferConversationTitle,
4960
+ consumeFirstRunIntro,
4961
+ resolveHarnessEnvironment,
4962
+ initProject,
4963
+ updateAgentGuidance,
4964
+ createRequestHandler,
4965
+ startDevServer,
4966
+ runOnce,
4967
+ runInteractive,
4968
+ listTools,
4969
+ copySkillsFromPackage,
4970
+ addSkill,
4971
+ runTests,
4972
+ buildTarget,
4973
+ mcpAdd,
4974
+ mcpList,
4975
+ mcpRemove,
4976
+ mcpToolsList,
4977
+ mcpToolsSelect,
4978
+ buildCli,
4979
+ main,
4980
+ packageRoot
4981
+ };