@juiceboxcreative/loop 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs ADDED
@@ -0,0 +1,3723 @@
1
+ #!/usr/bin/env node
2
+ import { pD } from "./_chunks/libs/@clack/core.mjs";
3
+ import { Ie, M, Se, Y, ge, he, ve, xe, ye } from "./_chunks/libs/@clack/prompts.mjs";
4
+ import { chmodSync, closeSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, extname, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { parseArgs } from "node:util";
8
+ import { clearLine, createInterface, cursorTo } from "node:readline";
9
+ import { Writable } from "node:stream";
10
+ import { homedir, tmpdir } from "node:os";
11
+ import { execFileSync, spawn } from "node:child_process";
12
+ import { randomBytes, randomUUID } from "node:crypto";
13
+ import { createServer } from "node:http";
14
+ var AuthError = class extends Error {
15
+ constructor() {
16
+ super("Not logged in or token expired. Run loop login");
17
+ }
18
+ };
19
+ var NetworkError = class extends Error {
20
+ constructor(message, cause) {
21
+ super(message, { cause });
22
+ }
23
+ };
24
+ var ApiError = class extends Error {
25
+ status;
26
+ body;
27
+ retryAfterMs;
28
+ constructor(status, message, body, retryAfterMs) {
29
+ super(message);
30
+ this.status = status;
31
+ this.body = body;
32
+ this.retryAfterMs = retryAfterMs;
33
+ }
34
+ };
35
+ function parseRetryAfter(value, now = Date.now()) {
36
+ const v = value?.trim();
37
+ if (!v) return void 0;
38
+ if (/^\d+$/.test(v)) return Number(v) * 1e3;
39
+ const at = Date.parse(v);
40
+ return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
41
+ }
42
+ function withKind(clarity) {
43
+ return {
44
+ ...clarity,
45
+ kind: clarity.code === "task_plan_choice" ? "plan_choice" : "question"
46
+ };
47
+ }
48
+ function messageFrom(body, status) {
49
+ if (body && typeof body === "object") {
50
+ const b = body;
51
+ const details = b.errors ? Object.values(b.errors).flat().filter((v) => typeof v === "string").join(" ") : "";
52
+ if (typeof b.message === "string" && b.message) return details && !b.message.includes(details) ? `${b.message} ${details}` : b.message;
53
+ }
54
+ return `Request failed with status ${status}`;
55
+ }
56
+ function networkFailure(err, timeoutMs) {
57
+ return new NetworkError(err instanceof Error && err.name === "TimeoutError" ? `Loop did not answer within ${Math.round(timeoutMs / 100) / 10} s` : err instanceof Error ? err.message : String(err), err);
58
+ }
59
+ function createClient(apiUrl, token, settings = {}) {
60
+ const base = apiUrl.replace(/\/+$/, "");
61
+ const clientTimeout = settings.timeoutMs ?? 3e4;
62
+ async function request(method, path, body, cap = Infinity) {
63
+ const timeoutMs = Math.max(1, Math.min(clientTimeout, cap));
64
+ let res;
65
+ try {
66
+ res = await fetch(`${base}${path}`, {
67
+ method,
68
+ headers: {
69
+ Authorization: `Bearer ${token}`,
70
+ Accept: "application/json",
71
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
72
+ },
73
+ body: body === void 0 ? void 0 : JSON.stringify(body),
74
+ signal: AbortSignal.timeout(timeoutMs)
75
+ });
76
+ } catch (err) {
77
+ throw networkFailure(err, timeoutMs);
78
+ }
79
+ if (res.status === 401) throw new AuthError();
80
+ let text;
81
+ try {
82
+ text = await res.text();
83
+ } catch (err) {
84
+ throw networkFailure(err, timeoutMs);
85
+ }
86
+ let json = null;
87
+ try {
88
+ json = text ? JSON.parse(text) : null;
89
+ } catch {
90
+ json = null;
91
+ }
92
+ if (!res.ok) throw new ApiError(res.status, messageFrom(json, res.status), json, parseRetryAfter(res.headers.get("retry-after")));
93
+ return json;
94
+ }
95
+ return {
96
+ get: (path, query, opts) => {
97
+ return request("GET", `${path}${query ? `?${new URLSearchParams(query)}` : ""}`, void 0, opts?.timeoutMs);
98
+ },
99
+ post: (path, body) => request("POST", path, body)
100
+ };
101
+ }
102
+ async function findProjectsByRepository(api, repository) {
103
+ return (await api.get("/api/v2/projects", {
104
+ repository,
105
+ per_page: "50"
106
+ })).data ?? [];
107
+ }
108
+ async function findProjectBySlug(api, slug) {
109
+ const res = await api.get(`/api/v2/projects/${encodeURIComponent(slug)}`);
110
+ return "data" in res && res.data ? res.data : res;
111
+ }
112
+ async function findSkillBySlug(api, slug) {
113
+ return ((await api.get("/api/skills", {
114
+ q: slug,
115
+ per_page: "100"
116
+ })).data ?? []).find((s) => s.slug === slug) ?? null;
117
+ }
118
+ function createTask(api, payload) {
119
+ return api.post("/api/v2/tasks", payload);
120
+ }
121
+ async function getTask(api, id) {
122
+ const res = await api.get(`/api/v2/tasks/${id}`);
123
+ return "data" in res && res.data ? res.data : res;
124
+ }
125
+ async function findTaskByKey(api, key) {
126
+ return (await api.get("/api/v2/tasks", {
127
+ key,
128
+ per_page: "1"
129
+ })).data?.[0] ?? null;
130
+ }
131
+ async function getMe(api) {
132
+ const res = await api.get("/api/me");
133
+ return "data" in res && res.data ? res.data : res;
134
+ }
135
+ function taskUrl(webUrl, task) {
136
+ return `${webUrl.replace(/\/+$/, "")}/tasks/${task.id}`;
137
+ }
138
+ async function approvePlan(api, task) {
139
+ try {
140
+ const res = await api.post(`/api/v2/tasks/${task.id}/plan/approve`, void 0);
141
+ return {
142
+ id: task.id,
143
+ key: task.key,
144
+ approved: true,
145
+ dispatched: res.dispatched ?? false,
146
+ queued: res.queued ?? false,
147
+ dispatch_error: res.dispatch_error ?? null
148
+ };
149
+ } catch (err) {
150
+ if (err instanceof ApiError && err.status === 409) throw new Error(`${task.key} has no plan waiting for approval. Create it with --plan, then wait for the plan.`, { cause: err });
151
+ throw err;
152
+ }
153
+ }
154
+ const REFUSED_BY_EXTENSION = Object.fromEntries(Object.entries({
155
+ "application/octet-stream": "bin bpk bpmn buffer class csr deploy dist distz dll dmn dms dst dump elc exe img kdb lha lrf lzh mar msm msp phar pkg pv pxf sea so sst",
156
+ "application/x-7z-compressed": "7z 7zip",
157
+ "application/x-abiword": "abw",
158
+ "application/x-ace-compressed": "ace",
159
+ "application/x-apple-diskimage": "dmg",
160
+ "application/x-arj": "arj",
161
+ "application/x-authorware-bin": "aab u32 vox x32",
162
+ "application/x-authorware-map": "aam",
163
+ "application/x-authorware-seg": "aas",
164
+ "application/x-bcpio": "bcpio",
165
+ "application/x-bdoc": "bdoc",
166
+ "application/x-bittorrent": "torrent",
167
+ "application/x-blender": "blend",
168
+ "application/x-blorb": "blb blorb",
169
+ "application/x-bzip": "bz",
170
+ "application/x-bzip2": "boz bz2",
171
+ "application/x-cbr": "cb7 cba cbr cbt cbz",
172
+ "application/x-cdlink": "vcd",
173
+ "application/x-cfs-compressed": "cfs",
174
+ "application/x-chat": "chat",
175
+ "application/x-chess-pgn": "pgn",
176
+ "application/x-chrome-extension": "crx",
177
+ "application/x-cocoa": "cco",
178
+ "application/x-compress": "z",
179
+ "application/x-conference": "nsc",
180
+ "application/x-cpio": "cpio",
181
+ "application/x-csh": "csh",
182
+ "application/x-debian-package": "deb udeb",
183
+ "application/x-dgc-compressed": "dgc",
184
+ "application/x-director": "cct cst cxt dcr dir dxr fgd swa w3d",
185
+ "application/x-doom": "wad",
186
+ "application/x-dtbncx+xml": "ncx",
187
+ "application/x-dtbook+xml": "dtb",
188
+ "application/x-dtbresource+xml": "res",
189
+ "application/x-dvi": "dvi",
190
+ "application/x-envoy": "evy",
191
+ "application/x-eva": "eva",
192
+ "application/x-font-bdf": "bdf",
193
+ "application/x-font-ghostscript": "gsf",
194
+ "application/x-font-linux-psf": "psf",
195
+ "application/x-font-pcf": "pcf",
196
+ "application/x-font-snf": "snf",
197
+ "application/x-font-type1": "afm pfa pfb pfm",
198
+ "application/x-freearc": "arc",
199
+ "application/x-futuresplash": "spl",
200
+ "application/x-gca-compressed": "gca",
201
+ "application/x-glulx": "ulx",
202
+ "application/x-gnumeric": "gnumeric",
203
+ "application/x-gramps-xml": "gramps",
204
+ "application/x-gtar": "gtar",
205
+ "application/x-hdf": "hdf",
206
+ "application/x-httpd-php": "php php3 php4 phtml",
207
+ "application/x-httpd-php-source": "phps",
208
+ "application/x-indesign": "indd",
209
+ "application/x-install-instructions": "install",
210
+ "application/x-ipynb+json": "ipynb",
211
+ "application/x-iso9660-image": "iso",
212
+ "application/x-iwork-keynote-sffkey": "key",
213
+ "application/x-iwork-numbers-sffnumbers": "numbers",
214
+ "application/x-iwork-pages-sffpages": "pages",
215
+ "application/x-java-archive-diff": "jardiff",
216
+ "application/x-java-jnlp-file": "jnlp",
217
+ "application/x-keepass2": "kdbx",
218
+ "application/x-latex": "latex",
219
+ "application/x-lua-bytecode": "luac",
220
+ "application/x-makeself": "run",
221
+ "application/x-mie": "mie",
222
+ "application/x-mobipocket-ebook": "mobi",
223
+ "application/x-ms-application": "application",
224
+ "application/x-ms-shortcut": "lnk",
225
+ "application/x-ms-wmd": "wmd",
226
+ "application/x-ms-xbap": "xbap",
227
+ "application/x-msaccess": "mdb",
228
+ "application/x-msbinder": "obd",
229
+ "application/x-mscardfile": "crd",
230
+ "application/x-msclip": "clp",
231
+ "application/x-msdownload": "bat com msi",
232
+ "application/x-msmediaview": "m13 m14 mvb",
233
+ "application/x-msmetafile": "emz wmz",
234
+ "application/x-msmoney": "mny",
235
+ "application/x-mspublisher": "pub",
236
+ "application/x-msschedule": "scd",
237
+ "application/x-msterminal": "trm",
238
+ "application/x-mswrite": "wri",
239
+ "application/x-ndjson": "ndjson",
240
+ "application/x-netcdf": "cdf nc",
241
+ "application/x-ns-proxy-autoconfig": "pac",
242
+ "application/x-nzb": "nzb",
243
+ "application/x-perl": "pl pm",
244
+ "application/x-photoshop": "psd",
245
+ "application/x-pilot": "pdb",
246
+ "application/x-pkcs10": "p10",
247
+ "application/x-pkcs12": "p12 pfx",
248
+ "application/x-pkcs7": "rsa",
249
+ "application/x-pkcs7-certificates": "p7b spc",
250
+ "application/x-pkcs7-certreqresp": "p7r",
251
+ "application/x-pkcs7-signature": "p7a",
252
+ "application/x-rar": "rar",
253
+ "application/x-research-info-systems": "ris",
254
+ "application/x-sh": "sh",
255
+ "application/x-shar": "shar",
256
+ "application/x-shockwave-flash": "swf",
257
+ "application/x-silverlight-app": "xap",
258
+ "application/x-sql": "sql",
259
+ "application/x-stuffit": "sit",
260
+ "application/x-stuffitx": "sitx",
261
+ "application/x-subrip": "srt",
262
+ "application/x-sv4cpio": "sv4cpio",
263
+ "application/x-sv4crc": "sv4crc",
264
+ "application/x-t3vm-image": "t3",
265
+ "application/x-tads": "gam",
266
+ "application/x-tar": "tar tgz",
267
+ "application/x-tcl": "tcl tk",
268
+ "application/x-tex": "tex",
269
+ "application/x-tex-tfm": "tfm",
270
+ "application/x-texinfo": "texi texinfo",
271
+ "application/x-ustar": "ustar",
272
+ "application/x-virtualbox-hdd": "hdd",
273
+ "application/x-virtualbox-ova": "ova",
274
+ "application/x-virtualbox-ovf": "ovf",
275
+ "application/x-virtualbox-vbox": "vbox",
276
+ "application/x-virtualbox-vbox-extpack": "vbox-extpack",
277
+ "application/x-virtualbox-vdi": "vdi",
278
+ "application/x-virtualbox-vhd": "vhd",
279
+ "application/x-virtualbox-vmdk": "vmdk",
280
+ "application/x-wais-source": "src",
281
+ "application/x-web-app-manifest+json": "webapp",
282
+ "application/x-x509-ca-cert": "crt der",
283
+ "application/x-x509-user-cert": "pem",
284
+ "application/x-xfig": "fig",
285
+ "application/x-xpinstall": "xpi",
286
+ "application/x-xz": "xz",
287
+ "application/x-zmachine": "z1 z2 z3 z4 z5 z6 z7 z8"
288
+ }).flatMap(([type, exts]) => exts.split(" ").map((ext) => [ext, type])));
289
+ const DENIED_EXTENSIONS = /* @__PURE__ */ new Set([
290
+ "exe",
291
+ "bat",
292
+ "cmd",
293
+ "com",
294
+ "scr",
295
+ "msi",
296
+ "sh",
297
+ "ps1",
298
+ "vbs",
299
+ "jar",
300
+ "app",
301
+ "dmg"
302
+ ]);
303
+ const CONTENT_TYPES = {
304
+ png: "image/png",
305
+ jpg: "image/jpeg",
306
+ jpeg: "image/jpeg",
307
+ gif: "image/gif",
308
+ webp: "image/webp",
309
+ avif: "image/avif",
310
+ svg: "image/svg+xml",
311
+ pdf: "application/pdf",
312
+ json: "application/json",
313
+ md: "text/markdown",
314
+ csv: "text/csv",
315
+ html: "text/html",
316
+ css: "text/css",
317
+ txt: "text/plain",
318
+ zip: "application/zip",
319
+ gz: "application/gzip",
320
+ mp4: "video/mp4",
321
+ mov: "video/quicktime",
322
+ webm: "video/webm",
323
+ mp3: "audio/mpeg",
324
+ wav: "audio/wav",
325
+ doc: "application/msword",
326
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
327
+ xls: "application/vnd.ms-excel",
328
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
329
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
330
+ };
331
+ function mimeDenied(type) {
332
+ return type === "application/octet-stream" || type === "application/vnd.microsoft.portable-executable" || type.startsWith("application/x-");
333
+ }
334
+ const MAGIC = [
335
+ {
336
+ type: "image/png",
337
+ bytes: "89504e47"
338
+ },
339
+ {
340
+ type: "image/jpeg",
341
+ bytes: "ffd8ff"
342
+ },
343
+ {
344
+ type: "image/gif",
345
+ bytes: "47494638"
346
+ },
347
+ {
348
+ type: "image/webp",
349
+ at: 8,
350
+ bytes: "57454250"
351
+ },
352
+ {
353
+ type: "image/vnd.adobe.photoshop",
354
+ bytes: "38425053"
355
+ },
356
+ {
357
+ type: "application/pdf",
358
+ bytes: "25504446"
359
+ },
360
+ {
361
+ type: "application/zip",
362
+ bytes: "504b0304"
363
+ },
364
+ {
365
+ type: "application/gzip",
366
+ bytes: "1f8b"
367
+ },
368
+ {
369
+ type: "video/mp4",
370
+ at: 4,
371
+ bytes: "66747970"
372
+ },
373
+ {
374
+ type: "application/x-executable",
375
+ bytes: "7f454c46"
376
+ },
377
+ {
378
+ type: "application/x-mach-binary",
379
+ bytes: "cffaedfe"
380
+ },
381
+ {
382
+ type: "application/x-mach-binary",
383
+ bytes: "feedfacf"
384
+ },
385
+ {
386
+ type: "application/x-mach-binary",
387
+ bytes: "cafebabe"
388
+ },
389
+ {
390
+ type: "application/vnd.microsoft.portable-executable",
391
+ bytes: "4d5a",
392
+ binary: true
393
+ },
394
+ {
395
+ type: "application/x-tar",
396
+ at: 257,
397
+ bytes: "7573746172"
398
+ },
399
+ {
400
+ type: "application/x-7z-compressed",
401
+ bytes: "377abcaf271c"
402
+ },
403
+ {
404
+ type: "application/x-bzip2",
405
+ bytes: "425a68",
406
+ binary: true
407
+ },
408
+ {
409
+ type: "application/x-xz",
410
+ bytes: "fd377a585a00"
411
+ },
412
+ {
413
+ type: "application/x-rar",
414
+ bytes: "526172211a07"
415
+ }
416
+ ];
417
+ function sniff(head) {
418
+ const text = !head.includes(0);
419
+ for (const m of MAGIC) {
420
+ if (m.binary && text) continue;
421
+ const at = m.at ?? 0;
422
+ if (head.subarray(at, at + m.bytes.length / 2).toString("hex") === m.bytes) return m.type;
423
+ }
424
+ return null;
425
+ }
426
+ function readHead(path) {
427
+ const fd = openSync(path, "r");
428
+ try {
429
+ const buf = Buffer.alloc(8192);
430
+ return buf.subarray(0, readSync(fd, buf, 0, buf.length, 0));
431
+ } finally {
432
+ closeSync(fd);
433
+ }
434
+ }
435
+ function own(table, key) {
436
+ return Object.hasOwn(table, key) ? table[key] : void 0;
437
+ }
438
+ function typeOf(head, ext) {
439
+ const magic = sniff(head);
440
+ if (magic) return magic;
441
+ const text = !head.includes(0);
442
+ if (text && (head.subarray(0, 2).toString() === "#!" || head.subarray(0, 5).toString() === "<?php")) return "text/plain";
443
+ return own(REFUSED_BY_EXTENSION, ext) ?? own(CONTENT_TYPES, ext) ?? (text ? "text/plain" : null);
444
+ }
445
+ function problem(path) {
446
+ let size;
447
+ try {
448
+ const st = statSync(path);
449
+ if (!st.isFile()) return { error: "is not a file" };
450
+ size = st.size;
451
+ } catch {
452
+ return { error: "was not found" };
453
+ }
454
+ const filename = basename(path);
455
+ const ext = extname(filename).slice(1).toLowerCase();
456
+ if (filename.length > 255) return { error: "has a name longer than 255 characters" };
457
+ if (size === 0) return { error: "is empty" };
458
+ if (size > 26214400) return { error: `is ${Math.ceil(size / 1048576)} MB and the limit is 25 MB` };
459
+ if (DENIED_EXTENSIONS.has(ext)) return { error: `is an executable type (.${ext})` };
460
+ const content_type = typeOf(readHead(path), ext);
461
+ if (!content_type) return { error: "is a binary file Loop cannot identify. Zip it, or attach it in Loop" };
462
+ if (mimeDenied(content_type)) return { error: `is a type Loop does not accept (${content_type}). Zip it, or attach it in Loop` };
463
+ return { file: {
464
+ path,
465
+ filename,
466
+ content_type,
467
+ size_bytes: size
468
+ } };
469
+ }
470
+ function checkAttachments(paths, cwd = process.cwd()) {
471
+ if (paths.length > 100) throw new Error(`Too many attachments (${paths.length}). A task takes 100.`);
472
+ const files = [];
473
+ const errors = [];
474
+ for (const raw of paths) {
475
+ const r = problem(resolve(cwd, raw));
476
+ if (r.file) files.push(r.file);
477
+ else errors.push(`${raw} ${r.error}`);
478
+ }
479
+ if (errors.length > 0) throw new Error(`Cannot attach: ${errors.join("; ")}. No task was created.`);
480
+ return files;
481
+ }
482
+ function uploadTimeoutMs(bytes) {
483
+ return Math.min(6e4 + 1e4 * Math.ceil(bytes / 1048576), 6e5);
484
+ }
485
+ function uploadTimedOut(timeoutMs, cause) {
486
+ return new Error(`The upload did not finish within ${Math.round(timeoutMs / 100) / 10} s`, { cause });
487
+ }
488
+ async function putBytes(creds, putUrl, bytes, contentType, timeoutMs) {
489
+ const target = new URL(putUrl);
490
+ const base = new URL(creds.api_url);
491
+ const own = target.host === base.host;
492
+ if (!own && target.protocol !== "https:") throw new Error("The upload URL is not https.");
493
+ let res;
494
+ try {
495
+ res = await fetch(own ? `${creds.api_url.replace(/\/+$/, "")}${target.pathname}${target.search}` : target, {
496
+ method: "PUT",
497
+ redirect: "error",
498
+ headers: {
499
+ "Content-Type": contentType,
500
+ ...own ? {
501
+ Authorization: `Bearer ${creds.token}`,
502
+ Accept: "application/json"
503
+ } : {}
504
+ },
505
+ body: new Uint8Array(bytes),
506
+ signal: AbortSignal.timeout(timeoutMs)
507
+ });
508
+ } catch (err) {
509
+ if (err instanceof Error && err.name === "TimeoutError") throw uploadTimedOut(timeoutMs, err);
510
+ throw err;
511
+ }
512
+ if (res.status === 401 && own) throw new AuthError();
513
+ if (!res.ok) {
514
+ let body = null;
515
+ try {
516
+ body = JSON.parse(await res.text());
517
+ } catch (err) {
518
+ if (err instanceof Error && err.name === "TimeoutError") throw uploadTimedOut(timeoutMs, err);
519
+ body = null;
520
+ }
521
+ throw new Error(messageFrom(body, res.status));
522
+ }
523
+ }
524
+ async function uploadAttachments(api, creds, taskId, files, opts = {}) {
525
+ const done = [];
526
+ for (const file of files) try {
527
+ const bytes = readFileSync(file.path);
528
+ const meta = {
529
+ filename: file.filename,
530
+ content_type: file.content_type,
531
+ size_bytes: bytes.length
532
+ };
533
+ const presigned = await api.post(`/api/v2/tasks/${taskId}/attachments/presign`, meta);
534
+ await putBytes(creds, presigned.put_url, bytes, file.content_type, opts.uploadTimeoutMs ?? uploadTimeoutMs(bytes.length));
535
+ const stored = await api.post(`/api/v2/tasks/${taskId}/attachments`, {
536
+ ...meta,
537
+ s3_key: presigned.s3_key
538
+ });
539
+ const row = "data" in stored && stored.data ? stored.data : stored;
540
+ done.push({
541
+ id: row.id,
542
+ filename: row.filename ?? file.filename,
543
+ content_type: row.content_type ?? file.content_type,
544
+ size_bytes: row.size_bytes ?? bytes.length
545
+ });
546
+ } catch (err) {
547
+ if (err instanceof AuthError) throw err;
548
+ const reason = err instanceof Error ? err.message : String(err);
549
+ throw new Error(`${file.filename}: ${reason} (${done.length} of ${files.length} attached)`, { cause: err });
550
+ }
551
+ return done;
552
+ }
553
+ function listProcesses(api) {
554
+ return api.get("/api/processes").then((r) => r.data ?? []);
555
+ }
556
+ const norm = (s) => s.trim().toLowerCase();
557
+ function newestPerKey(all) {
558
+ const byKey = /* @__PURE__ */ new Map();
559
+ for (const v of all) {
560
+ const have = byKey.get(norm(v.key));
561
+ const order = (v.version?.label ?? "").localeCompare(have?.version?.label ?? "", void 0, { numeric: true });
562
+ if (!have || order >= 0) byKey.set(norm(v.key), v);
563
+ }
564
+ return [...byKey.values()];
565
+ }
566
+ const options = (all) => all.map((x) => ` ${x.key} ${x.name}`).join("\n");
567
+ async function resolveProcess(api, wanted) {
568
+ const all = newestPerKey(await listProcesses(api));
569
+ const w = norm(wanted);
570
+ for (const field of ["key", "name"]) {
571
+ const hits = all.filter((x) => norm(x[field]) === w);
572
+ if (hits.length === 1) return hits[0].id;
573
+ if (hits.length > 1) throw new Error(`"${wanted}" matches ${hits.length} processes. Use one key:\n${options(hits)}`);
574
+ }
575
+ throw new Error(all.length === 0 ? `No process named "${wanted}": Loop offers no processes.` : `No process named "${wanted}". Choose one:\n${options(all)}`);
576
+ }
577
+ const ENV_URLS = {
578
+ prod: {
579
+ api_url: "https://api.loop.juicebox.agency",
580
+ web_url: "https://loop.juicebox.agency"
581
+ },
582
+ dev: {
583
+ api_url: "https://dev-api.loop.juicebox.agency",
584
+ web_url: "https://dev-loop.juicebox.agency"
585
+ }
586
+ };
587
+ function configDir() {
588
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
589
+ return join(base, "loop");
590
+ }
591
+ function configPath(name, env) {
592
+ return join(configDir(), env === "dev" ? `${name}.dev.json` : `${name}.json`);
593
+ }
594
+ function readJson(path) {
595
+ if (!existsSync(path)) return null;
596
+ try {
597
+ return JSON.parse(readFileSync(path, "utf-8"));
598
+ } catch {
599
+ return null;
600
+ }
601
+ }
602
+ function writeJson(path, value, mode) {
603
+ mkdirSync(configDir(), {
604
+ recursive: true,
605
+ mode: 448
606
+ });
607
+ writeFileSync(path, JSON.stringify(value, null, 2) + "\n", { mode });
608
+ chmodSync(path, mode);
609
+ }
610
+ function readCredentials(env) {
611
+ const creds = readJson(configPath("credentials", env));
612
+ return creds && typeof creds.token === "string" && typeof creds.api_url === "string" ? creds : null;
613
+ }
614
+ function writeCredentials(env, creds) {
615
+ const path = configPath("credentials", env);
616
+ writeJson(path, creds, 384);
617
+ return path;
618
+ }
619
+ function readRememberedProject(env, repository) {
620
+ const id = (readJson(configPath("repos", env)) ?? {})[repository.toLowerCase()];
621
+ return typeof id === "number" ? id : null;
622
+ }
623
+ function rememberProject(env, repository, projectId) {
624
+ const path = configPath("repos", env);
625
+ const repos = readJson(path) ?? {};
626
+ repos[repository.toLowerCase()] = projectId;
627
+ writeJson(path, repos, 384);
628
+ }
629
+ function readLastTask(env) {
630
+ return readJson(configPath("last", env));
631
+ }
632
+ function writeLastTask(env, task) {
633
+ writeJson(configPath("last", env), task, 384);
634
+ }
635
+ const updatePath = () => join(configDir(), "update.json");
636
+ function readUpdateCheck() {
637
+ const c = readJson(updatePath());
638
+ return c && typeof c.checked_at === "string" ? c : null;
639
+ }
640
+ function writeUpdateCheck(check) {
641
+ writeJson(updatePath(), check, 384);
642
+ }
643
+ function parseRemote(url) {
644
+ const trimmed = url.trim().replace(/\/+$/, "").replace(/\.git$/, "");
645
+ const scp = /^[^/@]+@[^/:]+:([^/:]+)\/([^/:]+)$/.exec(trimmed);
646
+ if (scp && scp[1] && scp[2]) return {
647
+ owner: scp[1],
648
+ name: scp[2]
649
+ };
650
+ const web = /^[a-z][a-z0-9+.-]*:\/\/[^/]+\/([^/:]+)\/([^/:]+)$/i.exec(trimmed);
651
+ if (web && web[1] && web[2]) return {
652
+ owner: web[1],
653
+ name: web[2]
654
+ };
655
+ return null;
656
+ }
657
+ var GitError = class extends Error {};
658
+ let interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
659
+ function setGitInteractive(on) {
660
+ interactive = on;
661
+ }
662
+ async function withNoGitPrompts(fn) {
663
+ const before = interactive;
664
+ interactive = false;
665
+ try {
666
+ return await fn();
667
+ } finally {
668
+ interactive = before;
669
+ }
670
+ }
671
+ const NO_PROMPT = {
672
+ GIT_TERMINAL_PROMPT: "0",
673
+ GCM_INTERACTIVE: "never"
674
+ };
675
+ const SSH_BATCH = { GIT_SSH_COMMAND: "ssh -o BatchMode=yes" };
676
+ function noPromptEnv(env, sshCommandConfigured) {
677
+ return Boolean(env.GIT_SSH_COMMAND || env.GIT_SSH) || sshCommandConfigured ? { ...NO_PROMPT } : {
678
+ ...NO_PROMPT,
679
+ ...SSH_BATCH
680
+ };
681
+ }
682
+ const sshConfigured = /* @__PURE__ */ new Map();
683
+ function hasConfiguredSshCommand(cwd) {
684
+ let known = sshConfigured.get(cwd);
685
+ if (known === void 0) {
686
+ try {
687
+ known = execFileSync("git", [
688
+ "config",
689
+ "--get",
690
+ "core.sshCommand"
691
+ ], {
692
+ cwd,
693
+ encoding: "utf-8",
694
+ stdio: [
695
+ "ignore",
696
+ "pipe",
697
+ "ignore"
698
+ ],
699
+ env: {
700
+ ...process.env,
701
+ ...NO_PROMPT
702
+ }
703
+ }).trim() !== "";
704
+ } catch {
705
+ known = false;
706
+ }
707
+ sshConfigured.set(cwd, known);
708
+ }
709
+ return known;
710
+ }
711
+ function scrub(text) {
712
+ return text.replace(/(\w+:\/\/)[^/@\s]+@/g, "$1");
713
+ }
714
+ function runGit(args, cwd, opts = {}) {
715
+ const out = runGitBytes(args, cwd, {
716
+ env: opts.env,
717
+ timeoutMs: opts.timeoutMs
718
+ }).toString("utf-8");
719
+ return opts.raw ? out : out.trim();
720
+ }
721
+ function runGitBytes(args, cwd, opts = {}) {
722
+ const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs(args);
723
+ try {
724
+ return execFileSync("git", args, {
725
+ cwd,
726
+ timeout: timeoutMs,
727
+ stdio: [
728
+ opts.input === void 0 ? "ignore" : "pipe",
729
+ "pipe",
730
+ "pipe"
731
+ ],
732
+ input: opts.input === void 0 ? void 0 : Buffer.from(opts.input),
733
+ env: {
734
+ ...process.env,
735
+ ...interactive ? {} : noPromptEnv(process.env, hasConfiguredSshCommand(cwd)),
736
+ ...opts.env
737
+ },
738
+ maxBuffer: 268435456
739
+ });
740
+ } catch (err) {
741
+ const e = err;
742
+ if (e.code === "ETIMEDOUT") throw new GitError(`git ${subcommandOf(args)} timed out after ${Math.round(timeoutMs / 100) / 10} s. Check your connection to origin and try again.`);
743
+ const detail = (e.stderr?.toString() || e.message).trim();
744
+ throw new GitError(scrub(`git ${args[0]} failed: ${detail}`));
745
+ }
746
+ }
747
+ const NETWORK_TIMEOUT_MS = 12e4;
748
+ const NETWORK_SUBCOMMANDS = /* @__PURE__ */ new Set([
749
+ "ls-remote",
750
+ "fetch",
751
+ "push"
752
+ ]);
753
+ function subcommandOf(args) {
754
+ for (let i = 0; i < args.length; i++) if (args[i] === "-c") i++;
755
+ else if (!args[i].startsWith("-")) return args[i];
756
+ return args[0] ?? "";
757
+ }
758
+ function defaultTimeoutMs(args) {
759
+ return NETWORK_SUBCOMMANDS.has(subcommandOf(args)) ? NETWORK_TIMEOUT_MS : 0;
760
+ }
761
+ const NO_LOCKS = { GIT_OPTIONAL_LOCKS: "0" };
762
+ function hasTrackedChanges(cwd) {
763
+ return runGit([
764
+ "status",
765
+ "--porcelain",
766
+ "--untracked-files=no"
767
+ ], cwd, { env: NO_LOCKS }) !== "";
768
+ }
769
+ const git = (args, cwd) => runGit(args, cwd);
770
+ function gitContext(cwd = process.cwd()) {
771
+ let remote;
772
+ try {
773
+ remote = git([
774
+ "remote",
775
+ "get-url",
776
+ "origin"
777
+ ], cwd);
778
+ } catch {
779
+ throw new GitError("No origin remote found. Run this inside a git repository with an origin.");
780
+ }
781
+ let parsed = parseRemote(remote);
782
+ if (!parsed) try {
783
+ parsed = parseRemote(git([
784
+ "config",
785
+ "--get",
786
+ "remote.origin.url"
787
+ ], cwd));
788
+ } catch {
789
+ parsed = null;
790
+ }
791
+ if (!parsed) throw new GitError(`Could not read owner/name from origin remote "${remote}".`);
792
+ const branch = git([
793
+ "rev-parse",
794
+ "--abbrev-ref",
795
+ "HEAD"
796
+ ], cwd);
797
+ const head_sha = git(["rev-parse", "HEAD"], cwd);
798
+ const dirty = runGit(["status", "--porcelain"], cwd, { env: NO_LOCKS }).length > 0;
799
+ return {
800
+ ...parsed,
801
+ repository: `${parsed.owner}/${parsed.name}`,
802
+ branch,
803
+ head_sha,
804
+ dirty
805
+ };
806
+ }
807
+ function withoutOwnBranches(names) {
808
+ for (const name of names) if (name.startsWith("loop/")) names.delete(name);
809
+ return names;
810
+ }
811
+ function listOriginBranches(cwd = process.cwd()) {
812
+ return originBranches(cwd).names;
813
+ }
814
+ function originBranches(cwd = process.cwd()) {
815
+ const names = /* @__PURE__ */ new Set();
816
+ try {
817
+ for (const line of runGit([
818
+ "ls-remote",
819
+ "--heads",
820
+ "origin"
821
+ ], cwd).split("\n")) {
822
+ const ref = line.split(" ")[1];
823
+ if (ref?.startsWith("refs/heads/")) names.add(ref.slice(11));
824
+ }
825
+ return {
826
+ names: withoutOwnBranches(names),
827
+ offline: false
828
+ };
829
+ } catch {
830
+ try {
831
+ const out = runGit([
832
+ "for-each-ref",
833
+ "--format=%(refname)",
834
+ "refs/remotes/origin"
835
+ ], cwd);
836
+ for (const ref of out.split("\n")) {
837
+ const name = ref.slice(20);
838
+ if (ref.startsWith("refs/remotes/origin/") && name !== "HEAD") names.add(name);
839
+ }
840
+ } catch {}
841
+ return {
842
+ names: withoutOwnBranches(names),
843
+ offline: true
844
+ };
845
+ }
846
+ }
847
+ function branchExistsOnOrigin(branch, cwd = process.cwd(), known = listOriginBranches(cwd)) {
848
+ return branch !== "HEAD" && known.has(branch);
849
+ }
850
+ function candidateBranches(p) {
851
+ const all = [
852
+ p?.dev_branch,
853
+ p?.base_branch,
854
+ p?.uat_branch,
855
+ p?.test_branch,
856
+ p?.production_branch
857
+ ];
858
+ return [...new Set(all.filter((b) => typeof b === "string" && b.trim() !== ""))];
859
+ }
860
+ function trackingRef(branch, cwd, fetchMissing) {
861
+ const ref = `refs/remotes/origin/${branch}`;
862
+ const has = () => {
863
+ try {
864
+ runGit([
865
+ "rev-parse",
866
+ "--verify",
867
+ "--quiet",
868
+ ref
869
+ ], cwd);
870
+ return true;
871
+ } catch {
872
+ return false;
873
+ }
874
+ };
875
+ if (has()) return { ref };
876
+ if (!fetchMissing) return { missing: "not_fetched" };
877
+ try {
878
+ runGit([
879
+ "fetch",
880
+ "--quiet",
881
+ "--no-tags",
882
+ "origin",
883
+ `refs/heads/${branch}:${ref}`
884
+ ], cwd);
885
+ } catch {
886
+ return { missing: "fetch_failed" };
887
+ }
888
+ return has() ? { ref } : { missing: "fetch_failed" };
889
+ }
890
+ function isShallow(cwd) {
891
+ try {
892
+ return runGit(["rev-parse", "--is-shallow-repository"], cwd) === "true";
893
+ } catch {
894
+ return false;
895
+ }
896
+ }
897
+ function upstreamOnOrigin(cwd) {
898
+ try {
899
+ const up = runGit([
900
+ "rev-parse",
901
+ "--abbrev-ref",
902
+ "--symbolic-full-name",
903
+ "@{upstream}"
904
+ ], cwd);
905
+ return up.startsWith("origin/") ? up.slice(7) : null;
906
+ } catch {
907
+ return null;
908
+ }
909
+ }
910
+ function chooseBaseBranch(branch, candidates, cwd = process.cwd(), fetchMissing = true) {
911
+ const { names, offline } = originBranches(cwd);
912
+ const choice = pickBase(branch, candidates, cwd, fetchMissing, names);
913
+ return offline ? {
914
+ ...choice,
915
+ offline: true
916
+ } : choice;
917
+ }
918
+ function pickBase(branch, candidates, cwd, fetchMissing, onOrigin) {
919
+ if (branchExistsOnOrigin(branch, cwd, onOrigin)) return {
920
+ branch,
921
+ source: "current"
922
+ };
923
+ const upstream = upstreamOnOrigin(cwd);
924
+ if (upstream && branchExistsOnOrigin(upstream, cwd, onOrigin)) return {
925
+ branch: upstream,
926
+ source: "upstream"
927
+ };
928
+ const present = candidates.filter((name) => branchExistsOnOrigin(name, cwd, onOrigin));
929
+ if (present.length > 0 && isShallow(cwd)) return {
930
+ branch: null,
931
+ source: "none",
932
+ reason: "shallow"
933
+ };
934
+ let best = null;
935
+ let unchecked;
936
+ for (const name of present) {
937
+ const tracking = trackingRef(name, cwd, fetchMissing);
938
+ if ("missing" in tracking) {
939
+ unchecked ??= tracking.missing;
940
+ continue;
941
+ }
942
+ let distance;
943
+ try {
944
+ const [behind, ahead] = runGit([
945
+ "rev-list",
946
+ "--left-right",
947
+ "--count",
948
+ `${tracking.ref}...HEAD`
949
+ ], cwd).split(/\s+/).map(Number);
950
+ distance = behind + ahead;
951
+ } catch {
952
+ unchecked ??= "fetch_failed";
953
+ continue;
954
+ }
955
+ if (Number.isNaN(distance)) continue;
956
+ if (!best || distance < best.distance) best = {
957
+ name,
958
+ distance
959
+ };
960
+ }
961
+ if (best) return {
962
+ branch: best.name,
963
+ source: "nearest"
964
+ };
965
+ return unchecked ? {
966
+ branch: null,
967
+ source: "none",
968
+ reason: unchecked
969
+ } : {
970
+ branch: null,
971
+ source: "none"
972
+ };
973
+ }
974
+ function describeBase(choice) {
975
+ switch (choice.source) {
976
+ case "current": return `${choice.branch} (your branch is on origin)`;
977
+ case "upstream": return `${choice.branch} (the branch yours tracks)`;
978
+ case "nearest": return `${choice.branch} (the project branch nearest your work)`;
979
+ default:
980
+ if (choice.reason === "not_fetched") return "the project default (project branches are on origin but not fetched; run git fetch)";
981
+ if (choice.reason === "shallow") return "the project default (this clone is shallow)";
982
+ return "the project default";
983
+ }
984
+ }
985
+ function baseWarning(choice, projectDefault) {
986
+ const offline = choice.offline ? OFFLINE_NOTE : null;
987
+ if (choice.branch !== null) return offline;
988
+ const base = unreachedWarning(choice, projectDefault);
989
+ return offline ? `${offline} ${base}` : base;
990
+ }
991
+ const OFFLINE_NOTE = "Could not reach origin; the base was chosen from your last fetch.";
992
+ function unreachedWarning(choice, projectDefault) {
993
+ const use = `Loop will use the project default${projectDefault ? ` (${projectDefault})` : ""}`;
994
+ switch (choice.reason) {
995
+ case "shallow": return `This clone is shallow, so the project branch nearest your work cannot be measured. ${use}. Run git fetch --unshallow, or push your branch.`;
996
+ case "fetch_failed": return `The base branch could not be checked (fetch failed), so ${use}. Check your connection to origin and try again, or push your branch.`;
997
+ case "not_fetched": return `The project's branches are on origin but not fetched, so ${use}. Run git fetch.`;
998
+ default: return `No branch of yours or of the project's is on origin, so ${use}. Push your branch, or check the pull request target.`;
999
+ }
1000
+ }
1001
+ const OWN_TRACKING_PREFIX = "refs/remotes/origin/loop/";
1002
+ const PUSHED_REFS = ["--exclude=origin/loop/*", "--remotes=origin"];
1003
+ const UNFETCHED_NOTE = "origin has not been fetched, so unpushed commits were not checked; run git fetch first for a full check.";
1004
+ const SECRET_NAMES = [
1005
+ /^\.env$/,
1006
+ /^\.env\..+$/,
1007
+ /\.pem$/,
1008
+ /\.key$/,
1009
+ /^id_(rsa|dsa|ecdsa|ed25519)/,
1010
+ /\.p12$/,
1011
+ /\.pfx$/,
1012
+ /\.jks$/,
1013
+ /\.keystore$/,
1014
+ /\.kdbx$/,
1015
+ /\.secret$/,
1016
+ /^secrets\.ya?ml$/,
1017
+ /\.tfvars(\.json)?$/,
1018
+ /\.tfstate(\..+)?$/,
1019
+ /^\.(npmrc|netrc|pypirc|htpasswd|git-credentials)$/,
1020
+ /^service-account.*\.json$/,
1021
+ /credentials.*\.json$/
1022
+ ];
1023
+ const SECRET_PATHS = [/(^|\/)\.aws\/credentials$/, /(^|\/)\.docker\/config\.json$/];
1024
+ const SECRET_ALLOWED = /* @__PURE__ */ new Set([".env.example", ".env.sample"]);
1025
+ function secretLooking(paths) {
1026
+ return paths.filter((path) => {
1027
+ const name = basename(path).toLowerCase();
1028
+ if (SECRET_ALLOWED.has(name)) return false;
1029
+ return SECRET_NAMES.some((re) => re.test(name)) || SECRET_PATHS.some((re) => re.test(path.toLowerCase()));
1030
+ });
1031
+ }
1032
+ const PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----/;
1033
+ const CONTENT_CHECK_MAX_BYTES = 2097152;
1034
+ function hasPrivateKey(content) {
1035
+ return PRIVATE_KEY.test(typeof content === "string" ? content : content.toString("latin1"));
1036
+ }
1037
+ function privateKeyFiles(root, paths) {
1038
+ return paths.filter((path) => {
1039
+ try {
1040
+ const full = join(root, path);
1041
+ const st = statSync(full);
1042
+ return st.isFile() && st.size <= CONTENT_CHECK_MAX_BYTES && hasPrivateKey(readFileSync(full));
1043
+ } catch {
1044
+ return false;
1045
+ }
1046
+ });
1047
+ }
1048
+ const LARGE_WIP_BYTES = 52428800;
1049
+ function changedSize(cwd, paths) {
1050
+ const root = runGit(["rev-parse", "--show-toplevel"], cwd);
1051
+ const sizes = [];
1052
+ for (const path of paths) try {
1053
+ const st = statSync(join(root, path));
1054
+ if (st.isFile()) sizes.push({
1055
+ path,
1056
+ bytes: st.size
1057
+ });
1058
+ } catch {}
1059
+ sizes.sort((a, b) => b.bytes - a.bytes);
1060
+ return {
1061
+ bytes: sizes.reduce((n, s) => n + s.bytes, 0),
1062
+ largest: sizes.slice(0, 3)
1063
+ };
1064
+ }
1065
+ const mb = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
1066
+ function largeWipWarning(size) {
1067
+ if (size.bytes <= 52428800) return null;
1068
+ const top = size.largest.map((f) => `${f.path} (${mb(f.bytes)})`).join(", ");
1069
+ return `Your local work is ${mb(size.bytes)}, over ${mb(LARGE_WIP_BYTES)}. Largest files: ${top}.`;
1070
+ }
1071
+ function detectWip(cwd) {
1072
+ const raw = runGit([
1073
+ "status",
1074
+ "--porcelain=v1",
1075
+ "-z",
1076
+ "--untracked-files=all"
1077
+ ], cwd, {
1078
+ raw: true,
1079
+ env: NO_LOCKS
1080
+ });
1081
+ const changed = [];
1082
+ const entries = raw.split("\0").filter(Boolean);
1083
+ for (let i = 0; i < entries.length; i++) {
1084
+ const entry = entries[i];
1085
+ changed.push(entry.slice(3));
1086
+ if (entry[0] === "R" || entry[0] === "C") i++;
1087
+ }
1088
+ const unfetched = !runGit([
1089
+ "for-each-ref",
1090
+ "--format=%(refname)",
1091
+ "refs/remotes/origin/"
1092
+ ], cwd).split("\n").some((ref) => ref && !ref.startsWith(OWN_TRACKING_PREFIX));
1093
+ const unpushed = unfetched ? 0 : Number(runGit([
1094
+ "rev-list",
1095
+ "--count",
1096
+ "HEAD",
1097
+ "--not",
1098
+ ...PUSHED_REFS
1099
+ ], cwd));
1100
+ const committed = unpushed === 0 ? [] : [...new Set(runGit([
1101
+ "log",
1102
+ "-z",
1103
+ "--name-only",
1104
+ "--pretty=format:",
1105
+ "HEAD",
1106
+ "--not",
1107
+ ...PUSHED_REFS
1108
+ ], cwd, { raw: true }).split("\0").map((path) => path.trim()).filter(Boolean))];
1109
+ return {
1110
+ changed,
1111
+ privateKeys: privateKeyFiles(runGit(["rev-parse", "--show-toplevel"], cwd), changed.filter((p) => !secretLooking([p]).length)),
1112
+ committedKeys: unpushed === 0 ? [] : privateKeysInUnpushed(cwd),
1113
+ unpushed,
1114
+ committed,
1115
+ unfetched
1116
+ };
1117
+ }
1118
+ function parseRaw(text) {
1119
+ const out = [];
1120
+ const tokens = text.split("\0");
1121
+ let commit = "";
1122
+ for (let i = 0; i < tokens.length; i++) {
1123
+ const token = tokens[i].replace(/^\n/, "");
1124
+ if (token.startsWith("")) commit = token.slice(1);
1125
+ else if (token.startsWith(":")) {
1126
+ const blob = token.split(" ")[3];
1127
+ const path = tokens[++i];
1128
+ if (blob && path !== void 0) out.push({
1129
+ commit,
1130
+ blob,
1131
+ path
1132
+ });
1133
+ }
1134
+ }
1135
+ return out;
1136
+ }
1137
+ const BATCH_MAX_BYTES = 67108864;
1138
+ const MIN_KEY_FILE_BYTES = 27;
1139
+ function blobsWithPrivateKey(cwd, ids, env) {
1140
+ const found = /* @__PURE__ */ new Set();
1141
+ const unique = [...new Set(ids)];
1142
+ if (unique.length === 0) return found;
1143
+ const checked = runGitBytes(["cat-file", "--batch-check"], cwd, {
1144
+ env,
1145
+ input: `${unique.join("\n")}\n`
1146
+ }).toString("latin1").split("\n");
1147
+ const wanted = [];
1148
+ for (const line of checked) {
1149
+ const [id, type, size] = line.split(" ");
1150
+ const n = Number(size);
1151
+ if (id && type === "blob" && n >= MIN_KEY_FILE_BYTES && n <= CONTENT_CHECK_MAX_BYTES) wanted.push({
1152
+ id,
1153
+ size: n
1154
+ });
1155
+ }
1156
+ for (let start = 0; start < wanted.length;) {
1157
+ let end = start;
1158
+ let bytes = 0;
1159
+ while (end < wanted.length && (end === start || bytes + wanted[end].size <= BATCH_MAX_BYTES)) {
1160
+ bytes += wanted[end].size;
1161
+ end++;
1162
+ }
1163
+ const out = runGitBytes(["cat-file", "--batch"], cwd, {
1164
+ env,
1165
+ input: `${wanted.slice(start, end).map((w) => w.id).join("\n")}\n`
1166
+ });
1167
+ for (let pos = 0; pos < out.length;) {
1168
+ const nl = out.indexOf(10, pos);
1169
+ if (nl < 0) break;
1170
+ const [id, , size] = out.toString("latin1", pos, nl).split(" ");
1171
+ const n = Number(size);
1172
+ if (!id || Number.isNaN(n)) break;
1173
+ if (hasPrivateKey(out.subarray(nl + 1, nl + 1 + n))) found.add(id);
1174
+ pos = nl + 1 + n + 1;
1175
+ }
1176
+ start = end;
1177
+ }
1178
+ return found;
1179
+ }
1180
+ function privateKeysInUnpushed(cwd) {
1181
+ const entries = parseRaw(runGitBytes([
1182
+ "log",
1183
+ "-z",
1184
+ "-m",
1185
+ "--reverse",
1186
+ "--no-renames",
1187
+ "--diff-filter=AMT",
1188
+ "--raw",
1189
+ "--no-abbrev",
1190
+ "--format=%x01%H",
1191
+ "HEAD",
1192
+ "--not",
1193
+ ...PUSHED_REFS
1194
+ ], cwd).toString("utf-8"));
1195
+ const withKey = blobsWithPrivateKey(cwd, entries.map((e) => e.blob));
1196
+ const found = /* @__PURE__ */ new Map();
1197
+ for (const e of entries) if (withKey.has(e.blob) && !found.has(e.path)) found.set(e.path, {
1198
+ path: e.path,
1199
+ commit: e.commit.slice(0, 7)
1200
+ });
1201
+ return [...found.values()];
1202
+ }
1203
+ function sendWip(start, exclude, opts = {}) {
1204
+ const cwd = runGit(["rev-parse", "--show-toplevel"], start);
1205
+ const dir = mkdtempSync(join(tmpdir(), "loop-wip-"));
1206
+ const env = {
1207
+ GIT_INDEX_FILE: join(dir, "index"),
1208
+ GIT_LITERAL_PATHSPECS: "1"
1209
+ };
1210
+ try {
1211
+ const real = resolve(cwd, runGit([
1212
+ "rev-parse",
1213
+ "--git-path",
1214
+ "index"
1215
+ ], cwd));
1216
+ if (existsSync(real)) copyFileSync(real, env.GIT_INDEX_FILE);
1217
+ else runGit(["read-tree", "HEAD"], cwd, { env });
1218
+ runGit(["add", "-A"], cwd, { env });
1219
+ if (!opts.includeSecrets) exclude = [.../* @__PURE__ */ new Set([...exclude, ...secretsInIndex(cwd, env)])];
1220
+ if (exclude.length > 0) runGit([
1221
+ "reset",
1222
+ "-q",
1223
+ "HEAD",
1224
+ "--",
1225
+ ...exclude
1226
+ ], cwd, { env });
1227
+ const tree = runGit(["write-tree"], cwd, { env });
1228
+ const head = runGit(["rev-parse", "HEAD"], cwd);
1229
+ let sha = head;
1230
+ if (tree !== runGit(["rev-parse", "HEAD^{tree}"], cwd)) {
1231
+ const args = [
1232
+ "commit-tree",
1233
+ tree,
1234
+ "-p",
1235
+ head,
1236
+ "-m",
1237
+ "Loop: local work in progress"
1238
+ ];
1239
+ try {
1240
+ sha = runGit(args, cwd);
1241
+ } catch {
1242
+ sha = runGit(args, cwd, { env: {
1243
+ GIT_AUTHOR_NAME: "Loop CLI",
1244
+ GIT_AUTHOR_EMAIL: "loop-cli@users.noreply.github.com",
1245
+ GIT_COMMITTER_NAME: "Loop CLI",
1246
+ GIT_COMMITTER_EMAIL: "loop-cli@users.noreply.github.com"
1247
+ } });
1248
+ }
1249
+ }
1250
+ const branch = `loop/wip-${randomBytes(3).toString("hex")}`;
1251
+ try {
1252
+ runGit([
1253
+ "push",
1254
+ "origin",
1255
+ `${sha}:refs/heads/${branch}`
1256
+ ], cwd);
1257
+ } catch (err) {
1258
+ throw new GitError(`Could not push your local work to origin as ${branch}, so no task was created. ${err.message}`);
1259
+ }
1260
+ return {
1261
+ branch,
1262
+ sha,
1263
+ excluded: exclude
1264
+ };
1265
+ } finally {
1266
+ rmSync(dir, {
1267
+ recursive: true,
1268
+ force: true
1269
+ });
1270
+ }
1271
+ }
1272
+ function secretsInIndex(cwd, env) {
1273
+ const entries = parseRaw(runGitBytes([
1274
+ "diff",
1275
+ "--cached",
1276
+ "--no-renames",
1277
+ "--diff-filter=AMT",
1278
+ "--raw",
1279
+ "--no-abbrev",
1280
+ "-z",
1281
+ "HEAD"
1282
+ ], cwd, { env }).toString("utf-8"));
1283
+ const byName = new Set(secretLooking(entries.map((e) => e.path)));
1284
+ const rest = entries.filter((e) => !byName.has(e.path));
1285
+ const withKey = blobsWithPrivateKey(cwd, rest.map((e) => e.blob), env);
1286
+ return [...byName, ...rest.filter((e) => withKey.has(e.blob)).map((e) => e.path)];
1287
+ }
1288
+ function deleteWipBranch(cwd, branch) {
1289
+ try {
1290
+ runGit([
1291
+ "push",
1292
+ "origin",
1293
+ "--delete",
1294
+ `refs/heads/${branch}`
1295
+ ], cwd);
1296
+ } catch {}
1297
+ }
1298
+ var ProjectUnresolved = class extends Error {};
1299
+ function detectAgent() {
1300
+ if (process.env.CLAUDECODE || process.env.CLAUDE_CODE) return "claude-code";
1301
+ if (process.env.CODEX_SANDBOX || process.env.CODEX_CI || process.env.CODEX_THREAD_ID) return "codex";
1302
+ return null;
1303
+ }
1304
+ function readBrief(source, words = []) {
1305
+ if (source) return source === "-" ? readFileSync(0, "utf-8") : readFileSync(source, "utf-8");
1306
+ return words.join(" ").trim() || null;
1307
+ }
1308
+ function titleFromBrief(brief) {
1309
+ const line = brief.split("\n").map((l) => l.replace(/^#+\s*/, "").trim()).find((l) => l && !/^(goal|brief)$/i.test(l));
1310
+ return line ? line.slice(0, 120) : null;
1311
+ }
1312
+ function buildPayload(opts, projectId, title, brief, skillIds, git, baseBranch, wip = null, processVersionId) {
1313
+ return {
1314
+ project_id: projectId,
1315
+ title,
1316
+ description: brief,
1317
+ type: opts.type,
1318
+ engine: opts.engine && opts.engine !== "auto" ? opts.engine : null,
1319
+ ...opts.model ? { model: opts.model } : {},
1320
+ assignee_type: "agent_machine",
1321
+ auto_run: !opts.noRun,
1322
+ source: "cli",
1323
+ source_meta: {
1324
+ ...git ? {
1325
+ repository: git.repository,
1326
+ branch: git.branch,
1327
+ head_sha: git.head_sha,
1328
+ dirty: git.dirty
1329
+ } : {},
1330
+ cli_version: opts.cliVersion,
1331
+ agent: detectAgent()
1332
+ },
1333
+ base_branch: baseBranch,
1334
+ skill_ids: skillIds,
1335
+ ...wip ? {
1336
+ wip_branch: wip.branch,
1337
+ wip_head_sha: wip.sha
1338
+ } : {},
1339
+ ...opts.plan ? { plan_first: true } : opts.noPlan ? { plan_first: false } : {},
1340
+ ...processVersionId ? { process_version_id: processVersionId } : {},
1341
+ ...opts.hotfix ? { is_hotfix: true } : {}
1342
+ };
1343
+ }
1344
+ function assertPlanFlags(opts) {
1345
+ if (opts.plan && opts.noPlan) throw new Error("Use either --plan or --no-plan.");
1346
+ }
1347
+ async function prepare(api, opts) {
1348
+ return {
1349
+ files: checkAttachments(opts.attach ?? []),
1350
+ processVersionId: opts.process ? await resolveProcess(api, opts.process) : void 0
1351
+ };
1352
+ }
1353
+ const clackChooser = async (projects) => {
1354
+ const choice = await ve({
1355
+ message: "Several Loop projects use this repository. Which one?",
1356
+ options: projects.map((pr) => ({
1357
+ value: pr.id,
1358
+ label: pr.client_name ? `${pr.client_name} / ${pr.name}` : pr.name,
1359
+ hint: pr.slug
1360
+ }))
1361
+ });
1362
+ if (pD(choice)) return null;
1363
+ return projects.find((pr) => pr.id === choice) ?? null;
1364
+ };
1365
+ async function resolveProject(api, env, repository, choose) {
1366
+ const projects = await findProjectsByRepository(api, repository);
1367
+ if (projects.length === 0) throw new ProjectUnresolved(`No Loop project is linked to ${repository}. Link the repository in Loop, or use loop task create --project <slug>.`);
1368
+ if (projects.length === 1) return projects[0];
1369
+ const remembered = readRememberedProject(env, repository);
1370
+ const match = projects.find((pr) => pr.id === remembered);
1371
+ if (match) return match;
1372
+ if (!choose) throw new ProjectUnresolved(`Several Loop projects use ${repository} (${projects.map((pr) => pr.slug).join(", ")}) and none is remembered, and there is no terminal to ask in. Use loop task create --project <slug>.`);
1373
+ const chosen = await choose(projects);
1374
+ if (!chosen) throw new ProjectUnresolved("No project chosen.");
1375
+ rememberProject(env, repository, chosen.id);
1376
+ return chosen;
1377
+ }
1378
+ async function resolveSkillIds(api, slugs) {
1379
+ const ids = [];
1380
+ for (const slug of slugs) {
1381
+ const skill = await findSkillBySlug(api, slug);
1382
+ if (!skill) throw new Error(`Skill "${slug}" not found in Loop.`);
1383
+ ids.push(skill.id);
1384
+ }
1385
+ return ids;
1386
+ }
1387
+ const APPROVAL_QUESTIONS = ["task_needs_clarifying", "task_plan_choice"];
1388
+ async function startRun(api, taskId) {
1389
+ try {
1390
+ return await api.post(`/api/v2/tasks/${taskId}/approve`, { run: true });
1391
+ } catch (err) {
1392
+ if (err instanceof ApiError && err.status === 422) {
1393
+ const clarity = { ...err.body ?? {} };
1394
+ delete clarity.message;
1395
+ delete clarity.reason;
1396
+ if (APPROVAL_QUESTIONS.includes(String(clarity.code))) return { clarity };
1397
+ }
1398
+ throw err;
1399
+ }
1400
+ }
1401
+ const sentence = (message) => `${message.replace(/[.\s]+$/, "")}.`;
1402
+ var TaskCreatedError = class extends Error {
1403
+ task;
1404
+ constructor(message, task, cause) {
1405
+ super(message, { cause });
1406
+ this.task = task;
1407
+ }
1408
+ };
1409
+ async function submit(api, creds, opts, payload, extra = {}, onCreateFailed, files = []) {
1410
+ const deferRun = files.length > 0 && payload.auto_run;
1411
+ let res;
1412
+ try {
1413
+ res = await createTask(api, deferRun ? {
1414
+ ...payload,
1415
+ auto_run: false
1416
+ } : payload);
1417
+ } catch (err) {
1418
+ const handled = onCreateFailed?.(err);
1419
+ if (handled) throw handled;
1420
+ if (err instanceof NetworkError) throw new Error(`${sentence(err.message)} The task may have been created; check loop ls.`, { cause: err });
1421
+ throw err;
1422
+ }
1423
+ const task = res.data;
1424
+ const url = taskUrl(creds.web_url, task);
1425
+ writeLastTask(opts.env, {
1426
+ id: task.id,
1427
+ key: task.key,
1428
+ url,
1429
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1430
+ });
1431
+ let attachments;
1432
+ let status = task.status;
1433
+ if (files.length > 0) {
1434
+ try {
1435
+ attachments = await uploadAttachments(api, creds, task.id, files);
1436
+ } catch (err) {
1437
+ if (err instanceof AuthError) throw err;
1438
+ throw new TaskCreatedError(`Created ${task.key} (${url}) but uploading failed: ${err.message}. ${deferRun ? `The run was not started. Add the rest and choose Approve and run at ${url}` : `Add the rest at ${url}`}`, {
1439
+ id: task.id,
1440
+ key: task.key,
1441
+ url
1442
+ }, err);
1443
+ }
1444
+ if (deferRun) try {
1445
+ const started = await startRun(api, task.id);
1446
+ res = {
1447
+ ...res,
1448
+ ...started,
1449
+ data: task
1450
+ };
1451
+ status = started.status ?? status;
1452
+ } catch (err) {
1453
+ if (err instanceof AuthError) throw err;
1454
+ throw new TaskCreatedError(`Created ${task.key} (${url}) with its files but could not start the run: ${err.message.replace(/\.$/, "")}. Choose Approve and run at ${url}`, {
1455
+ id: task.id,
1456
+ key: task.key,
1457
+ url
1458
+ }, err);
1459
+ }
1460
+ }
1461
+ const output = {
1462
+ id: task.id,
1463
+ key: task.key,
1464
+ status,
1465
+ project: task.project?.slug ?? null,
1466
+ url,
1467
+ dispatched: res.dispatched ?? false,
1468
+ queued: res.queued ?? false,
1469
+ dispatch_error: res.dispatch_error ?? null,
1470
+ base_branch: payload.base_branch ?? null,
1471
+ engine: task.engine ?? opts.engine ?? "auto",
1472
+ model: task.model ?? opts.model ?? null,
1473
+ clarity: res.clarity ? withKind(res.clarity) : null,
1474
+ ...attachments ? { attachments } : {},
1475
+ ...extra
1476
+ };
1477
+ return {
1478
+ exitCode: res.clarity ? 2 : 0,
1479
+ output
1480
+ };
1481
+ }
1482
+ async function resolveTitle(opts, brief) {
1483
+ if (opts.title) return opts.title;
1484
+ const derived = brief ? titleFromBrief(brief) : null;
1485
+ if (derived) return derived;
1486
+ if (opts.json || !process.stdin.isTTY) return null;
1487
+ const typed = await he({
1488
+ message: "Task title",
1489
+ validate: (v) => v?.trim() ? void 0 : "Required"
1490
+ });
1491
+ return pD(typed) ? null : typed.trim();
1492
+ }
1493
+ const clackWipPrompts = {
1494
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
1495
+ notify: (message) => M.error(message),
1496
+ confirm: async (message, initialValue) => {
1497
+ const answer = await ye({
1498
+ message,
1499
+ initialValue
1500
+ });
1501
+ return pD(answer) ? null : answer;
1502
+ }
1503
+ };
1504
+ async function ask(prompts, message, initialValue) {
1505
+ const answer = await prompts.confirm(message, initialValue);
1506
+ if (answer === null) throw new Error("Cancelled. No task was created.");
1507
+ return answer;
1508
+ }
1509
+ const list = (paths) => paths.map((x) => ` ${x}`).join("\n");
1510
+ async function decideWip(opts, state, prompts, size) {
1511
+ if (state.changed.length === 0 && state.unpushed === 0) return { status: "none" };
1512
+ if (opts.noWip) return {
1513
+ status: "not_sent",
1514
+ reason: "Declined with --no-wip."
1515
+ };
1516
+ const canAsk = !opts.json && prompts.interactive;
1517
+ if (state.committedKeys.length > 0) {
1518
+ const reason = `Unpushed commits contain a private key (${state.committedKeys.map((k) => `${k.path} (commit ${k.commit})`).join(", ")}), so nothing was sent. Rewrite or drop those commits, or push without them.`;
1519
+ if (opts.includeWip) throw new Error(`Could not send local work with --include-wip. ${reason}`);
1520
+ if (canAsk) {
1521
+ prompts.notify?.(reason);
1522
+ if (!await ask(prompts, "Create the task without your local work?", false)) throw new Error("Stopped. No task was created.");
1523
+ }
1524
+ return {
1525
+ status: "not_sent",
1526
+ reason
1527
+ };
1528
+ }
1529
+ if (!opts.includeWip) {
1530
+ if (!canAsk) return {
1531
+ status: "not_sent",
1532
+ reason: "Not asked (no terminal or --json), so only committed and pushed work was sent. Pass --include-wip to send local work."
1533
+ };
1534
+ const parts = [state.changed.length ? `${state.changed.length} uncommitted file(s)` : "", state.unpushed ? `${state.unpushed} commit(s) not on origin` : ""].filter(Boolean);
1535
+ const large = largeWipWarning(size);
1536
+ if (!await ask(prompts, `Send your local work (${parts.join(" and ")}) to Loop? Secret detection is best effort, so check what is in it first.${large ? `\n${large}` : ""}`, true)) return {
1537
+ status: "not_sent",
1538
+ reason: "Declined."
1539
+ };
1540
+ }
1541
+ const secrets = [.../* @__PURE__ */ new Set([...secretLooking(state.changed), ...state.privateKeys])];
1542
+ const committedSecrets = secretLooking(state.committed);
1543
+ if (committedSecrets.length > 0) {
1544
+ if (!(canAsk && await ask(prompts, `Your unpushed commits touch files that look like secrets:\n${list(committedSecrets)}\nSend them anyway?`, false))) {
1545
+ const reason = `Unpushed commits touch files that look like secrets (${committedSecrets.join(", ")}), so nothing was sent.`;
1546
+ if (opts.includeWip) throw new Error(`Could not send local work with --include-wip. ${reason}`);
1547
+ return {
1548
+ status: "not_sent",
1549
+ reason
1550
+ };
1551
+ }
1552
+ }
1553
+ let includeSecrets = false;
1554
+ if (secrets.length > 0 && canAsk) includeSecrets = await ask(prompts, `These files look like secrets and are left out by default:\n${list(secrets)}\nInclude them anyway?`, false);
1555
+ return {
1556
+ status: "send",
1557
+ exclude: includeSecrets ? [] : secrets,
1558
+ includeSecrets
1559
+ };
1560
+ }
1561
+ async function planWip(opts, cwd, prompts) {
1562
+ if (opts.includeWip && opts.noWip) throw new Error("Use either --include-wip or --no-wip.");
1563
+ const state = detectWip(cwd);
1564
+ const hidden = /* @__PURE__ */ new Set([...secretLooking(state.changed), ...state.privateKeys]);
1565
+ const size = changedSize(cwd, state.changed.filter((p) => !hidden.has(p)));
1566
+ const plan = await decideWip(opts, state, prompts, size);
1567
+ const note = [plan.status === "send" ? largeWipWarning(size) : null, state.unfetched ? UNFETCHED_NOTE : null].filter(Boolean).join(" ");
1568
+ return note ? {
1569
+ ...plan,
1570
+ note
1571
+ } : plan;
1572
+ }
1573
+ function onWipCreateFailed(err, cwd, branch) {
1574
+ if (err instanceof AuthError || err instanceof ApiError && err.status >= 400 && err.status < 500) {
1575
+ deleteWipBranch(cwd, branch);
1576
+ return;
1577
+ }
1578
+ const message = err instanceof Error ? err.message : String(err);
1579
+ return new Error(`${sentence(message)} The task may have been created; check loop ls. Your work is on ${branch}.`, { cause: err });
1580
+ }
1581
+ async function runHandoff(api, creds, opts, cwd = process.cwd(), choose = clackChooser, prompts = clackWipPrompts) {
1582
+ if (opts.includeWip && opts.noWip) throw new Error("Use either --include-wip or --no-wip.");
1583
+ assertPlanFlags(opts);
1584
+ const git = gitContext(cwd);
1585
+ const project = await resolveProject(api, opts.env, git.repository, !opts.json && prompts.interactive ? choose : null);
1586
+ const brief = readBrief(opts.brief, opts.words);
1587
+ const title = await resolveTitle(opts, brief);
1588
+ if (!title) throw new Error("A title is required. Pass --title or a --brief with a first line.");
1589
+ const skillIds = await resolveSkillIds(api, opts.skills);
1590
+ const { files, processVersionId } = await prepare(api, opts);
1591
+ const plan = await planWip(opts, cwd, prompts);
1592
+ const base = chooseBaseBranch(git.branch, candidateBranches(project), cwd);
1593
+ const wip = plan.status === "send" ? sendWip(cwd, plan.exclude, { includeSecrets: plan.includeSecrets }) : null;
1594
+ return submit(api, creds, opts, buildPayload(opts, project.id, title, brief, skillIds, git, base.branch, wip, processVersionId), {
1595
+ base_source: base.source,
1596
+ base_warning: baseWarning(base, project.base_branch),
1597
+ wip: plan.status === "send" ? "sent" : plan.status,
1598
+ wip_branch: wip?.branch ?? null,
1599
+ wip_sha: wip?.sha ?? null,
1600
+ wip_excluded: wip?.excluded ?? [],
1601
+ wip_reason: [plan.status === "not_sent" ? plan.reason : "", plan.note ?? ""].filter(Boolean).join(" ") || null
1602
+ }, wip ? (err) => onWipCreateFailed(err, cwd, wip.branch) : void 0, files);
1603
+ }
1604
+ async function runCreate(api, creds, opts) {
1605
+ if (!opts.project) throw new Error("--project <slug> is required.");
1606
+ assertPlanFlags(opts);
1607
+ const project = await findProjectBySlug(api, opts.project);
1608
+ const brief = readBrief(opts.brief, opts.words);
1609
+ const title = await resolveTitle(opts, brief);
1610
+ if (!title) throw new Error("A title is required. Pass --title or a --brief with a first line.");
1611
+ const skillIds = await resolveSkillIds(api, opts.skills);
1612
+ const { files, processVersionId } = await prepare(api, opts);
1613
+ return submit(api, creds, opts, buildPayload(opts, project.id, title, brief, skillIds, null, null, null, processVersionId), {}, void 0, files);
1614
+ }
1615
+ const APPROVE_ANYWAY = "/approve";
1616
+ function asQuestion(body) {
1617
+ if (!body || typeof body !== "object") return null;
1618
+ const b = body;
1619
+ if (typeof b.question !== "string" || !b.question) return null;
1620
+ if (b.code === "task_plan_choice" || b.kind === "plan_choice") return {
1621
+ kind: "plan_choice",
1622
+ question: b.question,
1623
+ helper: typeof b.helper === "string" ? b.helper : void 0,
1624
+ needs_plan: typeof b.needs_plan === "number" ? b.needs_plan : null,
1625
+ can_approve_anyway: false
1626
+ };
1627
+ return {
1628
+ kind: "question",
1629
+ question: b.question,
1630
+ question_key: typeof b.question_key === "string" ? b.question_key : void 0,
1631
+ can_approve_anyway: b.can_approve_anyway === true
1632
+ };
1633
+ }
1634
+ async function postClarity(api, taskId, body) {
1635
+ try {
1636
+ const res = await api.post(`/api/v2/tasks/${taskId}/clarity`, body);
1637
+ const next = asQuestion(res.clarity);
1638
+ if (next) return { next };
1639
+ return { done: {
1640
+ dispatched: res.dispatched ?? false,
1641
+ queued: res.queued ?? false,
1642
+ dispatch_error: res.dispatch_error ?? null
1643
+ } };
1644
+ } catch (err) {
1645
+ if (err instanceof ApiError && err.status === 422) {
1646
+ const b = err.body;
1647
+ const next = b?.code === "task_needs_clarifying" || b?.code === "task_plan_choice" ? asQuestion(err.body) : null;
1648
+ if (next) return { next };
1649
+ }
1650
+ throw err;
1651
+ }
1652
+ }
1653
+ async function postPlanChoice(api, taskId, planFirst) {
1654
+ const res = await api.post(`/api/v2/tasks/${taskId}/plan-choice`, { plan_first: planFirst });
1655
+ return {
1656
+ dispatched: res.dispatched ?? false,
1657
+ queued: res.queued ?? false,
1658
+ dispatch_error: res.dispatch_error ?? null,
1659
+ plan_first: planFirst
1660
+ };
1661
+ }
1662
+ function clarityBody(answer) {
1663
+ return answer.trim() === "/approve" ? { approve_anyway: true } : { answer: answer.trim() };
1664
+ }
1665
+ function describeDispatch(d) {
1666
+ if (d.dispatch_error) return `Approved, but Loop could not start it: ${d.dispatch_error}`;
1667
+ if (d.plan_first) return `Approved with a plan first. ${d.dispatched ? "Loop is writing the plan." : d.queued ? "The plan run is queued for a machine." : "The plan run has not started yet."} When the plan is ready, run loop approve to start the code.`;
1668
+ if (d.dispatched) return "Approved and running.";
1669
+ if (d.queued) return "Approved and queued for a machine.";
1670
+ return "Approved.";
1671
+ }
1672
+ async function answerClarity(api, taskId, first, ask, choose = askPlanChoiceInTerminal, onQuestion) {
1673
+ let question = first;
1674
+ for (;;) {
1675
+ onQuestion?.(question);
1676
+ if (question.kind === "plan_choice") {
1677
+ const planFirst = await choose(question);
1678
+ return planFirst === null ? null : postPlanChoice(api, taskId, planFirst);
1679
+ }
1680
+ const answer = await ask(question);
1681
+ if (!answer?.trim()) return null;
1682
+ const reply = await postClarity(api, taskId, clarityBody(answer));
1683
+ if ("done" in reply) return reply.done;
1684
+ question = reply.next;
1685
+ }
1686
+ }
1687
+ async function answerClarityInPlace(api, result, ask, choose) {
1688
+ const first = asQuestion(result.output.clarity);
1689
+ if (!first) return result;
1690
+ let latest = first;
1691
+ const done = await answerClarity(api, result.output.id, first, ask, choose, (q) => {
1692
+ latest = q;
1693
+ });
1694
+ if (!done) {
1695
+ if (latest === first) return result;
1696
+ return {
1697
+ exitCode: 2,
1698
+ output: {
1699
+ ...result.output,
1700
+ clarity: clarityOutput(latest)
1701
+ }
1702
+ };
1703
+ }
1704
+ return {
1705
+ exitCode: done.dispatch_error ? 1 : 0,
1706
+ output: {
1707
+ ...result.output,
1708
+ ...done,
1709
+ clarity: null
1710
+ }
1711
+ };
1712
+ }
1713
+ function clarityOutput(q) {
1714
+ return {
1715
+ code: q.kind === "plan_choice" ? "task_plan_choice" : "task_needs_clarifying",
1716
+ kind: q.kind ?? "question",
1717
+ question: q.question,
1718
+ ...q.question_key ? { question_key: q.question_key } : {},
1719
+ ...q.kind === "plan_choice" ? {
1720
+ helper: q.helper,
1721
+ needs_plan: q.needs_plan ?? null
1722
+ } : {},
1723
+ ...q.kind !== "plan_choice" ? { can_approve_anyway: q.can_approve_anyway === true } : {}
1724
+ };
1725
+ }
1726
+ async function askClarityInTerminal(q) {
1727
+ M.warn(`Loop has a question before it runs:\n${q.question}`);
1728
+ const answer = await he({
1729
+ message: q.can_approve_anyway ? `Your answer (or ${APPROVE_ANYWAY} to run it as it is)` : "Your answer",
1730
+ placeholder: "Leave empty to answer later"
1731
+ });
1732
+ return pD(answer) ? null : answer;
1733
+ }
1734
+ async function askPlanChoiceInTerminal(q) {
1735
+ M.warn(`${q.question}${q.helper ? `\n${q.helper}` : ""}`);
1736
+ const answer = await ve({
1737
+ message: "How should Loop start?",
1738
+ options: [{
1739
+ value: true,
1740
+ label: "Plan first, then run",
1741
+ hint: "Loop writes a plan and waits for loop approve"
1742
+ }, {
1743
+ value: false,
1744
+ label: "Run without a plan"
1745
+ }]
1746
+ });
1747
+ return pD(answer) ? null : answer;
1748
+ }
1749
+ const COMMANDS = [
1750
+ {
1751
+ name: "login",
1752
+ usage: "login",
1753
+ summary: "Sign in through the browser and store a token"
1754
+ },
1755
+ {
1756
+ name: "handoff",
1757
+ usage: "handoff [WORDS...]",
1758
+ summary: "Create a task for the current repository and branch"
1759
+ },
1760
+ {
1761
+ name: "add",
1762
+ usage: "add [WORDS...]",
1763
+ summary: "Capture a task in Backlog without running it"
1764
+ },
1765
+ {
1766
+ name: "task",
1767
+ usage: "task create [WORDS...]",
1768
+ summary: "Create a task without git context (--project required)"
1769
+ },
1770
+ {
1771
+ name: "status",
1772
+ usage: "status [KEY]",
1773
+ summary: "Show a task (defaults to the last created task)"
1774
+ },
1775
+ {
1776
+ name: "open",
1777
+ usage: "open [KEY]",
1778
+ summary: "Open a task in the browser"
1779
+ },
1780
+ {
1781
+ name: "checkout",
1782
+ usage: "checkout [KEY]",
1783
+ summary: "Check out the task's pull request branch"
1784
+ },
1785
+ {
1786
+ name: "ls",
1787
+ usage: "ls",
1788
+ summary: "List your open tasks for this repository"
1789
+ },
1790
+ {
1791
+ name: "wait",
1792
+ usage: "wait [KEY]",
1793
+ summary: "Wait until the task needs you or is final"
1794
+ },
1795
+ {
1796
+ name: "session",
1797
+ usage: "session [KEY]",
1798
+ summary: "Watch and drive a run in the terminal (--json for JSON Lines)"
1799
+ },
1800
+ {
1801
+ name: "approve",
1802
+ usage: "approve [KEY]",
1803
+ summary: "Approve the plan so the code run starts"
1804
+ },
1805
+ {
1806
+ name: "models",
1807
+ usage: "models",
1808
+ summary: "List the models Loop accepts for --model"
1809
+ },
1810
+ {
1811
+ name: "doctor",
1812
+ usage: "doctor",
1813
+ summary: "Check sign-in, token expiry, project, branch and version"
1814
+ },
1815
+ {
1816
+ name: "completion",
1817
+ usage: "completion zsh|bash",
1818
+ summary: "Print a shell completion script"
1819
+ }
1820
+ ];
1821
+ const SUBCOMMANDS = {
1822
+ task: ["create"],
1823
+ completion: ["zsh", "bash"]
1824
+ };
1825
+ const OPTIONS = {
1826
+ env: { type: "string" },
1827
+ "api-url": { type: "string" },
1828
+ "web-url": { type: "string" },
1829
+ paste: { type: "boolean" },
1830
+ title: { type: "string" },
1831
+ brief: { type: "string" },
1832
+ skill: {
1833
+ type: "string",
1834
+ multiple: true
1835
+ },
1836
+ attach: {
1837
+ type: "string",
1838
+ multiple: true
1839
+ },
1840
+ plan: { type: "boolean" },
1841
+ "no-plan": { type: "boolean" },
1842
+ process: { type: "string" },
1843
+ hotfix: { type: "boolean" },
1844
+ engine: { type: "string" },
1845
+ model: { type: "string" },
1846
+ "attach-session": {
1847
+ type: "boolean",
1848
+ short: "s"
1849
+ },
1850
+ type: { type: "string" },
1851
+ "no-run": { type: "boolean" },
1852
+ "include-wip": { type: "boolean" },
1853
+ "no-wip": { type: "boolean" },
1854
+ repo: { type: "string" },
1855
+ all: { type: "boolean" },
1856
+ mine: { type: "boolean" },
1857
+ timeout: { type: "string" },
1858
+ project: { type: "string" },
1859
+ json: { type: "boolean" },
1860
+ help: {
1861
+ type: "boolean",
1862
+ short: "h"
1863
+ },
1864
+ version: {
1865
+ type: "boolean",
1866
+ short: "v"
1867
+ }
1868
+ };
1869
+ function allFlags() {
1870
+ return Object.entries(OPTIONS).flatMap(([name, o]) => [`--${name}`, ..."short" in o ? [`-${o.short}`] : []]);
1871
+ }
1872
+ function commandLines() {
1873
+ const width = Math.max(...COMMANDS.map((c) => c.usage.length)) + 2;
1874
+ return COMMANDS.map((c) => ` ${c.usage.padEnd(width)}${c.summary}`).join("\n");
1875
+ }
1876
+ const SHELLS = ["zsh", "bash"];
1877
+ const quote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
1878
+ function zsh() {
1879
+ const commands = COMMANDS.map((c) => ` ${quote(`${c.name}:${c.summary.replace(/:/g, " -")}`)}`);
1880
+ const cases = Object.entries(SUBCOMMANDS).map(([cmd, subs]) => ` ${cmd}) if (( CURRENT == 3 )); then compadd -- ${subs.join(" ")}; return; fi ;;`);
1881
+ return `#compdef loop
1882
+ # Load with: eval "$(loop completion zsh)"
1883
+ _loop() {
1884
+ local -a commands
1885
+ commands=(
1886
+ ${commands.join("\n")}
1887
+ )
1888
+ local -a flags
1889
+ flags=(${allFlags().join(" ")})
1890
+ if [[ $words[CURRENT] == -* ]]; then compadd -- $flags; return; fi
1891
+ if (( CURRENT == 2 )); then _describe -t commands 'loop command' commands; return; fi
1892
+ case $words[2] in
1893
+ ${cases.join("\n")}
1894
+ esac
1895
+ _files
1896
+ }
1897
+ compdef _loop loop
1898
+ `;
1899
+ }
1900
+ function bash() {
1901
+ const names = COMMANDS.map((c) => c.name).join(" ");
1902
+ const cases = Object.entries(SUBCOMMANDS).map(([cmd, subs]) => ` ${cmd}) if (( COMP_CWORD == 2 )); then COMPREPLY=($(compgen -W ${quote(subs.join(" "))} -- "$cur")); return; fi ;;`);
1903
+ return `# Load with: eval "$(loop completion bash)"
1904
+ _loop() {
1905
+ local cur=\${COMP_WORDS[COMP_CWORD]}
1906
+ COMPREPLY=()
1907
+ if [[ $cur == -* ]]; then
1908
+ COMPREPLY=($(compgen -W ${quote(allFlags().join(" "))} -- "$cur"))
1909
+ return
1910
+ fi
1911
+ if (( COMP_CWORD == 1 )); then
1912
+ COMPREPLY=($(compgen -W ${quote(names)} -- "$cur"))
1913
+ return
1914
+ fi
1915
+ case \${COMP_WORDS[1]} in
1916
+ ${cases.join("\n")}
1917
+ esac
1918
+ COMPREPLY=($(compgen -f -- "$cur"))
1919
+ }
1920
+ complete -F _loop loop
1921
+ `;
1922
+ }
1923
+ function completionScript(shell) {
1924
+ return shell === "zsh" ? zsh() : bash();
1925
+ }
1926
+ const PACKAGE = "@juiceboxcreative/loop";
1927
+ const LATEST_URL = `https://registry.npmjs.org/${PACKAGE}/latest`;
1928
+ const DAY_MS$1 = 864e5;
1929
+ const parts = (v) => /^(\d+)\.(\d+)\.(\d+)/.exec(v)?.slice(1).map(Number);
1930
+ function isNewer(latest, current) {
1931
+ const a = parts(latest);
1932
+ const b = parts(current);
1933
+ if (!a || !b) return false;
1934
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
1935
+ return false;
1936
+ }
1937
+ async function fetchLatestVersion(url = process.env.LOOP_UPDATE_URL || LATEST_URL, timeoutMs = 1500, signal) {
1938
+ const controller = new AbortController();
1939
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1940
+ const cancel = () => controller.abort();
1941
+ if (signal?.aborted) cancel();
1942
+ signal?.addEventListener("abort", cancel, { once: true });
1943
+ try {
1944
+ const res = await fetch(url, {
1945
+ headers: { Accept: "application/json" },
1946
+ signal: controller.signal
1947
+ });
1948
+ if (!res.ok) return null;
1949
+ const body = await res.json();
1950
+ return typeof body.version === "string" ? body.version : null;
1951
+ } catch {
1952
+ return null;
1953
+ } finally {
1954
+ clearTimeout(timer);
1955
+ signal?.removeEventListener("abort", cancel);
1956
+ }
1957
+ }
1958
+ function updateCheckWanted(argv, env = process.env, tty = Boolean(process.stdout.isTTY && process.stderr.isTTY)) {
1959
+ return tty && !argv.includes("--json") && argv[0] !== "completion" && argv[0] !== "doctor" && !env.CI && !env.VITEST && !env.LOOP_NO_UPDATE_CHECK;
1960
+ }
1961
+ async function checkForUpdate(current, opts = {}) {
1962
+ try {
1963
+ const now = opts.now ?? Date.now();
1964
+ const cached = readUpdateCheck();
1965
+ if (cached && now - Date.parse(cached.checked_at) < DAY_MS$1) return null;
1966
+ const latest = await fetchLatestVersion(opts.url, opts.timeoutMs, opts.signal);
1967
+ if (opts.signal?.aborted) return null;
1968
+ writeUpdateCheck({
1969
+ checked_at: new Date(now).toISOString(),
1970
+ latest: latest ?? cached?.latest ?? null
1971
+ });
1972
+ return latest && isNewer(latest, current) ? latest : null;
1973
+ } catch {
1974
+ return null;
1975
+ }
1976
+ }
1977
+ function startUpdateCheck(current, opts = {}) {
1978
+ const controller = new AbortController();
1979
+ const result = checkForUpdate(current, {
1980
+ url: opts.url,
1981
+ now: opts.now,
1982
+ signal: controller.signal
1983
+ });
1984
+ return {
1985
+ cancel: () => controller.abort(),
1986
+ notice: async () => {
1987
+ let timer;
1988
+ const late = new Promise((resolve) => {
1989
+ timer = setTimeout(() => {
1990
+ controller.abort();
1991
+ resolve(null);
1992
+ }, opts.graceMs ?? 200);
1993
+ });
1994
+ try {
1995
+ return await Promise.race([result, late]);
1996
+ } finally {
1997
+ clearTimeout(timer);
1998
+ }
1999
+ }
2000
+ };
2001
+ }
2002
+ const EXPIRY_WARN_DAYS = 14;
2003
+ const DAY_MS = 864e5;
2004
+ function expiry(expiresAt, now) {
2005
+ const name = "Token expiry";
2006
+ if (!expiresAt) return {
2007
+ name,
2008
+ status: "ok",
2009
+ message: "Not recorded (pasted token)"
2010
+ };
2011
+ const at = Date.parse(expiresAt);
2012
+ if (Number.isNaN(at)) return {
2013
+ name,
2014
+ status: "warn",
2015
+ message: `Unreadable date "${expiresAt}"`
2016
+ };
2017
+ const days = Math.ceil((at - now) / DAY_MS);
2018
+ if (days <= 0) return {
2019
+ name,
2020
+ status: "fail",
2021
+ message: "Expired. Run loop login"
2022
+ };
2023
+ const on = new Date(at).toISOString().slice(0, 10);
2024
+ if (days < EXPIRY_WARN_DAYS) return {
2025
+ name,
2026
+ status: "warn",
2027
+ message: `Expires in ${days} day${days === 1 ? "" : "s"} (${on}). Run loop login to renew`
2028
+ };
2029
+ return {
2030
+ name,
2031
+ status: "ok",
2032
+ message: `Expires ${on} (${days} days)`
2033
+ };
2034
+ }
2035
+ function runDoctor(opts) {
2036
+ return withNoGitPrompts(() => collectChecks(opts));
2037
+ }
2038
+ async function collectChecks(opts) {
2039
+ const { creds, env } = opts;
2040
+ const now = opts.now ?? Date.now();
2041
+ const cwd = opts.cwd ?? process.cwd();
2042
+ const checks = [];
2043
+ let api = null;
2044
+ if (!creds) checks.push({
2045
+ name: "Signed in",
2046
+ status: "fail",
2047
+ message: "Not signed in. Run loop login"
2048
+ });
2049
+ else {
2050
+ const client = createClient(creds.api_url, creds.token);
2051
+ try {
2052
+ const me = await getMe(client);
2053
+ const who = me.name ?? me.email ?? "your account";
2054
+ checks.push({
2055
+ name: "Signed in",
2056
+ status: "ok",
2057
+ message: `${who} on ${new URL(creds.api_url).host}`
2058
+ });
2059
+ api = client;
2060
+ } catch (err) {
2061
+ checks.push({
2062
+ name: "Signed in",
2063
+ status: "fail",
2064
+ message: err instanceof AuthError ? "The token was rejected or has expired. Run loop login" : `Could not reach ${creds.api_url}: ${err instanceof Error ? err.message : String(err)}`
2065
+ });
2066
+ }
2067
+ checks.push(expiry(creds.expires_at, now));
2068
+ }
2069
+ let git = null;
2070
+ try {
2071
+ git = gitContext(cwd);
2072
+ } catch (err) {
2073
+ checks.push({
2074
+ name: "Repository",
2075
+ status: "warn",
2076
+ message: err instanceof Error ? err.message : String(err)
2077
+ });
2078
+ }
2079
+ let project = null;
2080
+ if (git && api) try {
2081
+ const projects = await findProjectsByRepository(api, git.repository);
2082
+ const slugs = projects.map((p) => p.slug).join(", ");
2083
+ if (projects.length === 0) checks.push({
2084
+ name: "Project",
2085
+ status: "fail",
2086
+ message: `No Loop project is linked to ${git.repository}. Link it in Loop, or use loop task create --project <slug>`
2087
+ });
2088
+ else if (projects.length === 1) {
2089
+ project = projects[0];
2090
+ checks.push({
2091
+ name: "Project",
2092
+ status: "ok",
2093
+ message: `${slugs} (${git.repository})`
2094
+ });
2095
+ } else {
2096
+ const remembered = readRememberedProject(env, git.repository);
2097
+ const chosen = projects.find((p) => p.id === remembered);
2098
+ project = chosen ?? null;
2099
+ checks.push(chosen ? {
2100
+ name: "Project",
2101
+ status: "ok",
2102
+ message: `${chosen.slug} (remembered; also ${slugs})`
2103
+ } : {
2104
+ name: "Project",
2105
+ status: "warn",
2106
+ message: `${projects.length} projects use ${git.repository} (${slugs}) and none is remembered. handoff will ask`
2107
+ });
2108
+ }
2109
+ } catch (err) {
2110
+ checks.push({
2111
+ name: "Project",
2112
+ status: "fail",
2113
+ message: err instanceof AuthError ? "The token was rejected" : err.message
2114
+ });
2115
+ }
2116
+ if (git) {
2117
+ if (git.branch === "HEAD") checks.push({
2118
+ name: "Branch",
2119
+ status: "warn",
2120
+ message: "Detached HEAD. Check out a branch"
2121
+ });
2122
+ else {
2123
+ const base = chooseBaseBranch(git.branch, candidateBranches(project), cwd, false);
2124
+ const baseText = `a hand-off would use base ${describeBase(base)}${base.offline ? `. ${OFFLINE_NOTE}` : ""}`;
2125
+ if (base.source === "current" && base.offline) checks.push({
2126
+ name: "Branch",
2127
+ status: "warn",
2128
+ message: `Could not reach origin; your last fetch has ${git.branch} on origin. A hand-off would use base ${describeBase(base)}`
2129
+ });
2130
+ else if (base.source === "current") checks.push({
2131
+ name: "Branch",
2132
+ status: "ok",
2133
+ message: `${git.branch} is on origin; ${baseText}`
2134
+ });
2135
+ else checks.push({
2136
+ name: "Branch",
2137
+ status: "warn",
2138
+ message: `${git.branch} is not on origin; ${baseText}. Push it, or pass --include-wip so handoff sends your local work`
2139
+ });
2140
+ }
2141
+ }
2142
+ const latest = Boolean((opts.processEnv ?? process.env).LOOP_NO_UPDATE_CHECK) ? void 0 : await (opts.latest ?? (() => fetchLatestVersion(void 0, 3e3)))();
2143
+ if (latest === void 0) checks.push({
2144
+ name: "Version",
2145
+ status: "ok",
2146
+ message: `${opts.version} (not checked: LOOP_NO_UPDATE_CHECK is set)`
2147
+ });
2148
+ else if (latest === null) checks.push({
2149
+ name: "Version",
2150
+ status: "warn",
2151
+ message: `${opts.version} (could not check the latest published version)`
2152
+ });
2153
+ else if (isNewer(latest, opts.version)) checks.push({
2154
+ name: "Version",
2155
+ status: "warn",
2156
+ message: `${opts.version}, and ${latest} is available. Run npm install -g ${PACKAGE}`
2157
+ });
2158
+ else checks.push({
2159
+ name: "Version",
2160
+ status: "ok",
2161
+ message: `${opts.version} (latest)`
2162
+ });
2163
+ return {
2164
+ ok: !checks.some((c) => c.status === "fail"),
2165
+ checks
2166
+ };
2167
+ }
2168
+ const clackPrChooser = async (prs) => {
2169
+ const choice = await ve({
2170
+ message: "This task has several pull requests. Which one?",
2171
+ options: prs.map((pr, i) => ({
2172
+ value: i,
2173
+ label: pr.repository ?? pr.url,
2174
+ hint: pr.head_branch ?? void 0
2175
+ }))
2176
+ });
2177
+ return pD(choice) ? null : prs[choice] ?? null;
2178
+ };
2179
+ const same = (a, b) => (a ?? "").toLowerCase() === b.toLowerCase();
2180
+ const PR_URL = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/i;
2181
+ function resolvePr(pr) {
2182
+ const m = PR_URL.exec(pr.url ?? "");
2183
+ return {
2184
+ ...pr,
2185
+ repository: pr.repo || (m ? `${m[1]}/${m[2]}` : null),
2186
+ number: m ? Number(m[3]) : null
2187
+ };
2188
+ }
2189
+ async function pickPullRequest(task, opts, choose = clackPrChooser) {
2190
+ let prs = (task.pull_requests ?? []).map(resolvePr);
2191
+ if (prs.length === 0) throw new Error(`${task.key} has no pull request to check out yet.`);
2192
+ if (opts.repo) {
2193
+ prs = prs.filter((pr) => same(pr.repository, opts.repo));
2194
+ if (prs.length === 0) throw new Error(`${task.key} has no pull request in ${opts.repo}.`);
2195
+ } else if (opts.origin) {
2196
+ const here = prs.filter((pr) => same(pr.repository, opts.origin));
2197
+ if (here.length > 0) prs = here;
2198
+ }
2199
+ const open = prs.filter((pr) => pr.status === "open");
2200
+ if (open.length > 0) prs = open;
2201
+ if (prs.length === 1) return prs[0];
2202
+ if (!opts.interactive) {
2203
+ const repos = new Set(prs.map((pr) => (pr.repository ?? pr.url).toLowerCase()));
2204
+ const urls = prs.map((pr) => pr.url).join(", ");
2205
+ throw new Error(repos.size > 1 ? `${task.key} has several pull requests (${urls}). Pass --repo <owner/name>.` : `${task.key} has several open pull requests in the same repository (${urls}). Run loop checkout in a terminal to choose one.`);
2206
+ }
2207
+ const chosen = await choose(prs);
2208
+ if (!chosen) throw new Error("No pull request chosen.");
2209
+ return chosen;
2210
+ }
2211
+ function branchExists(branch, cwd) {
2212
+ try {
2213
+ runGit([
2214
+ "rev-parse",
2215
+ "--verify",
2216
+ "--quiet",
2217
+ `refs/heads/${branch}`
2218
+ ], cwd);
2219
+ return true;
2220
+ } catch {
2221
+ return false;
2222
+ }
2223
+ }
2224
+ async function runCheckout(task, opts, choose = clackPrChooser) {
2225
+ const cwd = opts.cwd ?? process.cwd();
2226
+ const git = gitContext(cwd);
2227
+ if (hasTrackedChanges(cwd)) throw new GitError("You have uncommitted changes. Commit them, or stash them yourself, then run loop checkout again.");
2228
+ const pr = await pickPullRequest(task, {
2229
+ repo: opts.repo,
2230
+ origin: git.repository,
2231
+ interactive: opts.interactive
2232
+ }, choose);
2233
+ if (!pr.repository) throw new GitError(`Could not tell which repository ${pr.url} belongs to.`);
2234
+ if (!same(pr.repository, git.repository)) throw new GitError(`${task.key}'s pull request is in ${pr.repository}, but this repository is ${git.repository}. Run loop checkout from a clone of ${pr.repository}.`);
2235
+ let branch;
2236
+ let target;
2237
+ let track = false;
2238
+ if (pr.head_branch) {
2239
+ branch = pr.head_branch;
2240
+ if (branch.startsWith("-")) throw new GitError(`Refusing the branch name "${branch}".`);
2241
+ runGit([
2242
+ "check-ref-format",
2243
+ "--branch",
2244
+ branch
2245
+ ], cwd);
2246
+ target = `refs/remotes/origin/${branch}`;
2247
+ runGit([
2248
+ "fetch",
2249
+ "origin",
2250
+ `+refs/heads/${branch}:${target}`
2251
+ ], cwd);
2252
+ track = true;
2253
+ } else {
2254
+ if (pr.number === null) throw new GitError(`Could not read a pull request number from ${pr.url}.`);
2255
+ branch = `loop/pr-${pr.number}`;
2256
+ runGit([
2257
+ "fetch",
2258
+ "origin",
2259
+ `refs/pull/${pr.number}/head`
2260
+ ], cwd);
2261
+ target = runGit(["rev-parse", "FETCH_HEAD"], cwd);
2262
+ }
2263
+ let upToDate = true;
2264
+ if (branchExists(branch, cwd)) {
2265
+ runGit([
2266
+ "checkout",
2267
+ branch,
2268
+ "--"
2269
+ ], cwd);
2270
+ try {
2271
+ runGit([
2272
+ "merge",
2273
+ "--ff-only",
2274
+ target
2275
+ ], cwd);
2276
+ } catch {
2277
+ upToDate = false;
2278
+ }
2279
+ } else runGit([
2280
+ "checkout",
2281
+ "-b",
2282
+ branch,
2283
+ track ? "--track" : "--no-track",
2284
+ target
2285
+ ], cwd);
2286
+ return {
2287
+ key: task.key,
2288
+ repository: git.repository,
2289
+ branch,
2290
+ pull_request: pr.url,
2291
+ sha: runGit(["rev-parse", "HEAD"], cwd),
2292
+ up_to_date: upToDate
2293
+ };
2294
+ }
2295
+ function openInBrowser(url) {
2296
+ let u;
2297
+ try {
2298
+ u = new URL(url);
2299
+ } catch {
2300
+ return false;
2301
+ }
2302
+ if (u.protocol !== "http:" && u.protocol !== "https:") return false;
2303
+ const [cmd, args] = process.platform === "darwin" ? ["open", [u.href]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", u.href]] : ["xdg-open", [u.href]];
2304
+ try {
2305
+ spawn(cmd, args, {
2306
+ stdio: "ignore",
2307
+ detached: true
2308
+ }).on("error", () => {}).unref();
2309
+ return true;
2310
+ } catch {
2311
+ return false;
2312
+ }
2313
+ }
2314
+ function newState() {
2315
+ return randomBytes(24).toString("base64url");
2316
+ }
2317
+ function parseCallback(body, expectedState) {
2318
+ if (!body || typeof body !== "object") return { error: "Invalid body." };
2319
+ const b = body;
2320
+ if (typeof b.state !== "string" || b.state !== expectedState) return { error: "State mismatch. Start loop login again." };
2321
+ if (typeof b.token !== "string" || !b.token) return { error: "Missing token." };
2322
+ return {
2323
+ token: b.token,
2324
+ api_url: typeof b.api_url === "string" ? b.api_url : void 0,
2325
+ web_url: typeof b.web_url === "string" ? b.web_url : void 0,
2326
+ expires_at: typeof b.expires_at === "string" ? b.expires_at : null
2327
+ };
2328
+ }
2329
+ function corsHeaders(origin) {
2330
+ return {
2331
+ "Access-Control-Allow-Origin": origin,
2332
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
2333
+ "Access-Control-Allow-Headers": "Content-Type",
2334
+ "Access-Control-Allow-Private-Network": "true",
2335
+ "Access-Control-Max-Age": "600",
2336
+ Vary: "Origin"
2337
+ };
2338
+ }
2339
+ function listenForCallback(state, webOrigin, timeoutMs) {
2340
+ const server = createServer();
2341
+ const headers = corsHeaders(webOrigin);
2342
+ return {
2343
+ server,
2344
+ port: new Promise((resolve, reject) => {
2345
+ server.once("error", reject);
2346
+ server.listen(0, "127.0.0.1", () => {
2347
+ const addr = server.address();
2348
+ resolve(typeof addr === "object" && addr ? addr.port : 0);
2349
+ });
2350
+ }),
2351
+ callback: new Promise((resolve, reject) => {
2352
+ const timer = setTimeout(() => {
2353
+ server.close();
2354
+ reject(/* @__PURE__ */ new Error("Timed out waiting for the browser. Try loop login --paste."));
2355
+ }, timeoutMs);
2356
+ server.on("request", (req, res) => {
2357
+ const reply = (status, text) => {
2358
+ res.writeHead(status, {
2359
+ ...headers,
2360
+ ...text ? { "Content-Type": "text/plain" } : {}
2361
+ });
2362
+ res.end(text);
2363
+ };
2364
+ const origin = req.headers.origin;
2365
+ if (origin !== void 0 && origin !== webOrigin) return reply(403, "Forbidden origin.");
2366
+ if (new URL(req.url ?? "/", "http://127.0.0.1").pathname !== "/callback") return reply(404, "Not found");
2367
+ if (req.method === "OPTIONS") return reply(204);
2368
+ if (req.method !== "POST") return reply(405, "Method not allowed");
2369
+ let raw = "";
2370
+ req.on("data", (chunk) => {
2371
+ raw += chunk;
2372
+ if (raw.length > 16384) req.destroy();
2373
+ });
2374
+ req.on("end", () => {
2375
+ let body;
2376
+ try {
2377
+ body = JSON.parse(raw);
2378
+ } catch {
2379
+ return reply(400, "Invalid JSON.");
2380
+ }
2381
+ const result = parseCallback(body, state);
2382
+ if ("error" in result) return reply(400, result.error);
2383
+ res.writeHead(204, headers);
2384
+ res.end(() => {
2385
+ clearTimeout(timer);
2386
+ server.close();
2387
+ resolve(result);
2388
+ });
2389
+ });
2390
+ });
2391
+ })
2392
+ };
2393
+ }
2394
+ async function verifyToken(apiUrl, token) {
2395
+ await createClient(apiUrl, token).get("/api/me");
2396
+ }
2397
+ async function runLogin(opts) {
2398
+ const defaults = ENV_URLS[opts.env];
2399
+ let apiUrl = opts.apiUrl ?? defaults.api_url;
2400
+ let webUrl = opts.webUrl ?? defaults.web_url;
2401
+ const state = newState();
2402
+ Ie("loop login");
2403
+ let token;
2404
+ let expiresAt = null;
2405
+ if (opts.paste) {
2406
+ M.info(`Open this URL in any browser:\n${webUrl}/cli/connect?paste=1`);
2407
+ const pasted = await ge({ message: "Paste the token shown on the page" });
2408
+ if (pD(pasted) || !pasted.trim()) {
2409
+ xe("Login cancelled.");
2410
+ return 1;
2411
+ }
2412
+ token = pasted.trim();
2413
+ } else {
2414
+ const { port, callback } = listenForCallback(state, new URL(webUrl).origin, opts.timeoutMs ?? 3e5);
2415
+ const url = `${webUrl}/cli/connect?port=${await port}&state=${state}`;
2416
+ M.step(`Opening ${url}`);
2417
+ M.info("If the browser does not open, paste that URL yourself.");
2418
+ if (!openInBrowser(url)) M.warn("Could not open a browser. Paste the URL above.");
2419
+ const spinner = Y();
2420
+ spinner.start("Waiting for the browser");
2421
+ let cb;
2422
+ try {
2423
+ cb = await callback;
2424
+ } catch (err) {
2425
+ spinner.stop("No callback received");
2426
+ xe(err.message);
2427
+ return 1;
2428
+ }
2429
+ spinner.stop("Token received");
2430
+ token = cb.token;
2431
+ apiUrl = opts.apiUrl ?? cb.api_url ?? apiUrl;
2432
+ webUrl = opts.webUrl ?? cb.web_url ?? webUrl;
2433
+ expiresAt = cb.expires_at ?? null;
2434
+ }
2435
+ try {
2436
+ await verifyToken(apiUrl, token);
2437
+ } catch (err) {
2438
+ xe(`Token check failed against ${apiUrl}: ${err.message}`);
2439
+ return 1;
2440
+ }
2441
+ const creds = {
2442
+ api_url: apiUrl,
2443
+ web_url: webUrl,
2444
+ token,
2445
+ expires_at: expiresAt
2446
+ };
2447
+ const path = writeCredentials(opts.env, creds);
2448
+ Se(`Logged in to ${webUrl}. Credentials saved to ${path} (mode 600).`);
2449
+ return 0;
2450
+ }
2451
+ function age(iso, now = Date.now()) {
2452
+ const then = iso ? Date.parse(iso) : NaN;
2453
+ if (Number.isNaN(then)) return "-";
2454
+ const mins = Math.max(0, Math.floor((now - then) / 6e4));
2455
+ if (mins < 60) return `${mins}m`;
2456
+ if (mins < 1440) return `${Math.floor(mins / 60)}h`;
2457
+ return `${Math.floor(mins / 1440)}d`;
2458
+ }
2459
+ async function runLs(api, opts) {
2460
+ const query = {
2461
+ limit: String(200),
2462
+ owner: "me",
2463
+ open: "1"
2464
+ };
2465
+ let projectIds = null;
2466
+ if (!opts.all) {
2467
+ const git = gitContext(opts.cwd);
2468
+ const projects = await findProjectsByRepository(api, git.repository);
2469
+ if (projects.length === 0) throw new ProjectUnresolved(`No Loop project is linked to ${git.repository}. Use loop ls --all for every repository.`);
2470
+ projectIds = new Set(projects.map((pr) => pr.id));
2471
+ query.project_id = [...projectIds].join(",");
2472
+ }
2473
+ const me = await api.get("/api/me");
2474
+ const meId = me.data?.id ?? me.id;
2475
+ if (meId === void 0 || meId === null) throw new Error("Could not tell who you are from Loop; run loop doctor.");
2476
+ const cards = (await api.get("/api/v2/tasks", query)).data ?? [];
2477
+ return {
2478
+ rows: cards.filter((t) => (t.owner_id ?? t.created_by_user_id ?? t.created_by?.id) === meId).filter((t) => t.status !== "done").filter((t) => projectIds === null || t.project_id != null && projectIds.has(t.project_id) || (t.target_project_ids ?? []).some((id) => projectIds.has(id))).map((t) => ({
2479
+ key: t.key,
2480
+ title: t.title ?? "",
2481
+ status: t.status,
2482
+ engine: t.resolved_engine ?? t.engine ?? "auto",
2483
+ model: t.model ?? null,
2484
+ project: t.project_slug ?? null,
2485
+ created_at: t.created_at ?? null
2486
+ })),
2487
+ truncated: cards.length >= 200
2488
+ };
2489
+ }
2490
+ function truncate(text, max) {
2491
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
2492
+ }
2493
+ function formatTable(rows, now = Date.now()) {
2494
+ const cells = rows.map((r) => [
2495
+ r.key,
2496
+ truncate(r.title, 50),
2497
+ r.status,
2498
+ r.engine,
2499
+ age(r.created_at, now)
2500
+ ]);
2501
+ const widths = [
2502
+ 0,
2503
+ 1,
2504
+ 2,
2505
+ 3,
2506
+ 4
2507
+ ].map((i) => Math.max(...cells.map((c) => c[i].length)));
2508
+ return cells.map((c) => c.map((v, i) => v.padEnd(widths[i])).join(" ").trimEnd()).join("\n");
2509
+ }
2510
+ async function listModels(api) {
2511
+ return (await api.get("/api/v2/execution-models")).data ?? [];
2512
+ }
2513
+ function describeModels(models) {
2514
+ return models.map((m) => `${m.short_name} (${m.label})`).join(", ");
2515
+ }
2516
+ async function resolveEngineAndModel(api, engine, model) {
2517
+ if (model === void 0) return {
2518
+ engine,
2519
+ model: void 0
2520
+ };
2521
+ if (!model.trim()) throw new Error("--model needs a model name. Run loop models to see the accepted ones.");
2522
+ if (engine === "claude-code" || engine === "codex") throw new Error(`--model only works with the opencode engine (Open Models). ${engine} takes no model.`);
2523
+ if (engine !== void 0 && engine !== "auto" && engine !== "opencode") throw new Error(`--model cannot be used with --engine ${engine}.`);
2524
+ const models = await listModels(api);
2525
+ const wanted = model.trim().toLowerCase();
2526
+ const exact = models.find((m) => m.id.toLowerCase() === wanted || m.short_name.toLowerCase() === wanted);
2527
+ const prefixed = models.filter((m) => m.short_name.toLowerCase().startsWith(wanted) || m.id.toLowerCase().startsWith(wanted));
2528
+ if (!exact && prefixed.length > 1) throw new Error(`"${model}" matches more than one model: ${describeModels(prefixed)}.`);
2529
+ const match = exact ?? prefixed[0];
2530
+ if (!match) throw new Error(`Unknown model "${model}". Accepted models: ${describeModels(models)}.`);
2531
+ return {
2532
+ engine: match.engine || "opencode",
2533
+ model: match.id
2534
+ };
2535
+ }
2536
+ async function runModels(api) {
2537
+ return { models: await listModels(api) };
2538
+ }
2539
+ async function getTaskDetail(api, id, opts) {
2540
+ const res = await api.get(`/api/tasks/${id}`, void 0, opts);
2541
+ return "data" in res && res.data ? res.data : res;
2542
+ }
2543
+ const DONE = /* @__PURE__ */ new Set(["done", "in_review"]);
2544
+ const FAILED = /* @__PURE__ */ new Set([
2545
+ "stuck",
2546
+ "failed",
2547
+ "cancelled",
2548
+ "canceled"
2549
+ ]);
2550
+ function inBacklog(task) {
2551
+ return task.status === "todo" && !task.approved && !task.ran_at && !task.runs?.length;
2552
+ }
2553
+ function planReady(task) {
2554
+ return task.status === "stuck" && task.plan_state === "ready";
2555
+ }
2556
+ function verdict(task) {
2557
+ if (DONE.has(task.status)) return { code: 0 };
2558
+ if (planReady(task)) return {
2559
+ code: 2,
2560
+ reason: "plan"
2561
+ };
2562
+ if (FAILED.has(task.status)) return { code: 4 };
2563
+ const reason = task.clarity?.status === "asked" || task.plan_offer ? "clarity" : task.interaction?.status === "open" ? "card" : task.status === "waiting_for_user" ? "waiting_for_user" : inBacklog(task) ? "backlog" : null;
2564
+ return reason ? {
2565
+ code: 2,
2566
+ reason
2567
+ } : null;
2568
+ }
2569
+ function classify(task) {
2570
+ return verdict(task)?.code ?? null;
2571
+ }
2572
+ function questionOf(task) {
2573
+ if (planReady(task)) return `The plan is ready. Run loop approve ${task.key}.`;
2574
+ if (task.clarity?.status === "asked" && task.clarity.question) return task.clarity.question;
2575
+ if (task.plan_offer) return task.plan_offer.question;
2576
+ if (task.interaction?.status === "open") return task.interaction.body || task.interaction.title || null;
2577
+ if (inBacklog(task)) return `${task.key} is in the Backlog and not set to run. Approve it in Loop or run loop handoff.`;
2578
+ return task.run_outcome?.ask_preview ?? null;
2579
+ }
2580
+ function waitOutput(task, timedOut) {
2581
+ const outcome = task.run_outcome;
2582
+ return {
2583
+ key: task.key,
2584
+ status: task.status,
2585
+ outcome: outcome ? {
2586
+ failure_cause: outcome.failure_cause ?? null,
2587
+ next_step: outcome.next_step ?? null
2588
+ } : null,
2589
+ pull_requests: (task.pull_requests ?? []).map((pr) => pr.url),
2590
+ question: classify(task) === 2 ? questionOf(task) : null,
2591
+ timed_out: timedOut
2592
+ };
2593
+ }
2594
+ function transient(err) {
2595
+ if (err instanceof ApiError) return err.status >= 500 || err.status === 429 || err.status === 408;
2596
+ return err instanceof NetworkError;
2597
+ }
2598
+ const MAX_RETRY_AFTER_MS = 6e4;
2599
+ function retryAfterOf(err) {
2600
+ return err instanceof ApiError && err.retryAfterMs !== void 0 ? Math.min(err.retryAfterMs, MAX_RETRY_AFTER_MS) : void 0;
2601
+ }
2602
+ const MAX_RETRIES = 3;
2603
+ const FINAL_POLL_GRACE_MS = 2e3;
2604
+ function timedOut(task, key) {
2605
+ return {
2606
+ exitCode: 5,
2607
+ task,
2608
+ output: task ? waitOutput(task, true) : {
2609
+ key: key ?? null,
2610
+ status: null,
2611
+ outcome: null,
2612
+ pull_requests: [],
2613
+ question: null,
2614
+ timed_out: true
2615
+ }
2616
+ };
2617
+ }
2618
+ async function runWait(api, id, opts = {}) {
2619
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
2620
+ const now = opts.now ?? Date.now;
2621
+ const max = opts.maxDelayMs ?? 3e4;
2622
+ const deadline = opts.timeoutMs === void 0 ? Infinity : now() + opts.timeoutMs;
2623
+ let delay = opts.minDelayMs ?? 5e3;
2624
+ let retries = 0;
2625
+ let last = null;
2626
+ for (;;) {
2627
+ const left0 = deadline - now();
2628
+ const cap = left0 > 0 ? left0 : FINAL_POLL_GRACE_MS;
2629
+ let task;
2630
+ try {
2631
+ task = await getTaskDetail(api, id, Number.isFinite(cap) ? { timeoutMs: cap } : void 0);
2632
+ retries = 0;
2633
+ } catch (err) {
2634
+ if (!transient(err)) throw err;
2635
+ const left = deadline - now();
2636
+ if (left <= 0) return timedOut(last, opts.key);
2637
+ if (++retries > MAX_RETRIES) throw err;
2638
+ await sleep(Math.min(retryAfterOf(err) ?? delay, left));
2639
+ delay = Math.min(delay * 1.5, max);
2640
+ continue;
2641
+ }
2642
+ last = task;
2643
+ opts.onPoll?.(task);
2644
+ const code = classify(task);
2645
+ if (code !== null) return {
2646
+ exitCode: code,
2647
+ task,
2648
+ output: waitOutput(task, false)
2649
+ };
2650
+ const left = deadline - now();
2651
+ if (left <= 0) return timedOut(task);
2652
+ await sleep(Math.min(delay, left));
2653
+ delay = Math.min(delay * 1.5, max);
2654
+ }
2655
+ }
2656
+ const LIVE_INTERVAL_MS = 2e3;
2657
+ const IDLE_INTERVAL_MS = 1e4;
2658
+ const MAX_POLL_FAILURES = 5;
2659
+ const BOOST_POLLS = 5;
2660
+ const OVERLAP = 20;
2661
+ const STEP_SKEW_MS = 2e3;
2662
+ const KNOWN_COMMANDS = /* @__PURE__ */ new Set([
2663
+ "/quit",
2664
+ "/open",
2665
+ "/cancel",
2666
+ "/approve"
2667
+ ]);
2668
+ const STEER_PREFIX = "Steer the agent: ";
2669
+ const NOT_LIVE = "No run is live. Type continue to start one, or just send your message to Loop.";
2670
+ const STEER_MISROUTED = "Loop Assistant took that as a question, so the run did not get it. Rephrase it without words like show, open, latest, status or check.";
2671
+ const ENDED = /* @__PURE__ */ new Set([
2672
+ "in_review",
2673
+ "done",
2674
+ "stuck",
2675
+ "failed",
2676
+ "cancelled"
2677
+ ]);
2678
+ const LIVE = /* @__PURE__ */ new Set(["ready", "in_progress"]);
2679
+ const STATUS_LABELS = {
2680
+ todo: "Backlog",
2681
+ ready: "Queued",
2682
+ in_progress: "Running",
2683
+ waiting_for_user: "Waiting for an answer",
2684
+ stuck: "Stuck",
2685
+ failed: "Failed",
2686
+ cancelled: "Cancelled",
2687
+ plan_ready: "Plan ready",
2688
+ in_review: "Ready for review",
2689
+ done: "Done"
2690
+ };
2691
+ const statusLabel = (s) => STATUS_LABELS[s] ?? s;
2692
+ const DELIVERY = {
2693
+ append_only: "Saved to the conversation.",
2694
+ warm_delivered: "Sent, waiting for the agent to pick it up.",
2695
+ queued_for_resume: "Resuming the run with your message.",
2696
+ warm_delivery_failed: "Saved, but the agent could not be reached. Try again in a moment.",
2697
+ planning_replied: "Sent to Loop Assistant. Its reply will appear here."
2698
+ };
2699
+ function describeDelivery(state, answer = false) {
2700
+ if (answer && state === "queued_for_resume") return "Resuming the run with your answer.";
2701
+ return state && DELIVERY[state] || "Sent.";
2702
+ }
2703
+ function time(s) {
2704
+ const t = Date.parse(s ?? "");
2705
+ return Number.isNaN(t) ? 0 : t;
2706
+ }
2707
+ function indent(text) {
2708
+ return text.replace(/\n/g, "\n ");
2709
+ }
2710
+ function renderEntry(e, key = "KEY") {
2711
+ switch (e.type) {
2712
+ case "message": return `${e.visibility === "internal" ? "[internal] " : ""}${e.role === "user" ? "you" : e.role === "system" ? "system" : e.machine_task_id ? "agent" : "Loop"}: ${indent(e.body)}`;
2713
+ case "step": return ` - ${e.label} (${e.status})`;
2714
+ case "status": return e.previous === null ? `Status: ${statusLabel(e.status)}` : `Status: ${statusLabel(e.previous)} -> ${statusLabel(e.status)}`;
2715
+ case "card": {
2716
+ const lines = [`Question: ${e.title}`];
2717
+ if (e.body) lines.push(indent(e.body));
2718
+ if (e.kind === "enter_code") lines.push("Type the code. It is hidden as you type and never stored.");
2719
+ else {
2720
+ (e.options ?? []).forEach((o, i) => lines.push(` ${i + 1}) ${o.label}`));
2721
+ lines.push("Type a number to answer.");
2722
+ }
2723
+ return lines.join("\n");
2724
+ }
2725
+ case "clarity":
2726
+ if (e.kind === "plan_choice") return `${e.question}${e.helper ? `\n ${indent(e.helper)}` : ""}\n 1) Plan first, then run\n 2) Run without a plan\nType 1 or 2.`;
2727
+ return `Loop has a question before it runs:\n ${indent(e.question)}\nType your answer${e.can_approve_anyway ? ", or /approve to run it as it is" : ""}.`;
2728
+ case "pull_request": return `Pull request: ${e.url}`;
2729
+ case "end":
2730
+ if (e.reason === "plan") return `The plan is ready. Run loop approve ${key}.`;
2731
+ return [
2732
+ `Run ended: ${statusLabel(e.status)}`,
2733
+ ...e.outcome ? [`Outcome: ${e.outcome}`] : [],
2734
+ ...e.pull_requests.map((u) => `Pull request: ${u}`)
2735
+ ].join("\n");
2736
+ }
2737
+ }
2738
+ function outcomeText(d) {
2739
+ const o = d.run_outcome;
2740
+ if (!o) return null;
2741
+ return [o.next_step, o.failure_cause].filter(Boolean).join(" - ") || null;
2742
+ }
2743
+ function parseSelection(line, card) {
2744
+ const options = card.options ?? [];
2745
+ const picks = line.split(/[,\s]+/).filter(Boolean).map(Number);
2746
+ if (picks.some((n) => !Number.isInteger(n) || n < 1 || n > options.length)) return `Pick a number from 1 to ${options.length}.`;
2747
+ const unique = [...new Set(picks)];
2748
+ const min = card.min_selections ?? 1;
2749
+ const max = card.max_selections ?? 1;
2750
+ if (unique.length < min || unique.length > max) return min === max ? `Pick ${min}.` : `Pick between ${min} and ${max}.`;
2751
+ return unique.map((n) => options[n - 1].id);
2752
+ }
2753
+ var Session = class {
2754
+ api;
2755
+ task;
2756
+ webUrl;
2757
+ opts;
2758
+ cursor = 0;
2759
+ seenIds = /* @__PURE__ */ new Set();
2760
+ stepsSince = null;
2761
+ stepSeen = /* @__PURE__ */ new Map();
2762
+ ownIds = /* @__PURE__ */ new Set();
2763
+ seen = /* @__PURE__ */ new Set();
2764
+ status = null;
2765
+ pending = null;
2766
+ cancelAsked = false;
2767
+ planOfferShown = false;
2768
+ swallowNext = false;
2769
+ maskHold = false;
2770
+ endShown = false;
2771
+ retryAfterMs = 0;
2772
+ skippedFeeds = false;
2773
+ foundNew = false;
2774
+ runLive = false;
2775
+ pickupAfter = null;
2776
+ failures = 0;
2777
+ live = true;
2778
+ boost = 0;
2779
+ finished = false;
2780
+ exitCode = 0;
2781
+ left = false;
2782
+ onLeave = () => {};
2783
+ onNudge = () => {};
2784
+ constructor(api, task, webUrl, opts) {
2785
+ this.api = api;
2786
+ this.task = task;
2787
+ this.webUrl = webUrl;
2788
+ this.opts = opts;
2789
+ }
2790
+ interval() {
2791
+ const base = this.live || this.boost > 0 ? LIVE_INTERVAL_MS : IDLE_INTERVAL_MS;
2792
+ return Math.max(base, this.retryAfterMs);
2793
+ }
2794
+ noteFailure(err) {
2795
+ this.retryAfterMs = retryAfterOf(err) ?? 0;
2796
+ }
2797
+ nudge() {
2798
+ this.boost = BOOST_POLLS;
2799
+ this.onNudge();
2800
+ }
2801
+ say(text) {
2802
+ if (this.opts.json) return;
2803
+ if (this.opts.term) this.opts.term.print(text);
2804
+ else process.stdout.write(`${text}\n`);
2805
+ }
2806
+ emit(e) {
2807
+ if (this.opts.json) (this.opts.write ?? ((l) => process.stdout.write(`${l}\n`)))(JSON.stringify(e));
2808
+ else this.say(renderEntry(e, this.task.key));
2809
+ }
2810
+ attach(term) {
2811
+ this.opts = {
2812
+ ...this.opts,
2813
+ term
2814
+ };
2815
+ }
2816
+ mask(on) {
2817
+ this.opts.term?.mask(on);
2818
+ }
2819
+ isMasked() {
2820
+ return this.pending?.kind === "code" || this.maskHold;
2821
+ }
2822
+ setPending(p) {
2823
+ if (p?.kind === "code") {
2824
+ this.swallowNext = false;
2825
+ this.maskHold = false;
2826
+ }
2827
+ this.pending = p;
2828
+ this.mask(this.isMasked());
2829
+ }
2830
+ async poll() {
2831
+ const id = this.task.id;
2832
+ const readMessages = () => this.api.get(`/api/v2/tasks/${id}/messages`, this.cursor > OVERLAP ? { after_id: String(this.cursor - OVERLAP) } : void 0);
2833
+ const readSteps = () => this.api.get(`/api/v2/tasks/${id}/steps`, this.stepsSince ? { updated_since: this.stepsSince } : void 0);
2834
+ const everything = this.status === null || !this.live || this.boost > 0 || this.foundNew || this.skippedFeeds;
2835
+ let detail;
2836
+ let msgs;
2837
+ let steps;
2838
+ if (everything) [detail, msgs, steps] = await Promise.all([
2839
+ getTaskDetail(this.api, id),
2840
+ readMessages(),
2841
+ readSteps()
2842
+ ]);
2843
+ else {
2844
+ detail = await getTaskDetail(this.api, id);
2845
+ const moved = detail.status !== this.status || ENDED.has(detail.status) || verdict(detail);
2846
+ if (moved) [msgs, steps] = await Promise.all([readMessages(), readSteps()]);
2847
+ else [msgs, steps] = [{ data: [] }, { data: [] }];
2848
+ this.skippedFeeds = !moved;
2849
+ }
2850
+ if (everything) this.skippedFeeds = false;
2851
+ const first = this.status === null;
2852
+ this.failures = 0;
2853
+ this.retryAfterMs = 0;
2854
+ if (this.boost > 0) this.boost--;
2855
+ const entries = [];
2856
+ let proposal = null;
2857
+ const newMessages = (msgs.data ?? []).filter((m) => !this.seenIds.has(m.id)).sort((a, b) => a.id - b.id);
2858
+ for (const m of newMessages) {
2859
+ this.seenIds.add(m.id);
2860
+ this.cursor = Math.max(this.cursor, m.id);
2861
+ if (m.role === "user") {
2862
+ if (proposal && m.id > proposal.id) proposal = null;
2863
+ if (this.pending?.kind === "confirm" && m.id > this.pending.after) this.setPending(null);
2864
+ }
2865
+ const confirm = m.artifacts?.find((a) => a.kind === "confirm")?.item;
2866
+ if (m.role === "agent" && confirm) proposal = {
2867
+ tool: String(confirm.tool ?? ""),
2868
+ item: confirm,
2869
+ id: m.id
2870
+ };
2871
+ if (this.ownIds.delete(m.id)) continue;
2872
+ entries.push({
2873
+ at: time(m.created_at),
2874
+ entry: {
2875
+ type: "message",
2876
+ id: m.id,
2877
+ role: m.role,
2878
+ visibility: m.visibility,
2879
+ body: m.body,
2880
+ created_at: m.created_at,
2881
+ machine_task_id: m.machine_task_id ?? null,
2882
+ artifacts: m.artifacts ?? []
2883
+ }
2884
+ });
2885
+ }
2886
+ for (const s of steps.data ?? []) {
2887
+ const key = `${s.machine_task_id}:${s.index}`;
2888
+ const print = `${s.status}|${s.label}|${s.detail ?? ""}`;
2889
+ if (this.stepSeen.get(key) === print) continue;
2890
+ this.stepSeen.set(key, print);
2891
+ entries.push({
2892
+ at: time(s.timestamp),
2893
+ entry: {
2894
+ type: "step",
2895
+ ...s
2896
+ }
2897
+ });
2898
+ }
2899
+ const serverTime = Date.parse(steps.meta?.server_time ?? "");
2900
+ if (!Number.isNaN(serverTime)) this.stepsSince = (/* @__PURE__ */ new Date(serverTime - STEP_SKEW_MS)).toISOString();
2901
+ const shown = !this.opts.json && planReady(detail) ? "plan_ready" : detail.status;
2902
+ const statusChanged = shown !== this.status;
2903
+ const statusEntry = {
2904
+ type: "status",
2905
+ status: shown,
2906
+ previous: this.status
2907
+ };
2908
+ if (first && statusChanged) this.emit(statusEntry);
2909
+ entries.sort((a, b) => a.at - b.at).forEach((x) => this.emit(x.entry));
2910
+ const after = this.pickupAfter;
2911
+ if (after !== null && entries.some((x) => x.at > after && (x.entry.type === "step" || x.entry.type === "message" && x.entry.role === "agent"))) {
2912
+ this.pickupAfter = null;
2913
+ this.say("Delivered.");
2914
+ }
2915
+ if (!first && statusChanged) this.emit(statusEntry);
2916
+ this.status = shown;
2917
+ for (const pr of detail.pull_requests ?? []) if (this.once(`pr:${pr.url}`)) this.emit({
2918
+ type: "pull_request",
2919
+ url: pr.url,
2920
+ status: pr.status ?? null
2921
+ });
2922
+ const machine = detail.active_machine_task;
2923
+ this.runLive = machine != null && (machine.waiting_for_user || ["running", "waiting_for_user"].includes(machine.status));
2924
+ this.live = LIVE.has(detail.status) || detail.active_machine_task != null && !detail.active_machine_task.waiting_for_user;
2925
+ this.reconcileCard(detail.interaction ?? null);
2926
+ this.reconcileClarity(detail);
2927
+ this.reconcilePlanOffer(detail);
2928
+ if (proposal && (this.pending === null || this.pending.kind === "confirm")) {
2929
+ if (!(first && ENDED.has(detail.status))) this.proposeConfirm(proposal.tool, proposal.item, proposal.id);
2930
+ }
2931
+ this.foundNew = entries.length > 0;
2932
+ const v = verdict(detail);
2933
+ const stop = this.opts.json ? v : null;
2934
+ const parkedPlan = v?.reason === "plan";
2935
+ if (ENDED.has(detail.status) || stop) {
2936
+ if (!this.endShown) {
2937
+ this.endShown = true;
2938
+ this.emit({
2939
+ type: "end",
2940
+ status: detail.status,
2941
+ outcome: outcomeText(detail),
2942
+ pull_requests: (detail.pull_requests ?? []).map((p) => p.url),
2943
+ ...stop?.reason || parkedPlan ? { reason: stop?.reason ?? "plan" } : {}
2944
+ });
2945
+ if (!this.opts.json && !parkedPlan) {
2946
+ if ((detail.pull_requests ?? []).length > 0 || detail.status === "in_review") this.say(`Bring it back: loop checkout ${this.task.key}`);
2947
+ this.say("Type a message to keep going (for example \"continue\"), or /quit.");
2948
+ }
2949
+ }
2950
+ } else this.endShown = false;
2951
+ if (stop) {
2952
+ this.finished = true;
2953
+ this.exitCode = stop.code;
2954
+ }
2955
+ }
2956
+ once(key) {
2957
+ if (this.seen.has(key)) return false;
2958
+ this.seen.add(key);
2959
+ return true;
2960
+ }
2961
+ reconcileCard(card) {
2962
+ const open = card && card.status === "open" ? card : null;
2963
+ const p = this.pending;
2964
+ const mine = p?.kind === "card" ? p.interaction.id : p?.kind === "code" ? p.id : null;
2965
+ if (mine !== null && mine !== open?.id) {
2966
+ if (p?.kind === "code") {
2967
+ this.swallowNext = true;
2968
+ this.maskHold = true;
2969
+ this.say("The code question closed.");
2970
+ }
2971
+ this.setPending(null);
2972
+ }
2973
+ if (!open || !this.once(`card:${open.id}`)) return;
2974
+ this.emit({
2975
+ type: "card",
2976
+ id: open.id,
2977
+ kind: open.kind,
2978
+ title: open.title,
2979
+ body: open.body,
2980
+ options: open.options,
2981
+ expires_at: open.expires_at
2982
+ });
2983
+ if (this.opts.json) return;
2984
+ this.setPending(open.kind === "enter_code" ? {
2985
+ kind: "code",
2986
+ id: open.id
2987
+ } : {
2988
+ kind: "card",
2989
+ interaction: open
2990
+ });
2991
+ }
2992
+ reconcileClarity(detail) {
2993
+ const c = detail.clarity;
2994
+ const asked = c?.status === "asked" && c.question ? c : null;
2995
+ if (!asked) {
2996
+ if (this.pending?.kind === "clarity") this.setPending(null);
2997
+ return;
2998
+ }
2999
+ if (!this.once(`clarity:${asked.question_key}|${asked.question}`)) return;
3000
+ this.emit({
3001
+ type: "clarity",
3002
+ kind: "question",
3003
+ question: asked.question,
3004
+ question_key: asked.question_key,
3005
+ can_approve_anyway: asked.can_approve_anyway
3006
+ });
3007
+ if (!this.opts.json) this.setPending({
3008
+ kind: "clarity",
3009
+ canApprove: asked.can_approve_anyway
3010
+ });
3011
+ }
3012
+ reconcilePlanOffer(detail) {
3013
+ const offer = detail.plan_offer;
3014
+ if (!offer) {
3015
+ this.planOfferShown = false;
3016
+ if (this.pending?.kind === "plan_choice") this.setPending(null);
3017
+ return;
3018
+ }
3019
+ if (!this.once(`plan_offer:${offer.asked_at}`) || this.planOfferShown) return;
3020
+ this.planOfferShown = true;
3021
+ this.emit({
3022
+ type: "clarity",
3023
+ kind: "plan_choice",
3024
+ question: offer.question,
3025
+ question_key: null,
3026
+ can_approve_anyway: false,
3027
+ helper: offer.helper,
3028
+ needs_plan: offer.needs_plan
3029
+ });
3030
+ if (!this.opts.json) this.setPending({ kind: "plan_choice" });
3031
+ }
3032
+ proposeConfirm(tool, item, after) {
3033
+ if (this.opts.json) return;
3034
+ const preview = item.preview ?? {};
3035
+ const lines = [`Proposal: ${String(item.summary ?? tool)}`];
3036
+ if (typeof preview.message === "string") lines.push(` "${indent(preview.message)}"`);
3037
+ lines.push(tool === "steer_task" ? "Confirm this steer? (y/n)" : "Confirm this? (y/n)");
3038
+ this.say(lines.join("\n"));
3039
+ this.setPending({
3040
+ kind: "confirm",
3041
+ tool,
3042
+ after
3043
+ });
3044
+ }
3045
+ async pollSafe() {
3046
+ try {
3047
+ await this.poll();
3048
+ } catch (err) {
3049
+ if (!transient(err) || ++this.failures > MAX_POLL_FAILURES) throw err;
3050
+ this.noteFailure(err);
3051
+ if (this.failures === 1) this.say("Cannot reach Loop right now. Still trying.");
3052
+ }
3053
+ }
3054
+ leave() {
3055
+ this.left = true;
3056
+ this.onLeave();
3057
+ }
3058
+ async handleLine(raw, wasMasked = false) {
3059
+ const line = raw.trim();
3060
+ if (!line) return;
3061
+ const stray = this.swallowNext || wasMasked && this.pending?.kind !== "code";
3062
+ if (this.swallowNext) {
3063
+ this.swallowNext = false;
3064
+ this.maskHold = false;
3065
+ this.setPending(this.pending);
3066
+ }
3067
+ if (stray && !KNOWN_COMMANDS.has(line)) {
3068
+ this.say("That question closed; nothing was sent.");
3069
+ return;
3070
+ }
3071
+ if (this.cancelAsked) {
3072
+ this.cancelAsked = false;
3073
+ if (/^y(es)?$/i.test(line)) await this.cancelRun();
3074
+ else this.say("Not cancelled.");
3075
+ return;
3076
+ }
3077
+ if (line === "/quit") return this.leave();
3078
+ if (line === "/open") {
3079
+ const url = taskUrl(this.webUrl, this.task);
3080
+ this.say(url);
3081
+ (this.opts.open ?? openInBrowser)(url);
3082
+ return;
3083
+ }
3084
+ if (line === "/cancel") {
3085
+ this.cancelAsked = true;
3086
+ this.say("Cancel the current run? (y/n)");
3087
+ return;
3088
+ }
3089
+ const steer = /^\/steer(?:\s+([\s\S]*))?$/.exec(line);
3090
+ if (steer) try {
3091
+ return await this.steer((steer[1] ?? "").trim());
3092
+ } catch (err) {
3093
+ if (err instanceof AuthError) throw err;
3094
+ this.say(`error: ${err instanceof Error ? err.message : String(err)}`);
3095
+ return;
3096
+ }
3097
+ const p = this.pending;
3098
+ try {
3099
+ if (p?.kind === "code") return await this.answerCard(p.id, [], line);
3100
+ if (p?.kind === "clarity") return await this.answerClarity(line);
3101
+ if (p?.kind === "plan_choice") return await this.answerPlanChoice(line);
3102
+ if (p?.kind === "confirm" && /^(y|yes|n|no)$/i.test(line)) {
3103
+ if (/^n/i.test(line)) {
3104
+ this.setPending(null);
3105
+ this.say("Not sent.");
3106
+ return;
3107
+ }
3108
+ this.setPending(null);
3109
+ return await this.send("yes");
3110
+ }
3111
+ if (p?.kind === "card") {
3112
+ if (/^[\d,\s]+$/.test(line)) {
3113
+ const picked = parseSelection(line, p.interaction);
3114
+ if (typeof picked === "string") return this.say(picked);
3115
+ return await this.answerCard(p.interaction.id, picked, null);
3116
+ }
3117
+ }
3118
+ if (line === "/approve") return this.say("Nothing to approve.");
3119
+ if (p?.kind === "confirm") this.setPending(null);
3120
+ await this.send(line);
3121
+ } catch (err) {
3122
+ if (err instanceof AuthError) throw err;
3123
+ this.say(`error: ${err instanceof Error ? err.message : String(err)}`);
3124
+ }
3125
+ }
3126
+ async steer(text) {
3127
+ if (!text) return this.say("Usage: /steer TEXT");
3128
+ if (!this.runLive) return this.say(NOT_LIVE);
3129
+ if (this.pending?.kind === "confirm") this.setPending(null);
3130
+ await this.send(`${STEER_PREFIX}${text}`, true);
3131
+ }
3132
+ async send(body, steered = false) {
3133
+ const res = await this.api.post(`/api/v2/tasks/${this.task.id}/messages`, { body });
3134
+ if (typeof res.data?.id === "number") this.ownIds.add(res.data.id);
3135
+ this.say(describeDelivery(res.delivery_state));
3136
+ if (steered && res.delivery_state === "planning_replied") this.say(STEER_MISROUTED);
3137
+ this.pickupAfter = res.delivery_state === "warm_delivered" ? time(res.data?.created_at) : null;
3138
+ this.nudge();
3139
+ }
3140
+ async answerCard(id, selectionIds, text) {
3141
+ try {
3142
+ const res = await this.api.post(`/api/v2/tasks/${this.task.id}/process-interactions/${id}/responses`, {
3143
+ selection_ids: selectionIds,
3144
+ response_text: text,
3145
+ idempotency_key: randomUUID()
3146
+ });
3147
+ this.setPending(null);
3148
+ this.say(describeDelivery(res.delivery_state, true));
3149
+ this.pickupAfter = res.delivery_state === "warm_delivered" ? 0 : null;
3150
+ this.nudge();
3151
+ } catch (err) {
3152
+ if (!(err instanceof ApiError)) throw err;
3153
+ const body = err.body;
3154
+ if (err.status === 409) {
3155
+ this.setPending(null);
3156
+ this.say("That question was already answered.");
3157
+ } else if (err.status === 422 && body?.error === "interaction_expired") {
3158
+ this.setPending(null);
3159
+ this.say("That question has expired.");
3160
+ } else throw err;
3161
+ }
3162
+ }
3163
+ async answerClarity(line) {
3164
+ const reply = await postClarity(this.api, this.task.id, clarityBody(line));
3165
+ if ("done" in reply) {
3166
+ this.setPending(null);
3167
+ this.say(describeDispatch(reply.done));
3168
+ this.nudge();
3169
+ return;
3170
+ }
3171
+ this.showNextClarity(reply.next);
3172
+ }
3173
+ async answerPlanChoice(line) {
3174
+ const planFirst = /^(1|plan)$/i.test(line) ? true : /^(2|run)$/i.test(line) ? false : null;
3175
+ if (planFirst === null) {
3176
+ this.say("Type 1 to plan first, then run, or 2 to run without a plan.");
3177
+ return;
3178
+ }
3179
+ const done = await postPlanChoice(this.api, this.task.id, planFirst);
3180
+ this.setPending(null);
3181
+ this.say(describeDispatch(done));
3182
+ this.nudge();
3183
+ }
3184
+ showNextClarity(q) {
3185
+ if (q.kind === "plan_choice") {
3186
+ this.planOfferShown = true;
3187
+ this.emit({
3188
+ type: "clarity",
3189
+ kind: "plan_choice",
3190
+ question: q.question,
3191
+ question_key: null,
3192
+ can_approve_anyway: false,
3193
+ helper: q.helper,
3194
+ needs_plan: q.needs_plan ?? null
3195
+ });
3196
+ this.setPending({ kind: "plan_choice" });
3197
+ return;
3198
+ }
3199
+ this.once(`clarity:${q.question_key}|${q.question}`);
3200
+ this.emit({
3201
+ type: "clarity",
3202
+ kind: "question",
3203
+ question: q.question,
3204
+ question_key: q.question_key ?? null,
3205
+ can_approve_anyway: q.can_approve_anyway === true
3206
+ });
3207
+ this.setPending({
3208
+ kind: "clarity",
3209
+ canApprove: q.can_approve_anyway === true
3210
+ });
3211
+ }
3212
+ async cancelRun() {
3213
+ try {
3214
+ await this.api.post(`/api/tasks/${this.task.id}/runs/current/cancel`, {});
3215
+ this.say("Cancel requested.");
3216
+ this.nudge();
3217
+ } catch (err) {
3218
+ if (err instanceof AuthError) throw err;
3219
+ this.say(`error: ${err instanceof Error ? err.message : String(err)}`);
3220
+ }
3221
+ }
3222
+ };
3223
+ function createSleeper() {
3224
+ const timers = /* @__PURE__ */ new Set();
3225
+ return {
3226
+ sleep: (ms) => new Promise((resolve) => {
3227
+ const t = setTimeout(() => {
3228
+ timers.delete(t);
3229
+ resolve();
3230
+ }, ms);
3231
+ timers.add(t);
3232
+ }),
3233
+ clear: () => {
3234
+ for (const t of timers) clearTimeout(t);
3235
+ timers.clear();
3236
+ }
3237
+ };
3238
+ }
3239
+ function createTerminal(input = process.stdin, output = process.stdout) {
3240
+ let muted = false;
3241
+ let closed = false;
3242
+ const sink = new Writable({ write(chunk, encoding, cb) {
3243
+ if (!muted) output.write(chunk, encoding);
3244
+ cb();
3245
+ } });
3246
+ const tty = Boolean(input.isTTY && output.isTTY);
3247
+ const rl = createInterface({
3248
+ input,
3249
+ output: sink,
3250
+ terminal: tty,
3251
+ historySize: 0,
3252
+ prompt: "> "
3253
+ });
3254
+ let onClose = () => {};
3255
+ rl.on("close", () => {
3256
+ closed = true;
3257
+ onClose();
3258
+ });
3259
+ rl.on("SIGINT", () => rl.close());
3260
+ return {
3261
+ print(text) {
3262
+ if (closed || !tty) {
3263
+ output.write(`${text}\n`);
3264
+ return;
3265
+ }
3266
+ clearLine(output, 0);
3267
+ cursorTo(output, 0);
3268
+ output.write(`${text}\n`);
3269
+ rl.prompt(true);
3270
+ },
3271
+ onLine: (handler) => void rl.on("line", handler),
3272
+ onClose: (handler) => {
3273
+ onClose = handler;
3274
+ },
3275
+ mask: (on) => {
3276
+ muted = on;
3277
+ },
3278
+ typing: () => rl.line.length > 0,
3279
+ close: () => rl.close()
3280
+ };
3281
+ }
3282
+ async function runSession(api, task, webUrl, opts) {
3283
+ const sleeper = createSleeper();
3284
+ const sleep = opts.sleep ?? sleeper.sleep;
3285
+ const now = opts.now ?? Date.now;
3286
+ const session = new Session(api, task, webUrl, opts);
3287
+ if (opts.json) {
3288
+ let failures = 0;
3289
+ for (;;) {
3290
+ try {
3291
+ await session.poll();
3292
+ failures = 0;
3293
+ } catch (err) {
3294
+ if (!transient(err) || ++failures > MAX_POLL_FAILURES) throw err;
3295
+ session.noteFailure(err);
3296
+ }
3297
+ if (session.finished) return session.exitCode;
3298
+ await sleep(session.interval());
3299
+ }
3300
+ }
3301
+ const term = opts.term ?? createTerminal();
3302
+ session.attach(term);
3303
+ let leave = () => {};
3304
+ const leaving = new Promise((resolve) => leave = resolve);
3305
+ session.onLeave = leave;
3306
+ term.onClose(() => {
3307
+ session.left = true;
3308
+ leave();
3309
+ });
3310
+ let fatal = null;
3311
+ let chain = Promise.resolve();
3312
+ const serial = (fn) => {
3313
+ chain = chain.then(() => fatal ? void 0 : fn()).catch((err) => {
3314
+ fatal = err;
3315
+ session.leave();
3316
+ });
3317
+ return chain;
3318
+ };
3319
+ term.onLine((line) => {
3320
+ const masked = session.isMasked();
3321
+ serial(() => session.handleLine(line, masked));
3322
+ });
3323
+ term.print(`Session for ${task.key}${task.title ? `: ${task.title}` : ""}`);
3324
+ term.print("Type a message to Loop Assistant. /steer TEXT tells the running agent, /cancel stops the run, /open opens the browser, /quit leaves.");
3325
+ await serial(() => session.pollSafe());
3326
+ let lastPoll = now();
3327
+ let nudge = () => {};
3328
+ session.onNudge = () => nudge();
3329
+ while (!session.left) {
3330
+ const nudged = new Promise((resolve) => nudge = () => resolve(true));
3331
+ const wait = Math.max(0, lastPoll + session.interval() - now());
3332
+ const early = await Promise.race([
3333
+ sleep(wait).then(() => false),
3334
+ leaving.then(() => false),
3335
+ nudged
3336
+ ]);
3337
+ if (session.left) break;
3338
+ if (early && lastPoll + session.interval() > now()) continue;
3339
+ await serial(() => session.pollSafe());
3340
+ lastPoll = now();
3341
+ }
3342
+ await chain;
3343
+ if (!fatal) session.say(`Left the session. The run keeps going. Come back with: loop session ${task.key}`);
3344
+ term.close();
3345
+ sleeper.clear();
3346
+ if (fatal) throw fatal;
3347
+ return 0;
3348
+ }
3349
+ async function resolveTask(api, env, key) {
3350
+ const last = readLastTask(env);
3351
+ if (!key) {
3352
+ if (!last) throw new Error("No task given and none created yet. Pass a task key.");
3353
+ return getTask(api, last.id);
3354
+ }
3355
+ if (last && last.key.toLowerCase() === key.toLowerCase()) return getTask(api, last.id);
3356
+ if (/^[1-9]\d*$/.test(key)) return getTask(api, Number(key));
3357
+ const task = await findTaskByKey(api, key.toUpperCase());
3358
+ if (!task) throw new Error(`Task ${key} not found.`);
3359
+ return task;
3360
+ }
3361
+ async function runStatus(api, creds, env, key) {
3362
+ const task = await resolveTask(api, env, key);
3363
+ const detail = await getTaskDetail(api, task.id);
3364
+ const wait = waitOutput(detail, false);
3365
+ return {
3366
+ id: task.id,
3367
+ key: task.key,
3368
+ status: detail.status ?? task.status,
3369
+ title: detail.title ?? task.title ?? null,
3370
+ project: task.project?.slug ?? null,
3371
+ url: taskUrl(creds.web_url, task),
3372
+ engine: detail.engine ?? null,
3373
+ model: detail.model ?? null,
3374
+ outcome: wait.outcome,
3375
+ pull_requests: wait.pull_requests,
3376
+ question: wait.question
3377
+ };
3378
+ }
3379
+ function formatStatus(out) {
3380
+ const lines = [`${out.key} ${out.status} ${out.title ?? ""}`.trimEnd()];
3381
+ if (out.engine || out.model) lines.push(`Engine: ${[out.engine, out.model].filter(Boolean).join(" / ")}`);
3382
+ if (out.outcome?.failure_cause) lines.push(`Outcome: ${out.outcome.failure_cause}`);
3383
+ if (out.outcome?.next_step) lines.push(`Next: ${out.outcome.next_step}`);
3384
+ if (out.question) lines.push(`Question: ${out.question}`);
3385
+ for (const url of out.pull_requests) lines.push(`Pull request: ${url}`);
3386
+ lines.push(out.url);
3387
+ return lines.join("\n");
3388
+ }
3389
+ const __dirname = dirname(fileURLToPath(import.meta.url));
3390
+ function getVersion() {
3391
+ try {
3392
+ return JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf-8")).version;
3393
+ } catch {
3394
+ return "0.0.0";
3395
+ }
3396
+ }
3397
+ const VERSION = getVersion();
3398
+ const HELP = `Usage: loop <command> [options]
3399
+
3400
+ Hand local work to the Loop fleet.
3401
+
3402
+ Commands:
3403
+ ${commandLines()}
3404
+
3405
+ Login options:
3406
+ --api-url URL Override the API URL
3407
+ --web-url URL Override the web URL
3408
+ --paste Paste the token instead of waiting for the browser
3409
+
3410
+ Create options (handoff, add, task create):
3411
+ --title TEXT Task title (defaults to the first line of the brief)
3412
+ --brief FILE | - Markdown brief from a file or stdin (else the words after the command)
3413
+ --skill SLUG Attach a skill by slug (repeatable)
3414
+ --attach FILE Upload a file to the task (repeatable, 25 MB each, checked before the task is created)
3415
+ --plan Plan first: Loop writes a plan and waits for loop approve
3416
+ --no-plan Go straight to work: Loop does not offer a plan (not with --plan)
3417
+ --process SLUG|NAME Run the task through a Loop process (see the Loop catalogue)
3418
+ --hotfix Mark the task as an urgent production fix (needs permission)
3419
+ --engine NAME Engine: auto, claude-code, codex or opencode (default auto)
3420
+ --model ID Open Models only, by short name or id (implies --engine opencode)
3421
+ -s, --attach-session Open loop session for the new task straight after it is created
3422
+ --type TYPE Task type (default code)
3423
+ --no-run Create without starting a run
3424
+ --include-wip Send uncommitted changes and unpushed commits (handoff, add)
3425
+ --no-wip Never send them (handoff, add)
3426
+ --project SLUG Project slug (task create only)
3427
+ --json Print JSON only
3428
+
3429
+ Checkout, ls, wait options:
3430
+ --repo OWNER/NAME checkout: pick the pull request in this repository
3431
+ --all ls: every repository, not just this one
3432
+ --mine ls: your tasks only (the default; accepted so scripts can say it)
3433
+ --timeout MINUTES wait: give up after this long (exit 5)
3434
+
3435
+ Approve, doctor, completion:
3436
+ approve Exit 1 when no plan is waiting (create with --plan, then loop wait)
3437
+ doctor Exit 1 if any check fails; --json prints the checks as one object
3438
+ completion zsh|bash Load with: eval "$(loop completion zsh)"
3439
+
3440
+ Global options:
3441
+ --env dev Use the dev environment
3442
+ -h, --help Show help
3443
+ -v, --version Show version
3444
+
3445
+ Exit codes:
3446
+ 0 created / ok
3447
+ 1 error (including "Run loop login")
3448
+ 2 needs an answer: a clarity question, an open card, a waiting run or a ready plan (wait, session --json)
3449
+ 3 no Loop project matched this repository
3450
+ 4 the run is stuck, failed or cancelled (wait, session --json)
3451
+ 5 loop wait timed out
3452
+
3453
+ A newer version is announced on stderr at most once a day, in a terminal only.
3454
+ Set LOOP_NO_UPDATE_CHECK=1 to turn that off.
3455
+
3456
+ Credentials: $XDG_CONFIG_HOME/loop or ~/.config/loop (credentials.json, mode 600).
3457
+ `;
3458
+ function fail(message, json) {
3459
+ if (json) console.log(JSON.stringify({ error: message }));
3460
+ else console.error(`error: ${message}`);
3461
+ return 1;
3462
+ }
3463
+ function envFrom(value) {
3464
+ if (value === void 0 || value === "prod" || value === "production") return "prod";
3465
+ if (value === "dev") return "dev";
3466
+ throw new Error(`Unknown --env "${value}". Use dev.`);
3467
+ }
3468
+ const hasTerminal = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
3469
+ async function main(argv) {
3470
+ const jsonRequested = argv.includes("--json");
3471
+ let parsed;
3472
+ try {
3473
+ parsed = parseArgs({
3474
+ args: argv,
3475
+ options: OPTIONS,
3476
+ allowPositionals: true
3477
+ });
3478
+ } catch (err) {
3479
+ return fail(err.message, jsonRequested);
3480
+ }
3481
+ const { values, positionals } = parsed;
3482
+ const json = values.json ?? false;
3483
+ setGitInteractive(!json && hasTerminal());
3484
+ if (values.version) {
3485
+ console.log(VERSION);
3486
+ return 0;
3487
+ }
3488
+ const command = positionals[0];
3489
+ if (values.help || !command) {
3490
+ console.log(HELP);
3491
+ return 0;
3492
+ }
3493
+ if (!COMMANDS.some((c) => c.name === command)) return unknownCommand(positionals, json);
3494
+ let env;
3495
+ try {
3496
+ env = envFrom(values.env);
3497
+ } catch (err) {
3498
+ return fail(err.message, json);
3499
+ }
3500
+ if (command === "login") return runLogin({
3501
+ env,
3502
+ apiUrl: values["api-url"],
3503
+ webUrl: values["web-url"],
3504
+ paste: values.paste
3505
+ });
3506
+ if (command === "completion") {
3507
+ const shell = positionals[1];
3508
+ if (!SHELLS.includes(shell)) return fail(`Usage: loop completion ${SHELLS.join("|")}`, json);
3509
+ process.stdout.write(completionScript(shell));
3510
+ return 0;
3511
+ }
3512
+ const creds = readCredentials(env);
3513
+ if (command === "doctor") {
3514
+ const report = await runDoctor({
3515
+ env,
3516
+ creds,
3517
+ version: VERSION
3518
+ });
3519
+ if (json) console.log(JSON.stringify(report));
3520
+ else {
3521
+ Ie("loop doctor");
3522
+ for (const c of report.checks) {
3523
+ const log = {
3524
+ ok: M.success,
3525
+ warn: M.warn,
3526
+ fail: M.error
3527
+ }[c.status];
3528
+ log(`${c.name}: ${c.message}`);
3529
+ }
3530
+ const failed = report.checks.filter((c) => c.status === "fail").length;
3531
+ Se(failed ? `${failed} problem${failed === 1 ? "" : "s"} to fix` : "Ready to hand off");
3532
+ }
3533
+ return report.ok ? 0 : 1;
3534
+ }
3535
+ if (!creds) return fail("Not logged in. Run loop login", json);
3536
+ const api = createClient(creds.api_url, creds.token);
3537
+ const isTaskCreate = command === "task" && positionals[1] === "create";
3538
+ const createOptions = {
3539
+ env,
3540
+ title: values.title,
3541
+ brief: values.brief,
3542
+ words: positionals.slice(isTaskCreate ? 2 : 1),
3543
+ skills: values.skill ?? [],
3544
+ attach: values.attach ?? [],
3545
+ plan: values.plan,
3546
+ noPlan: values["no-plan"],
3547
+ process: values.process,
3548
+ hotfix: values.hotfix,
3549
+ engine: values.engine,
3550
+ noRun: command === "add" || (values["no-run"] ?? false),
3551
+ includeWip: values["include-wip"],
3552
+ noWip: values["no-wip"],
3553
+ type: values.type ?? "code",
3554
+ json,
3555
+ project: values.project,
3556
+ cliVersion: VERSION
3557
+ };
3558
+ try {
3559
+ if (command === "handoff" || command === "add" || isTaskCreate) {
3560
+ const attach = values["attach-session"] ?? false;
3561
+ if (attach && json) return fail("--attach-session cannot be used with --json. Run loop session --json KEY.", json);
3562
+ if (attach && !hasTerminal()) return fail("--attach-session needs a terminal (stdin and stdout). Create without -s, then run loop session --json KEY.", json);
3563
+ const { engine, model } = await resolveEngineAndModel(api, values.engine, values.model);
3564
+ createOptions.engine = engine;
3565
+ createOptions.model = model;
3566
+ if (!json) Ie(isTaskCreate ? "loop task create" : `loop ${command}`);
3567
+ let result = isTaskCreate ? await runCreate(api, creds, createOptions) : await runHandoff(api, creds, createOptions);
3568
+ let answered = false;
3569
+ if (!json && hasTerminal() && result.output.clarity) {
3570
+ const before = result;
3571
+ result = await answerClarityInPlace(api, result, askClarityInTerminal);
3572
+ answered = result !== before && !result.output.clarity;
3573
+ }
3574
+ if (json) console.log(JSON.stringify(result.output));
3575
+ else {
3576
+ const { key, url, base_branch, base_source, base_warning, engine: usedEngine, model: usedModel, clarity, attachments, wip, wip_branch, wip_sha, wip_excluded, wip_reason } = result.output;
3577
+ M.success(command === "add" ? `Added ${key} to the Backlog` : `Created ${key}`);
3578
+ M.info(`Engine: ${[usedEngine, usedModel].filter(Boolean).join(" / ") || "auto"}`);
3579
+ if (base_source) M.info(`Base branch: ${describeBase({
3580
+ branch: base_branch ?? null,
3581
+ source: base_source
3582
+ })}`);
3583
+ if (base_warning) M.warn(base_warning);
3584
+ if (attachments?.length) M.info(`Uploaded ${attachments.length} file(s): ${attachments.map((a) => a.filename).join(", ")}`);
3585
+ if (wip === "sent") {
3586
+ M.info(`Sent your local work as ${wip_branch} (${wip_sha?.slice(0, 7)}) on origin.`);
3587
+ if (wip_excluded?.length) M.warn(`Left out (look like secrets):\n${wip_excluded.join("\n")}`);
3588
+ } else if (wip === "not_sent") M.warn(`Local work was not sent. ${wip_reason}`);
3589
+ if (wip !== "not_sent" && wip_reason) M.warn(wip_reason);
3590
+ if (answered) {
3591
+ const dispatch = result.output;
3592
+ if (dispatch.dispatch_error) M.error(describeDispatch(dispatch));
3593
+ else M.info(describeDispatch(dispatch));
3594
+ }
3595
+ if (clarity && typeof clarity === "object" && "question" in clarity) M.warn(clarity.kind === "plan_choice" ? `Loop asks whether to plan first before it runs.\nChoose at ${url}, or create with --plan or --no-plan to answer it up front.` : `Loop has a question before it runs:\n${String(clarity.question)}\nAnswer it at ${url}`);
3596
+ if (!attach) M.info(`${createOptions.noRun ? "Talk to it" : "Follow it"}: loop session ${key}`);
3597
+ Se(url);
3598
+ }
3599
+ if (attach && result.exitCode !== 1) {
3600
+ const { id, key } = result.output;
3601
+ return runSession(api, {
3602
+ id,
3603
+ key,
3604
+ title: createOptions.title
3605
+ }, creds.web_url, { json: false });
3606
+ }
3607
+ return result.exitCode;
3608
+ }
3609
+ if (command === "approve") {
3610
+ const out = await approvePlan(api, await resolveTask(api, env, positionals[1]));
3611
+ if (json) console.log(JSON.stringify(out));
3612
+ else {
3613
+ M.success(`Approved the plan for ${out.key}`);
3614
+ if (out.dispatch_error) M.warn(`The run did not start: ${out.dispatch_error}`);
3615
+ else if (out.queued) M.info("The run is queued for a machine.");
3616
+ }
3617
+ return out.dispatch_error ? 1 : 0;
3618
+ }
3619
+ if (command === "models") {
3620
+ const out = await runModels(api);
3621
+ if (json) console.log(JSON.stringify(out));
3622
+ else for (const m of out.models) console.log(`${m.short_name} ${m.label} (${m.id})`);
3623
+ return 0;
3624
+ }
3625
+ if (command === "session") {
3626
+ if (!json && !hasTerminal()) return fail("loop session needs a terminal (stdin and stdout). Use loop session --json KEY.", json);
3627
+ return runSession(api, await resolveTask(api, env, positionals[1]), creds.web_url, { json });
3628
+ }
3629
+ if (command === "status") {
3630
+ const out = await runStatus(api, creds, env, positionals[1]);
3631
+ if (json) console.log(JSON.stringify(out));
3632
+ else console.log(formatStatus(out));
3633
+ return 0;
3634
+ }
3635
+ if (command === "checkout") {
3636
+ const out = await runCheckout(await getTaskDetail(api, (await resolveTask(api, env, positionals[1])).id), {
3637
+ repo: values.repo,
3638
+ interactive: !json && Boolean(process.stdin.isTTY && process.stdout.isTTY)
3639
+ });
3640
+ if (json) console.log(JSON.stringify(out));
3641
+ else {
3642
+ M.success(`Checked out ${out.branch} (${out.sha.slice(0, 7)}) for ${out.key}`);
3643
+ if (!out.up_to_date) M.warn(`Your local ${out.branch} has commits that are not on the pull request, so it was not fast-forwarded.`);
3644
+ }
3645
+ return 0;
3646
+ }
3647
+ if (command === "ls") {
3648
+ const { rows, truncated } = await runLs(api, { all: values.all ?? false });
3649
+ if (json) console.log(JSON.stringify({
3650
+ count: rows.length,
3651
+ truncated,
3652
+ tasks: rows
3653
+ }));
3654
+ else {
3655
+ console.log(rows.length ? formatTable(rows) : "No open tasks.");
3656
+ if (truncated) console.error(`warning: Loop returned its limit of 200 tasks, so older open tasks may be missing.`);
3657
+ }
3658
+ return 0;
3659
+ }
3660
+ if (command === "wait") {
3661
+ const minutes = values.timeout === void 0 ? void 0 : Number(values.timeout);
3662
+ if (minutes !== void 0 && !(minutes > 0)) return fail("--timeout takes a number of minutes greater than 0.", json);
3663
+ const task = await resolveTask(api, env, positionals[1]);
3664
+ let last = "";
3665
+ const result = await runWait(api, task.id, {
3666
+ key: task.key,
3667
+ timeoutMs: minutes === void 0 ? void 0 : minutes * 6e4,
3668
+ onPoll: (t) => {
3669
+ if (!json && t.status !== last) console.error(`${t.key}: ${t.status}`);
3670
+ last = t.status;
3671
+ }
3672
+ });
3673
+ if (json) console.log(JSON.stringify(result.output));
3674
+ else {
3675
+ const o = result.output;
3676
+ console.log(`${result.task?.key ?? task.key} ${result.task?.status ?? "unknown"}${result.exitCode === 5 ? " (timed out)" : ""}`);
3677
+ for (const url of o.pull_requests ?? []) console.log(url);
3678
+ if (o.question) console.log(`Question: ${o.question}`);
3679
+ }
3680
+ return result.exitCode;
3681
+ }
3682
+ if (command === "open") {
3683
+ const task = await resolveTask(api, env, positionals[1]);
3684
+ const url = taskUrl(creds.web_url, task);
3685
+ console.log(json ? JSON.stringify({ url }) : url);
3686
+ if (!json && hasTerminal()) openInBrowser(url);
3687
+ return 0;
3688
+ }
3689
+ } catch (err) {
3690
+ if (err instanceof AuthError) return fail("Run loop login", json);
3691
+ if (err instanceof ProjectUnresolved) {
3692
+ if (json) console.log(JSON.stringify({ error: err.message }));
3693
+ else console.error(`error: ${err.message}`);
3694
+ return 3;
3695
+ }
3696
+ if (err instanceof TaskCreatedError) {
3697
+ if (json) console.log(JSON.stringify({
3698
+ error: err.message,
3699
+ ...err.task
3700
+ }));
3701
+ else console.error(`error: ${err.message}`);
3702
+ return 1;
3703
+ }
3704
+ if (err instanceof ApiError || err instanceof GitError || err instanceof Error) return fail(err.message, json);
3705
+ return fail(String(err), json);
3706
+ }
3707
+ return unknownCommand(positionals, json);
3708
+ }
3709
+ function unknownCommand(positionals, json) {
3710
+ const text = `Unknown command: ${positionals.slice(0, 2).join(" ")}`;
3711
+ if (json) return fail(text, true);
3712
+ console.error(`${text}\n`);
3713
+ console.error(HELP);
3714
+ return 1;
3715
+ }
3716
+ const argv = process.argv.slice(2);
3717
+ const update = updateCheckWanted(argv) ? startUpdateCheck(VERSION) : null;
3718
+ process.exitCode = await main(argv);
3719
+ if (update) {
3720
+ const latest = process.exitCode ? (update.cancel(), null) : await update.notice();
3721
+ if (latest) console.error(`loop ${latest} is available (you have ${VERSION}). Run: npm install -g ${PACKAGE}`);
3722
+ }
3723
+ export {};