@h1r-ai/croche-cli 0.5.5 → 0.6.1

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 (44) hide show
  1. package/README.md +267 -148
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/dist/bin.js +29 -25
  4. package/dist/chunk-66EUX7EL.js +165 -0
  5. package/dist/chunk-DKT5HHSB.js +532 -0
  6. package/dist/chunk-K3UDT4EM.js +3110 -0
  7. package/dist/collector-credential.d.ts +9 -0
  8. package/dist/config-authoring.d.ts +19 -0
  9. package/dist/config-bases.d.ts +17 -0
  10. package/dist/config-push-base-35HX67AJ.js +2254 -0
  11. package/dist/config-push-base.d.ts +7 -0
  12. package/dist/control-address.d.ts +2 -0
  13. package/dist/control-server.d.ts +12 -15
  14. package/dist/control-server.js +9 -288
  15. package/dist/control-v2-auth.d.ts +24 -0
  16. package/dist/control-v2-capture.d.ts +34 -0
  17. package/dist/control-v2-json.d.ts +15 -0
  18. package/dist/control-v2-state.d.ts +90 -0
  19. package/dist/credentials.d.ts +2 -2
  20. package/dist/debugger/public/index.html +1 -0
  21. package/dist/debugger/public/stage-control.js +84 -0
  22. package/dist/debugger/public/stage-manifest.js +45 -0
  23. package/dist/debugger/public/stage-model.js +103 -0
  24. package/dist/debugger/public/stage-targets.js +18 -0
  25. package/dist/debugger/public/stage.css +459 -0
  26. package/dist/debugger/public/stage.html +17 -0
  27. package/dist/debugger/public/stage.js +113 -0
  28. package/dist/debugger/server/collector.js +42 -26
  29. package/dist/debugger/server/control-bridge.js +113 -0
  30. package/dist/debugger/server/server.js +10 -1
  31. package/dist/debugger/server/viewer-security.js +12 -0
  32. package/dist/debugger.d.ts +16 -6
  33. package/dist/index.d.ts +8 -1
  34. package/dist/index.js +17 -321
  35. package/dist/json-result.d.ts +2 -0
  36. package/package.json +2 -1
  37. package/dist/config.js +0 -100
  38. package/dist/control-client.js +0 -65
  39. package/dist/core-defaults.js +0 -2
  40. package/dist/credentials.js +0 -136
  41. package/dist/debug-keys.js +0 -141
  42. package/dist/debugger.js +0 -469
  43. package/dist/help.js +0 -158
  44. package/dist/text-file.js +0 -15
@@ -0,0 +1,3110 @@
1
+ import {
2
+ remoteAddress,
3
+ same
4
+ } from "./chunk-66EUX7EL.js";
5
+
6
+ // src/json-result.ts
7
+ var resultNouns = {
8
+ login: "account",
9
+ logout: "credential",
10
+ "auth whoami": "account",
11
+ "projects list": "projects",
12
+ "projects create": "project",
13
+ "projects get": "project",
14
+ "projects update": "project",
15
+ "projects operations": "operations",
16
+ "projects cost": "cost",
17
+ "projects usage": "usage",
18
+ "keys development list": "debug_keys",
19
+ "keys server list": "server_keys",
20
+ "attestation get": "attestation",
21
+ "runtimes list": "runtimes",
22
+ "debug-keys create": "debug_key",
23
+ "debug-keys list": "debug_keys",
24
+ "debug-keys revoke": "debug_key",
25
+ "config bases": "bases",
26
+ "config push-base": "base",
27
+ "config build": "config",
28
+ "config split": "config",
29
+ "config get": "config",
30
+ "config save": "config",
31
+ "config list": "versions",
32
+ "config effective": "config",
33
+ debug: "runtimes",
34
+ "debug start": "debugger",
35
+ "debug stop": "debugger",
36
+ "debug status": "debugger",
37
+ "debug connect": "debugger",
38
+ "debug disconnect": "debugger",
39
+ "debug token": "debugger",
40
+ "debug runtimes": "runtimes",
41
+ "control serve": "broker",
42
+ "runtime list": "attachments",
43
+ "runtime result": "request",
44
+ "runtime agents list": "request",
45
+ "runtime status": "request",
46
+ "runtime history": "request",
47
+ "runtime send": "request",
48
+ "runtime cancel": "request",
49
+ "runtime tools": "request"
50
+ };
51
+ function jsonResult(path2, result) {
52
+ const noun = resultNouns[path2];
53
+ if (!noun) throw new Error(`Missing JSON command contract: ${path2}`);
54
+ if (result !== null && typeof result === "object" && !Array.isArray(result)) {
55
+ const value2 = result;
56
+ if (path2 === "keys development list" && Object.hasOwn(value2, "debug_tokens")) {
57
+ const { debug_tokens, ...metadata } = value2;
58
+ return { ...metadata, debug_keys: debug_tokens };
59
+ }
60
+ if (noun === "request" && value2.request && typeof value2.request === "object") {
61
+ const request = value2.request;
62
+ const list = { "agents.list": "agents", history: "history", tools: "tools" }[String(request.command)];
63
+ if (list && Object.hasOwn(request, "result")) {
64
+ const payload = request.result;
65
+ if (Array.isArray(payload)) return { ...value2, request: { ...request, result: { [list]: payload } } };
66
+ if (payload !== null && typeof payload === "object" && Object.hasOwn(payload, list)) return result;
67
+ if (request.status === "completed") throw new Error("Invalid completed control list result.");
68
+ }
69
+ }
70
+ if (Object.hasOwn(value2, noun)) return result;
71
+ if (path2 === "debug") return { debugger: result };
72
+ }
73
+ return { [noun]: result };
74
+ }
75
+
76
+ // src/help.ts
77
+ var runtimeActions = ["list", "agents list", "status", "history", "send", "cancel", "tools", "result"];
78
+ var row = (path2, brief) => ({ label: path2, brief, paths: [path2] });
79
+ var sections = [
80
+ { title: "Getting started", rows: [
81
+ row("login", "Save your account key (typed at a hidden prompt)"),
82
+ row("logout", "Remove the saved account key"),
83
+ row("auth whoami", "Show your account and where the key comes from")
84
+ ] },
85
+ { title: "Projects", rows: [
86
+ row("projects list", "List your projects"),
87
+ row("projects create", "Create a project with a 10-credit monthly budget"),
88
+ row("projects get", "Show one project"),
89
+ row("projects update", "Rename a project or change its model routing"),
90
+ row("projects usage", "Usage per user and agent, and budget left"),
91
+ row("projects cost", "Reported cost by purpose (production or development)"),
92
+ row("projects operations", "Recent operations"),
93
+ row("runtimes list", "Runtimes enrolled with Cloud for a project")
94
+ ] },
95
+ { title: "Keys", rows: [
96
+ row("debug-keys create", "Issue a debug key and write it to .env"),
97
+ row("debug-keys list", "List debug keys (no secrets)"),
98
+ row("debug-keys revoke", "Revoke a debug key"),
99
+ row("keys development list", "Debug keys with installs, last use, warnings"),
100
+ row("keys server list", "Server keys with installs, last use, spend"),
101
+ row("attestation get", "App Attest and Play Integrity settings")
102
+ ] },
103
+ { title: "Config", rows: [
104
+ row("config build", "Build offline; unknown fields refused with paths"),
105
+ row("config split", "Split offline into numbered files and id manifest"),
106
+ row("config get", "Read a draft/revision/version for a build base"),
107
+ row("config effective", "Preview released config for --bundled-base"),
108
+ row("config bases", "List bundled bases, installs and upload hints"),
109
+ row("config push-base", "Upload one bundled base without publishing a release"),
110
+ row("config save", "Save a patch; --base is the draft CAS revision"),
111
+ row("config list", "Versions and draft for --bundled-base")
112
+ ] },
113
+ { title: "Debugger (development only)", rows: [
114
+ row("debug start", "Start the local debugger; prints a Studio link"),
115
+ row("debug", "Pick a running app to watch (--studio-link)"),
116
+ row("debug status", "Is the local debugger running?"),
117
+ row("debug runtimes", "Running apps the debugger can see"),
118
+ row("debug connect", "Observe an app-consented attachment; print viewer URL"),
119
+ row("debug disconnect", "Explain how the app revokes debugger consent"),
120
+ row("debug token", "Reveal one credential explicitly (--role)"),
121
+ row("debug stop", "Stop the local debugger")
122
+ ] },
123
+ { title: "Local Runtime control (advanced)", rows: [
124
+ row("control serve", "Start the local control broker"),
125
+ { label: "runtime <action>", brief: "Drive a local Runtime: croche runtime --help", paths: runtimeActions.map((action) => `runtime ${action}`) }
126
+ ] }
127
+ ];
128
+ var width = 24;
129
+ var line = (label, text2) => ` ${label.padEnd(Math.max(width, label.length + 2))}${text2}`.trimEnd();
130
+ var footer = [
131
+ "Options",
132
+ line("-h, --help", "Help; croche <command> --help for one command"),
133
+ line("--json", "Machine-readable output for scripts and agents"),
134
+ line("--version", "Print the CLI version"),
135
+ "",
136
+ "Environment",
137
+ line("CROCHE_PROJECT", "Default for project-scoped commands"),
138
+ line("CROCHE_ACCOUNT_KEY", "Account key, instead of croche login"),
139
+ line("CROCHE_CONTROL_TOKEN", "Token for the local control broker"),
140
+ line("CROCHE_CONTROL_URL", "Control broker (default http://127.0.0.1:8791)"),
141
+ "",
142
+ "Examples",
143
+ " croche login",
144
+ ' croche projects create --name "My app"',
145
+ " croche debug-keys create --project <project-id>",
146
+ "",
147
+ "Exit codes: 0 ok, 1 remote error, 2 usage or config, 3 auth, 4 network/timeout"
148
+ ];
149
+ function overview() {
150
+ const body = sections.map((s) => [s.title, ...s.rows.map((r) => line(r.label, r.brief))].join("\n")).join("\n\n");
151
+ return ["Croche CLI: build apps on Croche from your terminal.", "", "Usage: croche <command> [options]", "", body, "", ...footer].join("\n") + "\n";
152
+ }
153
+ var runtimeBriefs = {
154
+ "runtime list": "Runtimes attached to the control broker",
155
+ "runtime status": "Status of a local Runtime",
156
+ "runtime history": "Read a local Runtime's messages",
157
+ "runtime send": "Send a message to a local Runtime",
158
+ "runtime cancel": "Cancel a local Runtime's turn",
159
+ "runtime agents list": "List agents in an app-consented attachment",
160
+ "runtime tools": "List a local Runtime's tools",
161
+ "runtime result": "Look up an earlier control request"
162
+ };
163
+ var briefs = { ...Object.fromEntries(sections.flatMap((s) => s.rows.filter((r) => r.paths.length === 1).map((r) => [r.label, r.brief]))), ...runtimeBriefs };
164
+ var flagHelp = {
165
+ project: ["ID", "Project id (or set CROCHE_PROJECT)"],
166
+ "config project": ["ID", "Project id (or set CROCHE_PROJECT)"],
167
+ "project-id": ["ID", "Project id"],
168
+ name: ["NAME", "A name for the key"],
169
+ "projects create name": ["NAME", "Project name (required)"],
170
+ "projects update name": ["NAME", "New project name"],
171
+ "dotenv-file": ["PATH", "Where to write CROCHE_DEBUG_KEY (default ./.env)"],
172
+ force: ["", "Replace an existing CROCHE_DEBUG_KEY value"],
173
+ print: ["", "Also print the key (hidden by default)"],
174
+ port: ["PORT", "Debugger port (default 8790)"],
175
+ "control serve port": ["PORT", "Broker port (default 8791)"],
176
+ "connection-file": ["PATH", "Debugger connection file (default per OS)"],
177
+ "control-connection-file": ["PATH", "Control broker connection file"],
178
+ "studio-origin": ["ORIGIN", "A development Studio, e.g. http://localhost:5173"],
179
+ visibility: ["runtime", "The view to attach (runtime)"],
180
+ "studio-link": ["", "Print a fresh one-time Studio link instead"],
181
+ "runtime-id": ["ID", "The Runtime to act on"],
182
+ "attachment-id": ["ID", "Connected attachment from the live v2 roster"],
183
+ "agent-id": ["ID", "Agent definition from the live roster"],
184
+ instance: ["KEY", "Exact instance key (omit for default instance)"],
185
+ "open-sequence": ["N", "Exact reopen fence from the live roster"],
186
+ revision: ["ID", "Read this draft revision"],
187
+ version: ["N", "Export released patch version N"],
188
+ output: ["PATH", "Write to this file (-o PATH)"],
189
+ base: ["REVISION", "Draft CAS revision last read (null: empty draft)"],
190
+ "bundled-base": ["REVISION", "Build base (or CROCHE_CONFIG_BASE)"],
191
+ note: ["TEXT", "A note for this revision"],
192
+ "policy-file": ["PATH", "JSON runtime policy file"],
193
+ limit: ["N", "How many to return (server limit 500)"],
194
+ "runtime history limit": ["N", "How many messages to return"],
195
+ status: ["STATUS", "Only operations with this status"],
196
+ type: ["TYPE", "Only operations of this type"],
197
+ query: ["TEXT", "Only operations matching this text"],
198
+ period: ["PERIOD", "week, month (default) or all"],
199
+ purpose: ["PURPOSE", "production (default) or development"],
200
+ remote: ["IP", "Explicit viewer-only bind IP (requires --allow-origin)"],
201
+ role: ["ROLE", "Reveal pairing, ingest, observe, or controller token"],
202
+ "allow-origin": ["ORIGIN", "Allow this browser origin (CORS is off otherwise)"],
203
+ "control-url": ["URL", "Broker URL (default CROCHE_CONTROL_URL, then :8791)"],
204
+ "request-id": ["ID", "Request id, so a retry is not sent twice"],
205
+ "runtime result request-id": ["ID", "The request to look up"],
206
+ "wait-ms": ["MS", "How long to wait (send 120000, others 15000)"],
207
+ offset: ["N", "Skip this many messages"],
208
+ id: ["ID", "Input id for this message"],
209
+ text: ["TEXT", "Message text"],
210
+ kind: ["KIND", "user, app_event, app_state (requires send.kind)"],
211
+ "text-file": ["PATH", "Read the message text from a UTF-8 file"],
212
+ amount: ["AMOUNT", "The new budget"]
213
+ };
214
+ function flagLine(path2, flag) {
215
+ const [value2, text2] = flagHelp[`${path2} ${flag}`] ?? flagHelp[`${path2.split(" ")[0]} ${flag}`] ?? flagHelp[flag] ?? ["VALUE", ""];
216
+ return line(`--${flag}${value2 ? " " + value2 : ""}`, text2);
217
+ }
218
+ function wrap(text2, max = 80) {
219
+ const lines = [];
220
+ let current = "";
221
+ for (const word of text2.split(" ")) {
222
+ if (current && current.length + 1 + word.length > max) {
223
+ lines.push(current);
224
+ current = word;
225
+ } else current = current ? current + " " + word : word;
226
+ }
227
+ return [...lines, current].join("\n");
228
+ }
229
+ function commandHelp(command) {
230
+ const flags = [...(command.flags ?? []).filter((f) => f !== "cloud-url"), ...command.switches ?? []];
231
+ const usage = `Usage: croche ${command.path}${(command.positionals ?? []).map((p) => p === "project" ? " [PROJECT_ID]" : ` <${p}>`).join("")}${flags.length ? " [options]" : ""}`;
232
+ const options = flags.length ? ["", "Options", ...flags.map((f) => flagLine(command.path, f))] : [];
233
+ return [usage, "", wrap(command.summary), ...options, "", "All commands: croche --help"].join("\n") + "\n";
234
+ }
235
+ function groupHelp(prefix, group) {
236
+ const rows = group.map((c) => line(c.path, briefs[c.path] ?? ""));
237
+ return [`Commands under croche ${prefix}`, "", ...rows, "", "Options for one command: croche <command> --help"].join("\n") + "\n";
238
+ }
239
+
240
+ // src/credentials.ts
241
+ import { homedir } from "node:os";
242
+ import path from "node:path";
243
+ import { mkdir, chmod, lstat, readFile, open, rename, unlink } from "node:fs/promises";
244
+ import { randomUUID } from "node:crypto";
245
+ var validCredential = (key) => /^dk_[A-Za-z0-9_-]{32,256}$/.test(key) && !key.includes("\n");
246
+ function credentialPath(env, platform = process.platform, home = env.HOME ?? homedir()) {
247
+ if (platform === "win32") {
248
+ const profile = env.USERPROFILE, appData = env.APPDATA;
249
+ if (!profile || !appData || !path.win32.isAbsolute(profile) || !path.win32.isAbsolute(appData)) throw new CliError("invalid_configuration", "A user-profile application-data directory is required.");
250
+ const relative3 = path.win32.relative(profile, appData);
251
+ if (relative3 === ".." || relative3.startsWith("..\\") || path.win32.isAbsolute(relative3)) throw new CliError("invalid_configuration", "Credential storage must be inside the current user profile.");
252
+ return path.win32.join(appData, "croche", "credentials.json");
253
+ }
254
+ const root = platform === "darwin" ? path.join(home, "Library", "Application Support") : env.XDG_CONFIG_HOME ?? path.join(home, ".config");
255
+ if (!path.isAbsolute(root)) throw new CliError("invalid_configuration", "The configuration directory must be absolute.");
256
+ return path.join(root, "croche", "credentials.json");
257
+ }
258
+ function environmentCredential(env) {
259
+ return env.CROCHE_ACCOUNT_KEY;
260
+ }
261
+ function environmentCredentialNames(env) {
262
+ return ["CROCHE_ACCOUNT_KEY"].filter((name) => env[name] !== void 0);
263
+ }
264
+ async function resolveCredential(env) {
265
+ const fromEnv = environmentCredential(env);
266
+ if (fromEnv !== void 0) {
267
+ if (!validCredential(fromEnv)) throw new CliError("missing_credentials", "Supply a valid account key.", 3);
268
+ return { key: fromEnv, source: "env" };
269
+ }
270
+ const file = credentialPath(env);
271
+ try {
272
+ const info = await lstat(file), directory = await lstat(path.dirname(file));
273
+ if (!info.isFile() || info.isSymbolicLink() || directory.isSymbolicLink() || process.platform !== "win32" && ((info.mode & 63) !== 0 || (directory.mode & 63) !== 0)) throw new Error("unsafe");
274
+ const data = JSON.parse(await readFile(file, "utf8"));
275
+ if (!validCredential(data.developer_key)) throw new Error("invalid");
276
+ return { key: data.developer_key, source: "stored" };
277
+ } catch (error) {
278
+ if (error.code === "ENOENT") throw new CliError("missing_credentials", "Ask the user to run croche login in their terminal.", 3);
279
+ throw new CliError("invalid_credentials_file", "Stored credentials are unreadable or insecure; the user should run croche login again.", 3);
280
+ }
281
+ }
282
+ async function storeCredential(env, key) {
283
+ const file = credentialPath(env), directory = path.dirname(file);
284
+ await mkdir(directory, { recursive: true, mode: 448 });
285
+ if ((await lstat(directory)).isSymbolicLink()) throw new CliError("invalid_configuration", "Credential directory must not be a symbolic link.");
286
+ if (process.platform !== "win32") await chmod(directory, 448);
287
+ const temporary = path.join(directory, `.credentials-${randomUUID()}.tmp`);
288
+ let handle;
289
+ try {
290
+ handle = await open(temporary, "wx", 384);
291
+ await handle.writeFile(JSON.stringify({ developer_key: key }) + "\n");
292
+ await handle.sync();
293
+ await handle.close();
294
+ handle = void 0;
295
+ await rename(temporary, file);
296
+ return file;
297
+ } finally {
298
+ try {
299
+ await handle?.close();
300
+ } finally {
301
+ await unlink(temporary).catch(() => {
302
+ });
303
+ }
304
+ }
305
+ }
306
+ async function removeCredential(env) {
307
+ try {
308
+ await unlink(credentialPath(env));
309
+ } catch (error) {
310
+ if (error.code !== "ENOENT") throw error;
311
+ }
312
+ }
313
+ async function readCredentialInput(input = process.stdin, prompt = (text2) => {
314
+ process.stderr.write(text2);
315
+ }) {
316
+ if (!input.isTTY) {
317
+ let text2 = "";
318
+ for await (const chunk of input) {
319
+ text2 += chunk.toString();
320
+ if (text2.length > 512) throw new CliError("invalid_credentials", "Credential input is too long.", 3);
321
+ }
322
+ return text2.replace(/\r?\n$/, "");
323
+ }
324
+ prompt("Account key (hidden): ");
325
+ const wasRaw = input.isRaw, wasFlowing = input.readableFlowing;
326
+ return new Promise((resolve4, reject) => {
327
+ let text2 = "";
328
+ const finish = (error) => {
329
+ input.off("data", data);
330
+ input.off("end", ended);
331
+ input.setRawMode(wasRaw);
332
+ if (wasFlowing !== true) input.pause();
333
+ prompt("\n");
334
+ error ? reject(error) : resolve4(text2);
335
+ };
336
+ const ended = () => finish(new CliError("invalid_credentials", "Credential input ended unexpectedly.", 3));
337
+ const data = (chunk) => {
338
+ for (const char of chunk.toString()) {
339
+ if (char === "\r" || char === "\n") {
340
+ finish();
341
+ return;
342
+ }
343
+ if (char === "") {
344
+ finish(new CliError("cancelled", "Login cancelled.", 2));
345
+ return;
346
+ }
347
+ if (char === "\x7F" || char === "\b") text2 = text2.slice(0, -1);
348
+ else text2 += char;
349
+ if (text2.length > 259) {
350
+ finish(new CliError("invalid_credentials", "Credential input is too long.", 3));
351
+ return;
352
+ }
353
+ }
354
+ };
355
+ input.setRawMode(true);
356
+ input.on("data", data);
357
+ input.once("end", ended);
358
+ input.resume();
359
+ });
360
+ }
361
+
362
+ // src/config-bases.ts
363
+ var count = (value2) => typeof value2 === "number" && Number.isSafeInteger(value2) && value2 >= 0;
364
+ async function listBases(args, context) {
365
+ const project2 = args.project ?? context.env.CROCHE_PROJECT;
366
+ if (!project2 || !/^[A-Za-z0-9_.:-]{1,200}$/.test(project2)) throw new CliError("missing_argument", "Supply --project or CROCHE_PROJECT.");
367
+ const response = await context.request(`/api/studio/projects/${encodeURIComponent(project2)}/config/bases`);
368
+ if (!response || typeof response !== "object" || !("bases" in response) || !Array.isArray(response.bases)) throw new CliError("invalid_response", "Cloud did not return a bases list.", 1);
369
+ const bases = response.bases.map((row2) => {
370
+ if (!row2 || typeof row2 !== "object" || !("revision_id" in row2) || typeof row2.revision_id !== "string" || !("document_known" in row2) || typeof row2.document_known !== "boolean" || !("installs_7d" in row2) || !count(row2.installs_7d) || !("unknown_count" in row2) || !count(row2.unknown_count)) throw new CliError("invalid_response", "Cloud returned an invalid base entry.", 1);
371
+ return {
372
+ revision_id: row2.revision_id,
373
+ document_known: row2.document_known,
374
+ installs_7d: row2.installs_7d,
375
+ unknown_count: row2.unknown_count,
376
+ ...!row2.document_known ? { push_base_hint: `croche config push-base <file> --project ${project2}` } : {}
377
+ };
378
+ });
379
+ return { version: 1, bases };
380
+ }
381
+
382
+ // src/config.ts
383
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
384
+ import { mkdir as mkdir3, readFile as readFile2, rename as rename2, writeFile } from "node:fs/promises";
385
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2 } from "node:path";
386
+
387
+ // src/debugger.ts
388
+ import { spawn } from "node:child_process";
389
+ import { randomBytes } from "node:crypto";
390
+ import { constants } from "node:fs";
391
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, unlink as unlink2 } from "node:fs/promises";
392
+ import { homedir as homedir2 } from "node:os";
393
+
394
+ // src/collector-credential.ts
395
+ function collectorCredential(control) {
396
+ if (!control.observe_token) return;
397
+ return { url: control.url, token: control.observe_token };
398
+ }
399
+
400
+ // src/debugger.ts
401
+ import { dirname, isAbsolute, join, resolve } from "node:path";
402
+ import { fileURLToPath } from "node:url";
403
+
404
+ // src/control-client.ts
405
+ var identifier = (v) => typeof v === "string" && /^[A-Za-z0-9_.:-]{1,200}$/.test(v);
406
+ var errorCode = (v) => typeof v === "string" && /^[a-z][a-z0-9_]{0,99}$/.test(v) ? v : "control_error";
407
+ function endpoint(value2) {
408
+ let url;
409
+ try {
410
+ url = new URL(value2);
411
+ } catch {
412
+ throw new CliError("invalid_configuration", "Control URL must be a loopback HTTP origin.");
413
+ }
414
+ if (url.protocol !== "http:" || !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) || url.username || url.password || url.search || url.hash || url.pathname !== "/") throw new CliError("invalid_configuration", "Control URL must be a loopback HTTP origin.");
415
+ return url.origin;
416
+ }
417
+ function integer(value2, fallback, min, max) {
418
+ if (value2 === void 0) return fallback;
419
+ if (!/^\d+$/.test(value2) || !Number.isSafeInteger(Number(value2)) || Number(value2) < min || Number(value2) > max) throw new CliError("invalid_argument", `Expected an integer between ${min} and ${max}.`);
420
+ return Number(value2);
421
+ }
422
+ async function requestControl(command, args, env, transport = fetch, commandPayload) {
423
+ const origin2 = endpoint(args["control-url"] ?? env.CROCHE_CONTROL_URL ?? "http://127.0.0.1:8791"), token = env.CROCHE_CONTROL_TOKEN;
424
+ if (!token || !/^[A-Za-z0-9._~-]{24,4096}$/.test(token)) throw new CliError("missing_credentials", "Set CROCHE_CONTROL_TOKEN to the separate observe/controller credential.", 3);
425
+ const request = async (path2, body) => {
426
+ let response2;
427
+ try {
428
+ response2 = await transport(origin2 + "/v2/control" + path2, { method: body === void 0 ? "GET" : "POST", headers: { Authorization: "Bearer " + token, ...body === void 0 ? {} : { "Content-Type": "application/json" } }, ...body === void 0 ? {} : { body: JSON.stringify(body) }, credentials: "omit", redirect: "error", signal: AbortSignal.timeout(5e3) });
429
+ } catch {
430
+ throw new CliError("transport_error", "Control request failed; it was not resubmitted.", 4);
431
+ }
432
+ const data = await readResponse(response2);
433
+ if (!response2.ok) throw new CliError(errorCode(data?.error?.code), "Control v2 refused the request. No command was resubmitted.", [401, 403].includes(response2.status) ? 3 : 1);
434
+ return data;
435
+ };
436
+ if (command === "list") return request("/attachments");
437
+ if (command === "result") {
438
+ if (!identifier(args["request-id"])) throw new CliError("invalid_argument", "Supply --request-id.");
439
+ return request("/requests/" + encodeURIComponent(args["request-id"]));
440
+ }
441
+ if (!["agents.list", "status", "history", "send", "cancel", "tools"].includes(command)) throw new CliError("unsupported_capability", "Unknown or retired control command.");
442
+ if (!identifier(args["attachment-id"])) throw new CliError("invalid_argument", "Supply --attachment-id from the live v2 roster.");
443
+ const attachmentId = args["attachment-id"], requestId = args["request-id"] ?? crypto.randomUUID();
444
+ if (!identifier(requestId)) throw new CliError("invalid_argument", "Invalid --request-id.");
445
+ let target2;
446
+ if (command !== "agents.list") {
447
+ if (!identifier(args["agent-id"]) || args["open-sequence"] === void 0 || args.instance !== void 0 && !identifier(args.instance)) throw new CliError("invalid_argument", "Supply --agent-id and --open-sequence from the exact open row; --instance names a non-default instance.");
448
+ target2 = { agentId: args["agent-id"], instance: args.instance ?? null, openSequence: integer(args["open-sequence"], 0, 0, Number.MAX_SAFE_INTEGER) };
449
+ }
450
+ let payload = commandPayload ?? {};
451
+ if (command === "send") {
452
+ if (!identifier(args.id) || typeof args.text !== "string" || args.kind !== void 0 && !["user", "app_event", "app_state"].includes(args.kind)) throw new CliError("invalid_argument", "send requires a stable --id, text and an optional user/app_event/app_state kind.");
453
+ if (args.kind !== void 0) {
454
+ const roster = await request("/attachments");
455
+ const live = roster.attachments?.find((a) => a.attachmentId === attachmentId && a.state === "connected");
456
+ if (!live?.capabilities?.includes("send") || !live.capabilities.includes("send.kind")) throw new CliError("unsupported_capability", "The live Runtime must advertise send and send.kind to use --kind.");
457
+ }
458
+ payload = { id: args.id, text: args.text, ...args.kind === void 0 ? {} : { kind: args.kind } };
459
+ }
460
+ if (command === "history") payload = { offset: integer(args.offset, 0, 0, 1e6), limit: integer(args.limit, 100, 1, 1e3) };
461
+ const wait = integer(args["wait-ms"], command === "send" ? 12e4 : 15e3, 0, 6e5), deadline = Date.now() + wait;
462
+ let response = await request("/commands", { attachmentId, request_id: requestId, command, ...target2 ? { target: target2 } : {}, payload });
463
+ const validate2 = () => {
464
+ const r = response?.request;
465
+ if (r?.request_id !== requestId || r.attachmentId !== attachmentId || r.command !== command || !same(r.target, target2)) throw new CliError("invalid_response", "Uncorrelated control response; inspect the original request ID, never resend.", 4, { request_id: requestId });
466
+ };
467
+ validate2();
468
+ while (["queued", "dispatched"].includes(response.request.status) && Date.now() < deadline) {
469
+ await new Promise((resolve4) => setTimeout(resolve4, 200));
470
+ response = await request("/requests/" + encodeURIComponent(requestId));
471
+ validate2();
472
+ }
473
+ if (response.request.status === "failed") throw new CliError(errorCode(response.request.error?.code), "Control command failed. No automatic resend.", 1, { request_id: requestId, uncertain: response.request.error?.uncertain === true });
474
+ if (response.request.status !== "completed") throw new CliError("control_pending", "Outcome pending; inspect this request ID, not a replacement.", 4, { request_id: requestId, status: response.request.status });
475
+ return response;
476
+ }
477
+
478
+ // src/text-file.ts
479
+ function decodeTextFile(content, what) {
480
+ if (typeof content !== "string") {
481
+ if (content.length >= 2 && (content[0] === 255 && content[1] === 254 || content[0] === 254 && content[1] === 255))
482
+ throw new CliError("unsupported_encoding", `${what} is UTF-16 (${content[0] === 255 ? "little" : "big"}-endian); save it as UTF-8. In Windows PowerShell 5.1 use [IO.File]::WriteAllText(path, text); in pwsh 7, Set-Content writes UTF-8.`);
483
+ content = Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString("utf8");
484
+ }
485
+ return content.charCodeAt(0) === 65279 ? content.slice(1) : content;
486
+ }
487
+
488
+ // src/debugger.ts
489
+ var delay = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
490
+ var safeToken = (value2, min = 16) => typeof value2 === "string" && new RegExp(`^[A-Za-z0-9._~-]{${min},4096}$`).test(value2);
491
+ var terminalLabel = (value2) => value2.replace(/[\u0000-\u001f\u007f-\u009f\u2028-\u202e\u2066-\u2069]/g, "").slice(0, 180);
492
+ function validRemote(address, origins) {
493
+ if (!remoteAddress(address) || !Array.isArray(origins) || !origins.length || origins.length > 16) return false;
494
+ return origins.every((value2) => {
495
+ try {
496
+ const u = new URL(value2);
497
+ return typeof value2 === "string" && u.origin === value2 && ["http:", "https:"].includes(u.protocol);
498
+ } catch {
499
+ return false;
500
+ }
501
+ });
502
+ }
503
+ function origin(value2) {
504
+ let url;
505
+ try {
506
+ url = new URL(String(value2));
507
+ } catch {
508
+ throw new CliError("invalid_connection", "Connection file needs a loopback HTTP origin.");
509
+ }
510
+ if (url.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(url.hostname) || url.username || url.password || url.search || url.hash || url.pathname !== "/") throw new CliError("invalid_connection", "Connection file needs a loopback HTTP origin without credentials or a path.");
511
+ return url.origin;
512
+ }
513
+ function portNumber(value2, fallback) {
514
+ if (value2 === void 0) return fallback;
515
+ if (!/^\d+$/.test(value2) || Number(value2) < 1 || Number(value2) > 65535) throw new CliError("invalid_argument", "Port must be an integer from 1 to 65535.");
516
+ return Number(value2);
517
+ }
518
+ function defaultConnectionFile(kind, env = process.env, port = kind === "debugger" ? 8790 : 8791) {
519
+ const state = env.CROCHE_STATE_DIR ?? (process.platform === "win32" ? env.LOCALAPPDATA ?? join(homedir2(), "AppData", "Local") : process.platform === "darwin" ? join(homedir2(), "Library", "Application Support") : env.XDG_STATE_HOME ?? join(homedir2(), ".local", "state"));
520
+ if (!isAbsolute(state)) throw new CliError("invalid_configuration", "The OS user state directory must be absolute.");
521
+ return join(state, "croche", kind, port === (kind === "debugger" ? 8790 : 8791) ? "connection.json" : `connection-${port}.json`);
522
+ }
523
+ function location(kind, args, env) {
524
+ const configured = kind === "control" ? env.CROCHE_CONTROL_URL : void 0;
525
+ const url = configured ? origin(configured) : `http://127.0.0.1:${portNumber(kind === "debugger" ? args.port : void 0, kind === "debugger" ? 8790 : 8791)}`;
526
+ const port = Number(new URL(url).port || 80);
527
+ const file = resolve(kind === "debugger" ? args["connection-file"] ?? defaultConnectionFile(kind, env, port) : args["control-connection-file"] ?? env.CROCHE_CONTROL_CONNECTION_FILE ?? defaultConnectionFile(kind, env, port));
528
+ return { url, file, explicitPort: kind === "debugger" ? args.port !== void 0 : Boolean(configured) };
529
+ }
530
+ async function readConnection(file, kind) {
531
+ let parent = dirname(file);
532
+ while (parent !== dirname(parent)) {
533
+ try {
534
+ const info = await lstat2(parent);
535
+ if (info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 18) !== 0 && (info.mode & 512) === 0) throw new CliError("insecure_connection_file", "Connection directories must not be symbolic links or writable by other users.");
536
+ } catch (error) {
537
+ if (error.code !== "ENOENT") throw error;
538
+ }
539
+ parent = dirname(parent);
540
+ }
541
+ let handle;
542
+ try {
543
+ handle = await open2(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
544
+ } catch (error) {
545
+ if (error.code === "ENOENT") return;
546
+ throw new CliError("invalid_connection_file", "The private connection file could not be opened.");
547
+ }
548
+ try {
549
+ const stat = await handle.stat();
550
+ if (!stat.isFile() || stat.size > 16384 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || process.getuid && stat.uid !== process.getuid())) throw new CliError("insecure_connection_file", "The connection file must be owned by this user with mode 0600.");
551
+ let data;
552
+ try {
553
+ data = JSON.parse(decodeTextFile(await handle.readFile(), "The connection file"));
554
+ } catch (error) {
555
+ if (error instanceof CliError) throw error;
556
+ throw new CliError("invalid_connection_file", "The connection file must contain valid JSON.");
557
+ }
558
+ const url = origin(data?.url), token = kind === "debugger" ? data.pairingToken : data.token;
559
+ if (!safeToken(token, kind === "control" ? 24 : 16)) throw new CliError("invalid_connection_file", "The connection file does not contain a valid local token.");
560
+ if (kind === "control" && data.observe_token !== void 0 && (!safeToken(data.observe_token, 24) || [token, data.ingest_token].includes(data.observe_token))) throw new CliError("invalid_connection_file", "Observe credentials must be distinct from controller and ingest credentials.");
561
+ if (kind === "control" && data.remoteAddress !== void 0 && !validRemote(data.remoteAddress, data.origins)) throw new CliError("invalid_connection_file", "Remote viewer settings need an explicit IP and exact origin list.");
562
+ if (kind === "control" && (data.controlVersion !== 2 || !safeToken(data.ingest_token, 24) || data.ingest_token === token)) throw new CliError("protocol_mismatch", "Use a v2 private connection file with separate controller and ingest credentials.");
563
+ return { url, token, file, ...kind === "control" ? { ingest_token: data.ingest_token, ...data.observe_token ? { observe_token: data.observe_token } : {}, ...data.remoteAddress ? { remoteAddress: remoteAddress(data.remoteAddress), origins: data.origins } : {} } : {} };
564
+ } finally {
565
+ await handle.close();
566
+ }
567
+ }
568
+ async function probe(kind, connection, transport) {
569
+ return (await inspect(kind, connection, transport)).state;
570
+ }
571
+ async function inspect(kind, connection, transport) {
572
+ let response;
573
+ try {
574
+ response = await transport(connection.url + (kind === "debugger" ? "/api/probe" : "/v2/control/attachments"), { headers: connection.token ? { Authorization: `Bearer ${connection.token}` } : {}, credentials: "omit", redirect: "error", signal: AbortSignal.timeout(1e3) });
575
+ } catch (error) {
576
+ return { state: error?.cause?.code === "ECONNREFUSED" ? "offline" : "occupied" };
577
+ }
578
+ const reader = response.body?.getReader();
579
+ if (!reader) return { state: "occupied" };
580
+ try {
581
+ let raw = "", bytes = 0;
582
+ while (true) {
583
+ const next = await reader.read();
584
+ if (next.done) break;
585
+ bytes += next.value.byteLength;
586
+ if (bytes > 65536) return { state: "occupied" };
587
+ raw += new TextDecoder().decode(next.value);
588
+ }
589
+ const data = JSON.parse(raw);
590
+ if (!(response.ok && (kind === "debugger" ? data?.ok === true && typeof data.paused === "boolean" : Array.isArray(data?.attachments)))) return { state: "occupied" };
591
+ return { state: "running", ...Number.isSafeInteger(data.pid) && data.pid > 0 ? { pid: data.pid } : {} };
592
+ } catch {
593
+ return { state: "occupied" };
594
+ } finally {
595
+ void reader.cancel().catch(() => {
596
+ });
597
+ }
598
+ }
599
+ function studioOrigin(value2) {
600
+ if (value2 === void 0) return [];
601
+ let url;
602
+ try {
603
+ url = new URL(value2);
604
+ } catch {
605
+ throw new CliError("invalid_argument", "--studio-origin must be an origin such as http://localhost:5173.");
606
+ }
607
+ if (url.origin !== value2 || !(url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname))) throw new CliError("invalid_argument", "--studio-origin must be an HTTPS origin, or an HTTP loopback origin, with no path.");
608
+ return [url.origin];
609
+ }
610
+ async function studioLink(connection, transport, wanted) {
611
+ let data;
612
+ try {
613
+ const response = await transport(connection.url + "/api/debug/codes", { method: "POST", headers: { Authorization: `Bearer ${connection.token}` }, credentials: "omit", redirect: "error", signal: AbortSignal.timeout(2e3) });
614
+ if (!response.ok) throw new Error();
615
+ data = await response.json();
616
+ } catch {
617
+ throw new CliError("studio_link_unavailable", "The running debugger could not issue a Studio link. Restart it with this CLI version.", 4);
618
+ }
619
+ if (typeof data?.studioUrl !== "string" || typeof data?.expires_at !== "string") throw new CliError("studio_link_unavailable", "The running debugger returned no Studio link.", 4);
620
+ if (wanted.length && !data.studioUrl.startsWith(wanted[0] + "/")) throw new CliError("studio_origin_unavailable", "The running debugger was started without that Studio origin. Stop it, then run croche debug start --studio-origin ORIGIN.");
621
+ return { studioUrl: data.studioUrl, expiresAt: data.expires_at };
622
+ }
623
+ async function launch(kind, connection, options = {}) {
624
+ const port = new URL(connection.url).port || "80";
625
+ const script = fileURLToPath(new URL(kind === "debugger" ? "./debugger/server/server.js" : "./bin.js", import.meta.url));
626
+ const env = {};
627
+ for (const name of ["PATH", "SystemRoot", "WINDIR", "TMPDIR", "TEMP"]) if (process.env[name]) env[name] = process.env[name];
628
+ if (kind === "debugger") {
629
+ env.CROCHE_DEBUGGER_PORT = port;
630
+ env.CROCHE_DEBUGGER_TOKEN = connection.token;
631
+ if (options.studioOrigins?.length) env.CROCHE_DEBUGGER_STUDIO_ORIGINS = options.studioOrigins.join(",");
632
+ } else {
633
+ env.CROCHE_CONTROL_TOKEN = connection.token;
634
+ env.CROCHE_CONTROL_INGEST_TOKEN = connection.ingest_token;
635
+ env.CROCHE_CONTROL_OBSERVE_TOKEN = connection.observe_token;
636
+ }
637
+ if (kind === "debugger" && options.control) {
638
+ env.CROCHE_DEBUGGER_CONTROL_URL = options.control.url;
639
+ env.CROCHE_DEBUGGER_CONTROL_TOKEN = options.control.token;
640
+ }
641
+ if (kind === "debugger" && options.remoteControlOrigins?.length) env.CROCHE_DEBUGGER_REMOTE_CONTROL_ORIGINS = options.remoteControlOrigins.join(",");
642
+ const child = spawn(process.execPath, [script, ...kind === "control" ? ["control", "serve", "--port", port, ...connection.origins?.length || options.viewerOrigin ? ["--allow-origin", [options.viewerOrigin, ...connection.origins ?? []].filter(Boolean).join(",")] : [], ...connection.remoteAddress ? ["--remote", connection.remoteAddress] : []] : []], { detached: true, stdio: "ignore", windowsHide: true, env });
643
+ await new Promise((yes, no) => {
644
+ child.once("spawn", yes);
645
+ child.once("error", () => no(new CliError("debug_start_failed", "The bundled local service could not start.", 4)));
646
+ });
647
+ child.unref();
648
+ return child.pid;
649
+ }
650
+ var runFile = (file) => file + ".pid";
651
+ async function readRun(file) {
652
+ let handle;
653
+ try {
654
+ handle = await open2(runFile(file), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
655
+ } catch {
656
+ return;
657
+ }
658
+ try {
659
+ const stat = await handle.stat();
660
+ if (!stat.isFile() || stat.size > 1024) return;
661
+ const data = JSON.parse((await handle.readFile()).toString("utf8"));
662
+ return Number.isSafeInteger(data?.pid) && data.pid > 0 && typeof data.url === "string" ? { pid: data.pid, url: data.url } : void 0;
663
+ } catch {
664
+ return;
665
+ } finally {
666
+ await handle.close();
667
+ }
668
+ }
669
+ async function writeRun(file, pid, url) {
670
+ await unlink2(runFile(file)).catch(() => {
671
+ });
672
+ let handle;
673
+ try {
674
+ handle = await open2(runFile(file), "wx", 384);
675
+ await handle.writeFile(JSON.stringify({ pid, url }) + "\n");
676
+ } catch {
677
+ } finally {
678
+ await handle?.close();
679
+ }
680
+ }
681
+ async function locked(file, body) {
682
+ const lockFile = file + ".lock", deadline = Date.now() + 6e3;
683
+ let lock;
684
+ while (!lock) {
685
+ try {
686
+ lock = await open2(lockFile, "wx", 384);
687
+ } catch (error) {
688
+ if (error.code !== "EEXIST") throw new CliError("connection_write_failed", "The private connection directory is not writable.");
689
+ if (Date.now() >= deadline) throw new CliError("connection_busy", "Another local service startup or stop owns the connection lock. Retry after it finishes.");
690
+ await delay(100);
691
+ }
692
+ }
693
+ try {
694
+ return await body();
695
+ } finally {
696
+ await lock.close();
697
+ await unlink2(lockFile).catch(() => {
698
+ });
699
+ }
700
+ }
701
+ async function ensure(kind, args, context, start, control) {
702
+ if (kind === "control" && args.remote !== void 0 && !validRemote(args.remote, args["allow-origin"]?.split(",") ?? [])) throw new CliError("invalid_argument", "--remote requires an explicit non-loopback IP and an exact origin list; wildcard binds are refused.");
703
+ if (kind === "control" && args.remote !== void 0) args = { ...args, remote: remoteAddress(args.remote) };
704
+ const selected = location(kind, args, context.env), transport = context.fetch ?? fetch;
705
+ async function load() {
706
+ const saved = await readConnection(selected.file, kind);
707
+ if (kind === "control" && args.remote && saved && (saved.remoteAddress !== args.remote || JSON.stringify(saved.origins) !== JSON.stringify(args["allow-origin"]?.split(",") ?? []))) throw new CliError("connection_conflict", "The saved broker has different remote-viewer settings. Restart it explicitly with a separate connection file.");
708
+ if (saved && selected.explicitPort && saved.url !== selected.url) throw new CliError("connection_conflict", "The configured port and saved connection do not match. Use a separate connection file.");
709
+ if (kind === "control" && context.env.CROCHE_CONTROL_TOKEN) {
710
+ if (!safeToken(context.env.CROCHE_CONTROL_TOKEN, 24)) throw new CliError("invalid_configuration", "CROCHE_CONTROL_TOKEN must be a valid local token.");
711
+ if (!safeToken(context.env.CROCHE_CONTROL_INGEST_TOKEN, 24) || context.env.CROCHE_CONTROL_INGEST_TOKEN === context.env.CROCHE_CONTROL_TOKEN) throw new CliError("invalid_configuration", "Set a distinct CROCHE_CONTROL_INGEST_TOKEN for runtime attachment.");
712
+ const observed = context.env.CROCHE_CONTROL_OBSERVE_TOKEN;
713
+ if (observed !== void 0 && (!safeToken(observed, 24) || [context.env.CROCHE_CONTROL_TOKEN, context.env.CROCHE_CONTROL_INGEST_TOKEN].includes(observed))) throw new CliError("invalid_configuration", "CROCHE_CONTROL_OBSERVE_TOKEN must be a distinct observe credential.");
714
+ if (saved && (saved.token !== context.env.CROCHE_CONTROL_TOKEN || saved.url !== selected.url)) throw new CliError("connection_conflict", "The control environment and saved connection do not match.");
715
+ if (saved && saved.ingest_token !== context.env.CROCHE_CONTROL_INGEST_TOKEN) throw new CliError("connection_conflict", "The saved ingest credential does not match the environment.");
716
+ if (saved && observed !== void 0 && saved.observe_token !== observed) throw new CliError("connection_conflict", "The saved observe credential does not match the environment.");
717
+ return saved ?? { ...selected, token: context.env.CROCHE_CONTROL_TOKEN, ingest_token: context.env.CROCHE_CONTROL_INGEST_TOKEN, ...observed ? { observe_token: observed } : {}, ...args.remote ? { remoteAddress: args.remote, origins: args["allow-origin"]?.split(",") ?? [] } : {} };
718
+ }
719
+ return saved;
720
+ }
721
+ let connection = await load();
722
+ let status = connection ? await probe(kind, connection, transport) : "not_configured";
723
+ if (!start || status === "running") return { connection, status, started: false, file: selected.file, url: connection?.url ?? selected.url };
724
+ try {
725
+ await mkdir2(dirname(selected.file), { recursive: true, mode: 448 });
726
+ } catch (error) {
727
+ throw new CliError("connection_write_failed", `The private connection directory ${dirname(selected.file)} could not be created (${error.code ?? "unknown error"}). Choose a writable location with --${kind === "debugger" ? "connection-file" : "control-connection-file"}.`);
728
+ }
729
+ return locked(selected.file, async () => {
730
+ connection = await load();
731
+ const checked = connection ?? { ...selected, token: "" };
732
+ status = await probe(kind, checked, transport);
733
+ if (status === "running") return { connection, status, started: false, file: selected.file, url: checked.url };
734
+ if (status !== "offline") throw new CliError("local_port_occupied", "The local port is occupied or cannot be authenticated. Import its existing private connection file; the running service was not changed.", 4);
735
+ if (!connection) connection = { ...selected, token: randomBytes(32).toString("hex"), ...kind === "control" ? { ingest_token: randomBytes(32).toString("hex"), observe_token: randomBytes(32).toString("hex"), ...args.remote ? { remoteAddress: args.remote, origins: args["allow-origin"]?.split(",") ?? [] } : {} } : {} };
736
+ const content = kind === "debugger" ? { url: connection.url, pairedUrl: `${connection.url}/#token=${connection.token}`, pairingToken: connection.token } : { controlVersion: 2, url: connection.url, token: connection.token, ingest_token: connection.ingest_token, ...connection.observe_token ? { observe_token: connection.observe_token } : {}, ...connection.remoteAddress ? { remoteAddress: connection.remoteAddress, origins: connection.origins } : {} };
737
+ let file;
738
+ try {
739
+ file = await open2(selected.file, "wx", 384);
740
+ await file.writeFile(JSON.stringify(content) + "\n");
741
+ await file.sync();
742
+ } catch (error) {
743
+ if (error.code !== "EEXIST") throw new CliError("connection_write_failed", "The private connection file could not be saved.");
744
+ } finally {
745
+ await file?.close();
746
+ }
747
+ const reread = await readConnection(selected.file, kind);
748
+ if (!reread || reread.token !== connection.token || reread.url !== connection.url) throw new CliError("connection_conflict", "The connection changed during startup; no service was launched.");
749
+ const viewer = kind === "control" ? location("debugger", args, context.env) : void 0;
750
+ const viewerOrigin = viewer ? (await readConnection(viewer.file, "debugger"))?.url ?? viewer.url : void 0;
751
+ const remoteControlOrigins = (context.env.CROCHE_DEBUGGER_REMOTE_CONTROL_ORIGINS ?? "").split(",").filter(Boolean);
752
+ if (control?.remoteAddress) {
753
+ const host = control.remoteAddress.includes(":") ? "[" + control.remoteAddress + "]" : control.remoteAddress;
754
+ remoteControlOrigins.push("http://" + host + ":" + (new URL(control.url).port || "80"));
755
+ }
756
+ const bridge = control ? collectorCredential(control) : void 0;
757
+ if (control && !bridge) throw new CliError("missing_configuration", "The collector bridge requires a distinct observe credential. Configure CROCHE_CONTROL_OBSERVE_TOKEN with the broker; no controller fallback is allowed.");
758
+ const pid = await (context.launch ?? launch)(kind, connection, { studioOrigins: studioOrigin(args["studio-origin"]), control: bridge, viewerOrigin, remoteControlOrigins });
759
+ if (kind === "debugger" && typeof pid === "number") await writeRun(selected.file, pid, connection.url);
760
+ const readyDeadline = Date.now() + 5e3;
761
+ while (Date.now() < readyDeadline) {
762
+ if (await probe(kind, connection, transport) === "running") return { connection, status: "running", started: true, file: selected.file, url: connection.url };
763
+ await delay(100);
764
+ }
765
+ throw new CliError("debug_start_failed", "The local service did not become ready. Its saved token was preserved; no existing service was stopped.", 4);
766
+ });
767
+ }
768
+ async function stop(args, context) {
769
+ const selected = location("debugger", args, context.env), transport = context.fetch ?? fetch;
770
+ const saved = await readConnection(selected.file, "debugger");
771
+ if (!saved) return { status: "not_configured", stopped: false, url: selected.url, connectionFile: selected.file, instruction: "No debugger connection is saved here, so no debugger started by this CLI is running. Nothing was stopped." };
772
+ return locked(selected.file, async () => {
773
+ const connection = await readConnection(selected.file, "debugger");
774
+ if (!connection) return { status: "not_configured", stopped: false, url: selected.url, connectionFile: selected.file, instruction: "No debugger connection is saved here. Nothing was stopped." };
775
+ if (selected.explicitPort && connection.url !== selected.url) throw new CliError("connection_conflict", "The configured port and saved connection do not match. Use a separate connection file.");
776
+ const done = (method) => ({
777
+ status: "offline",
778
+ stopped: method !== void 0,
779
+ ...method ? { method } : {},
780
+ url: connection.url,
781
+ connectionFile: selected.file,
782
+ instruction: method ? "The debugger stopped; its captures are discarded. The pairing token is kept: croche debug start reuses it." : "The debugger is not running. Nothing was stopped. The pairing token is kept: croche debug start reuses it."
783
+ });
784
+ async function stopped(ms) {
785
+ const deadline = Date.now() + ms;
786
+ while (true) {
787
+ if (await probe("debugger", connection, transport) === "offline") return true;
788
+ if (Date.now() >= deadline) return false;
789
+ await delay(100);
790
+ }
791
+ }
792
+ const first = await inspect("debugger", connection, transport);
793
+ if (first.state === "offline") {
794
+ await unlink2(runFile(selected.file)).catch(() => {
795
+ });
796
+ return done(void 0);
797
+ }
798
+ if (first.state === "occupied") throw new CliError("local_port_occupied", "The debugger port is in use but did not answer as this collector (or not in time). Nothing was stopped.", 4);
799
+ let asked = false;
800
+ try {
801
+ asked = (await transport(connection.url + "/api/shutdown", { method: "POST", headers: { Authorization: `Bearer ${connection.token}` }, credentials: "omit", redirect: "error", signal: AbortSignal.timeout(2e3) })).ok;
802
+ } catch {
803
+ asked = true;
804
+ }
805
+ if (await stopped(asked ? 5e3 : 0)) {
806
+ await unlink2(runFile(selected.file)).catch(() => {
807
+ });
808
+ return done("shutdown");
809
+ }
810
+ const run = await readRun(selected.file), now = await inspect("debugger", connection, transport);
811
+ if (run && run.url === connection.url && now.state === "running" && now.pid === run.pid) {
812
+ try {
813
+ process.kill(run.pid);
814
+ } catch (error) {
815
+ if (error.code !== "ESRCH") throw new CliError("debug_stop_failed", "The debugger process could not be terminated.", 4);
816
+ }
817
+ if (await stopped(5e3)) {
818
+ await unlink2(runFile(selected.file)).catch(() => {
819
+ });
820
+ return done("terminated");
821
+ }
822
+ }
823
+ throw new CliError("debug_stop_failed", `The debugger is still running${asked ? "" : " (it predates croche debug stop)"} and its process could not be verified, so nothing was killed. Stop it from the terminal or task manager that shows its process.`, 4);
824
+ });
825
+ }
826
+ function publicStatus(value2) {
827
+ return { status: value2.status, url: value2.url, connectionFile: value2.file, started: value2.started };
828
+ }
829
+ async function debugCommand(action, args, context) {
830
+ if (action === "stop") return stop(args, context);
831
+ if (action === "status") return publicStatus(await ensure("debugger", args, context, false));
832
+ if (action === "token") {
833
+ const role = args.role ?? "pairing";
834
+ if (!["pairing", "ingest", "observe", "controller"].includes(role)) throw new CliError("invalid_argument", "--role must be pairing, ingest, observe, or controller.");
835
+ if (role !== "pairing") {
836
+ const selected2 = await ensure("control", args, context, false);
837
+ if (!selected2.connection) throw new CliError("not_configured", "Run croche debug start to create broker credentials.");
838
+ const token = role === "ingest" ? selected2.connection.ingest_token : role === "observe" ? selected2.connection.observe_token : selected2.connection.token;
839
+ if (!token) throw new CliError("missing_configuration", "The selected broker has no credential for this role.");
840
+ return { role, url: selected2.connection.url, token };
841
+ }
842
+ const selected = await ensure("debugger", args, context, false);
843
+ if (!selected.connection) throw new CliError("not_configured", "Run croche debug start to create a debugger connection.");
844
+ return { pairingToken: selected.connection.token };
845
+ }
846
+ const origins = studioOrigin(args["studio-origin"]);
847
+ if (action === "start") {
848
+ const broker = await ensure("control", args, context, true);
849
+ const started = await ensure("debugger", args, context, true, broker.connection), next = "The app must opt in using its ingest credential. Run croche debug runtimes to list connected attachments.";
850
+ let link2;
851
+ try {
852
+ link2 = await studioLink(started.connection, context.fetch ?? fetch, origins);
853
+ } catch (error) {
854
+ if (error instanceof CliError && error.code === "studio_link_unavailable" && !origins.length) return { ...publicStatus(started), instruction: `${next} This debugger cannot issue Studio links; restart it with this CLI version to observe from Studio.` };
855
+ throw error;
856
+ }
857
+ return { ...publicStatus(started), ...link2, instruction: `Open studioUrl in Studio to observe this debugger (one use, 10 minutes; croche debug --studio-link issues another). ${next}` };
858
+ }
859
+ if (action === "choose" && args["studio-link"] !== void 0) {
860
+ if (args["studio-link"] !== "true") throw new CliError("invalid_argument", "--studio-link takes no value.");
861
+ const broker = await ensure("control", args, context, true);
862
+ const started = await ensure("debugger", args, context, true, broker.connection);
863
+ return { ...await studioLink(started.connection, context.fetch ?? fetch, origins), instruction: "Open this link in Studio to observe runtime-visibility events from this debugger. It works once, for 10 minutes." };
864
+ }
865
+ const control = await ensure("control", args, context, true), connection = control.connection;
866
+ const env = { ...context.env, CROCHE_CONTROL_URL: connection.url, CROCHE_CONTROL_TOKEN: connection.token };
867
+ async function discover() {
868
+ try {
869
+ return await requestControl("list", {}, env, context.fetch);
870
+ } catch {
871
+ throw new CliError("control_unavailable", "The local control broker could not list Runtimes.", 4);
872
+ }
873
+ }
874
+ const list = await discover();
875
+ const runtimes = list.attachments.filter((entry) => entry.state === "connected").map((entry) => ({ id: String(entry.attachmentId), label: terminalLabel(String(entry.runtime?.project ?? "Runtime")), agents: entry.agents, capabilities: entry.capabilities }));
876
+ if (action === "runtimes" || action === "choose" && !context.selectRuntime) return { runtimes, instruction: "Select a connected attachment with --attachment-id. App consent is required; this command never attaches an app." };
877
+ if (action === "disconnect") throw new CliError("app_consent_required", "Detach using the app debugger API. Closing a viewer never changes app consent.");
878
+ let attachmentId = args["attachment-id"];
879
+ if (action === "choose") {
880
+ if (!runtimes.length) return { runtimes, instruction: "No Runtime is connected. Attach from your app using the separate ingest credential." };
881
+ attachmentId = await context.selectRuntime(runtimes) ?? "";
882
+ if (!attachmentId) return { cancelled: true };
883
+ }
884
+ if (!runtimes.some((runtime) => runtime.id === attachmentId)) throw new CliError("runtime_not_available", "Select a currently connected --attachment-id.");
885
+ const debuggerState = await ensure("debugger", args, context, true, connection), debuggerConnection = debuggerState.connection;
886
+ const link = await studioLink(debuggerConnection, context.fetch ?? fetch, origins);
887
+ return { attachmentId, observing: true, ...link, viewerUrl: `${debuggerConnection.url}/stage`, instruction: "The app remains in control of consent. Use croche debug token to pair locally; enabling commands requires the separately retrieved controller credential." };
888
+ }
889
+
890
+ // src/config.ts
891
+ var identity = /^sha256:[a-f0-9]{64}$/;
892
+ function revision(value2) {
893
+ if (!identity.test(value2)) throw new CliError("invalid_argument", "Revision must be sha256:<64 lowercase hex characters>.");
894
+ return value2;
895
+ }
896
+ function version(value2) {
897
+ if (!/^[1-9]\d*$/.test(value2) || !Number.isSafeInteger(Number(value2))) throw new CliError("invalid_argument", "Version must be a positive integer.");
898
+ return Number(value2);
899
+ }
900
+ function stateFile(c, project2, bundled) {
901
+ const dir = c.env.CROCHE_CLI_STATE_DIR ?? join2(dirname2(defaultConnectionFile("debugger", c.env)), "..", "config");
902
+ if (!isAbsolute2(dir)) throw new CliError("invalid_configuration", "CROCHE_CLI_STATE_DIR must be absolute.");
903
+ return join2(dir, createHash("sha256").update(`${c.env.CROCHE_CLOUD_URL}|${project2}|${bundled}`).digest("hex") + ".json");
904
+ }
905
+ async function readBase(c, project2, bundled) {
906
+ try {
907
+ const data = JSON.parse(await readFile2(stateFile(c, project2, bundled), "utf8"));
908
+ if (data.revision_id === null) return null;
909
+ return revision(data.revision_id);
910
+ } catch (error) {
911
+ if (error.code === "ENOENT") return null;
912
+ throw new CliError("invalid_state", "Saved config base cannot be read; use --base with an explicit revision.");
913
+ }
914
+ }
915
+ async function remember(c, project2, bundled, id) {
916
+ const file = stateFile(c, project2, bundled), temp = file + "." + randomUUID2() + ".tmp";
917
+ await mkdir3(dirname2(file), { recursive: true, mode: 448 });
918
+ await writeFile(temp, JSON.stringify({ revision_id: id }), { mode: 384 });
919
+ await rename2(temp, file);
920
+ }
921
+ async function configCommand(action, args, c) {
922
+ const project2 = args.project ?? c.env.CROCHE_PROJECT;
923
+ if (!project2 || !/^[A-Za-z0-9_.:-]{1,200}$/.test(project2)) throw new CliError("missing_argument", "Supply --project or CROCHE_PROJECT.");
924
+ const path2 = `/api/studio/projects/${encodeURIComponent(project2)}/config`;
925
+ const selected = args["bundled-base"] ?? c.env.CROCHE_CONFIG_BASE;
926
+ const chooseBase = async () => {
927
+ if (selected !== void 0) return revision(selected);
928
+ const { bases } = await c.request(path2 + "/bases");
929
+ if (!Array.isArray(bases)) throw new CliError("invalid_response", "Invalid config bases response.", 1);
930
+ const known = bases.filter((b) => b.document_known === true);
931
+ if (known.length !== 1) throw new CliError("bundled_base_required", "Choose --bundled-base from config bases: " + JSON.stringify(bases), 2);
932
+ const base = revision(known[0].revision_id);
933
+ c.stderr("Bundled base: " + base + "\n");
934
+ return base;
935
+ };
936
+ if (action === "effective") {
937
+ const bundled = await chooseBase(), preview = await c.request(path2 + "/effective?base=" + encodeURIComponent(bundled));
938
+ if (!preview || typeof preview !== "object" || Array.isArray(preview) || typeof preview.base !== "string" || !identity.test(preview.base) || typeof preview.revision_id !== "string" || !identity.test(preview.revision_id) || !(preview.patch_revision === null || typeof preview.patch_revision === "string" && identity.test(preview.patch_revision)) || !preview.document || typeof preview.document !== "object" || Array.isArray(preview.document))
939
+ throw new CliError("invalid_response", "Cloud returned a malformed effective config.", 1);
940
+ if (preview.base !== bundled) throw new CliError("stale_base", "Effective config does not target the selected bundled base.", 1);
941
+ return preview;
942
+ }
943
+ if (action === "get") {
944
+ if (args.revision && args.version) throw new CliError("invalid_argument", "Choose --revision or --version.");
945
+ if (args.revision) revision(args.revision);
946
+ if (args.version) version(args.version);
947
+ const bundled = await chooseBase(), query = "?base=" + encodeURIComponent(bundled);
948
+ const check = (doc) => {
949
+ if (doc !== null && doc.base !== bundled) throw new CliError("stale_base", "Patch does not target the selected bundled base.", 1);
950
+ return doc;
951
+ };
952
+ let id = null, document = null, exportVersion;
953
+ if (args.version) {
954
+ exportVersion = version(args.version);
955
+ const listed = await c.request(path2 + "/versions" + query);
956
+ const v = listed.versions.find((v2) => v2.version === exportVersion);
957
+ if (!v) throw new CliError("not_found", "Config version not found.", 1);
958
+ id = v.revision_id;
959
+ document = check((await c.request(path2 + "/revisions/" + encodeURIComponent(id))).revision.document);
960
+ } else if (args.revision) {
961
+ id = revision(args.revision);
962
+ document = check((await c.request(path2 + "/revisions/" + encodeURIComponent(id))).revision.document);
963
+ } else {
964
+ const { draft } = await c.request(path2 + "/draft" + query);
965
+ id = draft?.revision_id ?? null;
966
+ document = check(draft?.document ?? null);
967
+ await remember(c, project2, bundled, id);
968
+ }
969
+ if (id) c.stderr(id + "\n");
970
+ const result = exportVersion === void 0 ? document : { version: exportVersion, revision: id, config: document };
971
+ if (args.output) {
972
+ const text2 = JSON.stringify(result, null, 2) + "\n";
973
+ if (c.writeFile) await c.writeFile(args.output, text2);
974
+ else await writeFile(args.output, text2, "utf8");
975
+ return { file: args.output, revision_id: id, ...exportVersion === void 0 ? {} : { version: exportVersion } };
976
+ }
977
+ return result;
978
+ }
979
+ if (action === "save") {
980
+ let document;
981
+ try {
982
+ document = JSON.parse(await c.readFile(args.file, "The config file"));
983
+ } catch (e) {
984
+ if (e instanceof CliError) throw e;
985
+ throw new CliError("invalid_file", "Config file must contain JSON.");
986
+ }
987
+ if (document && typeof document === "object" && "version" in document && "revision" in document && "config" in document) document = document.config;
988
+ const patch = document;
989
+ if (!patch || patch.schema !== 7 || typeof patch.base !== "string") throw new CliError("invalid_configuration", "Save requires a schema-7 patch with document.base.");
990
+ const bundled = revision(patch.base);
991
+ for (const provided of [args["bundled-base"], c.env.CROCHE_CONFIG_BASE]) if (provided !== void 0 && revision(provided) !== bundled) throw new CliError("invalid_configuration", "Bundled base differs from document.base.");
992
+ const base = args.base === void 0 ? await readBase(c, project2, bundled) : args.base === "null" ? null : revision(args.base);
993
+ const result = await c.request(path2 + "/draft?base=" + encodeURIComponent(bundled), "PUT", { document, base_revision: bundled, base_revision_id: base, ...args.note ? { note: args.note } : {} });
994
+ await remember(c, project2, bundled, result.revision_id);
995
+ return result;
996
+ }
997
+ if (action === "list") {
998
+ const bundled = await chooseBase(), query = "?base=" + encodeURIComponent(bundled);
999
+ const [{ versions }, { draft }] = await Promise.all([c.request(path2 + "/versions" + query), c.request(path2 + "/draft" + query)]);
1000
+ if (draft && draft.document?.base !== bundled) throw new CliError("stale_base", "Draft does not target the selected bundled base.", 1);
1001
+ return { versions, draft };
1002
+ }
1003
+ throw new CliError("unknown_command", "Unknown config command.");
1004
+ }
1005
+
1006
+ // src/config-authoring.ts
1007
+ import { mkdir as mkdir4, readFile as readFile3, realpath, rm, writeFile as writeFile2 } from "node:fs/promises";
1008
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join3, relative, resolve as resolve2, sep, win32 } from "node:path";
1009
+
1010
+ // ../../vectors/config-capabilities.json
1011
+ var config_capabilities_default = {
1012
+ schema: 1,
1013
+ capabilities: []
1014
+ };
1015
+
1016
+ // ../../apps/cloud/data/v1.json
1017
+ var v1_default = {
1018
+ n: 1,
1019
+ sha256: "sha256:45bbe15dcb15bffbb46c1725a06eab61b8200adb2808ab1d9f22f4fcabad9b68",
1020
+ object: {
1021
+ schema: 1,
1022
+ n: 1,
1023
+ models: [
1024
+ {
1025
+ id: "anthropic/claude-opus-5.5",
1026
+ status: "offered",
1027
+ reasoning: {
1028
+ default: {},
1029
+ off: null,
1030
+ low: {
1031
+ reasoning: {
1032
+ effort: "low"
1033
+ }
1034
+ },
1035
+ medium: {
1036
+ reasoning: {
1037
+ effort: "medium"
1038
+ }
1039
+ },
1040
+ high: {
1041
+ reasoning: {
1042
+ effort: "high"
1043
+ }
1044
+ }
1045
+ },
1046
+ input_modalities: [
1047
+ "file",
1048
+ "image",
1049
+ "text"
1050
+ ],
1051
+ tokenizer: "claude-5",
1052
+ context_tokens: 1e6
1053
+ },
1054
+ {
1055
+ id: "anthropic/claude-sonnet-5.5",
1056
+ status: "offered",
1057
+ reasoning: {
1058
+ default: {},
1059
+ off: {
1060
+ reasoning: {
1061
+ effort: "minimal"
1062
+ }
1063
+ },
1064
+ low: {
1065
+ reasoning: {
1066
+ effort: "low"
1067
+ }
1068
+ },
1069
+ medium: {
1070
+ reasoning: {
1071
+ effort: "medium"
1072
+ }
1073
+ },
1074
+ high: {
1075
+ reasoning: {
1076
+ effort: "high"
1077
+ }
1078
+ }
1079
+ },
1080
+ input_modalities: [
1081
+ "file",
1082
+ "image",
1083
+ "text"
1084
+ ],
1085
+ tokenizer: "claude-5",
1086
+ context_tokens: 1e6
1087
+ },
1088
+ {
1089
+ id: "deepseek/deepseek-v4-flash-0731",
1090
+ status: "offered",
1091
+ reasoning: {
1092
+ default: {},
1093
+ off: {
1094
+ reasoning: {
1095
+ enabled: false
1096
+ }
1097
+ },
1098
+ low: {
1099
+ reasoning: {
1100
+ enabled: true
1101
+ }
1102
+ },
1103
+ medium: {
1104
+ reasoning: {
1105
+ enabled: true
1106
+ }
1107
+ },
1108
+ high: {
1109
+ reasoning: {
1110
+ enabled: true
1111
+ }
1112
+ }
1113
+ },
1114
+ input_modalities: [
1115
+ "text"
1116
+ ],
1117
+ tokenizer: "deepseek-v4",
1118
+ context_tokens: 1048576
1119
+ },
1120
+ {
1121
+ id: "deepseek/deepseek-v4-pro-0813",
1122
+ status: "offered",
1123
+ reasoning: {
1124
+ default: {},
1125
+ off: {
1126
+ reasoning: {
1127
+ enabled: false
1128
+ }
1129
+ },
1130
+ low: {
1131
+ reasoning: {
1132
+ effort: "low"
1133
+ }
1134
+ },
1135
+ medium: {
1136
+ reasoning: {
1137
+ effort: "medium"
1138
+ }
1139
+ },
1140
+ high: {
1141
+ reasoning: {
1142
+ effort: "high"
1143
+ }
1144
+ }
1145
+ },
1146
+ input_modalities: [
1147
+ "text"
1148
+ ],
1149
+ tokenizer: "deepseek-v4",
1150
+ context_tokens: 1048576
1151
+ },
1152
+ {
1153
+ id: "deepseek/deepseek-v4.1-flash",
1154
+ status: "offered",
1155
+ reasoning: {
1156
+ default: {},
1157
+ off: {
1158
+ reasoning: {
1159
+ enabled: false
1160
+ }
1161
+ },
1162
+ low: {
1163
+ reasoning: {
1164
+ enabled: true
1165
+ }
1166
+ },
1167
+ medium: {
1168
+ reasoning: {
1169
+ enabled: true
1170
+ }
1171
+ },
1172
+ high: {
1173
+ reasoning: {
1174
+ enabled: true
1175
+ }
1176
+ }
1177
+ },
1178
+ input_modalities: [
1179
+ "image",
1180
+ "text"
1181
+ ],
1182
+ tokenizer: "deepseek-v4",
1183
+ context_tokens: 1048576
1184
+ },
1185
+ {
1186
+ id: "google/gemini-3.1-pro-preview",
1187
+ status: "offered",
1188
+ reasoning: {
1189
+ default: {},
1190
+ off: null,
1191
+ low: {
1192
+ reasoning: {
1193
+ effort: "low"
1194
+ }
1195
+ },
1196
+ medium: {
1197
+ reasoning: {
1198
+ effort: "medium"
1199
+ }
1200
+ },
1201
+ high: {
1202
+ reasoning: {
1203
+ effort: "high"
1204
+ }
1205
+ }
1206
+ },
1207
+ input_modalities: [
1208
+ "audio",
1209
+ "file",
1210
+ "image",
1211
+ "text",
1212
+ "video"
1213
+ ],
1214
+ tokenizer: "gemini-3",
1215
+ context_tokens: 1048576
1216
+ },
1217
+ {
1218
+ id: "google/gemini-3.5-flash-lite",
1219
+ status: "offered",
1220
+ reasoning: {
1221
+ default: {},
1222
+ off: {
1223
+ reasoning: {
1224
+ effort: "minimal"
1225
+ }
1226
+ },
1227
+ low: {
1228
+ reasoning: {
1229
+ effort: "low"
1230
+ }
1231
+ },
1232
+ medium: {
1233
+ reasoning: {
1234
+ effort: "medium"
1235
+ }
1236
+ },
1237
+ high: {
1238
+ reasoning: {
1239
+ effort: "high"
1240
+ }
1241
+ }
1242
+ },
1243
+ input_modalities: [
1244
+ "audio",
1245
+ "file",
1246
+ "image",
1247
+ "text",
1248
+ "video"
1249
+ ],
1250
+ tokenizer: "gemini-3",
1251
+ context_tokens: 1048576
1252
+ },
1253
+ {
1254
+ id: "google/gemini-3.8-flash",
1255
+ status: "offered",
1256
+ reasoning: {
1257
+ default: {},
1258
+ off: null,
1259
+ low: {
1260
+ reasoning: {
1261
+ effort: "low"
1262
+ }
1263
+ },
1264
+ medium: {
1265
+ reasoning: {
1266
+ effort: "medium"
1267
+ }
1268
+ },
1269
+ high: {
1270
+ reasoning: {
1271
+ effort: "high"
1272
+ }
1273
+ }
1274
+ },
1275
+ input_modalities: [
1276
+ "audio",
1277
+ "file",
1278
+ "image",
1279
+ "text",
1280
+ "video"
1281
+ ],
1282
+ tokenizer: "gemini-3",
1283
+ context_tokens: 1048576
1284
+ },
1285
+ {
1286
+ id: "google/gemma-4-31b-it",
1287
+ status: "offered",
1288
+ reasoning: {
1289
+ default: {},
1290
+ off: {
1291
+ reasoning: {
1292
+ enabled: false
1293
+ }
1294
+ },
1295
+ low: {
1296
+ reasoning: {
1297
+ enabled: true
1298
+ }
1299
+ },
1300
+ medium: {
1301
+ reasoning: {
1302
+ enabled: true
1303
+ }
1304
+ },
1305
+ high: {
1306
+ reasoning: {
1307
+ enabled: true
1308
+ }
1309
+ }
1310
+ },
1311
+ input_modalities: [
1312
+ "image",
1313
+ "text",
1314
+ "video"
1315
+ ],
1316
+ tokenizer: "gemma-4",
1317
+ context_tokens: 262144
1318
+ },
1319
+ {
1320
+ id: "moonshotai/kimi-k3",
1321
+ status: "offered",
1322
+ reasoning: {
1323
+ default: {},
1324
+ off: {
1325
+ reasoning: {
1326
+ enabled: false
1327
+ }
1328
+ },
1329
+ low: {
1330
+ reasoning: {
1331
+ enabled: true
1332
+ }
1333
+ },
1334
+ medium: {
1335
+ reasoning: {
1336
+ enabled: true
1337
+ }
1338
+ },
1339
+ high: {
1340
+ reasoning: {
1341
+ enabled: true
1342
+ }
1343
+ }
1344
+ },
1345
+ input_modalities: [
1346
+ "image",
1347
+ "text",
1348
+ "video"
1349
+ ],
1350
+ tokenizer: "kimi-k3",
1351
+ context_tokens: 1048576
1352
+ },
1353
+ {
1354
+ id: "openai/gpt-6-astra",
1355
+ status: "offered",
1356
+ reasoning: {
1357
+ default: {},
1358
+ off: null,
1359
+ low: {
1360
+ reasoning: {
1361
+ effort: "low"
1362
+ }
1363
+ },
1364
+ medium: {
1365
+ reasoning: {
1366
+ effort: "medium"
1367
+ }
1368
+ },
1369
+ high: {
1370
+ reasoning: {
1371
+ effort: "high"
1372
+ }
1373
+ }
1374
+ },
1375
+ input_modalities: [
1376
+ "file",
1377
+ "image",
1378
+ "text"
1379
+ ],
1380
+ tokenizer: "gpt-6",
1381
+ context_tokens: 105e4
1382
+ },
1383
+ {
1384
+ id: "openai/gpt-6-luna",
1385
+ status: "offered",
1386
+ reasoning: {
1387
+ default: {},
1388
+ off: {
1389
+ reasoning: {
1390
+ enabled: false
1391
+ }
1392
+ },
1393
+ low: {
1394
+ reasoning: {
1395
+ effort: "low"
1396
+ }
1397
+ },
1398
+ medium: {
1399
+ reasoning: {
1400
+ effort: "medium"
1401
+ }
1402
+ },
1403
+ high: {
1404
+ reasoning: {
1405
+ effort: "high"
1406
+ }
1407
+ }
1408
+ },
1409
+ input_modalities: [
1410
+ "file",
1411
+ "image",
1412
+ "text"
1413
+ ],
1414
+ tokenizer: "gpt-6",
1415
+ context_tokens: 105e4
1416
+ },
1417
+ {
1418
+ id: "openai/gpt-6.1-sol",
1419
+ status: "offered",
1420
+ reasoning: {
1421
+ default: {},
1422
+ off: null,
1423
+ low: {
1424
+ reasoning: {
1425
+ effort: "low"
1426
+ }
1427
+ },
1428
+ medium: {
1429
+ reasoning: {
1430
+ effort: "medium"
1431
+ }
1432
+ },
1433
+ high: {
1434
+ reasoning: {
1435
+ effort: "high"
1436
+ }
1437
+ }
1438
+ },
1439
+ input_modalities: [
1440
+ "file",
1441
+ "image",
1442
+ "text"
1443
+ ],
1444
+ tokenizer: "gpt-6",
1445
+ context_tokens: 105e4
1446
+ },
1447
+ {
1448
+ id: "qwen/qwen3.7-flash",
1449
+ status: "offered",
1450
+ reasoning: {
1451
+ default: {},
1452
+ off: {
1453
+ reasoning: {
1454
+ enabled: false
1455
+ }
1456
+ },
1457
+ low: {
1458
+ reasoning: {
1459
+ enabled: true
1460
+ }
1461
+ },
1462
+ medium: {
1463
+ reasoning: {
1464
+ enabled: true
1465
+ }
1466
+ },
1467
+ high: {
1468
+ reasoning: {
1469
+ enabled: true
1470
+ }
1471
+ }
1472
+ },
1473
+ input_modalities: [
1474
+ "image",
1475
+ "text",
1476
+ "video"
1477
+ ],
1478
+ tokenizer: "qwen3",
1479
+ context_tokens: 1e6
1480
+ },
1481
+ {
1482
+ id: "x-ai/grok-4.7",
1483
+ status: "offered",
1484
+ reasoning: {
1485
+ default: {},
1486
+ off: null,
1487
+ low: {
1488
+ reasoning: {
1489
+ effort: "low"
1490
+ }
1491
+ },
1492
+ medium: {
1493
+ reasoning: {
1494
+ effort: "medium"
1495
+ }
1496
+ },
1497
+ high: {
1498
+ reasoning: {
1499
+ effort: "high"
1500
+ }
1501
+ }
1502
+ },
1503
+ input_modalities: [
1504
+ "file",
1505
+ "image",
1506
+ "text"
1507
+ ],
1508
+ tokenizer: "grok-4",
1509
+ context_tokens: 5e5
1510
+ },
1511
+ {
1512
+ id: "xiaomi/mimo-v2.6-flash",
1513
+ status: "offered",
1514
+ reasoning: {
1515
+ default: {},
1516
+ off: {
1517
+ reasoning: {
1518
+ enabled: false
1519
+ }
1520
+ },
1521
+ low: {
1522
+ reasoning: {
1523
+ enabled: true
1524
+ }
1525
+ },
1526
+ medium: {
1527
+ reasoning: {
1528
+ enabled: true
1529
+ }
1530
+ },
1531
+ high: {
1532
+ reasoning: {
1533
+ enabled: true
1534
+ }
1535
+ }
1536
+ },
1537
+ input_modalities: [
1538
+ "audio",
1539
+ "image",
1540
+ "text",
1541
+ "video"
1542
+ ],
1543
+ tokenizer: "mimo",
1544
+ context_tokens: 105e4
1545
+ },
1546
+ {
1547
+ id: "z-ai/glm-5.3",
1548
+ status: "offered",
1549
+ reasoning: {
1550
+ default: {},
1551
+ off: null,
1552
+ low: {
1553
+ reasoning: {
1554
+ enabled: true
1555
+ }
1556
+ },
1557
+ medium: {
1558
+ reasoning: {
1559
+ enabled: true
1560
+ }
1561
+ },
1562
+ high: {
1563
+ reasoning: {
1564
+ enabled: true
1565
+ }
1566
+ }
1567
+ },
1568
+ input_modalities: [
1569
+ "text"
1570
+ ],
1571
+ tokenizer: "glm-5",
1572
+ context_tokens: 1048576
1573
+ },
1574
+ {
1575
+ id: "z-ai/glm-5.3-flash",
1576
+ status: "offered",
1577
+ reasoning: {
1578
+ default: {},
1579
+ off: null,
1580
+ low: {
1581
+ reasoning: {
1582
+ effort: "low"
1583
+ }
1584
+ },
1585
+ medium: {
1586
+ reasoning: {
1587
+ effort: "medium"
1588
+ }
1589
+ },
1590
+ high: {
1591
+ reasoning: {
1592
+ effort: "high"
1593
+ }
1594
+ }
1595
+ },
1596
+ input_modalities: [
1597
+ "image",
1598
+ "text",
1599
+ "video"
1600
+ ],
1601
+ tokenizer: "glm-5",
1602
+ context_tokens: 1048576
1603
+ }
1604
+ ],
1605
+ tokenizers: {
1606
+ "claude-5": {
1607
+ ascii_letters: 0.275,
1608
+ digits: 0.37,
1609
+ ascii_other: 0.82,
1610
+ hangul: 1.376,
1611
+ cjk: 2.262,
1612
+ other: 1,
1613
+ per_message: 2,
1614
+ per_request: 6,
1615
+ per_image: 1500
1616
+ },
1617
+ "deepseek-v4": {
1618
+ ascii_letters: 0.21,
1619
+ digits: 0.427,
1620
+ ascii_other: 0.5,
1621
+ hangul: 0.905,
1622
+ cjk: 0.685,
1623
+ other: 0.8,
1624
+ per_message: 3,
1625
+ per_request: 2,
1626
+ per_image: 1e3
1627
+ },
1628
+ "gemini-3": {
1629
+ ascii_letters: 0.149,
1630
+ digits: 1.073,
1631
+ ascii_other: 0.619,
1632
+ hangul: 0.576,
1633
+ cjk: 2.187,
1634
+ other: 1,
1635
+ per_message: 1,
1636
+ per_request: 0,
1637
+ per_image: 1500
1638
+ },
1639
+ "gemma-4": {
1640
+ ascii_letters: 0.149,
1641
+ digits: 1.073,
1642
+ ascii_other: 0.619,
1643
+ hangul: 0.576,
1644
+ cjk: 2.187,
1645
+ other: 1,
1646
+ per_message: 5,
1647
+ per_request: 8,
1648
+ per_image: 1500
1649
+ },
1650
+ "kimi-k3": {
1651
+ ascii_letters: 0.148,
1652
+ digits: 0.364,
1653
+ ascii_other: 0.569,
1654
+ hangul: 0.956,
1655
+ cjk: 1.947,
1656
+ other: 1,
1657
+ per_message: 14,
1658
+ per_request: 7,
1659
+ per_image: 1500
1660
+ },
1661
+ "gpt-6": {
1662
+ ascii_letters: 0.16,
1663
+ digits: 0.364,
1664
+ ascii_other: 0.553,
1665
+ hangul: 0.654,
1666
+ cjk: 2.102,
1667
+ other: 1,
1668
+ per_message: 5,
1669
+ per_request: 1,
1670
+ per_image: 1500
1671
+ },
1672
+ qwen3: {
1673
+ ascii_letters: 0.148,
1674
+ digits: 1.052,
1675
+ ascii_other: 0.56,
1676
+ hangul: 0.492,
1677
+ cjk: 1.784,
1678
+ other: 1,
1679
+ per_message: 5,
1680
+ per_request: 7,
1681
+ per_image: 1500
1682
+ },
1683
+ "grok-4": {
1684
+ ascii_letters: 0.138,
1685
+ digits: 0.36,
1686
+ ascii_other: 0.637,
1687
+ hangul: 0.81,
1688
+ cjk: 1.642,
1689
+ other: 1,
1690
+ per_message: 4,
1691
+ per_request: 1238,
1692
+ per_image: 1500
1693
+ },
1694
+ mimo: {
1695
+ ascii_letters: 0.17,
1696
+ digits: 1,
1697
+ ascii_other: 0.47,
1698
+ hangul: 0.75,
1699
+ cjk: 1.62,
1700
+ other: 1,
1701
+ per_message: 6,
1702
+ per_request: 4,
1703
+ per_image: 1500
1704
+ },
1705
+ "glm-5": {
1706
+ ascii_letters: 0.154,
1707
+ digits: 0.648,
1708
+ ascii_other: 0.535,
1709
+ hangul: 0.948,
1710
+ cjk: 1.95,
1711
+ other: 1,
1712
+ per_message: 2,
1713
+ per_request: 11,
1714
+ per_image: 1500
1715
+ }
1716
+ },
1717
+ recommendations: {
1718
+ picker: [
1719
+ "deepseek/deepseek-v4.1-flash",
1720
+ "deepseek/deepseek-v4-flash-0731",
1721
+ "openai/gpt-6-luna",
1722
+ "anthropic/claude-sonnet-5.5",
1723
+ "anthropic/claude-opus-5.5",
1724
+ "google/gemini-3.8-flash"
1725
+ ],
1726
+ fallbacks: [
1727
+ {
1728
+ level: "off",
1729
+ family: {
1730
+ reasoning: {
1731
+ enabled: false
1732
+ }
1733
+ },
1734
+ models: [
1735
+ "openai/gpt-6-luna",
1736
+ "deepseek/deepseek-v4-flash-0731"
1737
+ ]
1738
+ },
1739
+ {
1740
+ level: "off",
1741
+ family: {
1742
+ reasoning: {
1743
+ effort: "minimal"
1744
+ }
1745
+ },
1746
+ models: []
1747
+ },
1748
+ {
1749
+ level: "low",
1750
+ family: {
1751
+ reasoning: {
1752
+ effort: "low"
1753
+ }
1754
+ },
1755
+ models: [
1756
+ "anthropic/claude-sonnet-5.5"
1757
+ ]
1758
+ }
1759
+ ],
1760
+ tools: {
1761
+ "web.search": {
1762
+ model: "google/gemini-3.8-flash"
1763
+ }
1764
+ },
1765
+ legacy_models: [
1766
+ "deepseek/deepseek-v4.1-flash",
1767
+ "openai/gpt-6-luna"
1768
+ ]
1769
+ }
1770
+ }
1771
+ };
1772
+
1773
+ // ../../apps/cloud/src/model-profiles.ts
1774
+ var table = v1_default.object;
1775
+ var PROFILE_MODEL_IDS = table.models.map((model) => model.id);
1776
+ var REASONING_LEVELS = ["default", "off", "low", "medium", "high"];
1777
+
1778
+ // ../../apps/cloud/src/crypto.ts
1779
+ var encoder = new TextEncoder();
1780
+ async function sha256(value2) {
1781
+ return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(value2))), (x) => x.toString(16).padStart(2, "0")).join("");
1782
+ }
1783
+
1784
+ // ../../vectors/croche-tools-schema3.json
1785
+ var croche_tools_schema3_default = {
1786
+ version: 1,
1787
+ schema: 3,
1788
+ source: "Founder search-only 2026-10-13 23:29Z, Keel/Leo 23:37Z",
1789
+ layering: "Each tool value replaces the inherited value atomically; omitted object fields use tool defaults.",
1790
+ bounds: {
1791
+ modelChars: 200,
1792
+ maxPerTurn: {
1793
+ min: 1,
1794
+ max: 10
1795
+ },
1796
+ maxResults: {
1797
+ min: 1,
1798
+ max: 5
1799
+ },
1800
+ domainCount: 20,
1801
+ domainChars: 253,
1802
+ domainPattern: "^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$",
1803
+ engine: "exa",
1804
+ timeoutMs: {
1805
+ min: 10,
1806
+ max: 3e5
1807
+ }
1808
+ },
1809
+ defaults: {
1810
+ "web.search": {
1811
+ model: "google/gemini-3.8-flash",
1812
+ engine: "exa",
1813
+ maxResults: 3,
1814
+ maxPerTurn: 3,
1815
+ timeoutMs: 3e4
1816
+ }
1817
+ },
1818
+ cases: [
1819
+ {
1820
+ name: "search true uses defaults",
1821
+ tool: "web.search",
1822
+ value: true,
1823
+ valid: true
1824
+ },
1825
+ {
1826
+ name: "search disabled",
1827
+ tool: "web.search",
1828
+ value: false,
1829
+ valid: true
1830
+ },
1831
+ {
1832
+ name: "empty search object uses defaults",
1833
+ tool: "web.search",
1834
+ value: {},
1835
+ valid: true
1836
+ },
1837
+ {
1838
+ name: "search maximums",
1839
+ tool: "web.search",
1840
+ value: {
1841
+ maxResults: 5,
1842
+ maxPerTurn: 10,
1843
+ engine: "exa",
1844
+ includeDomains: [
1845
+ "example.com"
1846
+ ],
1847
+ excludeDomains: [
1848
+ "other.example"
1849
+ ],
1850
+ timeoutMs: 3e5
1851
+ },
1852
+ valid: true
1853
+ },
1854
+ {
1855
+ name: "search unknown key",
1856
+ tool: "web.search",
1857
+ value: {
1858
+ apiKey: "not-a-key"
1859
+ },
1860
+ valid: false
1861
+ },
1862
+ {
1863
+ name: "search maxPerTurn eleven",
1864
+ tool: "web.search",
1865
+ value: {
1866
+ maxPerTurn: 11
1867
+ },
1868
+ valid: false
1869
+ },
1870
+ {
1871
+ name: "search results six",
1872
+ tool: "web.search",
1873
+ value: {
1874
+ maxResults: 6
1875
+ },
1876
+ valid: false
1877
+ },
1878
+ {
1879
+ name: "search results zero",
1880
+ tool: "web.search",
1881
+ value: {
1882
+ maxResults: 0
1883
+ },
1884
+ valid: false
1885
+ },
1886
+ {
1887
+ name: "search wrong engine",
1888
+ tool: "web.search",
1889
+ value: {
1890
+ engine: "parallel"
1891
+ },
1892
+ valid: false
1893
+ },
1894
+ {
1895
+ name: "domain scheme",
1896
+ tool: "web.search",
1897
+ value: {
1898
+ includeDomains: [
1899
+ "https://example.com"
1900
+ ]
1901
+ },
1902
+ valid: false
1903
+ },
1904
+ {
1905
+ name: "domain port",
1906
+ tool: "web.search",
1907
+ value: {
1908
+ includeDomains: [
1909
+ "example.com:443"
1910
+ ]
1911
+ },
1912
+ valid: false
1913
+ },
1914
+ {
1915
+ name: "domain path",
1916
+ tool: "web.search",
1917
+ value: {
1918
+ excludeDomains: [
1919
+ "example.com/path"
1920
+ ]
1921
+ },
1922
+ valid: false
1923
+ },
1924
+ {
1925
+ name: "domain uppercase",
1926
+ tool: "web.search",
1927
+ value: {
1928
+ includeDomains: [
1929
+ "EXAMPLE.com"
1930
+ ]
1931
+ },
1932
+ valid: false
1933
+ },
1934
+ {
1935
+ name: "domain overlap",
1936
+ tool: "web.search",
1937
+ value: {
1938
+ includeDomains: [
1939
+ "example.com"
1940
+ ],
1941
+ excludeDomains: [
1942
+ "example.com"
1943
+ ]
1944
+ },
1945
+ valid: false
1946
+ },
1947
+ {
1948
+ name: "search timeout above range",
1949
+ tool: "web.search",
1950
+ value: {
1951
+ timeoutMs: 300001
1952
+ },
1953
+ valid: false
1954
+ },
1955
+ {
1956
+ name: "search array",
1957
+ tool: "web.search",
1958
+ value: [],
1959
+ valid: false
1960
+ }
1961
+ ],
1962
+ boundary_cases: [
1963
+ {
1964
+ name: "search twenty domains",
1965
+ tool: "web.search",
1966
+ field: "includeDomains",
1967
+ count: 20,
1968
+ valid: true
1969
+ },
1970
+ {
1971
+ name: "search twenty-one domains",
1972
+ tool: "web.search",
1973
+ field: "includeDomains",
1974
+ count: 21,
1975
+ valid: false
1976
+ }
1977
+ ],
1978
+ atomic_cases: [
1979
+ {
1980
+ name: "model override drops parent maxResults",
1981
+ parent: {
1982
+ model: "google/gemini-3.8-flash",
1983
+ maxResults: 5
1984
+ },
1985
+ child: {
1986
+ model: "google/gemini-3.8-flash"
1987
+ },
1988
+ expected: {
1989
+ model: "google/gemini-3.8-flash"
1990
+ }
1991
+ },
1992
+ {
1993
+ name: "true drops parent settings",
1994
+ parent: {
1995
+ model: "google/gemini-3.8-flash",
1996
+ maxResults: 5
1997
+ },
1998
+ child: true,
1999
+ expected: true
2000
+ },
2001
+ {
2002
+ name: "false disables inherited tool",
2003
+ parent: true,
2004
+ child: false,
2005
+ expected: false
2006
+ }
2007
+ ]
2008
+ };
2009
+
2010
+ // ../../apps/cloud/src/tool-settings.ts
2011
+ var bounds = croche_tools_schema3_default.bounds;
2012
+ var object = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2);
2013
+ var chars = (value2) => [...value2].length;
2014
+ var pointer = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
2015
+ function toolShapeProblems(tool, value2, path2) {
2016
+ const problems = [], problem = (key, reason) => problems.push({ path: key ? path2 + "/" + pointer(key) : path2, reason });
2017
+ if (tool !== "image" && tool !== "web.search") {
2018
+ problem("", "tool is not available");
2019
+ return problems;
2020
+ }
2021
+ if (value2 === false) return problems;
2022
+ if (value2 === true) {
2023
+ problem("model", "an explicit model is required");
2024
+ return problems;
2025
+ }
2026
+ if (tool === "image") {
2027
+ if (!object(value2)) {
2028
+ problem("", "must be false or a complete settings object with an explicit model");
2029
+ return problems;
2030
+ }
2031
+ for (const key of Object.keys(value2)) if (!["model", "stylePrompt", "imageSize", "aspectRatio", "maxPerTurn", "timeoutMs"].includes(key)) problem(key, "unknown tool settings field");
2032
+ if (typeof value2.model !== "string" || !value2.model || chars(value2.model) > 128) problem("model", "model id of 1\u2013128 characters required");
2033
+ if ("stylePrompt" in value2 && (typeof value2.stylePrompt !== "string" || chars(value2.stylePrompt) > 500)) problem("stylePrompt", "text of at most 500 characters required");
2034
+ if ("imageSize" in value2 && !["512", "1K", "2K"].includes(value2.imageSize)) problem("imageSize", "must be 512, 1K or 2K");
2035
+ if ("aspectRatio" in value2 && !["1:1", "3:4", "4:3", "9:16", "16:9"].includes(value2.aspectRatio)) problem("aspectRatio", "unsupported aspect ratio");
2036
+ for (const [key, min, max] of [["maxPerTurn", 1, 4], ["timeoutMs", 1e4, 18e4]])
2037
+ if (key in value2 && (!Number.isSafeInteger(value2[key]) || Number(value2[key]) < min || Number(value2[key]) > max)) problem(key, `integer from ${min} to ${max} required`);
2038
+ return problems;
2039
+ }
2040
+ if (tool !== "web.search") {
2041
+ problem("", "tool is not available in 0.5.2");
2042
+ return problems;
2043
+ }
2044
+ if (!object(value2)) {
2045
+ problem("", "must be false or a complete settings object with an explicit model");
2046
+ return problems;
2047
+ }
2048
+ const keys = ["model", "engine", "maxResults", "includeDomains", "excludeDomains", "maxPerTurn", "timeoutMs"];
2049
+ for (const key of Object.keys(value2)) if (!keys.includes(key)) problem(key, "unknown tool settings field");
2050
+ if (typeof value2.model !== "string" || !value2.model || chars(value2.model) > bounds.modelChars) problem("model", `text of 1\u2013${bounds.modelChars} characters required`);
2051
+ const integer3 = (key, range) => {
2052
+ if (key in value2 && (!Number.isSafeInteger(value2[key]) || Number(value2[key]) < range.min || Number(value2[key]) > range.max)) problem(key, `integer from ${range.min} to ${range.max} required`);
2053
+ };
2054
+ integer3("maxPerTurn", bounds.maxPerTurn);
2055
+ integer3("timeoutMs", bounds.timeoutMs);
2056
+ integer3("maxResults", bounds.maxResults);
2057
+ if ("engine" in value2 && value2.engine !== bounds.engine) problem("engine", "must be exa");
2058
+ for (const key of ["includeDomains", "excludeDomains"]) if (key in value2) {
2059
+ const list = value2[key];
2060
+ if (!Array.isArray(list) || list.length > bounds.domainCount || list.some((host) => typeof host !== "string" || host.length > bounds.domainChars || !new RegExp(bounds.domainPattern).test(host)))
2061
+ problem(key, "up to 20 lowercase hostnames (max 253 characters), without scheme, path or port required");
2062
+ }
2063
+ if (Array.isArray(value2.includeDomains) && Array.isArray(value2.excludeDomains) && value2.includeDomains.some((host) => value2.excludeDomains.includes(host))) problem("excludeDomains", "includeDomains and excludeDomains must be disjoint");
2064
+ return problems;
2065
+ }
2066
+ function toolSettingsProblems(tool, value2, path2, data = v1_default.object) {
2067
+ const problems = toolShapeProblems(tool, value2, path2);
2068
+ if (problems.length || value2 === false) return problems;
2069
+ const row2 = data.recommendations.tools[tool];
2070
+ const model = object(value2) ? value2.model : void 0;
2071
+ if (typeof model !== "string" || !row2 || !(row2.models ?? [row2.model]).includes(model)) problems.push({ path: path2 + "/model", reason: "model must be in this tool\u2019s entitlement catalogue" });
2072
+ return problems;
2073
+ }
2074
+
2075
+ // ../config-contract/src/index.ts
2076
+ var ConfigError = class extends Error {
2077
+ constructor(status, code, message, details) {
2078
+ super(message);
2079
+ this.status = status;
2080
+ this.code = code;
2081
+ this.details = details;
2082
+ }
2083
+ };
2084
+ var fail = (status, code, message, details) => {
2085
+ throw new ConfigError(status, code, message, details);
2086
+ };
2087
+ var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
2088
+ var fields = /* @__PURE__ */ new Set(["instructions", "markerGuide", "toolGuide", "crocheTools", "tools", "wiki", "memory", "context", "limits", "maxContextTokens", "maxOutputTokens", "maxIterations", "model", "fallbacks", "reasoning", "temperature", "defaultLanguage", "languages", "agents", "schedule", "heartbeat", "modes", "instances"]);
2089
+ var crocheTools = /* @__PURE__ */ new Set(["memory.save", "memory.recall", "memory.history", "wiki", "schedule"]);
2090
+ var asciiFold = (tag) => tag.replace(/[A-Z]/g, (c) => c.toLowerCase());
2091
+ var languageTag = (tag) => typeof tag === "string" && tag.length <= 35 && /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.exec(tag)?.[0] === tag;
2092
+ var configModelId = (v) => typeof v === "string" && v.length > 0 && new TextEncoder().encode(v).byteLength <= 200;
2093
+ var words = /* @__PURE__ */ new Set(["summary", "description"]);
2094
+ var CanonicalError = class extends Error {
2095
+ constructor(path2, message) {
2096
+ super(message);
2097
+ this.path = path2;
2098
+ }
2099
+ code = "invalid_configuration";
2100
+ };
2101
+ var pointer2 = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
2102
+ function encodeCanonical(value2, path2 = "") {
2103
+ if (typeof value2 === "number" && (!Number.isFinite(value2) || Number.isInteger(value2) && !Number.isSafeInteger(value2))) throw new CanonicalError(path2, "unsafe or non-finite number");
2104
+ if (typeof value2 === "string") {
2105
+ for (let i = 0; i < value2.length; i++) {
2106
+ const c = value2.charCodeAt(i);
2107
+ if (c >= 55296 && c <= 56319) {
2108
+ const next = value2.charCodeAt(++i);
2109
+ if (!(next >= 56320 && next <= 57343)) throw new CanonicalError(path2, "Invalid Unicode");
2110
+ } else if (c >= 56320 && c <= 57343) throw new CanonicalError(path2, "Invalid Unicode");
2111
+ }
2112
+ return JSON.stringify(value2);
2113
+ }
2114
+ if (value2 === null || typeof value2 === "boolean" || typeof value2 === "number" && Number.isFinite(value2)) return JSON.stringify(value2);
2115
+ if (Array.isArray(value2)) return "[" + value2.map((v, i) => encodeCanonical(v, path2 + "/" + i)).join(",") + "]";
2116
+ if (isObject(value2)) return "{" + Object.keys(value2).sort().map((k) => encodeCanonical(k, path2 + "/" + pointer2(k)) + ":" + encodeCanonical(value2[k], path2 + "/" + pointer2(k))).join(",") + "}";
2117
+ throw new Error("Expected JSON");
2118
+ }
2119
+ function canonical(value2) {
2120
+ const encoded = encodeCanonical(value2);
2121
+ if (new TextEncoder().encode(encoded).byteLength > 256 * 1024) throw new CanonicalError("", "Project config exceeds 256 KiB.");
2122
+ return encoded;
2123
+ }
2124
+ function shape(value2) {
2125
+ if (Array.isArray(value2)) return value2.map(shape);
2126
+ if (isObject(value2)) return Object.fromEntries(Object.entries(value2).filter(([k]) => !words.has(k)).map(([k, v]) => [k, shape(v)]));
2127
+ return value2;
2128
+ }
2129
+ var shapeHash = async (command) => "sha256:" + await sha256(canonical(shape(command)));
2130
+ var CONFIG_CAPABILITIES = config_capabilities_default.capabilities;
2131
+ function inferredRequirements(document) {
2132
+ const present = (value2, segments) => {
2133
+ if (!segments.length) return true;
2134
+ const [key, ...rest] = segments;
2135
+ if (key === "*") {
2136
+ const children = Array.isArray(value2) ? value2 : isObject(value2) ? Object.values(value2) : [];
2137
+ return children.some((child) => present(child, rest));
2138
+ }
2139
+ if (Array.isArray(value2)) return /^(0|[1-9][0-9]*)$/.test(key) && Number(key) < value2.length && present(value2[Number(key)], rest);
2140
+ return isObject(value2) && Object.hasOwn(value2, key) && present(value2[key], rest);
2141
+ };
2142
+ return [...new Set(CONFIG_CAPABILITIES.filter((c) => c.paths.some((path2) => present(document, path2.slice(1).split("/").map((key) => key.replaceAll("~1", "/").replaceAll("~0", "~"))))).map((c) => c.id))].sort();
2143
+ }
2144
+ function compileRequirements(document) {
2145
+ if (!isObject(document)) return document;
2146
+ if (Object.hasOwn(document, "requires")) fail(400, "invalid_configuration", "requires is compiler-owned.", { problems: [{ path: "/requires", reason: "requires is compiler-owned" }] });
2147
+ const requires = inferredRequirements(document);
2148
+ return requires.length ? { ...document, requires } : document;
2149
+ }
2150
+ var MAX_BYTES = 256 * 1024;
2151
+ function validateDocumentShape(document, write = false) {
2152
+ const problems = [];
2153
+ const problem = (path2, reason) => {
2154
+ if (!problems.some((p) => p.path === path2 && p.reason === reason)) problems.push({ path: path2, reason });
2155
+ };
2156
+ const at2 = (path2, key) => path2 + "/" + pointer2(String(key));
2157
+ let encoded = "";
2158
+ try {
2159
+ encoded = encodeCanonical(document);
2160
+ } catch (error) {
2161
+ problem(error instanceof CanonicalError ? error.path : "", error instanceof Error ? error.message : "valid Unicode JSON required");
2162
+ }
2163
+ if (new TextEncoder().encode(encoded).byteLength > MAX_BYTES) fail(413, "config_too_large", "Project config exceeds 256 KiB.");
2164
+ if (!isObject(document) || !(write ? [6] : [2, 3, 4, 5, 6]).includes(Number(document.schema)) || typeof document.schema !== "number") problem("/schema", write ? "new writes require schema 6" : "stored schema must be 2, 3, 4, 5 or 6");
2165
+ const schema = isObject(document) ? document.schema : void 0;
2166
+ if (isObject(document)) {
2167
+ for (const k of Object.keys(document)) if (!(schema === 6 ? ["schema", "config", "requires"] : ["schema", "config"]).includes(k)) problem(at2("", k), "unknown document field");
2168
+ }
2169
+ if (schema === 6 && isObject(document)) {
2170
+ const requires = document.requires, inferred = inferredRequirements(document);
2171
+ if (requires !== void 0) {
2172
+ if (!Array.isArray(requires) || !requires.length || requires.length > 128) problem("/requires", "must be a nonempty array of at most 128 capabilities");
2173
+ else requires.forEach((id, i) => {
2174
+ if (typeof id !== "string" || !CONFIG_CAPABILITIES.some((c) => c.id === id)) problem(at2("/requires", i), "unsupported required capability");
2175
+ else if (i > 0 && String(requires[i - 1]) >= id) problem(at2("/requires", i), "capabilities must be sorted and unique");
2176
+ });
2177
+ }
2178
+ if (JSON.stringify(requires ?? []) !== JSON.stringify(inferred)) problem("/requires", "requirements must match the compiler-inferred capabilities");
2179
+ }
2180
+ const config = isObject(document) ? document.config : void 0;
2181
+ const defaultLanguage = isObject(config) && typeof config.defaultLanguage === "string" ? config.defaultLanguage : "en";
2182
+ const declarations = [], tools = /* @__PURE__ */ new Set();
2183
+ const nullableTemperature = /* @__PURE__ */ new Set();
2184
+ const collectTemperature = (value2, path2, depth = 0) => {
2185
+ if (depth > 64 || !isObject(value2)) return;
2186
+ if (typeof schema === "number" && schema >= 4) nullableTemperature.add(at2(path2, "temperature"));
2187
+ for (const field of ["languages", "agents"]) if (isObject(value2[field])) {
2188
+ for (const [name, layer] of Object.entries(value2[field])) collectTemperature(layer, at2(at2(path2, field), name), depth + 1);
2189
+ }
2190
+ };
2191
+ collectTemperature(config, "/config");
2192
+ const visitNull = (value2, path2, depth = 0) => {
2193
+ if (depth > 64) {
2194
+ problem(path2, "config is too deeply nested");
2195
+ return;
2196
+ }
2197
+ if (typeof value2 === "number" && (!Number.isFinite(value2) || Number.isInteger(value2) && !Number.isSafeInteger(value2))) problem(path2, "unsafe or non-finite number");
2198
+ if (value2 === null && !nullableTemperature.has(path2)) problem(path2, "null is not allowed");
2199
+ else if (typeof value2 === "string") {
2200
+ try {
2201
+ encodeCanonical(value2, path2);
2202
+ } catch (error) {
2203
+ problem(path2, error instanceof Error ? error.message : "Invalid Unicode");
2204
+ }
2205
+ } else if (Array.isArray(value2)) value2.forEach((v, i) => visitNull(v, at2(path2, i), depth + 1));
2206
+ else if (isObject(value2)) Object.entries(value2).forEach(([k, v]) => visitNull(v, at2(path2, k), depth + 1));
2207
+ };
2208
+ visitNull(document, "");
2209
+ const toolList = (value2, path2) => {
2210
+ if (!Array.isArray(value2)) {
2211
+ problem(path2, "must be an array");
2212
+ return;
2213
+ }
2214
+ try {
2215
+ if (new TextEncoder().encode(encodeCanonical(value2)).byteLength > 256e3) problem(path2, "tool registry exceeds 256,000 UTF-8 bytes");
2216
+ } catch {
2217
+ }
2218
+ const keys = /* @__PURE__ */ new Set(), names = /* @__PURE__ */ new Set();
2219
+ value2.forEach((tool, i) => {
2220
+ const p = at2(path2, i);
2221
+ if (!isObject(tool)) {
2222
+ problem(p, "must be an object");
2223
+ return;
2224
+ }
2225
+ for (const key of Object.keys(tool)) if (!["name", "summary", "commands"].includes(key)) problem(at2(p, key), "unknown field");
2226
+ if (typeof tool.name !== "string" || !tool.name.trim()) problem(at2(p, "name"), "required");
2227
+ else {
2228
+ if (["help", "memory", "wiki"].includes(tool.name)) problem(at2(p, "name"), "reserved tool name");
2229
+ if (names.has(tool.name)) problem(at2(p, "name"), "duplicate tool name");
2230
+ else names.add(tool.name);
2231
+ tools.add(tool.name);
2232
+ }
2233
+ if (typeof tool.summary !== "string" || !tool.summary.length) problem(at2(p, "summary"), "required");
2234
+ if (!Array.isArray(tool.commands)) problem(at2(p, "commands"), "must be an array");
2235
+ else {
2236
+ if (!tool.commands.length) problem(at2(p, "commands"), "at least one command");
2237
+ const routes = /* @__PURE__ */ new Set();
2238
+ tool.commands.forEach((command, j) => {
2239
+ const commandPath = at2(at2(p, "commands"), j);
2240
+ if (isObject(command)) {
2241
+ for (const key of Object.keys(command)) if (!["key", "name", "summary", "aliases", "timeoutMs", "reads", "flags", "positionals"].includes(key)) problem(at2(commandPath, key), "unknown field");
2242
+ for (const field of ["flags", "positionals"]) if (field in command) {
2243
+ const args = command[field], argPath = at2(commandPath, field);
2244
+ if (!Array.isArray(args)) problem(argPath, "must be an array");
2245
+ else args.forEach((arg, k) => {
2246
+ const ap = at2(argPath, k);
2247
+ if (!isObject(arg)) {
2248
+ problem(ap, "must be an object");
2249
+ return;
2250
+ }
2251
+ for (const key of Object.keys(arg)) if (!["name", "arg", "type", "description", "required", "default", "enum", "minimum", "maximum", "minLength", "maxLength", "aliases", "list"].includes(key)) problem(at2(ap, key), "unknown field");
2252
+ });
2253
+ }
2254
+ }
2255
+ if (isObject(command) && (typeof command.summary !== "string" || !command.summary.length)) problem(at2(commandPath, "summary"), "required");
2256
+ if (isObject(command) && "confirm" in command) problem(at2(at2(at2(p, "commands"), j), "confirm"), "unknown field");
2257
+ if (!isObject(command) || typeof command.key !== "string" || !command.key.length) problem(at2(at2(at2(p, "commands"), j), "key"), "required");
2258
+ else {
2259
+ const keyPath = at2(commandPath, "key");
2260
+ if (new TextEncoder().encode(command.key).byteLength > 100) problem(keyPath, "1\u2013100 UTF-8 bytes required");
2261
+ if (keys.has(command.key)) problem(keyPath, "duplicate command key");
2262
+ else keys.add(command.key);
2263
+ if ("name" in command && (typeof command.name !== "string" || !command.name.trim())) problem(at2(at2(at2(p, "commands"), j), "name"), "nonempty string required");
2264
+ const route = command.name === void 0 ? "" : typeof command.name === "string" ? command.name : void 0;
2265
+ if (route !== void 0) {
2266
+ if (routes.has(route)) problem("name" in command ? at2(commandPath, "name") : commandPath, "duplicate command route");
2267
+ else routes.add(route);
2268
+ }
2269
+ if (typeof tool.name === "string") declarations.push({ tool: tool.name, command });
2270
+ }
2271
+ });
2272
+ }
2273
+ });
2274
+ };
2275
+ const configLayer = (value2, path2, agent = false, root = false, depth = 0, language = false) => {
2276
+ if (depth > 64) {
2277
+ problem(path2, "config is too deeply nested");
2278
+ return;
2279
+ }
2280
+ if (!isObject(value2)) {
2281
+ problem(path2, "must be an object");
2282
+ return;
2283
+ }
2284
+ for (const k of Object.keys(value2)) if (!fields.has(k) && !(agent && k === "name") || !root && ["agents", "defaultLanguage", "instances"].includes(k) || language && k === "languages") problem(at2(path2, k), k === "recommendedFallbacks" ? "recommendedFallbacks was removed: use explicit fallbacks" : k === "memoryRecall" ? "memoryRecall was removed: the model reads memories with memory recall" : k === "timeContext" ? "timeContext was removed: each turn has a number and short local-time header" : "unknown field");
2285
+ if (schema === 6 && "maxContextTokens" in value2) problem(at2(path2, "maxContextTokens"), "removed: use context.turnTokens");
2286
+ if (schema !== 6 && "context" in value2) problem(at2(path2, "context"), "unknown field");
2287
+ if (root && (typeof value2.instructions !== "string" || !value2.instructions.trim())) problem(at2(path2, "instructions"), "nonempty string required");
2288
+ for (const field of ["instructions", "markerGuide"]) if (value2[field] !== void 0 && value2[field] !== null && (typeof value2[field] !== "string" || field === "instructions" && !String(value2[field]).trim())) problem(at2(path2, field), "nonempty instructions or text required");
2289
+ const range = (row2, field, min, max, p, zero = false) => {
2290
+ if (field in row2 && (!Number.isSafeInteger(row2[field]) || !(zero && row2[field] === 0) && !(Number(row2[field]) >= min && Number(row2[field]) <= max))) problem(at2(p, field), `integer from ${min} to ${max}${zero ? " or zero" : ""} required`);
2291
+ };
2292
+ for (const [field, min, max] of [["maxOutputTokens", 64, 1048576], ["maxIterations", 1, 32]]) range(value2, field, min, max, path2);
2293
+ if (schema !== 6) range(value2, "maxContextTokens", 250, 16777216, path2);
2294
+ if ("context" in value2) {
2295
+ const p = at2(path2, "context"), c = value2.context;
2296
+ if (!isObject(c)) problem(p, "must be an object");
2297
+ else {
2298
+ for (const key of Object.keys(c)) if (!["turnTokens", "memoryShare", "maxTokens"].includes(key)) problem(at2(p, key), "unknown field");
2299
+ range(c, "turnTokens", 1, 16777216, p);
2300
+ range(c, "maxTokens", 1, 16777216, p);
2301
+ if ("memoryShare" in c && (typeof c.memoryShare !== "number" || !Number.isFinite(c.memoryShare) || c.memoryShare < 0 || c.memoryShare > 0.5)) problem(at2(p, "memoryShare"), "number from 0 to 0.5 required");
2302
+ }
2303
+ }
2304
+ if ("limits" in value2) {
2305
+ const p = at2(path2, "limits"), limits = value2.limits;
2306
+ if (!isObject(limits)) problem(p, "must be an object");
2307
+ else {
2308
+ for (const key of Object.keys(limits)) if (!["userTextChars", "appStateChars", "toolResultChars"].includes(key)) problem(at2(p, key), "unknown field");
2309
+ range(limits, "userTextChars", 1e3, 2e5, p);
2310
+ range(limits, "appStateChars", 1e3, 2e5, p);
2311
+ range(limits, "toolResultChars", 1e3, 1e6, p);
2312
+ }
2313
+ }
2314
+ if ("temperature" in value2) {
2315
+ if (typeof schema !== "number" || schema < 4) problem(at2(path2, "temperature"), "unknown field");
2316
+ else if (value2.temperature !== null && (typeof value2.temperature !== "number" || !Number.isFinite(value2.temperature) || value2.temperature < 0 || value2.temperature > 2)) problem(at2(path2, "temperature"), "number from 0 to 2, or null to omit required");
2317
+ }
2318
+ if ("crocheTools" in value2) {
2319
+ const p = at2(path2, "crocheTools");
2320
+ if (!isObject(value2.crocheTools)) problem(p, "must be an object of boolean library switches");
2321
+ else for (const [key, on] of Object.entries(value2.crocheTools)) {
2322
+ if (key === "image" && typeof schema === "number" && schema >= 6) {
2323
+ for (const issue2 of toolShapeProblems(key, on, at2(p, key))) problem(issue2.path, issue2.reason);
2324
+ continue;
2325
+ }
2326
+ if (typeof schema === "number" && schema >= 3 && key === "web.search") {
2327
+ for (const issue2 of (typeof schema === "number" && schema >= 5 ? toolShapeProblems : toolSettingsProblems)(key, on, at2(p, key))) problem(issue2.path, issue2.reason);
2328
+ } else if (!crocheTools.has(key)) problem(at2(p, key), "unknown Croche tool");
2329
+ else if (typeof on !== "boolean") problem(at2(p, key), "must be a boolean");
2330
+ }
2331
+ }
2332
+ if ("instances" in value2) {
2333
+ const p = at2(path2, "instances");
2334
+ if (!isObject(value2.instances)) problem(p, "must be an object");
2335
+ else {
2336
+ for (const key of Object.keys(value2.instances)) if (key !== "maxBytes") problem(at2(p, key), "unknown field");
2337
+ range(value2.instances, "maxBytes", 0, 1073741824, p);
2338
+ }
2339
+ }
2340
+ if ("memory" in value2) {
2341
+ const p = at2(path2, "memory"), m = value2.memory;
2342
+ if (!isObject(m)) problem(p, "must be an object");
2343
+ else {
2344
+ const allowed = schema === 6 ? ["enabled", "policy"] : ["enabled", "policy", "maxTokens", "keepVerbatimTokens", "keepVerbatimTurns", "recallTokens", "prepareAfterMs", "activeMs", "foldMinTokens"];
2345
+ if (schema === 5) allowed.push("lowTokens", "summaryTokens", "answerFirst", "historyReach");
2346
+ for (const key of Object.keys(m)) if (!allowed.includes(key)) problem(at2(p, key), key === "recall" ? "memory.recall was removed: the model reads memories with memory recall" : key === "keys" ? "memory.keys was removed: Croche assigns memory ids; only the model writes memories" : key === "commands" ? 'memory.commands was removed: use crocheTools["memory.save"]' : "unknown field");
2347
+ if ("enabled" in m && typeof m.enabled !== "boolean") problem(at2(p, "enabled"), "must be a boolean");
2348
+ if (schema === 5) {
2349
+ for (const key of ["answerFirst", "historyReach"]) if (key in m && typeof m[key] !== "boolean") problem(at2(p, key), "must be a boolean");
2350
+ for (const key of ["lowTokens", "summaryTokens"]) range(m, key, 64, 16777216, p);
2351
+ }
2352
+ if ("policy" in m && (typeof m.policy !== "string" || [...m.policy].length > 4e3)) problem(at2(p, "policy"), "text of at most 4000 characters required");
2353
+ if (schema !== 6) for (const [field, min, max, zero] of [["maxTokens", 125, 16777216, false], ["keepVerbatimTokens", 0, 16777216, false], ["keepVerbatimTurns", 1, 200, false], ["recallTokens", 50, 16777216, false], ["foldMinTokens", 125, 16777216, false], ["prepareAfterMs", 3e4, 6048e5, true], ["activeMs", 6e4, 6048e5, true]]) range(m, field, min, max, p, zero);
2354
+ const prepare = Number(m.prepareAfterMs ?? (root ? 24e4 : 0)), active = Number(m.activeMs ?? (root ? 3e5 : 0));
2355
+ if (schema !== 6 && prepare > 0 && active > 0 && prepare >= active) problem(p, "prepareAfterMs must be shorter than activeMs");
2356
+ }
2357
+ }
2358
+ if ("wiki" in value2) {
2359
+ const p = at2(path2, "wiki"), w = value2.wiki;
2360
+ if (!isObject(w)) problem(p, "must be an object");
2361
+ else {
2362
+ for (const key of Object.keys(w)) if (!["docs", "include", "exclude"].includes(key)) problem(at2(p, key), "unknown field");
2363
+ let globBytes = 0;
2364
+ for (const field of ["include", "exclude"]) if (field in w) {
2365
+ const globs = w[field];
2366
+ if (!Array.isArray(globs) || globs.length > 50 || globs.some((g) => typeof g !== "string" || !g.length)) problem(at2(p, field), "up to 50 nonempty globs required");
2367
+ else globBytes += globs.reduce((n, g) => n + new TextEncoder().encode(g).length + 1, 0);
2368
+ }
2369
+ if (globBytes > 256) problem(p, "combined glob automaton exceeds 256 bytes");
2370
+ if ("docs" in w) {
2371
+ if (!Array.isArray(w.docs) || w.docs.length > 2e3) problem(at2(p, "docs"), "up to 2000 documents required");
2372
+ else w.docs.forEach((doc, i) => {
2373
+ const dp = at2(at2(p, "docs"), i);
2374
+ if (!isObject(doc)) {
2375
+ problem(dp, "must be an object");
2376
+ return;
2377
+ }
2378
+ for (const key of Object.keys(doc)) if (!["path", "markdown", "agents"].includes(key)) problem(at2(dp, key), "unknown field");
2379
+ const cleaned = typeof doc.path === "string" ? doc.path.trim().replaceAll("\\", "/") : "";
2380
+ if (!cleaned || new TextEncoder().encode(cleaned).length > 256 || cleaned.startsWith("/") || cleaned.endsWith("/") || /[\u0000-\u001f\u007f-\u009f]/.test(cleaned) || cleaned.split("/").some((s) => !s || s === "." || s === "..") || typeof doc.path === "string" && doc.path.startsWith("user/")) problem(at2(dp, "path"), "invalid app wiki path");
2381
+ if (typeof doc.markdown !== "string" || new TextEncoder().encode(doc.markdown).length > 65536) problem(at2(dp, "markdown"), "text of at most 65536 bytes required");
2382
+ if ("agents" in doc && (!Array.isArray(doc.agents) || doc.agents.some((a) => typeof a !== "string"))) problem(at2(dp, "agents"), "must be an array of strings");
2383
+ });
2384
+ }
2385
+ }
2386
+ }
2387
+ if (root && "defaultLanguage" in value2 && !languageTag(value2.defaultLanguage)) problem(at2(path2, "defaultLanguage"), "invalid language tag");
2388
+ if ("name" in value2 && (typeof value2.name !== "string" || !value2.name.length || value2.name.length > 100)) problem(at2(path2, "name"), "1\u2013100 characters required");
2389
+ if ("fallbacks" in value2) {
2390
+ if (typeof schema !== "number" || schema < 5) problem(at2(path2, "fallbacks"), "unknown field");
2391
+ else if (!Array.isArray(value2.fallbacks) || value2.fallbacks.length > 4 || value2.fallbacks.some((id) => !configModelId(id)) || new Set(value2.fallbacks).size !== value2.fallbacks.length) problem(at2(path2, "fallbacks"), "at most 4 distinct nonempty model ids required");
2392
+ }
2393
+ if ("model" in value2 && !configModelId(value2.model)) problem(at2(path2, "model"), "nonempty model id required");
2394
+ if ("reasoning" in value2 && (typeof value2.reasoning !== "string" || !REASONING_LEVELS.includes(value2.reasoning))) problem(at2(path2, "reasoning"), "must be default, off, low, medium or high");
2395
+ if ("toolGuide" in value2 && typeof value2.toolGuide !== "string") problem(at2(path2, "toolGuide"), "must be a string");
2396
+ if ("tools" in value2) toolList(value2.tools, at2(path2, "tools"));
2397
+ if ("schedule" in value2) {
2398
+ const p = at2(path2, "schedule");
2399
+ if (!isObject(value2.schedule)) problem(p, "must be an object");
2400
+ else for (const k of Object.keys(value2.schedule)) problem(at2(p, k), k === "commands" ? 'schedule.commands was removed: use crocheTools["schedule"]' : "unknown field");
2401
+ }
2402
+ if ("heartbeat" in value2) {
2403
+ const p = at2(path2, "heartbeat");
2404
+ if (!isObject(value2.heartbeat)) problem(p, "must be an object");
2405
+ else {
2406
+ for (const k of Object.keys(value2.heartbeat)) if (k !== "everyMs") problem(at2(p, k), "unknown field");
2407
+ const ms = value2.heartbeat.everyMs;
2408
+ if (!Number.isSafeInteger(ms) || Number(ms) < 9e5 || Number(ms) > 864e5) problem(at2(p, "everyMs"), "integer from 900000 to 86400000 required");
2409
+ }
2410
+ }
2411
+ if ("modes" in value2) {
2412
+ const p = at2(path2, "modes");
2413
+ if (!isObject(value2.modes)) problem(p, "must be an object");
2414
+ else for (const [name, mode] of Object.entries(value2.modes)) {
2415
+ const m = at2(p, name);
2416
+ if (!/^[A-Za-z0-9_.:-]{1,64}$/.test(name)) problem(m, "invalid mode name");
2417
+ if (!isObject(mode)) {
2418
+ problem(m, "must be an object");
2419
+ continue;
2420
+ }
2421
+ for (const k of Object.keys(mode)) if (!["tools", "toolGuide"].includes(k)) problem(at2(m, k), "unknown field");
2422
+ if ("toolGuide" in mode && typeof mode.toolGuide !== "string") problem(at2(m, "toolGuide"), "must be a string");
2423
+ if ("tools" in mode) toolList(mode.tools, at2(m, "tools"));
2424
+ }
2425
+ }
2426
+ if (!language && "languages" in value2) {
2427
+ const p = at2(path2, "languages");
2428
+ if (!isObject(value2.languages)) problem(p, "must be an object");
2429
+ else {
2430
+ if (!Object.keys(value2.languages).length) problem(p, "must be a nonempty object");
2431
+ const tags = /* @__PURE__ */ new Set();
2432
+ for (const tag of Object.keys(value2.languages).sort()) {
2433
+ if (!languageTag(tag)) problem(at2(p, tag), "invalid language tag");
2434
+ const folded = asciiFold(tag);
2435
+ if (tags.has(folded)) problem(at2(p, tag), "duplicate language tag");
2436
+ tags.add(folded);
2437
+ if (folded === asciiFold(defaultLanguage)) problem(at2(p, tag), "default language belongs in config");
2438
+ configLayer(value2.languages[tag], at2(p, tag), agent, false, depth + 1, true);
2439
+ }
2440
+ }
2441
+ }
2442
+ if (root && "agents" in value2) {
2443
+ if (!isObject(value2.agents)) problem(at2(path2, "agents"), "must be an object");
2444
+ else Object.entries(value2.agents).forEach(([id, v]) => {
2445
+ const p = at2(at2(path2, "agents"), id);
2446
+ if (!/^[A-Za-z0-9_.:-]{1,200}$/.test(id)) problem(p, "invalid id");
2447
+ configLayer(v, p, true, false, depth + 1);
2448
+ });
2449
+ }
2450
+ };
2451
+ configLayer(config, "/config", false, true);
2452
+ if (problems.length) fail(400, "invalid_configuration", "Project config is invalid.", { problems });
2453
+ return { encoded, declarations, tools };
2454
+ }
2455
+ async function documentIdentity(document, write) {
2456
+ const { encoded, declarations, tools } = validateDocumentShape(document, write);
2457
+ const commands2 = [];
2458
+ for (const { tool, command } of declarations) {
2459
+ const hash = await shapeHash(command);
2460
+ if (!commands2.some((c) => c.tool === tool && c.key === command.key && c.shape_hash === hash)) commands2.push({ tool, key: String(command.key), shape_hash: hash });
2461
+ }
2462
+ return { id: "sha256:" + await sha256(encoded), schema: Number(document.schema), document: encoded, commands: commands2, tools: [...tools] };
2463
+ }
2464
+ var validateDocument = (document) => documentIdentity(document, true);
2465
+
2466
+ // src/config-authoring.ts
2467
+ var object2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2);
2468
+ var pointer3 = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
2469
+ var at = (path2, key) => path2 + "/" + pointer3(key);
2470
+ var entries = (row2) => Object.keys(row2).sort().map((key) => [key, row2[key]]);
2471
+ var reference = (value2) => object2(value2) && Object.hasOwn(value2, "$file");
2472
+ function issue(file, path2, reason) {
2473
+ throw new CliError("invalid_configuration", `${file}${path2 ? `#${path2}` : ""}: ${reason}`, 2, { problems: [{ file, path: path2, reason }] });
2474
+ }
2475
+ function referencePath(value2, source) {
2476
+ if (typeof value2 !== "string" || !value2 || isAbsolute3(value2) || win32.isAbsolute(value2) || value2.includes("\\") || value2.split("/").some((p) => !p || p === "." || p === "..") || /[\u0000-\u001f]/.test(value2))
2477
+ issue(source.file, source.pointer, "File references must be relative paths without . or .. segments.");
2478
+ return value2;
2479
+ }
2480
+ async function text(file, path2 = "") {
2481
+ let bytes;
2482
+ try {
2483
+ bytes = await readFile3(file);
2484
+ } catch {
2485
+ issue(file, path2, "Cannot read file.");
2486
+ }
2487
+ try {
2488
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
2489
+ } catch {
2490
+ issue(file, path2, "UTF-8 text required.");
2491
+ }
2492
+ }
2493
+ function json(value2, file) {
2494
+ try {
2495
+ return JSON.parse(value2.charCodeAt(0) === 65279 ? value2.slice(1) : value2);
2496
+ } catch {
2497
+ issue(file, "", "Invalid JSON.");
2498
+ }
2499
+ }
2500
+ async function visitLayer(layer, path2, visit, agent, depth = 0) {
2501
+ if (depth > 64) return;
2502
+ if (!object2(layer)) return;
2503
+ for (const field of ["instructions", "markerGuide", "toolGuide"]) if (field in layer) await visit(layer, field, at(path2, field));
2504
+ if (object2(layer.memory) && "policy" in layer.memory) await visit(layer.memory, "policy", at(at(path2, "memory"), "policy"));
2505
+ if (object2(layer.modes)) {
2506
+ for (const [id, mode] of entries(layer.modes)) if (object2(mode) && "toolGuide" in mode) await visit(mode, "toolGuide", at(at(at(path2, "modes"), id), "toolGuide"));
2507
+ }
2508
+ if (object2(layer.languages)) for (const [id, language] of entries(layer.languages)) await visitLayer(language, at(at(path2, "languages"), id), visit, agent, depth + 1);
2509
+ if (path2 === "/config" && object2(layer.agents)) for (const id of Object.keys(layer.agents).sort()) {
2510
+ const agentPath = at(at(path2, "agents"), id);
2511
+ await agent(layer.agents, id, agentPath);
2512
+ await visitLayer(layer.agents[id], agentPath, visit, agent, depth + 1);
2513
+ }
2514
+ }
2515
+ async function validate(document, sources, fallback) {
2516
+ try {
2517
+ return await validateDocument(document);
2518
+ } catch (error) {
2519
+ if (!(error instanceof ConfigError)) throw error;
2520
+ const problems = error.details?.problems;
2521
+ if (!problems) issue(fallback, "", error.message);
2522
+ const located = problems.map((p) => {
2523
+ let prefix = p.path;
2524
+ while (!sources.has(prefix) && prefix) prefix = prefix.slice(0, prefix.lastIndexOf("/"));
2525
+ const source = sources.get(prefix) ?? { file: fallback, pointer: "" };
2526
+ return { file: source.file, path: source.pointer + p.path.slice(prefix.length), reason: p.reason };
2527
+ });
2528
+ throw new CliError(error.code, located.map((p) => `${p.file}#${p.path}: ${p.reason}`).join("\n"), 2, { problems: located });
2529
+ }
2530
+ }
2531
+ async function buildConfig(directory) {
2532
+ let root;
2533
+ try {
2534
+ root = await realpath(resolve2(directory));
2535
+ } catch {
2536
+ issue(directory, "", "Cannot read authoring directory.");
2537
+ }
2538
+ const project2 = join3(root, "project.json");
2539
+ const sources = /* @__PURE__ */ new Map([["", { file: project2, pointer: "" }]]);
2540
+ const load = async (value2, path2) => {
2541
+ let prefix = path2;
2542
+ while (!sources.has(prefix) && prefix) prefix = prefix.slice(0, prefix.lastIndexOf("/"));
2543
+ const parent = sources.get(prefix) ?? { file: project2, pointer: "" };
2544
+ const source = { file: parent.file, pointer: parent.pointer + path2.slice(prefix.length) };
2545
+ if (Object.keys(value2).length !== 1) issue(source.file, source.pointer, "A file reference must contain only $file.");
2546
+ const name = referencePath(value2.$file, source);
2547
+ let file;
2548
+ try {
2549
+ file = await realpath(join3(root, name));
2550
+ } catch {
2551
+ issue(join3(root, name), "", "Cannot read referenced file.");
2552
+ }
2553
+ const rel = relative(root, file);
2554
+ if (rel === ".." || rel.startsWith(".." + sep) || isAbsolute3(rel)) issue(source.file, source.pointer, "File reference leaves the authoring directory.");
2555
+ sources.set(path2, { file, pointer: "" });
2556
+ return { file, value: await text(file) };
2557
+ };
2558
+ const document = json((await load({ $file: "project.json" }, "")).value, project2);
2559
+ const agent = async (row2, key, path2) => {
2560
+ if (!reference(row2[key])) return;
2561
+ const ref = row2[key];
2562
+ const loaded = await load(ref, path2);
2563
+ const parsed = json(loaded.value, loaded.file);
2564
+ if (object2(parsed) && Object.hasOwn(parsed, "id") && Object.hasOwn(parsed, "config")) {
2565
+ for (const field of Object.keys(parsed)) if (!["id", "config"].includes(field)) issue(loaded.file, at("", field), "Unknown agent file field.");
2566
+ if (parsed.id !== key) issue(loaded.file, "/id", "Agent id must match the project.json agent key.");
2567
+ row2[key] = parsed.config;
2568
+ sources.set(path2, { file: loaded.file, pointer: "/config" });
2569
+ } else row2[key] = parsed;
2570
+ if (reference(row2[key])) issue(loaded.file, "", "Agent files must contain a config layer, not another reference.");
2571
+ };
2572
+ if (object2(document)) await visitLayer(document.config, "/config", async (row2, key, path2) => {
2573
+ if (reference(row2[key])) row2[key] = (await load(row2[key], path2)).value;
2574
+ }, agent);
2575
+ let compiled;
2576
+ try {
2577
+ compiled = compileRequirements(document);
2578
+ } catch (error) {
2579
+ if (error instanceof ConfigError) issue(project2, "/requires", "requires is compiler-owned.");
2580
+ throw error;
2581
+ }
2582
+ const result = await validate(compiled, sources, project2);
2583
+ return { id: result.id, schema: result.schema, document: result.document };
2584
+ }
2585
+ async function splitConfig(file, directory) {
2586
+ const document = json(await text(file), file);
2587
+ if (object2(document)) await visitLayer(document.config, "/config", async (row2, key, path2) => {
2588
+ if (reference(row2[key])) {
2589
+ referencePath(row2[key].$file, { file, pointer: path2 });
2590
+ issue(file, path2, "A snapshot cannot contain an authoring reference.");
2591
+ }
2592
+ }, async (row2, key, path2) => {
2593
+ if (reference(row2[key])) {
2594
+ referencePath(row2[key].$file, { file, pointer: path2 });
2595
+ issue(file, path2, "A snapshot cannot contain an authoring reference.");
2596
+ }
2597
+ });
2598
+ const result = await validate(document, /* @__PURE__ */ new Map(), file);
2599
+ if (object2(document)) delete document.requires;
2600
+ const files = /* @__PURE__ */ new Map();
2601
+ const manifest = {};
2602
+ let textIndex = 0, agentIndex = 0;
2603
+ if (object2(document)) await visitLayer(document.config, "/config", async (row2, key, path2) => {
2604
+ if (typeof row2[key] !== "string") return;
2605
+ const name = `text/${String(++textIndex).padStart(6, "0")}.txt`;
2606
+ manifest[name] = { path: path2 };
2607
+ files.set(name, row2[key]);
2608
+ row2[key] = { $file: name };
2609
+ }, async () => {
2610
+ });
2611
+ if (object2(document) && object2(document.config) && object2(document.config.agents)) {
2612
+ for (const [id, layer] of entries(document.config.agents)) {
2613
+ const name = `agents/${String(++agentIndex).padStart(6, "0")}.json`;
2614
+ manifest[name] = { path: at("/config/agents", id), id };
2615
+ files.set(name, JSON.stringify({ id, config: layer }, null, 2) + "\n");
2616
+ document.config.agents[id] = { $file: name };
2617
+ }
2618
+ }
2619
+ files.set("manifest.json", JSON.stringify({ schema: 1, files: manifest }, null, 2) + "\n");
2620
+ files.set("project.json", JSON.stringify(document, null, 2) + "\n");
2621
+ const output = resolve2(directory);
2622
+ await mkdir4(dirname3(output), { recursive: true });
2623
+ try {
2624
+ await mkdir4(output);
2625
+ } catch {
2626
+ issue(output, "", "Output directory already exists or cannot be created; nothing was overwritten.");
2627
+ }
2628
+ try {
2629
+ for (const [name, value2] of files) {
2630
+ const target2 = join3(output, name);
2631
+ await mkdir4(dirname3(target2), { recursive: true });
2632
+ await writeFile2(target2, value2, { flag: "wx" });
2633
+ }
2634
+ } catch (error) {
2635
+ await rm(output, { recursive: true, force: true });
2636
+ throw error;
2637
+ }
2638
+ return { directory: output, revision_id: result.id, schema: result.schema };
2639
+ }
2640
+ async function authoringCommand(action, args) {
2641
+ if (!args.output) throw new CliError("missing_argument", "Supply --output.");
2642
+ if (action === "split") return splitConfig(args.file, args.output);
2643
+ const result = await buildConfig(args.directory);
2644
+ try {
2645
+ await writeFile2(args.output, result.document, { flag: "wx" });
2646
+ } catch {
2647
+ issue(args.output, "", "Output file already exists or cannot be written; nothing was overwritten.");
2648
+ }
2649
+ return { file: args.output, revision_id: result.id, schema: result.schema };
2650
+ }
2651
+
2652
+ // src/core-defaults.ts
2653
+ var DEFAULT_CLOUD_URL = "https://api.croche.ai";
2654
+
2655
+ // src/debug-keys.ts
2656
+ import { appendFile, lstat as lstat3, open as open3, readFile as readFile4, realpath as realpath2, rename as rename3, unlink as unlink3 } from "node:fs/promises";
2657
+ import { execFile } from "node:child_process";
2658
+ import { promisify } from "node:util";
2659
+ import { basename, dirname as dirname4, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
2660
+ import { randomUUID as randomUUID3 } from "node:crypto";
2661
+ var exec = promisify(execFile);
2662
+ var assignment = /^(?:export[ \t]+)?CROCHE_DEBUG_KEY[ \t]*=([^\r\n]*)(\r?)$/gm;
2663
+ var value = (line2) => line2.trim().replace(/^(['"])(.*)\1$/, "$2");
2664
+ async function git(root, args) {
2665
+ try {
2666
+ return (await exec("git", ["-C", root, ...args])).stdout.trim();
2667
+ } catch (error) {
2668
+ if (error.code === "ENOENT") throw new CliError("git_unavailable", "Git is required to protect the debug-key file.");
2669
+ return null;
2670
+ }
2671
+ }
2672
+ async function target(file, force, stderr) {
2673
+ const requested = resolve3(file), parent = await realpath2(dirname4(requested)).catch(() => {
2674
+ throw new CliError("invalid_env_file", "The env file directory must exist.");
2675
+ });
2676
+ const path2 = resolve3(parent, basename(requested));
2677
+ let before = null, mode = 384;
2678
+ try {
2679
+ const info = await lstat3(path2);
2680
+ if (!info.isFile() || info.isSymbolicLink()) throw new CliError("invalid_env_file", "The env file must be a regular file, not a symlink.");
2681
+ before = await readFile4(path2);
2682
+ mode = info.mode & 4095;
2683
+ } catch (error) {
2684
+ if (error.code !== "ENOENT") throw error;
2685
+ }
2686
+ const root = await git(parent, ["rev-parse", "--show-toplevel"]);
2687
+ let ignore;
2688
+ if (root) {
2689
+ const entry = relative2(root, path2).split(sep2).join("/");
2690
+ if (await git(root, ["ls-files", "--error-unmatch", "--", entry]) !== null) throw new CliError("tracked_env_file", "Refusing to write a debug key into a tracked file.");
2691
+ if (await git(root, ["check-ignore", "--", entry]) === null) ignore = { root, entry };
2692
+ }
2693
+ const existing = before ? [...before.toString("latin1").matchAll(assignment)] : [];
2694
+ if (existing.length > 1) throw new CliError("invalid_env_file", "The env file contains multiple CROCHE_DEBUG_KEY assignments.");
2695
+ if (existing.some((match) => value(match[1]) !== "") && !force) throw new CliError("debug_key_exists", "CROCHE_DEBUG_KEY is already set; use --force to replace it. No key was issued.");
2696
+ if (before && mode & 63) stderr("warning: the existing env file is group- or world-readable; its mode will be preserved.\n");
2697
+ return { path: path2, before, mode, ignore };
2698
+ }
2699
+ async function ignoreFile(t) {
2700
+ if (!t.ignore) return;
2701
+ const path2 = resolve3(t.ignore.root, ".gitignore");
2702
+ let before = "";
2703
+ try {
2704
+ before = await readFile4(path2, "utf8");
2705
+ } catch (error) {
2706
+ if (error.code !== "ENOENT") throw error;
2707
+ }
2708
+ const entry = "/" + t.ignore.entry.replace(/[\\*?\[\]#! ]/g, "\\$&");
2709
+ await appendFile(path2, (before && !before.endsWith("\n") ? "\n" : "") + entry + "\n");
2710
+ }
2711
+ async function writeDebugEnv(t, secret) {
2712
+ const text2 = t.before?.toString("latin1") ?? "";
2713
+ const matches = [...text2.matchAll(assignment)];
2714
+ if (matches.length === 1 && value(matches[0][1]) === secret) return;
2715
+ const newline = text2.includes("\r\n") ? "\r\n" : "\n";
2716
+ const updated = matches.length ? text2.replace(assignment, (_line, _old, cr) => `CROCHE_DEBUG_KEY=${secret}${cr}`) : text2 + (text2 && !text2.endsWith("\n") ? newline : "") + `CROCHE_DEBUG_KEY=${secret}${newline}`;
2717
+ const temporary = resolve3(dirname4(t.path), `.croche-debug-${randomUUID3()}.tmp`);
2718
+ let handle;
2719
+ try {
2720
+ handle = await open3(temporary, "wx", 384);
2721
+ await handle.writeFile(Buffer.from(updated, "latin1"));
2722
+ if (t.before) await handle.chmod(t.mode);
2723
+ await handle.sync();
2724
+ await handle.close();
2725
+ handle = void 0;
2726
+ let current = null;
2727
+ try {
2728
+ current = await readFile4(t.path);
2729
+ } catch (error) {
2730
+ if (error.code !== "ENOENT") throw error;
2731
+ }
2732
+ if (t.before === null ? current !== null : current === null || !current.equals(t.before)) throw new Error("env file changed");
2733
+ await rename3(temporary, t.path);
2734
+ } finally {
2735
+ try {
2736
+ await handle?.close();
2737
+ } finally {
2738
+ await unlink3(temporary).catch(() => {
2739
+ });
2740
+ }
2741
+ }
2742
+ }
2743
+ async function debugKeys(action, args, client) {
2744
+ const project2 = args.project;
2745
+ if (!project2 || !/^[A-Za-z0-9_.:-]{1,200}$/.test(project2)) throw new CliError("missing_argument", "Supply --project with a project id.");
2746
+ const path2 = `/api/studio/projects/${encodeURIComponent(project2)}/debug-tokens`;
2747
+ const metadata = (t) => ({ id: t.id, name: t.name, prefix: typeof t.prefix === "string" ? t.prefix.slice(0, 12) : t.prefix, created_at: t.created_at, last_used_at: t.last_used_at, revoked_at: t.revoked_at, installations: t.installations, warning: t.warning });
2748
+ if (action === "list") {
2749
+ const result2 = await client.request(path2);
2750
+ return { debug_keys: result2.debug_tokens.map(metadata) };
2751
+ }
2752
+ if (action === "revoke") {
2753
+ if (!args["key-id"] || !/^[A-Za-z0-9_.:-]{1,200}$/.test(args["key-id"])) throw new CliError("missing_argument", "Supply a debug key id.");
2754
+ const result2 = await client.request(path2 + "/" + encodeURIComponent(args["key-id"]), "DELETE");
2755
+ return { debug_key: metadata(result2.debug_token) };
2756
+ }
2757
+ const stderr = client.context.stderr ?? ((text2) => process.stderr.write(text2));
2758
+ const destination = args.print === "true" && !args["dotenv-file"] ? void 0 : await target(args["dotenv-file"] ?? "./.env", args.force === "true", stderr);
2759
+ if (destination) await ignoreFile(destination);
2760
+ const result = await client.request(path2, "POST", { name: args.name ?? "Coding agent" });
2761
+ const key = metadata(result.debug_token);
2762
+ if (typeof result.secret !== "string" || !/^cdt_[a-f0-9]{64}$/.test(result.secret)) throw new CliError("invalid_response", `Cloud returned an invalid debug credential; revoke issued key ${key.id}.`, 1);
2763
+ if (destination) {
2764
+ try {
2765
+ await writeDebugEnv(destination, result.secret);
2766
+ } catch {
2767
+ throw new CliError("env_write_failed", `Could not safely write the env file. Revoke issued key ${key.id} with debug-keys revoke.`, 1, { key_id: key.id });
2768
+ }
2769
+ }
2770
+ return { debug_key: key, ...destination ? { dotenv_file: destination.path } : {}, ...args.print === "true" ? { secret: result.secret } : {} };
2771
+ }
2772
+
2773
+ // src/index.ts
2774
+ import { readFileSync } from "node:fs";
2775
+ import { readFile as readLocalFile } from "node:fs/promises";
2776
+ var CliError = class extends Error {
2777
+ constructor(code, message, exitCode = 2, details) {
2778
+ super(message);
2779
+ this.code = code;
2780
+ this.exitCode = exitCode;
2781
+ this.details = details;
2782
+ }
2783
+ };
2784
+ var segment = (value2) => {
2785
+ if (!value2 || value2.length > 200 || !/^[A-Za-z0-9_.:-]+$/.test(value2)) throw new CliError("invalid_argument", "Identifiers must contain 1\u2013200 letters, digits, dots, colons, underscores or hyphens.");
2786
+ return encodeURIComponent(value2);
2787
+ };
2788
+ function required(args, key) {
2789
+ const value2 = args[key];
2790
+ if (value2 === void 0 || !value2.trim()) throw new CliError("missing_argument", `Supply --${key}.`);
2791
+ return value2;
2792
+ }
2793
+ function number(value2, key, min = 0, max = 1e4) {
2794
+ if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value2) || !Number.isFinite(Number(value2)) || Number(value2) < min || Number(value2) > max) throw new CliError("invalid_argument", `${key} must be a number between ${min} and ${max}.`);
2795
+ return Number(value2);
2796
+ }
2797
+ function integer2(value2, key, min, max) {
2798
+ const result = number(value2, key, min, max);
2799
+ if (!Number.isInteger(result)) throw new CliError("invalid_argument", `${key} must be an integer.`);
2800
+ return result;
2801
+ }
2802
+ var project = (args) => `/api/studio/projects/${segment(required(args, "project"))}`;
2803
+ function projectBody(args) {
2804
+ return args.name !== void 0 ? { name: args.name } : {};
2805
+ }
2806
+ var localCommands = ["agents list", "status", "history", "send", "cancel", "tools"];
2807
+ var commandTable = [
2808
+ { path: "config bases", summary: "List known and unknown bundled bases, installation counts, and upload instructions.", flags: ["project", "cloud-url"], run: (a, c) => listBases(a, c) },
2809
+ { path: "config push-base", summary: "Upload one validated bundled config as an immutable base; does not publish a release.", positionals: ["file"], flags: ["project", "cloud-url"], run: async (a, c) => (await import("./config-push-base-35HX67AJ.js")).pushBase(a, c) },
2810
+ ...["build", "split"].map((action) => ({ path: `config ${action}`, summary: action === "build" ? "Build one validated snapshot from project.json and referenced agent/text files; unknown fields are refused with their source path." : "Split a snapshot into bounded numbered files and an id manifest in a new directory.", positionals: [action === "build" ? "directory" : "file"], flags: ["output"], run: (a) => authoringCommand(action, a) })),
2811
+ ...["create", "list", "revoke"].map((action) => ({ path: `debug-keys ${action}`, summary: { create: "Issue a debug key and safely write CROCHE_DEBUG_KEY to .env; the secret is hidden unless --print is explicit.", list: "List debug-key metadata without secrets.", revoke: "Revoke a debug key." }[action], positionals: action === "revoke" ? ["key-id"] : [], flags: ["project", ...action === "create" ? ["name", "dotenv-file"] : []], switches: action === "create" ? ["force", "print"] : [], run: (a, c) => debugKeys(action, a, c) })),
2812
+ ...["choose", "start", "stop", "status", "connect", "disconnect", "token", "runtimes"].map((action) => ({ path: action === "choose" ? "debug" : `debug ${action}`, summary: { choose: "Discover local Runtimes and select one interactively; automation gets a list. --studio-link prints a fresh one-time Studio link instead.", start: "Start or reuse the bundled local debugger without clearing captures, and print a one-time Studio link.", stop: "Stop the local debugger that debug start launched (its captures are discarded); the pairing token is kept. Not running is success.", status: "Inspect local debugger availability without printing credentials.", connect: "Observe an app-consented v2 attachment and print its viewer URL without a token.", disconnect: "Explain app-owned detachment; a viewer cannot change app consent.", token: "Explicitly reveal one saved credential: --role pairing (default), ingest, observe, or controller.", runtimes: "List local Runtimes and their debugger capability." }[action], flags: ["port", "connection-file", ...action === "stop" ? [] : ["control-connection-file"], ...["connect", "disconnect"].includes(action) ? ["attachment-id"] : [], ...["choose", "start", "connect"].includes(action) ? ["studio-origin"] : [], ...action === "start" ? ["remote", "allow-origin"] : [], ...action === "token" ? ["role"] : []], switches: action === "choose" ? ["studio-link"] : [], run: (a, c) => debugCommand(action, a, { env: c.env, fetch: c.context.fetch, selectRuntime: c.context.selectRuntime, launch: c.context.launchDebuggerService }) })),
2813
+ ...["get", "save", "list", "effective"].map((action) => ({ path: `config ${action}`, summary: { get: "Read a build-base-scoped draft or revision/version; --bundled-base selects the build base.", save: "Save a schema-7 patch; --base is the last read draft revision (CAS), --bundled-base is the build base.", list: "List versions and draft for --bundled-base (the build base).", effective: "Preview the latest released config applied to --bundled-base." }[action], positionals: action === "save" ? ["file"] : [], flags: ["project", "cloud-url", "bundled-base", ...{ get: ["revision", "version", "output"], save: ["base", "note"], list: [], effective: [] }[action]], run: (a, c) => configCommand(action, a, { ...c, writeFile: c.context.writeFile, stderr: c.context.stderr ?? ((text2) => process.stderr.write(text2)) }) })),
2814
+ { path: "login", summary: "Human-only: validate and save an account key from hidden terminal input or stdin. Never pass a key as an argument.", run: async (_, c) => {
2815
+ const key = await (c.context.readCredential ?? readCredentialInput)();
2816
+ if (!validCredential(key)) throw new CliError("invalid_credentials", "Supply a valid account key.", 3);
2817
+ const account = await c.request("/api/studio/account", "GET", void 0, key);
2818
+ const file = await storeCredential(c.env, key);
2819
+ return { account: account.account, stored_in: file };
2820
+ } },
2821
+ { path: "logout", summary: "Remove the saved account key; a key in the environment remains set.", run: async (_, c) => {
2822
+ await removeCredential(c.env);
2823
+ const active = environmentCredentialNames(c.env);
2824
+ return { logged_out: true, ...active.length ? { notice: `${active.join(" and ")} ${active.length > 1 ? "remain" : "remains"} set in your environment.` } : {} };
2825
+ } },
2826
+ { path: "auth whoami", summary: "Show your account, credential source with a prefix only, and the Studio that issues this Cloud's account keys.", run: async (_, c) => {
2827
+ const credential = await c.credential();
2828
+ return { ...await c.request("/api/studio/account", "GET", void 0, credential.key), credential: { source: credential.source, prefix: credential.key.slice(0, 11) }, ...c.cloud() };
2829
+ } },
2830
+ { path: "projects list", summary: "List your projects.", run: (_, c) => c.request("/api/studio/projects") },
2831
+ { path: "projects create", summary: "Create a project with a 10-credit monthly budget and app access enabled.", flags: ["name"], run: (a, c) => c.request("/api/studio/projects", "POST", { ...projectBody(a), name: required(a, "name") }) },
2832
+ { path: "projects get", summary: "Inspect a project.", positionals: ["project"], run: (a, c) => c.request(project(a)) },
2833
+ { path: "projects update", summary: "Rename a project or update routing from a JSON runtime policy file.", positionals: ["project"], flags: ["name", "policy-file"], run: async (a, c) => {
2834
+ const body = projectBody(a);
2835
+ if (a["policy-file"]) {
2836
+ try {
2837
+ const policy = JSON.parse(await c.readFile(a["policy-file"], "The runtime policy file"));
2838
+ if (!policy || typeof policy !== "object" || Array.isArray(policy) || Object.keys(policy).length !== 1 || !Object.hasOwn(policy, "routing")) throw new CliError("invalid_policy", "The runtime policy file may contain only routing. Change budgets, allowances and security settings in web Studio.");
2839
+ body.runtime_policy = policy;
2840
+ } catch (error) {
2841
+ if (error instanceof CliError) throw error;
2842
+ throw new CliError("invalid_file", "Runtime policy file must contain a readable JSON object.");
2843
+ }
2844
+ }
2845
+ if (!Object.keys(body).length) throw new CliError("missing_argument", "Supply at least one project setting.");
2846
+ return c.request(project(a), "PATCH", body);
2847
+ } },
2848
+ { path: "projects operations", summary: "List recent operations (server limit 500).", positionals: ["project"], flags: ["limit", "status", "type", "query"], run: (a, c) => {
2849
+ const query = new URLSearchParams();
2850
+ for (const flag of ["limit", "status", "type", "query"]) if (a[flag] !== void 0) query.set(flag === "query" ? "q" : flag, flag === "limit" ? String(integer2(a[flag], flag, 1, 500)) : a[flag]);
2851
+ return c.request(`${project(a)}/operations?${query}`);
2852
+ } },
2853
+ { path: "projects cost", summary: "Show all-time reported operation cost; usage your runtimes did not report is not included. Purpose defaults to production. Development credits are consumption of the development allowance, not extra charges. Unknown amounts make the total null. Zero operations means no received reports, not free usage.", positionals: ["project"], flags: ["purpose"], run: (a, c) => {
2854
+ const purpose = a.purpose ?? "production";
2855
+ if (!["production", "development"].includes(purpose)) throw new CliError("invalid_argument", "purpose must be production or development.");
2856
+ return c.request(`${project(a)}/cost${a.purpose === void 0 ? "" : `?purpose=${purpose}`}`);
2857
+ } },
2858
+ // Key metadata is readable with an account key; issuance and revocation belong to web Studio.
2859
+ ...[["development", "debug-tokens", "debug key (cdt_) for simulators and your own devices"], ["server", "server-keys", "server key (csk_) for a web app's own backend"]].flatMap(([kind, route]) => [
2860
+ { path: `keys ${kind} list`, summary: `List a project's ${kind === "development" ? "debug" : kind} keys with installations, last use${kind === "server" ? " and Runtime Credit spent" : " and misuse warnings"}.`, positionals: ["project"], run: (a, c) => c.request(`${project(a)}/${route}`) }
2861
+ ]),
2862
+ { path: "projects usage", summary: "Usage per end user and per agent, project budget left and the weekly development allowance left.", positionals: ["project"], flags: ["period"], run: (a, c) => {
2863
+ const period = a.period ?? "month";
2864
+ if (!["week", "month", "all"].includes(period)) throw new CliError("invalid_argument", "period must be week, month or all.");
2865
+ return c.request(`${project(a)}/usage?period=${period}`);
2866
+ } },
2867
+ { path: "attestation get", summary: "Show the App Attest and Play Integrity settings (the decryption key is never returned).", positionals: ["project"], run: (a, c) => c.request(`${project(a)}/attestation`) },
2868
+ { path: "runtimes list", summary: "List Cloud Runtime enrollments for a project.", flags: ["project"], run: (a, c) => c.request(`${project(a)}/runtimes`) },
2869
+ { path: "control serve", summary: "Start a v2 loopback broker with distinct ingest/controller credentials.", flags: ["port", "allow-origin", "remote"], run: async (a, c) => {
2870
+ if (!c.context.serveControl) throw new CliError("unavailable", "Control server is unavailable in this embedding.", 1);
2871
+ const token = c.env.CROCHE_CONTROL_TOKEN, ingestToken = c.env.CROCHE_CONTROL_INGEST_TOKEN;
2872
+ if (!token || !ingestToken || token === ingestToken) throw new CliError("missing_configuration", "Set distinct CROCHE_CONTROL_TOKEN and CROCHE_CONTROL_INGEST_TOKEN for v2.");
2873
+ return c.context.serveControl({ token, ingestToken, ...c.env.CROCHE_CONTROL_OBSERVE_TOKEN ? { observeToken: c.env.CROCHE_CONTROL_OBSERVE_TOKEN } : {}, port: integer2(a.port ?? "8791", "port", 1, 65535), origins: a["allow-origin"] ? a["allow-origin"].split(",") : [], ...a.remote ? { remoteAddress: a.remote } : {} });
2874
+ } },
2875
+ { path: "runtime list", summary: "List Runtimes explicitly attached to the local control broker.", flags: ["control-url"], run: (a, c) => requestControl("list", a, c.env, c.context.fetch) },
2876
+ { path: "runtime result", summary: "Inspect a prior control request without resubmitting it.", flags: ["request-id", "control-url"], run: (a, c) => requestControl("result", { ...a, "request-id": required(a, "request-id") }, c.env, c.context.fetch) },
2877
+ ...localCommands.map((action) => ({ path: `runtime ${action}`, summary: `Run local Runtime ${action}; requires its advertised capability and exact v2 target.`, flags: ["attachment-id", "agent-id", "instance", "open-sequence", "control-url", "request-id", "wait-ms", ...action === "send" ? ["id", "text", "text-file", "kind"] : [], ...action === "history" ? ["offset", "limit"] : []], run: async (a, c) => {
2878
+ required(a, "attachment-id");
2879
+ if (action === "send") {
2880
+ required(a, "id");
2881
+ if (a.text !== void 0 === (a["text-file"] !== void 0)) throw new CliError("invalid_argument", "Supply exactly one of --text or --text-file.");
2882
+ if (a["text-file"]) {
2883
+ try {
2884
+ a = { ...a, text: await c.readFile(a["text-file"], "The text file") };
2885
+ } catch (error) {
2886
+ if (error instanceof CliError) throw error;
2887
+ throw new CliError("invalid_file", "The text file could not be read.");
2888
+ }
2889
+ }
2890
+ }
2891
+ return requestControl(action.replace(" ", "."), a, c.env, c.context.fetch);
2892
+ } }))
2893
+ ];
2894
+ var commands = commandTable.map((command) => command.positionals?.includes("project") ? { ...command, flags: [...command.flags ?? [], "project"] } : command);
2895
+ function help(prefix = "") {
2896
+ if (!prefix) return overview();
2897
+ const visible = commands.filter((command) => command.path === prefix || command.path.startsWith(prefix + " "));
2898
+ if (!visible.length) throw new CliError("unknown_command", "Unknown command. Run croche --help.");
2899
+ const exact = visible.find((command) => command.path === prefix);
2900
+ if (visible.length === 1 && exact) return commandHelp(exact);
2901
+ return groupHelp(prefix, visible) + (exact ? "\n" + commandHelp(exact) : "");
2902
+ }
2903
+ function globalOptions(argv) {
2904
+ const words2 = [];
2905
+ let json2 = false, asking = false, version2 = false;
2906
+ for (let index = 0; index < argv.length; index++) {
2907
+ const token = argv[index];
2908
+ if (token === "--json") {
2909
+ json2 = true;
2910
+ continue;
2911
+ }
2912
+ if (token === "--version" && !(argv[0] === "config" && argv[1] === "get" && index > 1)) {
2913
+ version2 = true;
2914
+ continue;
2915
+ }
2916
+ if (token === "--help" || token === "-h") {
2917
+ asking = true;
2918
+ continue;
2919
+ }
2920
+ words2.push(token);
2921
+ if (token.startsWith("--") && !token.includes("=") && !commands.some((c) => c.switches?.includes(token.slice(2))) && index + 1 < argv.length) words2.push(argv[++index]);
2922
+ }
2923
+ return { words: words2, json: json2, asking, version: version2 };
2924
+ }
2925
+ function cliVersion() {
2926
+ try {
2927
+ return String(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
2928
+ } catch {
2929
+ throw new CliError("unavailable", "The CLI version could not be read.", 1);
2930
+ }
2931
+ }
2932
+ function parse(argv, env) {
2933
+ const { words: words2, json: json2, asking, version: version2 } = globalOptions(argv);
2934
+ if (version2 && !asking) return { args: {}, json: json2, version: cliVersion() };
2935
+ if (!words2.length || asking) {
2936
+ const prefix = words2.slice(0, words2.findIndex((word) => word.startsWith("--")) < 0 ? void 0 : words2.findIndex((word) => word.startsWith("--"))).join(" ");
2937
+ const exact = commands.find((c) => prefix === c.path || prefix.startsWith(c.path + " "));
2938
+ return { args: {}, json: json2, help: help(exact?.path ?? prefix) };
2939
+ }
2940
+ const command = [...commands].sort((a, b) => b.path.length - a.path.length).find((c) => c.path.split(" ").every((word, index) => words2[index] === word));
2941
+ if (!command) throw new CliError("unknown_command", "Unknown command. Run croche --help.");
2942
+ const rest = words2.slice(command.path.split(" ").length), args = {}, positional = [...command.positionals ?? []];
2943
+ let positionalProject;
2944
+ for (let index = 0; index < rest.length; index++) {
2945
+ const token = rest[index] === "-o" && command.path === "config get" ? "--output" : rest[index];
2946
+ if (!token.startsWith("--")) {
2947
+ const key2 = positional.shift();
2948
+ if (!key2) throw new CliError("unexpected_argument", "Unexpected positional argument.");
2949
+ if (key2 === "project") {
2950
+ positionalProject = token;
2951
+ continue;
2952
+ }
2953
+ if (args[key2] !== void 0) throw new CliError("duplicate_argument", `Duplicate ${key2}.`);
2954
+ args[key2] = token;
2955
+ continue;
2956
+ }
2957
+ const equals = token.indexOf("="), key = token.slice(2, equals < 0 ? void 0 : equals);
2958
+ if (key === "project-id") throw new CliError("invalid_argument", "--project-id is retired; use --project.");
2959
+ if (command.switches?.includes(key) && equals < 0) {
2960
+ if (args[key] !== void 0) throw new CliError("duplicate_argument", `Duplicate --${key}.`);
2961
+ args[key] = "true";
2962
+ continue;
2963
+ }
2964
+ if (![...command.flags ?? [], ...command.switches ?? [], ...command.positionals ?? []].includes(key)) throw new CliError("unknown_option", `Unknown option --${key}.`);
2965
+ if (args[key] !== void 0) throw new CliError("duplicate_argument", `Duplicate --${key}.`);
2966
+ const value2 = equals < 0 ? rest[++index] : token.slice(equals + 1);
2967
+ if (value2 === void 0) throw new CliError("missing_argument", `Supply a value for --${key}.`);
2968
+ args[key] = value2;
2969
+ }
2970
+ if (command.flags?.includes("project")) {
2971
+ if (positionalProject !== void 0 && args.project !== void 0 && positionalProject !== args.project) throw new CliError("invalid_argument", "The positional project id and --project must agree.");
2972
+ args.project = args.project ?? positionalProject ?? env.CROCHE_PROJECT ?? "";
2973
+ segment(required(args, "project"));
2974
+ }
2975
+ for (const key of command.positionals ?? []) required(args, key);
2976
+ return { command, args, json: json2 };
2977
+ }
2978
+ var STUDIO_FOR = { "https://api.croche.ai": "https://studio.croche.ai", "https://api.dev.croche.ai": "https://studio.dev.croche.ai" };
2979
+ function studioUrl(origin2) {
2980
+ return Object.hasOwn(STUDIO_FOR, origin2) ? STUDIO_FOR[origin2] : null;
2981
+ }
2982
+ function cloudUrl(value2) {
2983
+ if (value2 === void 0) return DEFAULT_CLOUD_URL;
2984
+ let url;
2985
+ try {
2986
+ url = new URL(value2);
2987
+ } catch {
2988
+ throw new CliError("invalid_configuration", "CROCHE_CLOUD_URL must be an absolute HTTPS origin.");
2989
+ }
2990
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || !(url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) throw new CliError("invalid_configuration", "CROCHE_CLOUD_URL must be HTTPS, or HTTP on loopback, without credentials, query, fragment, or path.");
2991
+ return url.origin;
2992
+ }
2993
+ async function runCli(argv, context = {}) {
2994
+ const env = context.env ?? process.env, stdout = context.stdout ?? ((text2) => process.stdout.write(text2)), stderr = context.stderr ?? ((text2) => process.stderr.write(text2));
2995
+ const jsonMode = globalOptions(argv).json;
2996
+ const secrets = new Set([env.CROCHE_ACCOUNT_KEY, env.CROCHE_DEVELOPER_KEY, env.CROCHE_CONTROL_TOKEN].filter((value2) => Boolean(value2)));
2997
+ try {
2998
+ const parsed = parse(argv, env);
2999
+ if (parsed.help) {
3000
+ stdout(parsed.json ? JSON.stringify({ ok: true, data: { help: parsed.help } }) + "\n" : parsed.help);
3001
+ return 0;
3002
+ }
3003
+ if (parsed.version) {
3004
+ stdout(parsed.json ? JSON.stringify({ ok: true, data: { version: parsed.version } }) + "\n" : `croche ${parsed.version}
3005
+ `);
3006
+ return 0;
3007
+ }
3008
+ const clientEnv = { ...env, ...parsed.command?.path.startsWith("config ") && parsed.args["cloud-url"] !== void 0 ? { CROCHE_CLOUD_URL: parsed.args["cloud-url"] } : {} };
3009
+ if (clientEnv.CROCHE_CLOUD_URL === void 0) clientEnv.CROCHE_CLOUD_URL = DEFAULT_CLOUD_URL;
3010
+ const cloud = () => {
3011
+ const origin2 = cloudUrl(clientEnv.CROCHE_CLOUD_URL);
3012
+ return { cloud_url: origin2, studio_url: studioUrl(origin2) };
3013
+ };
3014
+ const credentialFor = async () => {
3015
+ try {
3016
+ return await resolveCredential(clientEnv);
3017
+ } catch (error) {
3018
+ if (error instanceof CliError && error.code === "missing_credentials") throw new CliError(error.code, error.message, error.exitCode, { ...error.details && typeof error.details === "object" ? error.details : {}, ...cloud() });
3019
+ throw error;
3020
+ }
3021
+ };
3022
+ const client = { env: clientEnv, cloud, credential: credentialFor, context: parsed.json ? { ...context, selectRuntime: void 0 } : context, readFile: async (path2, what) => decodeTextFile(context.readFile ? await context.readFile(path2) : await readLocalFile(path2), what), request: async (path2, method = "GET", body, override) => {
3023
+ const credential = override ?? (await credentialFor()).key;
3024
+ secrets.add(credential);
3025
+ const origin2 = cloudUrl(clientEnv.CROCHE_CLOUD_URL);
3026
+ const headers = { Authorization: `Bearer ${credential}` };
3027
+ if (body !== void 0) headers["Content-Type"] = "application/json";
3028
+ let response;
3029
+ try {
3030
+ response = await (context.fetch ?? fetch)(origin2 + path2, { method, headers, body: body === void 0 ? void 0 : JSON.stringify(body), credentials: "omit", redirect: "error", signal: AbortSignal.timeout(3e4) });
3031
+ } catch {
3032
+ throw new CliError("transport_error", "Cloud request failed or timed out; no automatic retry was made.", 4);
3033
+ }
3034
+ const data = await readResponse(response);
3035
+ if (!response.ok) throw new CliError(String(data?.error?.code ?? "remote_error"), String(data?.error?.message ?? "Cloud rejected the request.") + (data?.error?.code === "draft_conflict" ? ` Current head: ${data.error.details?.head ?? "null"}.` : ""), [401, 403].includes(response.status) ? 3 : 1, data?.error?.details);
3036
+ return data;
3037
+ } };
3038
+ const result = await parsed.command.run(parsed.args, client);
3039
+ if (!parsed.json && parsed.command.path.startsWith("debug")) {
3040
+ const debugResult = result;
3041
+ if (debugResult.viewerUrl) stdout(`${debugResult.viewerUrl}${debugResult.studioUrl ? `
3042
+ ${debugResult.studioUrl}` : ""}
3043
+
3044
+ ${debugResult.instruction}
3045
+ `);
3046
+ else if (debugResult.studioUrl && !debugResult.status) stdout(`${debugResult.studioUrl}
3047
+
3048
+ ${debugResult.instruction}
3049
+ `);
3050
+ else if (debugResult.pairingToken) stdout(`${debugResult.pairingToken}
3051
+ `);
3052
+ else stdout(JSON.stringify(result, null, 2) + "\n");
3053
+ return 0;
3054
+ }
3055
+ stdout(JSON.stringify(parsed.json ? { ok: true, data: jsonResult(parsed.command.path, result) } : result, null, parsed.json ? void 0 : 2) + "\n");
3056
+ return 0;
3057
+ } catch (error) {
3058
+ const issue2 = error instanceof CliError ? error : new CliError("internal_error", "The command could not be completed.", 1);
3059
+ let message = issue2.message;
3060
+ for (const secret of secrets) if (secret) message = message.replaceAll(secret, "[redacted]");
3061
+ const output = { ok: false, error: { code: issue2.code, message, ...issue2.details ? { details: issue2.details } : {} } };
3062
+ let rendered = jsonMode ? JSON.stringify(output) + "\n" : `${issue2.code}: ${message}
3063
+ `;
3064
+ for (const secret of secrets) if (secret) rendered = rendered.replaceAll(secret, "[redacted]");
3065
+ if (jsonMode) stdout(rendered);
3066
+ else stderr(rendered);
3067
+ return issue2.exitCode;
3068
+ }
3069
+ }
3070
+ async function readResponse(response, limit = 1024 * 1024) {
3071
+ const reader = response.body?.getReader();
3072
+ if (!reader) throw new CliError("invalid_response", "The server returned an empty response.", 4);
3073
+ const chunks = [];
3074
+ let length = 0;
3075
+ try {
3076
+ while (true) {
3077
+ const part = await reader.read();
3078
+ if (part.done) break;
3079
+ length += part.value.byteLength;
3080
+ if (length > limit) throw new CliError("response_too_large", "The response exceeded its size limit; request a smaller page.", 4);
3081
+ chunks.push(part.value);
3082
+ }
3083
+ } catch (error) {
3084
+ void reader.cancel().catch(() => {
3085
+ });
3086
+ throw error instanceof CliError ? error : new CliError("transport_error", "The response body could not be read.", 4);
3087
+ } finally {
3088
+ reader.releaseLock();
3089
+ }
3090
+ const bytes = new Uint8Array(length);
3091
+ let offset = 0;
3092
+ for (const chunk of chunks) {
3093
+ bytes.set(chunk, offset);
3094
+ offset += chunk.byteLength;
3095
+ }
3096
+ try {
3097
+ return JSON.parse(new TextDecoder().decode(bytes));
3098
+ } catch {
3099
+ throw new CliError("invalid_response", "The server returned invalid JSON.", 4);
3100
+ }
3101
+ }
3102
+
3103
+ export {
3104
+ CliError,
3105
+ commands,
3106
+ help,
3107
+ studioUrl,
3108
+ runCli,
3109
+ readResponse
3110
+ };