@cloop/runner 0.3.51 → 0.3.54

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.
@@ -10,6 +10,317 @@ import {
10
10
  getOrigin
11
11
  } from "./chunk-D5UZW42X.js";
12
12
 
13
+ // ../clo0p-app/contracts/run-result.ts
14
+ var WIZARD_STEPS_MAX = 6;
15
+ 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";
16
+ var CHECK_BACK_MIN_MINUTES = 5;
17
+ var CHECK_BACK_MAX_MINUTES = 3 * 24 * 60;
18
+ var CHECK_BACK_WHY_MAX = 300;
19
+ var RUN_IMAGES_MAX = 6;
20
+ var RUN_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
21
+ var RUN_IMAGE_TYPES = { png: "image/png", jpg: "image/jpeg", webp: "image/webp" };
22
+ function imageExt(bytes) {
23
+ const at = (i, ...want) => want.every((b, j) => bytes[i + j] === b);
24
+ if (at(0, 137, 80, 78, 71, 13, 10, 26, 10)) return "png";
25
+ if (at(0, 255, 216, 255)) return "jpg";
26
+ if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return "webp";
27
+ return null;
28
+ }
29
+ var RUN_MEDIA_KEY = runMediaPattern("[0-9a-f-]{36}\\/[0-9a-f-]{36}\\/");
30
+ var RUN_MEDIA_FILE = runMediaPattern("");
31
+ var RUN_PREVIEWS_MAX = 3;
32
+ var PREVIEW_HOURS = 24;
33
+ var BOX_PREVIEW_HOURS = 6;
34
+ var PREVIEW_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
35
+ function isPort(v) {
36
+ return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 65535;
37
+ }
38
+ function isPreviewPath(v) {
39
+ return typeof v === "string" && v.length <= 400 && v.startsWith("/") && !v.startsWith("//") && !/[\s\\]/.test(v);
40
+ }
41
+ function runMediaPattern(folder) {
42
+ return new RegExp(`^${folder}[0-9a-f-]{36}\\.(${Object.keys(RUN_IMAGE_TYPES).join("|")})$`);
43
+ }
44
+ var RESULT_INSTRUCTION = [
45
+ "When you finish, end your final message with a fenced block tagged cloop-result containing JSON, for example:",
46
+ "```cloop-result",
47
+ '{"summary": "One or two sentences on what you did.", "outputs": [{"kind": "pr", "title": "fix: the thing", "url": "https://github.com/org/repo/pull/1"}], "checks": [{"name": "Tests", "outcome": "passed"}]}',
48
+ "```",
49
+ "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.",
50
+ "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.",
51
+ `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.`,
52
+ "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.",
53
+ "When the ask is to find, compare, summarise or research something, put the whole answer in a doc output with a body, so the owner has one page to read; the summary stays one or two sentences."
54
+ ].join("\n");
55
+ var MACHINE_RESULT_INSTRUCTION = [
56
+ RESULT_INSTRUCTION,
57
+ `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.`,
58
+ `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.`,
59
+ `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.`
60
+ ].join("\n");
61
+ var SUMMARY_MAX = 4e3;
62
+ var ASKS_MAX = 1e3;
63
+ var DOC_BODY_MAX = 8e3;
64
+ var ITEMS_MAX = 10;
65
+ var BLOCK = /```cloop-result\s*\n([\s\S]*?)```/g;
66
+ var text = (v, max) => typeof v === "string" && v.length <= max;
67
+ var optionalText = (v, max) => v === void 0 || text(v, max);
68
+ function isHttps(v) {
69
+ try {
70
+ return typeof v === "string" && new URL(v).protocol === "https:";
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+ var GITHUB_PR = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/(\d+)$/;
76
+ function addressOutput(value) {
77
+ const url = value.trim();
78
+ if (!isHttps(url)) return null;
79
+ const pr = url.match(GITHUB_PR);
80
+ if (pr) return { kind: "pr", title: `Pull request #${pr[1]}`, url };
81
+ const { host, pathname } = new URL(url);
82
+ return { kind: "link", title: `${host}${pathname === "/" ? "" : pathname}`.slice(0, 120), url };
83
+ }
84
+ function readOutput(o) {
85
+ if (typeof o === "string") return addressOutput(o);
86
+ if (!o || typeof o !== "object") return null;
87
+ const out = o;
88
+ if (!text(out.title, 120)) return null;
89
+ const title = out.title;
90
+ switch (out.kind) {
91
+ case "pr":
92
+ case "link":
93
+ return isHttps(out.url) ? out.kind === "pr" ? { kind: "pr", title, url: out.url } : { kind: "link", title, url: out.url } : null;
94
+ case "draft":
95
+ return text(out.body, 4e3) && optionalText(out.to, 200) && (out.url === void 0 || isHttps(out.url)) ? {
96
+ kind: "draft",
97
+ title,
98
+ body: out.body,
99
+ ...out.to !== void 0 ? { to: out.to } : {},
100
+ ...out.url !== void 0 ? { url: out.url } : {}
101
+ } : null;
102
+ case "doc": {
103
+ const body = typeof out.body === "string" && out.body.length > DOC_BODY_MAX ? `${out.body.slice(0, DOC_BODY_MAX - 1)}\u2026` : out.body;
104
+ if (!optionalText(body, DOC_BODY_MAX) || out.url !== void 0 && !isHttps(out.url)) return null;
105
+ if (out.url === void 0 && !body?.trim()) return null;
106
+ return {
107
+ kind: "doc",
108
+ title,
109
+ ...out.url !== void 0 ? { url: out.url } : {},
110
+ ...body !== void 0 ? { body } : {}
111
+ };
112
+ }
113
+ case "image": {
114
+ const media = typeof out.media === "string" && RUN_MEDIA_KEY.test(out.media) ? out.media : void 0;
115
+ if (out.path === void 0) return media ? { kind: "image", title, media } : null;
116
+ if (!text(out.path, 400)) return null;
117
+ return { kind: "image", title, path: out.path, ...media ? { media } : {} };
118
+ }
119
+ case "preview":
120
+ if (!isPort(out.port) || out.path !== void 0 && !isPreviewPath(out.path)) return null;
121
+ return {
122
+ kind: "preview",
123
+ title,
124
+ port: out.port,
125
+ ...out.path !== void 0 ? { path: out.path } : {},
126
+ ...typeof out.preview === "string" && PREVIEW_ID.test(out.preview) ? { preview: out.preview } : {}
127
+ };
128
+ case "wizard":
129
+ return Array.isArray(out.steps) && out.steps.length ? { kind: "wizard", title, steps: out.steps } : null;
130
+ default:
131
+ return null;
132
+ }
133
+ }
134
+ function readCheckBack(v) {
135
+ if (!v || typeof v !== "object") return null;
136
+ const { in_minutes: minutes, why } = v;
137
+ if (typeof minutes !== "number" || !Number.isFinite(minutes) || typeof why !== "string" || !why.trim()) return null;
138
+ return {
139
+ in_minutes: Math.min(CHECK_BACK_MAX_MINUTES, Math.max(CHECK_BACK_MIN_MINUTES, Math.round(minutes))),
140
+ why: why.trim().slice(0, CHECK_BACK_WHY_MAX)
141
+ };
142
+ }
143
+ function readCheck(c) {
144
+ if (!c || typeof c !== "object") return null;
145
+ const check = c;
146
+ if (!text(check.name, 80) || !["passed", "failed", "skipped"].includes(check.outcome)) return null;
147
+ if (!optionalText(check.detail, 200)) return null;
148
+ return {
149
+ name: check.name,
150
+ outcome: check.outcome,
151
+ ...check.detail !== void 0 ? { detail: check.detail } : {}
152
+ };
153
+ }
154
+ function readRunResult(message) {
155
+ const none = { dropped: { outputs: 0, checks: 0 } };
156
+ const block = [...(message ?? "").matchAll(BLOCK)].at(-1)?.[1];
157
+ if (!block) return none;
158
+ let value;
159
+ try {
160
+ value = JSON.parse(block);
161
+ } catch {
162
+ return none;
163
+ }
164
+ const summary = typeof value?.summary === "string" ? value.summary.trim() : "";
165
+ if (!summary) return none;
166
+ const list = (v) => Array.isArray(v) ? v : [];
167
+ const asks = typeof value?.asks === "string" ? value.asks.trim() : "";
168
+ const outputs = list(value?.outputs).flatMap((o) => readOutput(o) ?? []);
169
+ const checks = list(value?.checks).flatMap((c) => readCheck(c) ?? []);
170
+ const checkBack = readCheckBack(value?.check_back);
171
+ return {
172
+ result: {
173
+ summary: summary.length > SUMMARY_MAX ? `${summary.slice(0, SUMMARY_MAX - 1)}\u2026` : summary,
174
+ outputs: outputs.slice(0, ITEMS_MAX),
175
+ checks: checks.slice(0, ITEMS_MAX),
176
+ ...value?.nothing_new === true ? { nothing_new: true } : {},
177
+ ...asks ? { asks: asks.length > ASKS_MAX ? `${asks.slice(0, ASKS_MAX - 1)}\u2026` : asks } : {},
178
+ ...checkBack ? { check_back: checkBack } : {}
179
+ },
180
+ dropped: { outputs: list(value?.outputs).length - outputs.length, checks: list(value?.checks).length - checks.length }
181
+ };
182
+ }
183
+ function hasResultBlock(message) {
184
+ return /```cloop-result\s*\n/.test(message ?? "");
185
+ }
186
+ function resultText(final, earlier) {
187
+ return (hasResultBlock(final) ? final : hasResultBlock(earlier) ? earlier : final) ?? void 0;
188
+ }
189
+
190
+ // src/run-result.ts
191
+ var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
192
+ var prNumber = (url) => Number(url.slice(url.lastIndexOf("/") + 1));
193
+ function prUrlIn(text3) {
194
+ const urls = text3?.match(PR_URL) ?? [];
195
+ return urls.reduce(
196
+ (newest, url) => newest && prNumber(newest) >= prNumber(url) ? newest : url,
197
+ null
198
+ );
199
+ }
200
+ function resultPrUrl(finalMessage) {
201
+ const result = parseRunResult(finalMessage);
202
+ if (!result) return prUrlIn(finalMessage);
203
+ const prs = result.outputs.flatMap((o) => o.kind === "pr" ? [o.url] : []);
204
+ return prs.at(-1) ?? null;
205
+ }
206
+ function parseRunResult(message) {
207
+ return readRunResult(message).result;
208
+ }
209
+ function droppedLine(dropped, run2) {
210
+ return dropped.outputs || dropped.checks ? `result_items_dropped run=${run2} outputs=${dropped.outputs} checks=${dropped.checks}` : null;
211
+ }
212
+
213
+ // src/drivers/driver.ts
214
+ function ownHarnessFirst(reports, driver) {
215
+ return reports.filter((h) => h !== null && (h.id === driver || h.signedIn)).sort((a, b) => Number(b.id === driver) - Number(a.id === driver));
216
+ }
217
+ var RUNTIME_MODES = /* @__PURE__ */ new Set([
218
+ "approval-required",
219
+ "auto-accept-edits",
220
+ "auto",
221
+ "full-access"
222
+ ]);
223
+ function cloneLine(repository) {
224
+ 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.`;
225
+ }
226
+ var BoxToolError = class extends Error {
227
+ constructor(code) {
228
+ super(code);
229
+ this.code = code;
230
+ this.name = "BoxToolError";
231
+ }
232
+ code;
233
+ };
234
+ var CLOOP_THREAD_PREFIX = "cloop:";
235
+ function questionLine(questions) {
236
+ return questions.map(
237
+ (x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
238
+ ).join(" ").slice(0, 500);
239
+ }
240
+ function isProgressSentence(value) {
241
+ return typeof value === "string" && /\S[ \t]+\S/.test(value.trim().split(/\r?\n/)[0] ?? "");
242
+ }
243
+ var PROGRESS_MS = 3e4;
244
+ var RUN_TEXT_MAX = 4e3;
245
+ function finalWords(text3) {
246
+ return text3.replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim();
247
+ }
248
+ function nextProgress(clock, text3, now, ms = PROGRESS_MS, force = false) {
249
+ const summary = (parseRunResult(text3)?.summary ?? text3.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, RUN_TEXT_MAX);
250
+ if (!isProgressSentence(summary)) return null;
251
+ if (!force && now - clock.lastProgressAt < ms) return null;
252
+ clock.lastProgressAt = now;
253
+ return summary;
254
+ }
255
+ var YES_WORDS = /* @__PURE__ */ new Set([
256
+ "y",
257
+ "yes",
258
+ "yep",
259
+ "yeah",
260
+ "allow",
261
+ "allow it",
262
+ "ok",
263
+ "okay",
264
+ "approve",
265
+ "approved",
266
+ "go ahead",
267
+ "sure",
268
+ "do it"
269
+ ]);
270
+ function isYes(reply) {
271
+ return YES_WORDS.has(
272
+ reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
273
+ );
274
+ }
275
+ var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
276
+ function limitedModel(said) {
277
+ const name = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1];
278
+ return name && !/usage|weekly|daily|session|hour|month/i.test(name) ? name : null;
279
+ }
280
+ function refusedModel(said) {
281
+ return /The '([^']+)' model is not supported/i.exec(said ?? "")?.[1] ?? null;
282
+ }
283
+ function nextModel(listed, tried) {
284
+ return listed.find((m) => !tried.includes(m)) ?? null;
285
+ }
286
+ var MODEL_REFUSAL_MS = 24 * 36e5;
287
+ function refusedRecently(refusals, now) {
288
+ return refusals.filter((r) => now - Date.parse(r.at) < MODEL_REFUSAL_MS).map((r) => r.model);
289
+ }
290
+ function refusedModelLine(harness, refused, next) {
291
+ return `${harness} cannot use ${refused} on this account, so this ran on ${next}.`;
292
+ }
293
+ function apiErrorWords(said) {
294
+ try {
295
+ const inner = JSON.parse(said)?.error?.message;
296
+ return typeof inner === "string" && inner.trim() ? inner.trim() : said;
297
+ } catch {
298
+ return said;
299
+ }
300
+ }
301
+ 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;
302
+ var LIMIT_HOLD_MS = 60 * 6e4;
303
+ var HARNESS_STATE = {
304
+ limit: "at its usage limit",
305
+ signed_out: "signed out here",
306
+ missing: "not installed here"
307
+ };
308
+ function movedLine(reason, from, to, tense) {
309
+ return `${from} ${tense} ${HARNESS_STATE[reason]}, so ${to} did this run.`;
310
+ }
311
+ function movingLine(reason, from, to) {
312
+ return `${from} is ${HARNESS_STATE[reason]}, so I moved this to ${to}`;
313
+ }
314
+ var STOPPED_BECAUSE = {
315
+ limit: "stopped at its usage limit",
316
+ signed_out: "could not sign in"
317
+ };
318
+ function handoverPrompt(prompt, from, reason = "limit") {
319
+ return `${prompt}
320
+
321
+ ${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.`;
322
+ }
323
+
13
324
  // src/environment.ts
14
325
  import { homedir } from "os";
15
326
  import { join } from "path";
@@ -704,285 +1015,85 @@ var T3Client = class {
704
1015
  });
705
1016
  }
706
1017
  /**
707
- * A streaming request, such as `orchestration.subscribeThread`, on its own
708
- * socket. Every item is acked, as Effect RPC requires. `done` resolves with
709
- * the reason the stream ended and never rejects; `close` interrupts it.
710
- */
711
- async stream(tag, payload, onItem) {
712
- const ws = await this.openSocket();
713
- let resolveDone = () => {
714
- };
715
- const done = new Promise((r) => {
716
- resolveDone = r;
717
- });
718
- const end = (reason) => {
719
- resolveDone(reason);
720
- try {
721
- ws.close();
722
- } catch {
723
- }
724
- };
725
- ws.on("error", (err) => end(`error: ${err instanceof Error ? err.message : String(err)}`));
726
- ws.on("close", () => end("closed"));
727
- ws.on("open", () => {
728
- ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
729
- });
730
- ws.on("message", (data) => {
731
- for (const msg of parseFrames(data)) {
732
- if (String(msg.requestId) !== "1") continue;
733
- if (msg._tag === "Chunk") {
734
- ws.send(JSON.stringify({ _tag: "Ack", requestId: msg.requestId }));
735
- for (const value of msg.values) onItem(value);
736
- } else if (msg._tag === "Exit") {
737
- const exit = msg.exit;
738
- end(
739
- exit._tag === "Success" ? "exit" : `failed: ${JSON.stringify(exit.cause).slice(0, 300)}`
740
- );
741
- }
742
- }
743
- });
744
- return {
745
- done,
746
- close: () => {
747
- try {
748
- ws.send(JSON.stringify({ _tag: "Interrupt", requestId: "1" }));
749
- } catch {
750
- }
751
- end("closed by client");
752
- }
753
- };
754
- }
755
- };
756
- function parseFrames(data) {
757
- try {
758
- const raw = JSON.parse(String(data));
759
- return Array.isArray(raw) ? raw : [raw];
760
- } catch {
761
- return [];
762
- }
763
- }
764
-
765
- // src/drivers/t3.ts
766
- import { execFile as execFile2, execFileSync as execFileSync3 } from "child_process";
767
- import { randomUUID } from "crypto";
768
- import { existsSync as existsSync2 } from "fs";
769
- import { join as join7 } from "path";
770
-
771
- // ../clo0p-app/contracts/work-spec.ts
772
- var IMAGE_TYPES = {
773
- "image/jpeg": "jpg",
774
- "image/png": "png",
775
- "image/webp": "webp",
776
- "image/gif": "gif"
777
- };
778
- function isImageType(type) {
779
- return Object.hasOwn(IMAGE_TYPES, type);
780
- }
781
- var IMAGE_MAX_BYTES = 10 * 1024 * 1024;
782
- var ATTACHMENTS_MAX = 8;
783
- function repoName(repository) {
784
- const name = repository?.trim().toLowerCase().split("/").filter(Boolean).at(-1);
785
- return name || null;
786
- }
787
-
788
- // ../clo0p-app/contracts/run-result.ts
789
- var WIZARD_STEPS_MAX = 6;
790
- 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";
791
- var CHECK_BACK_MIN_MINUTES = 5;
792
- var CHECK_BACK_MAX_MINUTES = 3 * 24 * 60;
793
- var CHECK_BACK_WHY_MAX = 300;
794
- var RUN_IMAGES_MAX = 6;
795
- var RUN_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
796
- var RUN_IMAGE_TYPES = { png: "image/png", jpg: "image/jpeg", webp: "image/webp" };
797
- function imageExt(bytes) {
798
- const at = (i, ...want) => want.every((b, j) => bytes[i + j] === b);
799
- if (at(0, 137, 80, 78, 71, 13, 10, 26, 10)) return "png";
800
- if (at(0, 255, 216, 255)) return "jpg";
801
- if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return "webp";
802
- return null;
803
- }
804
- var RUN_MEDIA_KEY = runMediaPattern("[0-9a-f-]{36}\\/[0-9a-f-]{36}\\/");
805
- var RUN_MEDIA_FILE = runMediaPattern("");
806
- var RUN_PREVIEWS_MAX = 3;
807
- var PREVIEW_HOURS = 24;
808
- var BOX_PREVIEW_HOURS = 6;
809
- var PREVIEW_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
810
- function isPort(v) {
811
- return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 65535;
812
- }
813
- function isPreviewPath(v) {
814
- return typeof v === "string" && v.length <= 400 && v.startsWith("/") && !v.startsWith("//") && !/[\s\\]/.test(v);
815
- }
816
- function runMediaPattern(folder) {
817
- return new RegExp(`^${folder}[0-9a-f-]{36}\\.(${Object.keys(RUN_IMAGE_TYPES).join("|")})$`);
818
- }
819
- var RESULT_INSTRUCTION = [
820
- "When you finish, end your final message with a fenced block tagged cloop-result containing JSON, for example:",
821
- "```cloop-result",
822
- '{"summary": "One or two sentences on what you did.", "outputs": [{"kind": "pr", "title": "fix: the thing", "url": "https://github.com/org/repo/pull/1"}], "checks": [{"name": "Tests", "outcome": "passed"}]}',
823
- "```",
824
- "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.",
825
- "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.",
826
- `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.`,
827
- "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.",
828
- "When the ask is to find, compare, summarise or research something, put the whole answer in a doc output with a body, so the owner has one page to read; the summary stays one or two sentences."
829
- ].join("\n");
830
- var MACHINE_RESULT_INSTRUCTION = [
831
- RESULT_INSTRUCTION,
832
- `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.`,
833
- `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.`,
834
- `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.`
835
- ].join("\n");
836
- var SUMMARY_MAX = 4e3;
837
- var ASKS_MAX = 1e3;
838
- var DOC_BODY_MAX = 8e3;
839
- var ITEMS_MAX = 10;
840
- var BLOCK = /```cloop-result\s*\n([\s\S]*?)```/g;
841
- var text = (v, max) => typeof v === "string" && v.length <= max;
842
- var optionalText = (v, max) => v === void 0 || text(v, max);
843
- function isHttps(v) {
844
- try {
845
- return typeof v === "string" && new URL(v).protocol === "https:";
846
- } catch {
847
- return false;
848
- }
849
- }
850
- var GITHUB_PR = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/(\d+)$/;
851
- function addressOutput(value) {
852
- const url = value.trim();
853
- if (!isHttps(url)) return null;
854
- const pr = url.match(GITHUB_PR);
855
- if (pr) return { kind: "pr", title: `Pull request #${pr[1]}`, url };
856
- const { host, pathname } = new URL(url);
857
- return { kind: "link", title: `${host}${pathname === "/" ? "" : pathname}`.slice(0, 120), url };
858
- }
859
- function readOutput(o) {
860
- if (typeof o === "string") return addressOutput(o);
861
- if (!o || typeof o !== "object") return null;
862
- const out = o;
863
- if (!text(out.title, 120)) return null;
864
- const title = out.title;
865
- switch (out.kind) {
866
- case "pr":
867
- case "link":
868
- return isHttps(out.url) ? out.kind === "pr" ? { kind: "pr", title, url: out.url } : { kind: "link", title, url: out.url } : null;
869
- case "draft":
870
- return text(out.body, 4e3) && optionalText(out.to, 200) && (out.url === void 0 || isHttps(out.url)) ? {
871
- kind: "draft",
872
- title,
873
- body: out.body,
874
- ...out.to !== void 0 ? { to: out.to } : {},
875
- ...out.url !== void 0 ? { url: out.url } : {}
876
- } : null;
877
- case "doc": {
878
- const body = typeof out.body === "string" && out.body.length > DOC_BODY_MAX ? `${out.body.slice(0, DOC_BODY_MAX - 1)}\u2026` : out.body;
879
- if (!optionalText(body, DOC_BODY_MAX) || out.url !== void 0 && !isHttps(out.url)) return null;
880
- if (out.url === void 0 && !body?.trim()) return null;
881
- return {
882
- kind: "doc",
883
- title,
884
- ...out.url !== void 0 ? { url: out.url } : {},
885
- ...body !== void 0 ? { body } : {}
886
- };
887
- }
888
- case "image": {
889
- const media = typeof out.media === "string" && RUN_MEDIA_KEY.test(out.media) ? out.media : void 0;
890
- if (out.path === void 0) return media ? { kind: "image", title, media } : null;
891
- if (!text(out.path, 400)) return null;
892
- return { kind: "image", title, path: out.path, ...media ? { media } : {} };
893
- }
894
- case "preview":
895
- if (!isPort(out.port) || out.path !== void 0 && !isPreviewPath(out.path)) return null;
896
- return {
897
- kind: "preview",
898
- title,
899
- port: out.port,
900
- ...out.path !== void 0 ? { path: out.path } : {},
901
- ...typeof out.preview === "string" && PREVIEW_ID.test(out.preview) ? { preview: out.preview } : {}
902
- };
903
- case "wizard":
904
- return Array.isArray(out.steps) && out.steps.length ? { kind: "wizard", title, steps: out.steps } : null;
905
- default:
906
- return null;
1018
+ * A streaming request, such as `orchestration.subscribeThread`, on its own
1019
+ * socket. Every item is acked, as Effect RPC requires. `done` resolves with
1020
+ * the reason the stream ended and never rejects; `close` interrupts it.
1021
+ */
1022
+ async stream(tag, payload, onItem) {
1023
+ const ws = await this.openSocket();
1024
+ let resolveDone = () => {
1025
+ };
1026
+ const done = new Promise((r) => {
1027
+ resolveDone = r;
1028
+ });
1029
+ const end = (reason) => {
1030
+ resolveDone(reason);
1031
+ try {
1032
+ ws.close();
1033
+ } catch {
1034
+ }
1035
+ };
1036
+ ws.on("error", (err) => end(`error: ${err instanceof Error ? err.message : String(err)}`));
1037
+ ws.on("close", () => end("closed"));
1038
+ ws.on("open", () => {
1039
+ ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
1040
+ });
1041
+ ws.on("message", (data) => {
1042
+ for (const msg of parseFrames(data)) {
1043
+ if (String(msg.requestId) !== "1") continue;
1044
+ if (msg._tag === "Chunk") {
1045
+ ws.send(JSON.stringify({ _tag: "Ack", requestId: msg.requestId }));
1046
+ for (const value of msg.values) onItem(value);
1047
+ } else if (msg._tag === "Exit") {
1048
+ const exit = msg.exit;
1049
+ end(
1050
+ exit._tag === "Success" ? "exit" : `failed: ${JSON.stringify(exit.cause).slice(0, 300)}`
1051
+ );
1052
+ }
1053
+ }
1054
+ });
1055
+ return {
1056
+ done,
1057
+ close: () => {
1058
+ try {
1059
+ ws.send(JSON.stringify({ _tag: "Interrupt", requestId: "1" }));
1060
+ } catch {
1061
+ }
1062
+ end("closed by client");
1063
+ }
1064
+ };
907
1065
  }
908
- }
909
- function readCheckBack(v) {
910
- if (!v || typeof v !== "object") return null;
911
- const { in_minutes: minutes, why } = v;
912
- if (typeof minutes !== "number" || !Number.isFinite(minutes) || typeof why !== "string" || !why.trim()) return null;
913
- return {
914
- in_minutes: Math.min(CHECK_BACK_MAX_MINUTES, Math.max(CHECK_BACK_MIN_MINUTES, Math.round(minutes))),
915
- why: why.trim().slice(0, CHECK_BACK_WHY_MAX)
916
- };
917
- }
918
- function readCheck(c) {
919
- if (!c || typeof c !== "object") return null;
920
- const check = c;
921
- if (!text(check.name, 80) || !["passed", "failed", "skipped"].includes(check.outcome)) return null;
922
- if (!optionalText(check.detail, 200)) return null;
923
- return {
924
- name: check.name,
925
- outcome: check.outcome,
926
- ...check.detail !== void 0 ? { detail: check.detail } : {}
927
- };
928
- }
929
- function readRunResult(message) {
930
- const none = { dropped: { outputs: 0, checks: 0 } };
931
- const block = [...(message ?? "").matchAll(BLOCK)].at(-1)?.[1];
932
- if (!block) return none;
933
- let value;
1066
+ };
1067
+ function parseFrames(data) {
934
1068
  try {
935
- value = JSON.parse(block);
1069
+ const raw = JSON.parse(String(data));
1070
+ return Array.isArray(raw) ? raw : [raw];
936
1071
  } catch {
937
- return none;
1072
+ return [];
938
1073
  }
939
- const summary = typeof value?.summary === "string" ? value.summary.trim() : "";
940
- if (!summary) return none;
941
- const list = (v) => Array.isArray(v) ? v : [];
942
- const asks = typeof value?.asks === "string" ? value.asks.trim() : "";
943
- const outputs = list(value?.outputs).flatMap((o) => readOutput(o) ?? []);
944
- const checks = list(value?.checks).flatMap((c) => readCheck(c) ?? []);
945
- const checkBack = readCheckBack(value?.check_back);
946
- return {
947
- result: {
948
- summary: summary.length > SUMMARY_MAX ? `${summary.slice(0, SUMMARY_MAX - 1)}\u2026` : summary,
949
- outputs: outputs.slice(0, ITEMS_MAX),
950
- checks: checks.slice(0, ITEMS_MAX),
951
- ...value?.nothing_new === true ? { nothing_new: true } : {},
952
- ...asks ? { asks: asks.length > ASKS_MAX ? `${asks.slice(0, ASKS_MAX - 1)}\u2026` : asks } : {},
953
- ...checkBack ? { check_back: checkBack } : {}
954
- },
955
- dropped: { outputs: list(value?.outputs).length - outputs.length, checks: list(value?.checks).length - checks.length }
956
- };
957
- }
958
- function hasResultBlock(message) {
959
- return /```cloop-result\s*\n/.test(message ?? "");
960
- }
961
- function resultText(final, earlier) {
962
- return (hasResultBlock(final) ? final : hasResultBlock(earlier) ? earlier : final) ?? void 0;
963
1074
  }
964
1075
 
965
- // src/run-result.ts
966
- var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
967
- var prNumber = (url) => Number(url.slice(url.lastIndexOf("/") + 1));
968
- function prUrlIn(text3) {
969
- const urls = text3?.match(PR_URL) ?? [];
970
- return urls.reduce(
971
- (newest, url) => newest && prNumber(newest) >= prNumber(url) ? newest : url,
972
- null
973
- );
974
- }
975
- function resultPrUrl(finalMessage) {
976
- const result = parseRunResult(finalMessage);
977
- if (!result) return prUrlIn(finalMessage);
978
- const prs = result.outputs.flatMap((o) => o.kind === "pr" ? [o.url] : []);
979
- return prs.at(-1) ?? null;
980
- }
981
- function parseRunResult(message) {
982
- return readRunResult(message).result;
1076
+ // src/drivers/t3.ts
1077
+ import { execFile as execFile2, execFileSync as execFileSync3 } from "child_process";
1078
+ import { randomUUID } from "crypto";
1079
+ import { existsSync as existsSync2 } from "fs";
1080
+ import { join as join7 } from "path";
1081
+
1082
+ // ../clo0p-app/contracts/work-spec.ts
1083
+ var IMAGE_TYPES = {
1084
+ "image/jpeg": "jpg",
1085
+ "image/png": "png",
1086
+ "image/webp": "webp",
1087
+ "image/gif": "gif"
1088
+ };
1089
+ function isImageType(type) {
1090
+ return Object.hasOwn(IMAGE_TYPES, type);
983
1091
  }
984
- function droppedLine(dropped, run2) {
985
- return dropped.outputs || dropped.checks ? `result_items_dropped run=${run2} outputs=${dropped.outputs} checks=${dropped.checks}` : null;
1092
+ var IMAGE_MAX_BYTES = 10 * 1024 * 1024;
1093
+ var ATTACHMENTS_MAX = 8;
1094
+ function repoName(repository) {
1095
+ const name = repository?.trim().toLowerCase().split("/").filter(Boolean).at(-1);
1096
+ return name || null;
986
1097
  }
987
1098
 
988
1099
  // src/drivers/attachments.ts
@@ -1068,114 +1179,6 @@ function attachedLine(attached, missed, paths) {
1068
1179
  return parts.join(" ");
1069
1180
  }
1070
1181
 
1071
- // src/drivers/driver.ts
1072
- var RUNTIME_MODES = /* @__PURE__ */ new Set([
1073
- "approval-required",
1074
- "auto-accept-edits",
1075
- "auto",
1076
- "full-access"
1077
- ]);
1078
- function cloneLine(repository) {
1079
- 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.`;
1080
- }
1081
- var BoxToolError = class extends Error {
1082
- constructor(code) {
1083
- super(code);
1084
- this.code = code;
1085
- this.name = "BoxToolError";
1086
- }
1087
- code;
1088
- };
1089
- var CLOOP_THREAD_PREFIX = "cloop:";
1090
- function questionLine(questions) {
1091
- return questions.map(
1092
- (x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
1093
- ).join(" ").slice(0, 500);
1094
- }
1095
- function isProgressSentence(value) {
1096
- return typeof value === "string" && /\S[ \t]+\S/.test(value.trim().split(/\r?\n/)[0] ?? "");
1097
- }
1098
- var PROGRESS_MS = 3e4;
1099
- var RUN_TEXT_MAX = 4e3;
1100
- function finalWords(text3) {
1101
- return text3.replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim();
1102
- }
1103
- function nextProgress(clock, text3, now, ms = PROGRESS_MS, force = false) {
1104
- const summary = (parseRunResult(text3)?.summary ?? text3.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, RUN_TEXT_MAX);
1105
- if (!isProgressSentence(summary)) return null;
1106
- if (!force && now - clock.lastProgressAt < ms) return null;
1107
- clock.lastProgressAt = now;
1108
- return summary;
1109
- }
1110
- var YES_WORDS = /* @__PURE__ */ new Set([
1111
- "y",
1112
- "yes",
1113
- "yep",
1114
- "yeah",
1115
- "allow",
1116
- "allow it",
1117
- "ok",
1118
- "okay",
1119
- "approve",
1120
- "approved",
1121
- "go ahead",
1122
- "sure",
1123
- "do it"
1124
- ]);
1125
- function isYes(reply) {
1126
- return YES_WORDS.has(
1127
- reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
1128
- );
1129
- }
1130
- var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
1131
- function limitedModel(said) {
1132
- const name = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1];
1133
- return name && !/usage|weekly|daily|session|hour|month/i.test(name) ? name : null;
1134
- }
1135
- function refusedModel(said) {
1136
- return /The '([^']+)' model is not supported/i.exec(said ?? "")?.[1] ?? null;
1137
- }
1138
- function nextModel(listed, tried) {
1139
- return listed.find((m) => !tried.includes(m)) ?? null;
1140
- }
1141
- var MODEL_REFUSAL_MS = 24 * 36e5;
1142
- function refusedRecently(refusals, now) {
1143
- return refusals.filter((r) => now - Date.parse(r.at) < MODEL_REFUSAL_MS).map((r) => r.model);
1144
- }
1145
- function refusedModelLine(harness, refused, next) {
1146
- return `${harness} cannot use ${refused} on this account, so this ran on ${next}.`;
1147
- }
1148
- function apiErrorWords(said) {
1149
- try {
1150
- const inner = JSON.parse(said)?.error?.message;
1151
- return typeof inner === "string" && inner.trim() ? inner.trim() : said;
1152
- } catch {
1153
- return said;
1154
- }
1155
- }
1156
- 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;
1157
- var LIMIT_HOLD_MS = 60 * 6e4;
1158
- var HARNESS_STATE = {
1159
- limit: "at its usage limit",
1160
- signed_out: "signed out here",
1161
- missing: "not installed here"
1162
- };
1163
- function movedLine(reason, from, to, tense) {
1164
- return `${from} ${tense} ${HARNESS_STATE[reason]}, so ${to} did this run.`;
1165
- }
1166
- function movingLine(reason, from, to) {
1167
- return `${from} is ${HARNESS_STATE[reason]}, so I moved this to ${to}`;
1168
- }
1169
- var STOPPED_BECAUSE = {
1170
- limit: "stopped at its usage limit",
1171
- signed_out: "could not sign in"
1172
- };
1173
- function handoverPrompt(prompt, from, reason = "limit") {
1174
- return `${prompt}
1175
-
1176
- ${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.`;
1177
- }
1178
-
1179
1182
  // src/drivers/usage.ts
1180
1183
  import { createHash } from "crypto";
1181
1184
  var TOKEN_SCOPE = "agent session logs on this machine";
@@ -1506,26 +1509,38 @@ function pendingQuestions(p) {
1506
1509
  if (!item.requestId) continue;
1507
1510
  if (item.type === "user_input_request" && item.questions?.length)
1508
1511
  asked.set(item.requestId, item.questions);
1509
- if (item.type === "approval_request")
1510
- approvals.set(item.requestId, item.prompt?.trim() || null);
1512
+ if (item.type === "approval_request") approvals.set(item.requestId, item);
1511
1513
  }
1512
1514
  return (p.runtimeRequests ?? []).filter((r) => r.status === "pending").sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")).flatMap((r) => {
1513
1515
  const questions = r.kind === "user_input" ? asked.get(r.id) : void 0;
1514
1516
  if (questions) return [{ request_id: r.id, questions }];
1515
- if (Object.hasOwn(APPROVAL_WORDS, r.kind) && approvals.has(r.id))
1517
+ const item = approvals.get(r.id);
1518
+ if (Object.hasOwn(APPROVAL_WORDS, r.kind) && item)
1516
1519
  return [
1517
- { request_id: r.id, approval: { kind: r.kind, prompt: approvals.get(r.id) ?? null } }
1520
+ {
1521
+ request_id: r.id,
1522
+ approval: {
1523
+ kind: r.kind,
1524
+ prompt: item.prompt?.trim() || null,
1525
+ reason: item.reason?.trim() || null
1526
+ }
1527
+ }
1518
1528
  ];
1519
1529
  return [];
1520
1530
  });
1521
1531
  }
1532
+ var oneLine = (text3, max) => {
1533
+ const flat = text3.replace(/[\r\n\t]+/g, " ");
1534
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
1535
+ };
1522
1536
  function questionText(q) {
1523
1537
  if (!q.approval) return questionLine(q.questions);
1524
- const words = APPROVAL_WORDS[q.approval.kind] ?? "go on";
1525
- const prompt = q.approval.prompt?.replace(/[\r\n\t]+/g, " ");
1526
- if (!prompt) return `${words}. OK?`;
1527
- return `${words}. OK?
1528
- (${prompt.length > 158 ? `${prompt.slice(0, 157)}\u2026` : prompt})`;
1538
+ const { kind, prompt, reason } = q.approval;
1539
+ return [
1540
+ `${APPROVAL_WORDS[kind] ?? "go on"}. OK?`,
1541
+ reason ? `It stopped because: ${oneLine(reason, 300)}` : null,
1542
+ prompt ? `(${oneLine(prompt, 158)})` : null
1543
+ ].filter(Boolean).join("\n");
1529
1544
  }
1530
1545
  function latestRun(runs) {
1531
1546
  return runs.reduce(
@@ -3562,6 +3577,7 @@ export {
3562
3577
  hasResultBlock,
3563
3578
  resultText,
3564
3579
  resultPrUrl,
3580
+ ownHarnessFirst,
3565
3581
  RUNTIME_MODES,
3566
3582
  BoxToolError,
3567
3583
  CLOOP_THREAD_PREFIX,