@cloop/runner 0.3.68 → 0.3.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/{box-YFGM56QY.js → box-N5NOCXH3.js} +194 -522
  2. package/dist/{chunk-7LPSTDZE.js → chunk-4JTIWZHB.js} +1 -1
  3. package/dist/{chunk-TCNIRZLU.js → chunk-CLOYOD2X.js} +10 -6
  4. package/dist/{chunk-6LYMSWSB.js → chunk-DN6TQALA.js} +265 -1961
  5. package/dist/{chunk-HWNRORIZ.js → chunk-EE7PMIGC.js} +1 -1
  6. package/dist/chunk-EEG5JOZ7.js +939 -0
  7. package/dist/chunk-GAEZIKCK.js +626 -0
  8. package/dist/chunk-HIBAH65V.js +1178 -0
  9. package/dist/chunk-JDGGRIS3.js +43 -0
  10. package/dist/{chunk-7ZL3Z3IO.js → chunk-JI5FWLDU.js} +6 -6
  11. package/dist/chunk-JJWSPBM4.js +40 -0
  12. package/dist/{chunk-L7D3ANPW.js → chunk-KUGUMEYC.js} +4 -2
  13. package/dist/{chunk-BVPS6DCH.js → chunk-MUFILIJS.js} +574 -1673
  14. package/dist/chunk-PQURJJOD.js +459 -0
  15. package/dist/{chunk-34VZ5LZI.js → chunk-UX4D6FY7.js} +3 -83
  16. package/dist/chunk-VB4V65JR.js +85 -0
  17. package/dist/{connect-D2SXLADA.js → connect-5D5CIC4V.js} +11 -47
  18. package/dist/disconnect-CQXE6ZNH.js +163 -0
  19. package/dist/existing-runner-4QQYKV7I.js +15 -0
  20. package/dist/index.js +14 -14
  21. package/dist/{login-VNDFCJD4.js → login-KHJQD25C.js} +3 -2
  22. package/dist/{mcp-server-XPHCDBFR.js → mcp-server-4D476KMH.js} +10 -10
  23. package/dist/{runner-A3HFZ727.js → runner-6GIMXVD5.js} +4 -3
  24. package/dist/{runs-DOFU45TW.js → runs-TWUGWGNU.js} +4 -2
  25. package/dist/{statusline-VA2DSWVT.js → statusline-3TZ26LKY.js} +1 -1
  26. package/dist/{takeover-U2EHJ5GW.js → takeover-5QSP6YAG.js} +6 -4
  27. package/dist/{use-7D5GQFGB.js → use-HY5BO4BW.js} +20 -13
  28. package/package.json +1 -1
  29. package/dist/disconnect-7SJKPYIN.js +0 -30
  30. package/dist/existing-runner-XT3HLIPM.js +0 -20
@@ -0,0 +1,626 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CONFIG_DIR,
4
+ PRODUCTION_ORIGIN,
5
+ STAGING_ORIGIN,
6
+ getOrigin
7
+ } from "./chunk-D5UZW42X.js";
8
+
9
+ // src/environment.ts
10
+ import { homedir } from "os";
11
+ import { join } from "path";
12
+ var ENVIRONMENTS = {
13
+ production: {
14
+ origin: PRODUCTION_ORIGIN,
15
+ dir: (home) => join(home, CONFIG_DIR),
16
+ suffix: "",
17
+ flag: "",
18
+ mcpUrl: "https://app.mycloop.com/api/mcp/mcp",
19
+ mcpName: "cloop"
20
+ },
21
+ staging: {
22
+ origin: STAGING_ORIGIN,
23
+ dir: (home) => join(home, CONFIG_DIR, "staging"),
24
+ suffix: "staging",
25
+ flag: "--staging",
26
+ mcpUrl: "https://mcp-staging.mycloop.com/mcp",
27
+ mcpName: "cloop-staging"
28
+ }
29
+ };
30
+ function environmentOf(origin) {
31
+ return origin.replace(/\/+$/, "") === ENVIRONMENTS.staging.origin ? "staging" : "production";
32
+ }
33
+ function runnerEnvironment() {
34
+ return environmentOf(getOrigin());
35
+ }
36
+ function runnerDir(env = runnerEnvironment(), home = homedir()) {
37
+ return ENVIRONMENTS[env].dir(home);
38
+ }
39
+ function runnerPath(env, override, inDir) {
40
+ const own = runnerEnvironment();
41
+ return override && (env ?? own) === own ? override : inDir(runnerDir(env ?? own));
42
+ }
43
+ function cloopCommand(env, args) {
44
+ return ["cloop", args, ENVIRONMENTS[env].flag].filter(Boolean).join(" ");
45
+ }
46
+ var KIND = {
47
+ workstation: { name: "box", task: "Cloop Box" },
48
+ local: { name: "runner", task: "Cloop Runner" }
49
+ };
50
+ function serviceIdentity(kind, env) {
51
+ const { suffix } = ENVIRONMENTS[env];
52
+ const { name, task } = KIND[kind];
53
+ const file = ["cloop", name, suffix].filter(Boolean).join("-");
54
+ return {
55
+ label: ["com.cloop", name, suffix].filter(Boolean).join("."),
56
+ unit: `${file}.service`,
57
+ task: suffix ? `${task} ${suffix[0]?.toUpperCase()}${suffix.slice(1)}` : task,
58
+ file
59
+ };
60
+ }
61
+
62
+ // ../clo0p-app/contracts/run-result.ts
63
+ var WIZARD_STEPS_MAX = 6;
64
+ var WIZARD_FOR = "steps only the user can do by hand: a sign-in, an app permission, a key from a dashboard, or a change in a dashboard or console you cannot make yourself";
65
+ var CHECK_BACK_MIN_MINUTES = 5;
66
+ var CHECK_BACK_MAX_MINUTES = 3 * 24 * 60;
67
+ var CHECK_BACK_WHY_MAX = 300;
68
+ var UNDERWAY_MAX = 3;
69
+ var GITHUB_WORK = /^https:\/\/(?:www\.)?github\.com\/[\w.-]+\/[\w.-]+\/(?:pull|issues)\/[1-9]\d*(?:[/?#]|$)/i;
70
+ var RUN_IMAGES_MAX = 6;
71
+ var RUN_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
72
+ var RUN_FILES_MAX = 6;
73
+ var RUN_FILE_MAX_BYTES = 20 * 1024 * 1024;
74
+ var RUN_MEDIA_CLASSES = {
75
+ image: { max: RUN_IMAGES_MAX, maxBytes: RUN_IMAGE_MAX_BYTES },
76
+ file: { max: RUN_FILES_MAX, maxBytes: RUN_FILE_MAX_BYTES }
77
+ };
78
+ var startsWith = (bytes, at, want) => want.every((b, j) => bytes[at + j] === b);
79
+ var ascii = (word) => [...word].map((c) => c.charCodeAt(0));
80
+ var PROOFS = {
81
+ png: (bytes) => startsWith(bytes, 0, [137, 80, 78, 71, 13, 10, 26, 10]),
82
+ jpg: (bytes) => startsWith(bytes, 0, [255, 216, 255]),
83
+ webp: (bytes) => startsWith(bytes, 0, ascii("RIFF")) && startsWith(bytes, 8, ascii("WEBP")),
84
+ pdf: (bytes) => startsWith(bytes, 0, ascii("%PDF-")),
85
+ // A docx, an xlsx and a pptx are each a zip: the bytes say zip, the name says which.
86
+ zip: (bytes) => startsWith(bytes, 0, [80, 75, 3, 4]),
87
+ text: (bytes) => {
88
+ if (bytes.includes(0)) return false;
89
+ try {
90
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
91
+ return true;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+ };
97
+ var RUN_MEDIA_TYPES = {
98
+ png: { mime: "image/png", class: "image", proof: "png" },
99
+ jpg: { mime: "image/jpeg", class: "image", proof: "jpg" },
100
+ webp: { mime: "image/webp", class: "image", proof: "webp" },
101
+ pdf: { mime: "application/pdf", class: "file", proof: "pdf" },
102
+ docx: { mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", class: "file", proof: "zip" },
103
+ xlsx: { mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", class: "file", proof: "zip" },
104
+ pptx: { mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation", class: "file", proof: "zip" },
105
+ csv: { mime: "text/csv", class: "file", proof: "text" },
106
+ txt: { mime: "text/plain", class: "file", proof: "text" },
107
+ md: { mime: "text/markdown", class: "file", proof: "text" }
108
+ };
109
+ var EXTS = Object.keys(RUN_MEDIA_TYPES);
110
+ function imageExt(bytes) {
111
+ return EXTS.find((ext) => RUN_MEDIA_TYPES[ext].class === "image" && PROOFS[RUN_MEDIA_TYPES[ext].proof](bytes)) ?? null;
112
+ }
113
+ function mediaExt(bytes, name) {
114
+ const image = imageExt(bytes);
115
+ if (image) return image;
116
+ const dot = name?.lastIndexOf(".") ?? -1;
117
+ const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
118
+ if (!Object.hasOwn(RUN_MEDIA_TYPES, ext)) return null;
119
+ const type = RUN_MEDIA_TYPES[ext];
120
+ return type.class === "file" && PROOFS[type.proof](bytes) ? ext : null;
121
+ }
122
+ var RUN_MEDIA_KEY = runMediaPattern("[0-9a-f-]{36}\\/[0-9a-f-]{36}\\/");
123
+ var RUN_MEDIA_FILE = runMediaPattern("");
124
+ var RUN_PREVIEWS_MAX = 3;
125
+ var PREVIEW_HOURS = 24;
126
+ var BOX_PREVIEW_HOURS = 6;
127
+ var PREVIEW_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
128
+ function isPort(v) {
129
+ return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 65535;
130
+ }
131
+ function isPreviewPath(v) {
132
+ return typeof v === "string" && v.length <= 400 && v.startsWith("/") && !v.startsWith("//") && !/[\s\\]/.test(v);
133
+ }
134
+ function fileTypes() {
135
+ const files = EXTS.filter((ext) => RUN_MEDIA_TYPES[ext].class === "file");
136
+ return `${files.slice(0, -1).join(", ")} or ${files.at(-1)}`;
137
+ }
138
+ function runMediaPattern(folder) {
139
+ return new RegExp(`^${folder}[0-9a-f-]{36}\\.(${Object.keys(RUN_MEDIA_TYPES).join("|")})$`);
140
+ }
141
+ var RESULT_INSTRUCTION = [
142
+ "When you finish, end your final message with a fenced block tagged cloop-result containing JSON, for example:",
143
+ "```cloop-result",
144
+ '{"summary": "Your conclusion or what you did, in one or two sentences.", "outputs": [{"kind": "pr", "title": "fix: the thing", "url": "https://github.com/org/repo/pull/1"}], "checks": [{"name": "Tests", "outcome": "passed"}]}',
145
+ "```",
146
+ "An output kind is one of: pr or link (title, url), draft (title, body, optional to, optional url), doc (title, optional url or body), wizard (title, steps). A check outcome is passed, failed or skipped.",
147
+ "A draft's body is the message itself, as the recipient will read it; if you saved it somewhere (a Gmail draft), put that link in url, never in body. A doc's body is the whole page in GitHub Markdown: headings, lists, bold and tables all show; a table suits one row per item. Give every product, page or source you mention as a full https link.",
148
+ `A wizard is for ${WIZARD_FOR}. When the work needs such a step, return a wizard for it, not only words. A wizard has 1 to ${WIZARD_STEPS_MAX} steps in order, each {"title", "body" in Markdown, optional https "url"}. Never ask the user to paste a password, key or other secret anywhere. The user sees a wizard as a walkthrough: in your own words, call it a walkthrough, never a wizard.`,
149
+ "List as outputs only what this run made. A PR or page you only read, checked or cited goes in the summary, never in outputs.",
150
+ "When you push a branch and open no PR, list the branch as a link output with its GitHub address, https://github.com/org/repo/tree/<branch>: Cloop asks the owner whether to open one.",
151
+ `When an open GitHub PR or issue already does this Task and you found it, not made it, add "underway": [{"title": "feat: the thing", "url": "https://github.com/org/repo/pull/1"}] to the block, at most ${UNDERWAY_MAX}: Cloop links each one to the Task. Never list it in outputs.`,
152
+ 'Your final message is your reply on the Task, and the owner reads it as a chat message. Keep it short: one to three plain sentences that say what you did or what you concluded, and what you need from the owner, if anything. Write it as a person writes in a chat: no headings, no tables, no long lists. When the answer needs more, such as options compared, a plan, research or a table, put that in a doc output, and say in the reply what you recommend and that the detail is on the page. The summary is that same short reply. A doc holds the method and caveats and does not repeat the reply. Title a doc for what it says, never "Full answer" or "Summary".'
153
+ ].join("\n");
154
+ var MACHINE_RESULT_INSTRUCTION = [
155
+ RESULT_INSTRUCTION,
156
+ `To show the owner a picture, such as a screenshot of a UI change or a result a picture explains better than words, save it as a PNG, JPEG or WebP file outside the repository (for example in /tmp) and list it as an output: {"kind": "image", "title": "The new sign-in page", "path": "/tmp/sign-in.png"}, with the file's absolute path. Cloop uploads the file and shows it on the run. At most ${RUN_IMAGES_MAX} images, each under ${RUN_IMAGE_MAX_BYTES / (1024 * 1024)} MB. On a Cloop Box, take a picture of a website with the cloop \`browser\` tool: action screenshot shows you the page, and with a title Cloop also attaches the picture to this run and shows it to the owner. You need not list it in your outputs. Use the Playwright browser tool only for a page on localhost, and list its file by path.`,
157
+ `To hand the owner a file Cloop cannot show, such as a spreadsheet, a deck, a Word document, a PDF or a CSV, list it as an output: {"kind": "file", "title": "Converge model", "path": "/abs/path/Converge_Model.xlsx"}, with the file's absolute path. Cloop uploads it and the owner downloads it from the Task. Never give the owner a path on this machine as the deliverable: they cannot open it. A file is one of ${fileTypes()}, named with its type's extension. At most ${RUN_FILES_MAX} files, each under ${RUN_FILE_MAX_BYTES / (1024 * 1024)} MB. A page you write (a report, notes, research) is a doc output with the whole text in its body, never a Markdown file: Cloop shows the page and the owner can download it there.`,
158
+ `To let the owner open a web app or page you are running on this machine, such as a dev server, leave the server running after your turn ends: start it in the background, detached from your shell (for example \`nohup npm run dev -- --port 5173 > /tmp/dev.log 2>&1 &\`), and check it answers on its port. Then list it as an output: {"kind": "preview", "title": "The new sign-in page", "port": 5173, "path": "/sign-in"}, with the port it listens on and an optional path to open first. Cloop gives the owner a private link to it for ${PREVIEW_HOURS} hours while this machine is on, or ${BOX_PREVIEW_HOURS} hours on a Cloop Box, where a live preview keeps the box awake: say how long when you give the link. At most ${RUN_PREVIEWS_MAX} previews a run.`,
159
+ `When you started something that keeps running after this turn (a build, a deploy, a long job) or you wait on something outside, do not wait in the turn: add "check_back": {"in_minutes": 120, "why": "Read the training log and report the score."} to the block. Cloop sends you a message in this conversation then, with your why, and you carry on from there. Give ${CHECK_BACK_MIN_MINUTES} to ${CHECK_BACK_MAX_MINUTES} minutes. Leave it out when the work is done.`
160
+ ].join("\n");
161
+ var SUMMARY_MAX = 4e3;
162
+ var ASKS_MAX = 1e3;
163
+ var DOC_BODY_MAX = 8e3;
164
+ var ITEMS_MAX = 10;
165
+ var BLOCK = /```cloop-result\s*\n([\s\S]*?)```/g;
166
+ var text = (v, max) => typeof v === "string" && v.length <= max;
167
+ var optionalText = (v, max) => v === void 0 || text(v, max);
168
+ function isHttps(v) {
169
+ try {
170
+ return typeof v === "string" && new URL(v).protocol === "https:";
171
+ } catch {
172
+ return false;
173
+ }
174
+ }
175
+ var GITHUB_PR = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/(\d+)$/;
176
+ function addressOutput(value) {
177
+ const url = value.trim();
178
+ if (!isHttps(url)) return null;
179
+ const pr = url.match(GITHUB_PR);
180
+ if (pr) return { kind: "pr", title: `Pull request #${pr[1]}`, url };
181
+ const { host, pathname } = new URL(url);
182
+ return { kind: "link", title: `${host}${pathname === "/" ? "" : pathname}`.slice(0, 120), url };
183
+ }
184
+ function readOutput(o) {
185
+ if (typeof o === "string") return addressOutput(o);
186
+ if (!o || typeof o !== "object") return null;
187
+ const out = o;
188
+ if (!text(out.title, 120)) return null;
189
+ const title = out.title;
190
+ switch (out.kind) {
191
+ case "pr":
192
+ case "link":
193
+ return isHttps(out.url) ? out.kind === "pr" ? { kind: "pr", title, url: out.url } : { kind: "link", title, url: out.url } : null;
194
+ case "draft":
195
+ return text(out.body, 4e3) && optionalText(out.to, 200) && (out.url === void 0 || isHttps(out.url)) ? {
196
+ kind: "draft",
197
+ title,
198
+ body: out.body,
199
+ ...out.to !== void 0 ? { to: out.to } : {},
200
+ ...out.url !== void 0 ? { url: out.url } : {}
201
+ } : null;
202
+ case "doc": {
203
+ const body = typeof out.body === "string" && out.body.length > DOC_BODY_MAX ? `${out.body.slice(0, DOC_BODY_MAX - 1)}\u2026` : out.body;
204
+ if (!optionalText(body, DOC_BODY_MAX) || out.url !== void 0 && !isHttps(out.url)) return null;
205
+ if (out.url === void 0 && !body?.trim()) return null;
206
+ return {
207
+ kind: "doc",
208
+ title,
209
+ ...out.url !== void 0 ? { url: out.url } : {},
210
+ ...body !== void 0 ? { body } : {}
211
+ };
212
+ }
213
+ case "image": {
214
+ const media = typeof out.media === "string" && RUN_MEDIA_KEY.test(out.media) ? out.media : void 0;
215
+ if (out.path === void 0) return media ? { kind: "image", title, media } : null;
216
+ if (!text(out.path, 400)) return null;
217
+ return { kind: "image", title, path: out.path, ...media ? { media } : {} };
218
+ }
219
+ // Only the runner writes a file's `media` or `unsent`, after this read: a run that wrote its own claims nothing.
220
+ case "file":
221
+ return text(out.path, 400) ? { kind: "file", title, path: out.path } : null;
222
+ case "preview":
223
+ if (!isPort(out.port) || out.path !== void 0 && !isPreviewPath(out.path)) return null;
224
+ return {
225
+ kind: "preview",
226
+ title,
227
+ port: out.port,
228
+ ...out.path !== void 0 ? { path: out.path } : {},
229
+ ...typeof out.preview === "string" && PREVIEW_ID.test(out.preview) ? { preview: out.preview } : {}
230
+ };
231
+ case "wizard":
232
+ return Array.isArray(out.steps) && out.steps.length ? { kind: "wizard", title, steps: out.steps } : null;
233
+ default:
234
+ return null;
235
+ }
236
+ }
237
+ function readCheckBack(v) {
238
+ if (!v || typeof v !== "object") return null;
239
+ const { in_minutes: minutes, why } = v;
240
+ if (typeof minutes !== "number" || !Number.isFinite(minutes) || typeof why !== "string" || !why.trim()) return null;
241
+ return {
242
+ in_minutes: Math.min(CHECK_BACK_MAX_MINUTES, Math.max(CHECK_BACK_MIN_MINUTES, Math.round(minutes))),
243
+ why: why.trim().slice(0, CHECK_BACK_WHY_MAX)
244
+ };
245
+ }
246
+ function readUnderway(v) {
247
+ return (Array.isArray(v) ? v : []).flatMap((u) => {
248
+ const { title, url } = u && typeof u === "object" ? u : {};
249
+ return text(title, 120) && typeof url === "string" && GITHUB_WORK.test(url) ? [{ title, url }] : [];
250
+ }).slice(0, UNDERWAY_MAX);
251
+ }
252
+ function readCheck(c) {
253
+ if (!c || typeof c !== "object") return null;
254
+ const check = c;
255
+ if (!text(check.name, 80) || !["passed", "failed", "skipped"].includes(check.outcome)) return null;
256
+ if (!optionalText(check.detail, 200)) return null;
257
+ return {
258
+ name: check.name,
259
+ outcome: check.outcome,
260
+ ...check.detail !== void 0 ? { detail: check.detail } : {}
261
+ };
262
+ }
263
+ function readRunResult(message) {
264
+ const none = { dropped: { outputs: 0, checks: 0 } };
265
+ const block = [...(message ?? "").matchAll(BLOCK)].at(-1)?.[1];
266
+ if (!block) return none;
267
+ let value;
268
+ try {
269
+ value = JSON.parse(block);
270
+ } catch {
271
+ return none;
272
+ }
273
+ const summary = typeof value?.summary === "string" ? value.summary.trim() : "";
274
+ if (!summary) return none;
275
+ const list = (v) => Array.isArray(v) ? v : [];
276
+ const asks = typeof value?.asks === "string" ? value.asks.trim() : "";
277
+ const outputs = list(value?.outputs).flatMap((o) => readOutput(o) ?? []);
278
+ const checks = list(value?.checks).flatMap((c) => readCheck(c) ?? []);
279
+ const checkBack = readCheckBack(value?.check_back);
280
+ const underway = readUnderway(value?.underway);
281
+ return {
282
+ result: {
283
+ summary: summary.length > SUMMARY_MAX ? `${summary.slice(0, SUMMARY_MAX - 1)}\u2026` : summary,
284
+ outputs: outputs.slice(0, ITEMS_MAX),
285
+ checks: checks.slice(0, ITEMS_MAX),
286
+ ...value?.nothing_new === true ? { nothing_new: true } : {},
287
+ ...asks ? { asks: asks.length > ASKS_MAX ? `${asks.slice(0, ASKS_MAX - 1)}\u2026` : asks } : {},
288
+ ...checkBack ? { check_back: checkBack } : {},
289
+ ...underway.length ? { underway } : {}
290
+ },
291
+ dropped: { outputs: list(value?.outputs).length - outputs.length, checks: list(value?.checks).length - checks.length }
292
+ };
293
+ }
294
+ function hasResultBlock(message) {
295
+ return /```cloop-result\s*\n/.test(message ?? "");
296
+ }
297
+ function resultText(final, earlier) {
298
+ return (hasResultBlock(final) ? final : hasResultBlock(earlier) ? earlier : final) ?? void 0;
299
+ }
300
+
301
+ // src/run-result.ts
302
+ var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
303
+ var prNumber = (url) => Number(url.slice(url.lastIndexOf("/") + 1));
304
+ function prUrlIn(text2) {
305
+ const urls = text2?.match(PR_URL) ?? [];
306
+ return urls.reduce(
307
+ (newest, url) => newest && prNumber(newest) >= prNumber(url) ? newest : url,
308
+ null
309
+ );
310
+ }
311
+ function resultPrUrl(finalMessage) {
312
+ const result = parseRunResult(finalMessage);
313
+ if (!result) return prUrlIn(finalMessage);
314
+ const prs = result.outputs.flatMap((o) => o.kind === "pr" ? [o.url] : []);
315
+ return prs.at(-1) ?? null;
316
+ }
317
+ function parseRunResult(message) {
318
+ return readRunResult(message).result;
319
+ }
320
+ function droppedLine(dropped, run) {
321
+ return dropped.outputs || dropped.checks ? `result_items_dropped run=${run} outputs=${dropped.outputs} checks=${dropped.checks}` : null;
322
+ }
323
+
324
+ // src/drivers/driver.ts
325
+ var LOCAL_DRIVERS = ["claude-code", "codex"];
326
+ function isLocalDriver(name) {
327
+ return LOCAL_DRIVERS.includes(name);
328
+ }
329
+ function ownHarnessFirst(reports, driver) {
330
+ return reports.filter((h) => h !== null && (h.id === driver || h.signedIn)).sort((a, b) => Number(b.id === driver) - Number(a.id === driver));
331
+ }
332
+ var RUNTIME_MODES = /* @__PURE__ */ new Set([
333
+ "approval-required",
334
+ "auto-accept-edits",
335
+ "auto",
336
+ "full-access"
337
+ ]);
338
+ function cloneLine(repository) {
339
+ return `This Task names the repository ${repository}, and this machine has no project for it. Clone it outside this folder, or find it on this machine, and work in it.`;
340
+ }
341
+ var BoxToolError = class extends Error {
342
+ constructor(code) {
343
+ super(code);
344
+ this.code = code;
345
+ this.name = "BoxToolError";
346
+ }
347
+ code;
348
+ };
349
+ var CLOOP_THREAD_PREFIX = "cloop:";
350
+ function questionLine(questions) {
351
+ return questions.map(
352
+ (x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
353
+ ).join(" ").slice(0, 500);
354
+ }
355
+ function isProgressSentence(value) {
356
+ return typeof value === "string" && /\S[ \t]+\S/.test(value.trim().split(/\r?\n/)[0] ?? "");
357
+ }
358
+ var PROGRESS_MS = 3e4;
359
+ var IDLE_SETTLE_MS = 20 * 6e4;
360
+ function holdsForNextTurn(turn) {
361
+ return turn.completed && !turn.limited && !turn.result;
362
+ }
363
+ var RUN_TEXT_MAX = 4e3;
364
+ function finalWords(text2) {
365
+ return text2.replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim();
366
+ }
367
+ function nextProgress(clock, text2, now, ms = PROGRESS_MS, force = false) {
368
+ const summary = (parseRunResult(text2)?.summary ?? text2.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, RUN_TEXT_MAX);
369
+ if (!isProgressSentence(summary)) return null;
370
+ if (!force && now - clock.lastProgressAt < ms) return null;
371
+ clock.lastProgressAt = now;
372
+ return summary;
373
+ }
374
+ var YES_WORDS = /* @__PURE__ */ new Set([
375
+ "y",
376
+ "yes",
377
+ "yep",
378
+ "yeah",
379
+ "allow",
380
+ "allow it",
381
+ "ok",
382
+ "okay",
383
+ "approve",
384
+ "approved",
385
+ "go ahead",
386
+ "sure",
387
+ "do it"
388
+ ]);
389
+ function isYes(reply) {
390
+ return YES_WORDS.has(
391
+ reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
392
+ );
393
+ }
394
+ var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
395
+ function limitedModel(said) {
396
+ const name = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1];
397
+ return name && !/usage|weekly|daily|session|hour|month/i.test(name) ? name : null;
398
+ }
399
+ function refusedModel(said) {
400
+ return /The '([^']+)' model is not supported/i.exec(said ?? "")?.[1] ?? null;
401
+ }
402
+ function nextModel(listed, tried) {
403
+ return listed.find((m) => !tried.includes(m)) ?? null;
404
+ }
405
+ var MODEL_REFUSAL_MS = 24 * 36e5;
406
+ function refusedRecently(refusals, now) {
407
+ return refusals.filter((r) => now - Date.parse(r.at) < MODEL_REFUSAL_MS).map((r) => r.model);
408
+ }
409
+ function refusedModelLine(harness, refused, next) {
410
+ return `${harness} cannot use ${refused} on this account, so this ran on ${next}.`;
411
+ }
412
+ function apiErrorWords(said) {
413
+ try {
414
+ const inner = JSON.parse(said)?.error?.message;
415
+ return typeof inner === "string" && inner.trim() ? inner.trim() : said;
416
+ } catch {
417
+ return said;
418
+ }
419
+ }
420
+ var HARNESS_SIGNED_OUT = /^\s*(Failed to authenticate:\s*OAuth session expired and could not be refreshed\b|Your access token could not be refreshed\b|Your authentication session could not be refreshed\b|Not signed in\. Please run 'codex login'|unexpected status 401\b)/i;
421
+ var CLAUDE_AUTH_LOCKED = /another Claude Code process is refreshing/i;
422
+ var LIMIT_HOLD_MS = 60 * 6e4;
423
+ var HARNESS_STATE = {
424
+ limit: "at its usage limit",
425
+ signed_out: "signed out here",
426
+ missing: "not installed here"
427
+ };
428
+ function movedLine(reason, from, to, tense) {
429
+ return `${from} ${tense} ${HARNESS_STATE[reason]}, so ${to} did this run.`;
430
+ }
431
+ function movingLine(reason, from, to) {
432
+ return `${from} is ${HARNESS_STATE[reason]}, so I moved this to ${to}`;
433
+ }
434
+ var STOPPED_BECAUSE = {
435
+ limit: "stopped at its usage limit",
436
+ signed_out: "could not sign in"
437
+ };
438
+ function handoverPrompt(prompt, from, reason = "limit") {
439
+ return `${prompt}
440
+
441
+ ${from} started this work and ${STOPPED_BECAUSE[reason]}. Its changes, if any, are in this checkout. Read \`git status\` and \`git log\` first, and carry on from there.`;
442
+ }
443
+
444
+ // src/runner-config.ts
445
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
446
+ import { dirname, join as join2 } from "path";
447
+ var BOX_FILE = "box.json";
448
+ function boxPath(env = runnerEnvironment()) {
449
+ return runnerPath(env, process.env.CLOOP_BOX_FILE, (dir) => join2(dir, BOX_FILE));
450
+ }
451
+ function isLocal(cfg) {
452
+ return isLocalDriver(cfg.driver);
453
+ }
454
+ function isHosted(cfg) {
455
+ return cfg.driver === "cloudroom";
456
+ }
457
+ function isT3(cfg) {
458
+ return cfg.driver === void 0 || cfg.driver === "t3";
459
+ }
460
+ function showsOtherThreads(cfg) {
461
+ return cfg?.hideOtherThreads !== true;
462
+ }
463
+ function otherThreadsChoice(argv, previous) {
464
+ if (argv.includes("--hide-other-threads")) return true;
465
+ if (argv.includes("--show-other-threads")) return false;
466
+ return previous?.hideOtherThreads === true;
467
+ }
468
+ function readRunnerConfig(env) {
469
+ let parsed;
470
+ try {
471
+ parsed = JSON.parse(readFileSync(boxPath(env), "utf-8"));
472
+ } catch {
473
+ return null;
474
+ }
475
+ if (isLocalDriver(parsed.driver)) {
476
+ const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
477
+ return ok ? parsed : null;
478
+ }
479
+ if (parsed.driver === "cloudroom") {
480
+ const ok = ["harness", "coreUrl", "coreToken", "deviceToken", "origin", "environmentId"].every(
481
+ (key) => typeof parsed[key] === "string" && parsed[key]
482
+ );
483
+ return ok && /^[a-z0-9-]{1,40}$/.test(parsed.harness) ? parsed : null;
484
+ }
485
+ if (typeof parsed.t3Url !== "string" || typeof parsed.token !== "string") return null;
486
+ return parsed;
487
+ }
488
+ function writeBoxConfig(cfg) {
489
+ const path = boxPath();
490
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
491
+ const temp = `${path}.${process.pid}.tmp`;
492
+ writeFileSync(temp, `${JSON.stringify(cfg, null, 2)}
493
+ `, { mode: 384 });
494
+ chmodSync(temp, 384);
495
+ renameSync(temp, path);
496
+ }
497
+
498
+ // src/spawn-command.ts
499
+ import { execFileSync } from "child_process";
500
+ function commandFor(bin, args, platform = process.platform, comspec = process.env.ComSpec) {
501
+ if (platform !== "win32") return { file: bin, args };
502
+ const executable = windowsExecutable(bin) ?? bin;
503
+ if (!/\.(cmd|bat)$/i.test(executable)) return { file: executable, args };
504
+ return {
505
+ file: comspec ?? "cmd.exe",
506
+ args: ["/d", "/s", "/c", `"${[executable, ...args].map(quoteWindowsArg).join(" ")}"`],
507
+ windowsVerbatimArguments: true
508
+ };
509
+ }
510
+ function quoteWindowsArg(arg) {
511
+ if (arg && !/[ \t"]/.test(arg)) return arg;
512
+ let quoted = '"';
513
+ let backslashes = 0;
514
+ for (const ch of arg) {
515
+ if (ch === "\\") {
516
+ backslashes++;
517
+ continue;
518
+ }
519
+ quoted += "\\".repeat(ch === '"' ? backslashes * 2 + 1 : backslashes) + ch;
520
+ backslashes = 0;
521
+ }
522
+ return `${quoted}${"\\".repeat(backslashes * 2)}"`;
523
+ }
524
+ function preferExecutable(lines) {
525
+ return lines.find((line) => /\.exe$/i.test(line)) ?? lines.find((line) => /\.(cmd|bat)$/i.test(line)) ?? null;
526
+ }
527
+ var windowsExecutables = /* @__PURE__ */ new Map();
528
+ function windowsExecutable(bin) {
529
+ if (/[\\/]/.test(bin)) return bin;
530
+ if (process.platform !== "win32") return null;
531
+ const key = JSON.stringify([bin, process.env.PATH, process.env.PATHEXT]);
532
+ if (windowsExecutables.has(key)) return windowsExecutables.get(key) ?? null;
533
+ let resolved = null;
534
+ try {
535
+ resolved = preferExecutable(
536
+ execFileSync("where.exe", [bin], { encoding: "utf-8", timeout: 5e3 }).split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
537
+ );
538
+ } catch {
539
+ }
540
+ windowsExecutables.set(key, resolved);
541
+ if (!resolved)
542
+ console.error(
543
+ `[runner:spawn] Could not resolve ${bin} to an executable on PATH. Install the agent and reconnect the runner.`
544
+ );
545
+ return resolved;
546
+ }
547
+ function which(bin) {
548
+ return process.platform === "win32" ? windowsExecutable(bin) : whichPosix(bin);
549
+ }
550
+ function whichPosix(bin) {
551
+ try {
552
+ return execFileSync("which", [bin], {
553
+ encoding: "utf-8",
554
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH }
555
+ }).trim() || null;
556
+ } catch {
557
+ return null;
558
+ }
559
+ }
560
+ function windowsPowerShellEnv(env = process.env) {
561
+ return Object.fromEntries(
562
+ Object.entries(env).filter(([key]) => key.toLowerCase() !== "psmodulepath")
563
+ );
564
+ }
565
+
566
+ export {
567
+ ENVIRONMENTS,
568
+ environmentOf,
569
+ runnerEnvironment,
570
+ runnerDir,
571
+ runnerPath,
572
+ cloopCommand,
573
+ serviceIdentity,
574
+ RUN_MEDIA_CLASSES,
575
+ RUN_MEDIA_TYPES,
576
+ imageExt,
577
+ mediaExt,
578
+ RUN_PREVIEWS_MAX,
579
+ MACHINE_RESULT_INSTRUCTION,
580
+ readRunResult,
581
+ hasResultBlock,
582
+ resultText,
583
+ prUrlIn,
584
+ resultPrUrl,
585
+ droppedLine,
586
+ LOCAL_DRIVERS,
587
+ isLocalDriver,
588
+ ownHarnessFirst,
589
+ RUNTIME_MODES,
590
+ cloneLine,
591
+ BoxToolError,
592
+ CLOOP_THREAD_PREFIX,
593
+ questionLine,
594
+ isProgressSentence,
595
+ IDLE_SETTLE_MS,
596
+ holdsForNextTurn,
597
+ RUN_TEXT_MAX,
598
+ finalWords,
599
+ nextProgress,
600
+ isYes,
601
+ HARNESS_LIMIT,
602
+ limitedModel,
603
+ refusedModel,
604
+ nextModel,
605
+ refusedRecently,
606
+ refusedModelLine,
607
+ apiErrorWords,
608
+ HARNESS_SIGNED_OUT,
609
+ CLAUDE_AUTH_LOCKED,
610
+ LIMIT_HOLD_MS,
611
+ movedLine,
612
+ movingLine,
613
+ handoverPrompt,
614
+ boxPath,
615
+ isLocal,
616
+ isHosted,
617
+ isT3,
618
+ showsOtherThreads,
619
+ otherThreadsChoice,
620
+ readRunnerConfig,
621
+ writeBoxConfig,
622
+ commandFor,
623
+ quoteWindowsArg,
624
+ which,
625
+ windowsPowerShellEnv
626
+ };