@usepowerplant/cli 0.4.25 → 0.4.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d8a10efc-d51d-5eaf-94f5-f1daf8755a2a")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c205f968-8b28-5dc5-9420-5b3fae8d2c6f")}catch(e){}}();
3
3
  import { createRequire as __cliCreateRequire } from 'node:module';
4
4
  const require = __cliCreateRequire(import.meta.url);
5
5
  var __create = Object.create;
@@ -56526,18 +56526,6 @@ function harnessFromLegacySessionSource(source) {
56526
56526
  if (source === "github-pr") return { kind: "not-harness", source };
56527
56527
  return { kind: "harness", harness: SESSION_SOURCE_HARNESSES[source] };
56528
56528
  }
56529
- var LEGACY_SESSION_SOURCE_BY_HARNESS = {
56530
- "claude-local": "claude-code",
56531
- "claude-cloud": "claude-cloud",
56532
- "codex-local": "codex",
56533
- "codex-cloud": null,
56534
- "cursor-local": "cursor",
56535
- "cursor-cloud": "cursor-cloud"
56536
- };
56537
- function legacySessionSourceFromHarness(harness) {
56538
- const source = LEGACY_SESSION_SOURCE_BY_HARNESS[harness];
56539
- return source === null ? { kind: "unsupported", harness } : { kind: "supported", source };
56540
- }
56541
56529
 
56542
56530
  // ../core/src/sessionIngest.ts
56543
56531
  var LEGACY_SESSION_SOURCES = [
@@ -56555,24 +56543,13 @@ function isLegacySessionSource(source) {
56555
56543
  }
56556
56544
  var SESSION_ACTIVE_WINDOW_MS = 30 * 60 * 1e3;
56557
56545
  var LEGACY_COLLECTOR_SESSION_SOURCES = ["claude-code", "codex", "cursor"];
56558
- var LEGACY_PREVIEW_REGISTRABLE_SOURCES = [
56559
- ...LEGACY_COLLECTOR_SESSION_SOURCES,
56560
- "cursor-cloud"
56561
- ];
56562
56546
  var COLLECTOR_SESSION_HARNESSES = [
56563
56547
  "claude-local",
56564
56548
  "codex-local",
56565
56549
  "cursor-local"
56566
56550
  ];
56567
- var PREVIEW_REGISTRABLE_HARNESSES = [
56568
- ...COLLECTOR_SESSION_HARNESSES,
56569
- "cursor-cloud"
56570
- ];
56571
56551
  var MAX_INGEST_BATCH = 500;
56572
56552
  var MAX_RAW_UPLOAD_BYTES = 256 * 1024 * 1024;
56573
- var MAX_PREVIEW_URL_LENGTH = 2e3;
56574
- var MAX_REGISTERED_PREVIEWS = 10;
56575
- var MAX_PREVIEW_LABEL_LENGTH = 60;
56576
56553
  var MAX_BRANCH_FACTS = 50;
56577
56554
 
56578
56555
  // ../core/src/menubarAnalytics.ts
@@ -56587,46 +56564,6 @@ var menubarEventSchema = external_exports.discriminatedUnion("event", [
56587
56564
  mcpWarningDismissalSchema.extend({ event: external_exports.literal(MENUBAR_MCP_WARNING_REMOVE) })
56588
56565
  ]);
56589
56566
 
56590
- // ../core/src/messageOrigin.ts
56591
- var CLAUDE_CODE_NATIVE_ORIGINS = /* @__PURE__ */ new Set(["human", "agent", "harness", "tool"]);
56592
- var CLAUDE_CODE_TASK_NOTIFICATION_ORIGIN = "task-notification";
56593
- var SYSTEM_REMINDER = /<system-reminder(?:\s|>)/u;
56594
- function claudeCodeMessageOrigin(facts, text) {
56595
- let origin = !facts.originRecorded && facts.recordType === "assistant" && facts.role === "assistant" ? "agent" : "unknown";
56596
- if (facts.nativeOrigin !== null && CLAUDE_CODE_NATIVE_ORIGINS.has(facts.nativeOrigin)) {
56597
- origin = facts.nativeOrigin;
56598
- }
56599
- if (facts.nativeOrigin === CLAUDE_CODE_TASK_NOTIFICATION_ORIGIN || facts.commandMode === CLAUDE_CODE_TASK_NOTIFICATION_ORIGIN || facts.isMeta === true || facts.isCompactSummary === true || facts.model === "<synthetic>") {
56600
- origin = "harness";
56601
- }
56602
- return origin === "human" && SYSTEM_REMINDER.test(text) ? "mixed" : origin;
56603
- }
56604
- var CODEX_USER_MESSAGE_MARKER = "## My request for Codex:";
56605
- var CODEX_MARKER_LINE = /^## My request for Codex:/mu;
56606
- var CODEX_CONTEXT_BLOCK = /^<[a-z_]+>/i;
56607
- var CODEX_AGENTS_MD_BLOCK = /^#+ AGENTS\.md instructions/;
56608
- var CODEX_CONTEXT_WINDOW_OPEN = "<context_window>";
56609
- var CODEX_CONTEXT_WINDOW_CLOSE = "</context_window>";
56610
- function isCodexMarkerPrefix(prefix) {
56611
- const trimmed = prefix.trim();
56612
- if (trimmed === "") return true;
56613
- return trimmed.startsWith(CODEX_CONTEXT_WINDOW_OPEN) && trimmed.endsWith(CODEX_CONTEXT_WINDOW_CLOSE) && trimmed.indexOf(CODEX_CONTEXT_WINDOW_CLOSE) === trimmed.length - CODEX_CONTEXT_WINDOW_CLOSE.length;
56614
- }
56615
- function codexPromptBlock(text) {
56616
- const trimmed = text.trim();
56617
- if (trimmed === "" || CODEX_AGENTS_MD_BLOCK.test(trimmed)) return { origin: "harness", ask: null };
56618
- const marker = CODEX_MARKER_LINE.exec(text);
56619
- if (marker !== null && isCodexMarkerPrefix(text.slice(0, marker.index))) {
56620
- return { origin: "human", ask: text.slice(marker.index + CODEX_USER_MESSAGE_MARKER.length).trim() };
56621
- }
56622
- if (CODEX_CONTEXT_BLOCK.test(trimmed)) return { origin: "harness", ask: null };
56623
- return { origin: "unknown", ask: trimmed };
56624
- }
56625
- function codexPromptOrigin(keptBlockOrigins) {
56626
- if (keptBlockOrigins.length === 0) return "unknown";
56627
- return keptBlockOrigins.every((origin) => origin === "human") ? "human" : "unknown";
56628
- }
56629
-
56630
56567
  // ../core/src/rawTranscriptBundle.ts
56631
56568
  var RAW_TRANSCRIPT_BUNDLE_CONTENT_TYPE = "application/vnd.powerplant.raw-transcript-bundle";
56632
56569
  var RAW_TRANSCRIPT_PART_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
@@ -56871,15 +56808,6 @@ function describeImageBlock(block2) {
56871
56808
  }
56872
56809
  return { mediaType, bytes: null };
56873
56810
  }
56874
- function describeImageUrl(url2) {
56875
- if (typeof url2 !== "string") return { mediaType: null, bytes: null };
56876
- const dataUri = IMAGE_DATA_URI_RE.exec(url2);
56877
- if (dataUri) {
56878
- const [, mediaType = "", data = ""] = dataUri;
56879
- return { mediaType, bytes: base64ByteLength(data) };
56880
- }
56881
- return { mediaType: null, bytes: null };
56882
- }
56883
56811
  function imageLabel(image) {
56884
56812
  const detail = [image.mediaType, image.bytes === null ? null : formatByteSize(image.bytes)].filter((part) => part !== null).join(", ");
56885
56813
  return detail === "" ? "[image]" : `[image: ${detail}]`;
@@ -57179,532 +57107,8 @@ function boundText(redacted, maxBytes) {
57179
57107
  return { text: cut, truncated: true, originalBytes: bytes.length };
57180
57108
  }
57181
57109
 
57182
- // ../core/src/codeHost.ts
57183
- function pullRequestId(ref) {
57184
- return `${repositoryId(ref.host, ref.repository)}#${ref.number}`;
57185
- }
57186
- function repositoryId(host, repository) {
57187
- return `${host}:${repository}`;
57188
- }
57189
- var REMOTE_SCHEME = /^(?:https?|ssh|git):\/\//;
57190
- var REMOTE_USER = /^[^/@\s]+@/;
57191
- var REMOTE_PORT = /^:\d+\//;
57192
- var REMOTE_PATH_SEGMENT = /^[\w.-]+$/;
57193
- function githubRepositoryOfRemote(url2) {
57194
- const hasScheme = REMOTE_SCHEME.test(url2);
57195
- const afterUser = url2.replace(REMOTE_SCHEME, "").replace(REMOTE_USER, "");
57196
- const host = afterUser.startsWith("ssh.") ? afterUser.slice("ssh.".length) : afterUser;
57197
- if (!host.startsWith("github.com")) return null;
57198
- let path55 = host.slice("github.com".length);
57199
- const port = hasScheme ? REMOTE_PORT.exec(path55) : null;
57200
- if (port !== null) path55 = path55.slice(port[0].length);
57201
- else if (path55.startsWith("/") || path55.startsWith(":")) path55 = path55.slice(1);
57202
- else return null;
57203
- if (path55.endsWith("/")) path55 = path55.slice(0, -1);
57204
- if (path55.endsWith(".git")) path55 = path55.slice(0, -".git".length);
57205
- const segments = path55.split("/");
57206
- if (segments.length !== 2 || !segments.every((segment) => REMOTE_PATH_SEGMENT.test(segment))) return null;
57207
- return path55;
57208
- }
57209
- var PUSH_DESTINATION = /\bTo\s+([^\s\\"]+)/g;
57210
- function pushDestinationsInText(text) {
57211
- const repositories = [];
57212
- for (const match of text.matchAll(PUSH_DESTINATION)) {
57213
- const repository = githubRepositoryOfRemote(match[1]);
57214
- if (repository !== null) repositories.push(repositoryId("github", repository));
57215
- }
57216
- return repositories;
57217
- }
57218
- var GITHUB_PULL_URL = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)(?!\d)/g;
57219
- function pullRequestRefsInText(text) {
57220
- const refs = [];
57221
- const seen = /* @__PURE__ */ new Set();
57222
- for (const match of text.matchAll(GITHUB_PULL_URL)) {
57223
- const ref = { host: "github", repository: match[1], number: Number(match[2]) };
57224
- const id = pullRequestId(ref);
57225
- if (seen.has(id)) continue;
57226
- seen.add(id);
57227
- refs.push(ref);
57228
- }
57229
- return refs;
57230
- }
57231
- var PULL_REQUEST_ALREADY_EXISTS = /a pull request for branch \S+ into branch \S+ already exists:/;
57232
- function pullRequestAlreadyExistsInText(text) {
57233
- return PULL_REQUEST_ALREADY_EXISTS.test(text);
57234
- }
57235
- function pullRequestRefFromUrl(url2) {
57236
- return pullRequestRefsInText(url2)[0] ?? null;
57237
- }
57238
- var MAY_TOUCH_HOST = /\b(?:git|gh)\b/;
57239
- function readCodeHostCommands(command, currentBranch) {
57240
- return readCommands(command, currentBranch, 0);
57241
- }
57242
- var SUBSTITUTION_DEPTH_MAX = 4;
57243
- function readCommands(command, currentBranch, depth) {
57244
- const result = { pushes: [], pullRequestCreates: [] };
57245
- if (!MAY_TOUCH_HOST.test(command)) return result;
57246
- const chain = shellCommands(command);
57247
- let branch = currentBranch;
57248
- chain.forEach((simple, i) => {
57249
- const program = programOf(simple.words);
57250
- if (program === null) {
57251
- if (depth >= SUBSTITUTION_DEPTH_MAX) return;
57252
- const alone = simple.words.length === 1 && simple.next === null;
57253
- for (const substituted of simple.assignedSubstitutions) {
57254
- for (const create of readCommands(substituted, branch, depth + 1).pullRequestCreates) {
57255
- result.pullRequestCreates.push({ ...create, ownExitStatus: create.ownExitStatus && alone });
57256
- }
57257
- }
57258
- return;
57259
- }
57260
- if (program.name === "git") {
57261
- const git = gitSubcommand(program.args);
57262
- if (git === null) return;
57263
- if (git.name === "push") {
57264
- const ownExitStatus = exitStatusIsOwn(chain, i);
57265
- const { remote, branches } = pushedBranches(git.args, branch);
57266
- result.pushes.push(...branches.map((pushed) => ({ remote, branch: pushed, ownExitStatus })));
57267
- } else if (git.name === "checkout" || git.name === "switch") {
57268
- const target = checkoutTarget(git.args);
57269
- if (target !== void 0) branch = target;
57270
- }
57271
- } else if (program.name === "gh") {
57272
- const args = ghSubcommandArgs(program.args);
57273
- if (args[0] === "pr" && args[1] === "create") {
57274
- const head = optionValue(args.slice(2), ["--head", "-H"]);
57275
- result.pullRequestCreates.push({ head: head ?? branch, ownExitStatus: chain[i].next === null });
57276
- }
57277
- }
57278
- });
57279
- return result;
57280
- }
57281
- var REJECTED_REF = /!\s+\[(?:remote )?rejected\]\s+\S+\s+->\s+([A-Za-z0-9._/-]+)/g;
57282
- var UPDATED_REF = /(?:\*\s+\[new branch\]|\+?\s*[0-9a-f]{6,}\.{2,3}[0-9a-f]{6,})\s+\S+\s+->\s+([A-Za-z0-9._/-]+)/g;
57283
- function pushOutcomeInText(text, branch) {
57284
- const rejected = [...text.matchAll(REJECTED_REF)].map((match) => match[1]);
57285
- if (rejected.includes(branch)) return false;
57286
- const updated = [...text.matchAll(UPDATED_REF)].map((match) => match[1]);
57287
- if (updated.includes(branch)) return true;
57288
- if (rejected.length > 0 || /error: failed to push some refs/.test(text)) return false;
57289
- return /Everything up-to-date/.test(text) ? true : null;
57290
- }
57291
- var ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
57292
- var ASSIGNMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*=$/;
57293
- function programOf(words) {
57294
- let i = 0;
57295
- while (i < words.length && (ENV_ASSIGNMENT.test(words[i]) || words[i] === "env")) i += 1;
57296
- const program = words[i];
57297
- if (program === void 0) return null;
57298
- return { name: program.slice(program.lastIndexOf("/") + 1), args: words.slice(i + 1) };
57299
- }
57300
- var GIT_GLOBAL_VALUE_OPTIONS = /* @__PURE__ */ new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"]);
57301
- function gitSubcommand(args) {
57302
- for (let i = 0; i < args.length; i++) {
57303
- const arg = args[i];
57304
- if (arg.startsWith("-")) {
57305
- if (GIT_GLOBAL_VALUE_OPTIONS.has(arg)) i += 1;
57306
- continue;
57307
- }
57308
- return { name: arg, args: args.slice(i + 1) };
57309
- }
57310
- return null;
57311
- }
57312
- var GH_GLOBAL_VALUE_OPTIONS = /* @__PURE__ */ new Set(["-R", "--repo"]);
57313
- function ghSubcommandArgs(args) {
57314
- for (let i = 0; i < args.length; i++) {
57315
- const arg = args[i];
57316
- if (!arg.startsWith("-")) return args.slice(i);
57317
- if (GH_GLOBAL_VALUE_OPTIONS.has(arg)) i += 1;
57318
- }
57319
- return [];
57320
- }
57321
- var PUSH_VALUE_OPTIONS = /* @__PURE__ */ new Set(["-o", "--push-option", "--receive-pack", "--exec", "--repo"]);
57322
- var PUSH_WITHOUT_BRANCH = /* @__PURE__ */ new Set(["--all", "--branches", "--mirror", "--tags", "-d", "--delete", "-n", "--dry-run"]);
57323
- var REF_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
57324
- function pushedBranches(args, currentBranch) {
57325
- const positional = [];
57326
- for (let i = 0; i < args.length; i++) {
57327
- const arg = args[i];
57328
- if (arg === "--") {
57329
- positional.push(...args.slice(i + 1));
57330
- break;
57331
- }
57332
- if (PUSH_WITHOUT_BRANCH.has(arg)) return { remote: null, branches: [] };
57333
- if (arg.startsWith("-")) {
57334
- if (PUSH_VALUE_OPTIONS.has(arg)) i += 1;
57335
- continue;
57336
- }
57337
- positional.push(arg);
57338
- }
57339
- const remote = positional[0] ?? null;
57340
- const refspecs = positional.slice(1);
57341
- if (refspecs.length === 0) return { remote, branches: [currentBranch] };
57342
- const branches = [];
57343
- for (const refspec of refspecs) {
57344
- const branch = refspecBranch(refspec, currentBranch);
57345
- if (branch !== void 0) branches.push(branch);
57346
- }
57347
- return { remote, branches };
57348
- }
57349
- function refspecBranch(refspec, currentBranch) {
57350
- const spec = refspec.startsWith("+") ? refspec.slice(1) : refspec;
57351
- if (spec.startsWith(":")) return void 0;
57352
- const colon = spec.indexOf(":");
57353
- const destination = colon === -1 ? spec : spec.slice(colon + 1);
57354
- if (destination === "HEAD") return currentBranch;
57355
- if (destination.startsWith("refs/heads/")) return destination.slice("refs/heads/".length);
57356
- if (destination.startsWith("refs/")) return void 0;
57357
- return REF_NAME.test(destination) ? destination : void 0;
57358
- }
57359
- function checkoutTarget(args) {
57360
- const created = optionValue(args, ["-b", "-B", "-c", "-C"]);
57361
- if (created !== null) return REF_NAME.test(created) ? created : null;
57362
- if (args.includes("--")) return void 0;
57363
- if (args.includes("-") || args.includes("--detach") || args.includes("-d")) return null;
57364
- const positional = args.filter((arg) => !arg.startsWith("-"));
57365
- if (positional.length !== 1) return void 0;
57366
- return REF_NAME.test(positional[0]) ? positional[0] : null;
57367
- }
57368
- function optionValue(args, names) {
57369
- for (let i = 0; i < args.length; i++) {
57370
- const arg = args[i];
57371
- for (const name of names) {
57372
- if (arg === name) return args[i + 1] ?? null;
57373
- if (name.startsWith("--") && arg.startsWith(`${name}=`)) return arg.slice(name.length + 1);
57374
- }
57375
- }
57376
- return null;
57377
- }
57378
- function exitStatusIsOwn(chain, index) {
57379
- for (let i = index; i < chain.length; i++) {
57380
- const next = chain[i].next;
57381
- if (next === null) return true;
57382
- if (next !== "&&") return false;
57383
- }
57384
- return true;
57385
- }
57386
- function shellCommands(text) {
57387
- const commands = [];
57388
- let words = [];
57389
- let assignedSubstitutions = [];
57390
- let word = "";
57391
- let inWord = false;
57392
- let quote = null;
57393
- let heredocs = [];
57394
- const endWord = () => {
57395
- if (inWord) words.push(word);
57396
- word = "";
57397
- inWord = false;
57398
- };
57399
- const endCommand = (next) => {
57400
- endWord();
57401
- if (words.length > 0) commands.push({ words: withoutRedirections(words), assignedSubstitutions, next });
57402
- words = [];
57403
- assignedSubstitutions = [];
57404
- };
57405
- for (let i = 0; i < text.length; i++) {
57406
- const ch = text[i];
57407
- if (quote !== null) {
57408
- if (ch === quote) {
57409
- quote = null;
57410
- } else if (quote === '"' && ch === "\\" && i + 1 < text.length) {
57411
- word += text[++i];
57412
- } else {
57413
- word += ch;
57414
- }
57415
- inWord = true;
57416
- continue;
57417
- }
57418
- if (ch === "'" || ch === '"') {
57419
- quote = ch;
57420
- inWord = true;
57421
- } else if (ch === "$" && text[i + 1] === "(" || ch === "`") {
57422
- const end = substitutionEnd(text, i);
57423
- const after = text[end + 1];
57424
- const endsWord = after === void 0 || /[\s;&|)]/.test(after);
57425
- if (ch === "$" && text[end] === ")" && ASSIGNMENT_NAME.test(word) && endsWord) {
57426
- assignedSubstitutions.push(text.slice(i + 2, end));
57427
- }
57428
- word += text.slice(i, end + 1);
57429
- inWord = true;
57430
- i = end;
57431
- } else if (ch === "\\") {
57432
- const next = text[i + 1];
57433
- i += 1;
57434
- if (next !== void 0 && next !== "\n") {
57435
- word += next;
57436
- inWord = true;
57437
- }
57438
- } else if (ch === "#" && !inWord) {
57439
- i = lineEnd(text, i) - 1;
57440
- } else if (ch === "<" && text[i + 1] === "<" && text[i + 2] !== "<") {
57441
- endWord();
57442
- const heredoc = heredocDelimiter(text, i + 2);
57443
- heredocs.push(heredoc.delimiter);
57444
- i = heredoc.end;
57445
- } else if (ch === "&" && text[i + 1] === "&") {
57446
- endCommand("&&");
57447
- i += 1;
57448
- } else if (ch === "|" && text[i + 1] === "|") {
57449
- endCommand("||");
57450
- i += 1;
57451
- } else if (ch === "&" && (word.endsWith(">") || word.endsWith("<") || text[i + 1] === ">")) {
57452
- word += ch;
57453
- inWord = true;
57454
- } else if (ch === "|" || ch === "&" || ch === ";") {
57455
- endCommand(ch);
57456
- } else if (ch === "\n") {
57457
- endCommand("\n");
57458
- if (heredocs.length > 0) {
57459
- i = heredocBodiesEnd(text, i + 1, heredocs) - 1;
57460
- heredocs = [];
57461
- }
57462
- } else if (/\s/.test(ch) || ch === "(" || ch === ")") {
57463
- endWord();
57464
- } else {
57465
- word += ch;
57466
- inWord = true;
57467
- }
57468
- }
57469
- endCommand(null);
57470
- return commands;
57471
- }
57472
- function lineEnd(text, from) {
57473
- const end = text.indexOf("\n", from);
57474
- return end === -1 ? text.length : end;
57475
- }
57476
- function heredocDelimiter(text, from) {
57477
- let i = from;
57478
- if (text[i] === "-") i += 1;
57479
- while (i < text.length && (text[i] === " " || text[i] === " ")) i += 1;
57480
- const quote = text[i];
57481
- if (quote === "'" || quote === '"') {
57482
- const close2 = text.indexOf(quote, i + 1);
57483
- const end2 = close2 === -1 ? text.length - 1 : close2;
57484
- return { delimiter: text.slice(i + 1, end2), end: end2 };
57485
- }
57486
- let end = i;
57487
- while (end < text.length && !/[\s;|&<>()]/.test(text[end])) end += 1;
57488
- return { delimiter: text.slice(i, end), end: end - 1 };
57489
- }
57490
- function heredocBodiesEnd(text, from, delimiters) {
57491
- let i = from;
57492
- for (const delimiter of delimiters) {
57493
- for (; ; ) {
57494
- if (i >= text.length) return text.length;
57495
- const end = lineEnd(text, i);
57496
- const line = text.slice(i, end).trim();
57497
- i = end + 1;
57498
- if (line === delimiter) break;
57499
- }
57500
- }
57501
- return Math.min(i, text.length);
57502
- }
57503
- function substitutionEnd(text, start) {
57504
- if (text[start] === "`") {
57505
- const close2 = text.indexOf("`", start + 1);
57506
- return close2 === -1 ? text.length - 1 : close2;
57507
- }
57508
- let depth = 0;
57509
- for (let i = start + 1; i < text.length; i++) {
57510
- if (text[i] === "(") depth += 1;
57511
- else if (text[i] === ")" && --depth === 0) return i;
57512
- }
57513
- return text.length - 1;
57514
- }
57515
- var REDIRECTION_ALONE = /^\d*&?[<>]{1,3}$/;
57516
- var REDIRECTION_WITH_TARGET = /^\d*&?[<>]{1,3}\S/;
57517
- function withoutRedirections(words) {
57518
- const kept = [];
57519
- for (let i = 0; i < words.length; i++) {
57520
- const word = words[i];
57521
- if (REDIRECTION_ALONE.test(word)) {
57522
- i += 1;
57523
- continue;
57524
- }
57525
- if (REDIRECTION_WITH_TARGET.test(word)) continue;
57526
- kept.push(word);
57527
- }
57528
- return kept;
57529
- }
57530
-
57531
- // ../core/src/prEvidence.ts
57532
- var WATCHED_CALLS_MAX = 32;
57533
- var PUSH_EVIDENCE_MAX = 50;
57534
- var PrEvidenceCollector = class {
57535
- evidence = [];
57536
- seen = /* @__PURE__ */ new Set();
57537
- watched = /* @__PURE__ */ new Map();
57538
- /** By process id: what a watched call left unsettled when its result said
57539
- * the process still runs. */
57540
- running = /* @__PURE__ */ new Map();
57541
- dropped = 0;
57542
- /** The harness recorded the pull request for this session. Repeats (a
57543
- * record per turn while a PR stays bound) keep the first time. */
57544
- linked(ref, at, line) {
57545
- this.add({ kind: "pull-request-linked", at, prId: pullRequestId(ref), repository: null, branch: null, line });
57546
- }
57547
- /** A shell command the session ran: watched until its result arrives when
57548
- * it pushes a branch or creates a pull request, ignored otherwise. */
57549
- command(callId, command, currentBranch, startedAt = null) {
57550
- this.watch(callId, readCodeHostCommands(command, currentBranch), startedAt);
57551
- }
57552
- /** A tool call that would push or create a pull request, in the code host
57553
- * adapter's terms (a harness's own pull request tool, for example). */
57554
- watch(callId, commands, startedAt = null) {
57555
- if (commands.pushes.length === 0 && commands.pullRequestCreates.length === 0) return;
57556
- keepBounded(this.watched, callId, { ...commands, startedAt });
57557
- }
57558
- /** A call that reads more output of a running process (Codex's
57559
- * write_stdin poll; Claude Code's TaskOutput, or a read of a background
57560
- * task's output file): its result is read as the rest of the watched call
57561
- * that started the process. */
57562
- follow(callId, process2) {
57563
- const unsettled = this.running.get(process2);
57564
- if (unsettled === void 0) return;
57565
- this.running.delete(process2);
57566
- this.watch(callId, unsettled, unsettled.startedAt);
57567
- }
57568
- /** Whether any process is followed, so a parser reads an unwatched
57569
- * call's output only while it could matter. */
57570
- following() {
57571
- return this.running.size > 0;
57572
- }
57573
- /** Another call now runs a process under this id: a later poll of the id
57574
- * is no longer the rest of the watched call that left it running. */
57575
- forget(process2) {
57576
- this.running.delete(process2);
57577
- }
57578
- /** Watches several watched calls as one, in the order given: the parts of
57579
- * a call whose output cannot be told apart, read once as a whole. The
57580
- * parts are one call's, so they started together and the first part's
57581
- * time is the whole's. */
57582
- merge(callIds, into) {
57583
- const parts = callIds.flatMap((callId) => this.watched.get(callId) ?? []);
57584
- for (const callId of callIds) this.watched.delete(callId);
57585
- this.watch(
57586
- into,
57587
- {
57588
- pushes: parts.flatMap((part) => part.pushes),
57589
- pullRequestCreates: parts.flatMap((part) => part.pullRequestCreates)
57590
- },
57591
- parts[0]?.startedAt ?? null
57592
- );
57593
- }
57594
- watching(callId) {
57595
- return this.watched.has(callId);
57596
- }
57597
- /**
57598
- * A watched call's result. A push counts when git's output reports the
57599
- * branch updated (or already current), or, when the output says nothing
57600
- * about it, when the call succeeded and that status is the push's own.
57601
- * Its repository is the `To <url>` git printed: a chain's pushes pair
57602
- * with the `To` lines in order, or all take the one repository the text
57603
- * names when they all name one remote (a retry that printed
57604
- * `Everything up-to-date` prints no `To`); otherwise the repository is
57605
- * unknown, never a guess. A creation counts when the
57606
- * result names the pull request: gh prints the created PR's URL last, so
57607
- * a call with one creation takes the last URL and a call with several
57608
- * only when the text names exactly as many; a failed call whose status
57609
- * is the creation's own counts nothing, and neither does a call whose
57610
- * text carries gh's refusal because the pull request exists (the URL it
57611
- * prints is that pull request's, and a result read from a file states no
57612
- * status). A text cut to the URL alone (`| tail -1`, a `grep` of the
57613
- * output file) hides the refusal, and the URL then counts.
57614
- *
57615
- * When the result says one process still runs, whatever it settled
57616
- * neither way waits for that process's later output (`follow`). A push
57617
- * git rejected, or a command whose own status failed, is settled: a
57618
- * later output never revives it.
57619
- */
57620
- result(callId, outcome) {
57621
- const commands = this.watched.get(callId);
57622
- if (commands === void 0) return;
57623
- this.watched.delete(callId);
57624
- const destinations = pushDestinationsInText(outcome.text);
57625
- const oneRemote = new Set(commands.pushes.map((push) => push.remote)).size === 1;
57626
- const shared = oneRemote && new Set(destinations).size === 1 ? destinations[0] : null;
57627
- const unsettled = { pushes: [], pullRequestCreates: [], startedAt: commands.startedAt };
57628
- for (const [i, push] of commands.pushes.entries()) {
57629
- if (push.branch === null) continue;
57630
- const pushed = pushOutcomeInText(outcome.text, push.branch) ?? (push.ownExitStatus ? outcome.succeeded : null);
57631
- if (pushed === null) unsettled.pushes.push(push);
57632
- if (pushed !== true) continue;
57633
- const repository = destinations.length === commands.pushes.length ? destinations[i] : shared;
57634
- this.addPush({ kind: "branch-pushed", at: outcome.at, prId: null, repository, branch: push.branch, line: outcome.line });
57635
- }
57636
- const creates = commands.pullRequestCreates;
57637
- const refs = pullRequestRefsInText(outcome.text);
57638
- const paired = creates.length === 1 ? [refs.at(-1)] : refs.length === creates.length ? refs : [];
57639
- const refused = pullRequestAlreadyExistsInText(outcome.text);
57640
- creates.forEach((create, i) => {
57641
- const ref = paired[i];
57642
- if (refused || outcome.succeeded === false && create.ownExitStatus) return;
57643
- if (ref === void 0) {
57644
- unsettled.pullRequestCreates.push(create);
57645
- return;
57646
- }
57647
- this.add({
57648
- kind: "pull-request-created",
57649
- at: outcome.at,
57650
- prId: pullRequestId(ref),
57651
- repository: null,
57652
- branch: create.head,
57653
- line: outcome.line,
57654
- commandStartedAt: commands.startedAt
57655
- });
57656
- });
57657
- if (outcome.running === null || unsettled.pushes.length === 0 && unsettled.pullRequestCreates.length === 0) return;
57658
- keepBounded(this.running, outcome.running, unsettled);
57659
- }
57660
- /** The evidence collected, in transcript order, with pushes past the cap
57661
- * dropped oldest first. Calls still watched and processes still followed
57662
- * are dropped: their results never arrived. */
57663
- finish() {
57664
- this.watched.clear();
57665
- this.running.clear();
57666
- const pushes = this.evidence.filter((item) => item.kind === "branch-pushed");
57667
- if (pushes.length <= PUSH_EVIDENCE_MAX) return this.evidence;
57668
- const cut = new Set(pushes.slice(0, pushes.length - PUSH_EVIDENCE_MAX));
57669
- this.dropped = cut.size;
57670
- return this.evidence.filter((item) => !cut.has(item));
57671
- }
57672
- /** Pushes the cap dropped (the oldest first), so a session that pushed
57673
- * more than PUSH_EVIDENCE_MAX times is reported, not silently cut. */
57674
- droppedPushes() {
57675
- return this.dropped;
57676
- }
57677
- /** A link is one fact per pull request, and so is a creation per command:
57678
- * repeats keep the first. Two commands that each named the pull request
57679
- * are two facts (a refused retry read before the first command's own
57680
- * output), because the match keeps only the one whose command can have
57681
- * opened it. */
57682
- add(item) {
57683
- const key = `${item.kind}|${item.prId ?? ""}|${item.branch ?? ""}|${item.commandStartedAt ?? ""}`;
57684
- if (this.seen.has(key)) return;
57685
- this.seen.add(key);
57686
- this.evidence.push(item);
57687
- }
57688
- /** Every push is kept with its own time; only an exact repeat (one chain
57689
- * pushing the same branch twice, reported on the same line) is one fact. */
57690
- addPush(item) {
57691
- const key = `${item.kind}|${item.repository ?? ""}|${item.branch ?? ""}|${item.at ?? ""}|${item.line}`;
57692
- if (this.seen.has(key)) return;
57693
- this.seen.add(key);
57694
- this.evidence.push(item);
57695
- }
57696
- };
57697
- function keepBounded(map2, key, value) {
57698
- map2.delete(key);
57699
- map2.set(key, value);
57700
- if (map2.size > WATCHED_CALLS_MAX) map2.delete(map2.keys().next().value);
57701
- }
57702
-
57703
57110
  // ../core/src/digest.ts
57704
57111
  var TOOL_CALL_INPUT_MAX_BYTES = 65536;
57705
- function boundedToolInput(value) {
57706
- return boundRedactedText(JSON.stringify(value), TOOL_CALL_INPUT_MAX_BYTES);
57707
- }
57708
57112
  var tokenCount = external_exports.number().nonnegative();
57709
57113
  var costStateSchema = external_exports.object({
57710
57114
  sessionId: external_exports.string(),
@@ -57721,389 +57125,6 @@ var costStateSchema = external_exports.object({
57721
57125
  })
57722
57126
  )
57723
57127
  });
57724
- function runCostOf(record2) {
57725
- const parsed = costStateSchema.safeParse(record2);
57726
- if (!parsed.success) return null;
57727
- const runStartedAt = new Date(parsed.data.startTime);
57728
- if (Number.isNaN(runStartedAt.getTime())) return null;
57729
- return {
57730
- sessionId: parsed.data.sessionId,
57731
- runStartedAt: runStartedAt.toISOString(),
57732
- // Claude Code's own restore reads a missing flag as false.
57733
- unknownModelCost: parsed.data.hasUnknownModelCost ?? false,
57734
- byModel: Object.entries(parsed.data.modelUsage).map(([model, usage]) => ({
57735
- model,
57736
- costUsd: usage.costUSD,
57737
- tokens: {
57738
- inputTokens: usage.inputTokens,
57739
- outputTokens: usage.outputTokens,
57740
- cacheReadTokens: usage.cacheReadInputTokens,
57741
- cacheWriteTokens: usage.cacheCreationInputTokens
57742
- }
57743
- })).sort((a, b2) => a.model < b2.model ? -1 : a.model > b2.model ? 1 : 0)
57744
- };
57745
- }
57746
- function createDigestTurnParser(options = {}) {
57747
- const turns = [];
57748
- let pendingTools = [];
57749
- let pendingUsage = null;
57750
- let pendingAt = null;
57751
- let currentId = null;
57752
- let currentCarrier = null;
57753
- let currentBase = null;
57754
- let currentCounted = false;
57755
- const countedEnvelopes = /* @__PURE__ */ new Map();
57756
- let currentReplay = null;
57757
- let transcriptStartedAt = null;
57758
- let transcriptSessionId = null;
57759
- let lastRecordAt = null;
57760
- let runCost = null;
57761
- let recordedThrough = null;
57762
- let laterEnvelopes = [];
57763
- let laterSet = /* @__PURE__ */ new Set();
57764
- let usageRevisedAfter = false;
57765
- const envelopes = [];
57766
- let pendingEnvelopes = [];
57767
- let currentEnvelope = null;
57768
- const evidence = new PrEvidenceCollector();
57769
- const backgroundTasks = { started: /* @__PURE__ */ new Map(), reads: /* @__PURE__ */ new Map() };
57770
- let line = -1;
57771
- const resum = (envelope) => {
57772
- const landed = envelope.turn === -1 ? pendingEnvelopes : envelopes.filter((e) => e.turn === envelope.turn);
57773
- const usage = landed.reduce((sum2, e) => mergeUsage(sum2, e.usage), null);
57774
- if (envelope.turn === -1) pendingUsage = usage;
57775
- else turns[envelope.turn].usage = usage;
57776
- };
57777
- const noteRevision = (envelope, recorded, at) => {
57778
- if (sameUsage(recorded, envelope.usage)) return;
57779
- const time3 = at === null ? Number.NaN : Date.parse(at);
57780
- if (Number.isNaN(time3)) envelope.revisedAt = null;
57781
- else if (envelope.revisedAt !== null && (envelope.revisedAt === void 0 || Date.parse(envelope.revisedAt) < time3)) {
57782
- envelope.revisedAt = at;
57783
- }
57784
- if (runCost !== null && !laterSet.has(envelope)) usageRevisedAfter = true;
57785
- };
57786
- const landPending = (turn) => {
57787
- for (const envelope of pendingEnvelopes) {
57788
- envelope.turn = turn;
57789
- envelopes.push(envelope);
57790
- }
57791
- pendingEnvelopes = [];
57792
- };
57793
- return {
57794
- pushLine(raw) {
57795
- line += 1;
57796
- const trimmed = raw.trim();
57797
- if (trimmed === "") return;
57798
- let record2;
57799
- try {
57800
- const parsed = JSON.parse(trimmed);
57801
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return;
57802
- record2 = parsed;
57803
- } catch {
57804
- return;
57805
- }
57806
- transcriptStartedAt ??= recordTime(record2);
57807
- if (record2.type === "cost-state") {
57808
- runCost = runCostOf(record2);
57809
- recordedThrough = lastRecordAt;
57810
- laterEnvelopes = [];
57811
- laterSet = /* @__PURE__ */ new Set();
57812
- usageRevisedAfter = false;
57813
- return;
57814
- }
57815
- if (typeof record2.sessionId === "string") transcriptSessionId ??= record2.sessionId;
57816
- const recordAt = recordTime(record2);
57817
- if (recordAt !== null && (lastRecordAt === null || Date.parse(recordAt) > Date.parse(lastRecordAt))) lastRecordAt = recordAt;
57818
- if (record2.type === "pr-link") {
57819
- const ref = pullRequestRefFromUrl(typeof record2.prUrl === "string" ? record2.prUrl : "");
57820
- if (ref !== null) evidence.linked(ref, recordTime(record2), line);
57821
- return;
57822
- }
57823
- if (record2.isMeta === true) return;
57824
- const at = recordTime(record2);
57825
- if (record2.type === "user") {
57826
- toolResults(record2, evidence, backgroundTasks, line);
57827
- const text = userText(record2);
57828
- if (text) {
57829
- const origin = claudeCodeMessageOrigin(originFacts(record2), text);
57830
- turns.push({ kind: "human_prompt", text, origin, toolCalls: [], usage: null, at });
57831
- }
57832
- return;
57833
- }
57834
- if (record2.type !== "assistant") return;
57835
- const message2 = record2.message;
57836
- if (!message2 || message2.model === "<synthetic>" || !Array.isArray(message2.content)) return;
57837
- pendingAt ??= at;
57838
- const id = messageIdOf(record2, message2);
57839
- if (id === null || id !== currentId) {
57840
- currentId = id;
57841
- currentCarrier = null;
57842
- currentBase = pendingUsage;
57843
- currentReplay = id === null ? null : countedEnvelopes.get(id) ?? null;
57844
- currentCounted = currentReplay !== null;
57845
- }
57846
- const parsedUsage = recordTurnUsage(message2);
57847
- if (parsedUsage) {
57848
- if (currentReplay) {
57849
- const recorded = currentReplay.usage;
57850
- keepRecordedFacts(parsedUsage, recorded, message2.usage?.inference_geo);
57851
- currentReplay.usage = parsedUsage;
57852
- noteRevision(currentReplay, recorded, at);
57853
- resum(currentReplay);
57854
- } else if (currentCounted) {
57855
- const recorded = currentEnvelope?.usage;
57856
- if (recorded !== void 0) keepRecordedFacts(parsedUsage, recorded, message2.usage?.inference_geo);
57857
- const updated = mergeUsage(currentBase, parsedUsage);
57858
- if (currentCarrier) currentCarrier.usage = updated;
57859
- else pendingUsage = updated;
57860
- if (currentEnvelope !== null && recorded !== void 0) {
57861
- currentEnvelope.usage = parsedUsage;
57862
- noteRevision(currentEnvelope, recorded, at);
57863
- }
57864
- } else if (currentCarrier) {
57865
- currentCarrier.usage = mergeUsage(currentCarrier.usage, parsedUsage);
57866
- currentCounted = true;
57867
- currentEnvelope = { turn: turns.indexOf(currentCarrier), at, usage: parsedUsage, branch: recordBranch(record2) };
57868
- envelopes.push(currentEnvelope);
57869
- laterEnvelopes.push(currentEnvelope);
57870
- laterSet.add(currentEnvelope);
57871
- if (id !== null) countedEnvelopes.set(id, currentEnvelope);
57872
- } else {
57873
- pendingUsage = mergeUsage(pendingUsage, parsedUsage);
57874
- currentCounted = true;
57875
- currentEnvelope = { turn: -1, at, usage: parsedUsage, branch: recordBranch(record2) };
57876
- pendingEnvelopes.push(currentEnvelope);
57877
- laterEnvelopes.push(currentEnvelope);
57878
- laterSet.add(currentEnvelope);
57879
- if (id !== null) countedEnvelopes.set(id, currentEnvelope);
57880
- }
57881
- }
57882
- const model = typeof message2.model === "string" ? message2.model : null;
57883
- const facts = originFacts(record2);
57884
- for (const block2 of message2.content) {
57885
- const part = block2;
57886
- if (part.type === "tool_use" && typeof part.name === "string") {
57887
- const call = { name: part.name, ...toolFilePath(part.input) };
57888
- if (options.keepToolInputs === true && isRecord(part.input)) {
57889
- call.input = boundedToolInput(part.input);
57890
- }
57891
- pendingTools.push(call);
57892
- if (part.name === "Bash" && typeof part.id === "string" && typeof part.input?.command === "string") {
57893
- evidence.command(part.id, part.input.command, recordBranch(record2), at);
57894
- }
57895
- if (typeof part.id === "string") followBackgroundTask(part.id, part.name, part.input, evidence, backgroundTasks);
57896
- }
57897
- if (part.type === "text" && typeof part.text === "string" && part.text.trim() !== "") {
57898
- const origin = claudeCodeMessageOrigin(facts, part.text);
57899
- if (currentCarrier === null) {
57900
- const turn = {
57901
- kind: "agent_text",
57902
- text: part.text,
57903
- origin,
57904
- toolCalls: pendingTools,
57905
- // A message written again carries zero of its own: its money
57906
- // landed where it was first counted.
57907
- usage: pendingUsage ?? (currentReplay ? zeroUsage(model) : null),
57908
- at: pendingAt
57909
- };
57910
- turns.push(turn);
57911
- currentCarrier = turn;
57912
- pendingUsage = null;
57913
- landPending(turns.length - 1);
57914
- } else {
57915
- turns.push({
57916
- kind: "agent_text",
57917
- text: part.text,
57918
- origin,
57919
- toolCalls: pendingTools,
57920
- usage: currentCounted ? zeroUsage(model) : null,
57921
- // A sibling block of the same record began when the record did.
57922
- at: pendingAt ?? at
57923
- });
57924
- }
57925
- pendingTools = [];
57926
- pendingAt = null;
57927
- }
57928
- }
57929
- },
57930
- finish() {
57931
- if (pendingTools.length > 0 || pendingUsage !== null) {
57932
- turns.push({ kind: "agent_text", text: "", origin: "agent", toolCalls: pendingTools, usage: pendingUsage, at: pendingAt });
57933
- landPending(turns.length - 1);
57934
- pendingTools = [];
57935
- pendingUsage = null;
57936
- pendingAt = null;
57937
- }
57938
- return turns;
57939
- },
57940
- usageEnvelopes() {
57941
- return envelopes;
57942
- },
57943
- harnessCost() {
57944
- if (runCost === null || runCost.sessionId !== transcriptSessionId) return null;
57945
- const { runStartedAt, unknownModelCost, byModel } = runCost;
57946
- const laterUsage = laterEnvelopes.map((envelope) => envelope.usage);
57947
- return { runStartedAt, transcriptStartedAt, recordedThrough, unknownModelCost, byModel, usageRevisedAfter, laterUsage };
57948
- },
57949
- prEvidence() {
57950
- return evidence.finish();
57951
- },
57952
- prEvidenceDroppedPushes() {
57953
- return evidence.droppedPushes();
57954
- }
57955
- };
57956
- }
57957
- function originFacts(record2) {
57958
- const message2 = isRecord(record2.message) ? record2.message : null;
57959
- const origin = isRecord(record2.origin) ? record2.origin : null;
57960
- const recordType = typeof record2.type === "string" ? record2.type : null;
57961
- return {
57962
- recordType,
57963
- role: typeof message2?.role === "string" ? message2.role : recordType,
57964
- originRecorded: record2.origin !== void 0,
57965
- nativeOrigin: typeof origin?.kind === "string" ? origin.kind : null,
57966
- isMeta: typeof record2.isMeta === "boolean" ? record2.isMeta : null,
57967
- isCompactSummary: typeof record2.isCompactSummary === "boolean" ? record2.isCompactSummary : null,
57968
- model: typeof message2?.model === "string" ? message2.model : null,
57969
- commandMode: null
57970
- };
57971
- }
57972
- function recordTime(record2) {
57973
- return typeof record2.timestamp === "string" && record2.timestamp !== "" ? record2.timestamp : null;
57974
- }
57975
- function isRecord(value) {
57976
- return value !== null && typeof value === "object" && !Array.isArray(value);
57977
- }
57978
- function recordBranch(record2) {
57979
- return typeof record2.gitBranch === "string" && record2.gitBranch !== "" ? record2.gitBranch : null;
57980
- }
57981
- function followBackgroundTask(callId, tool, input2, evidence, tasks) {
57982
- if (tasks.started.size === 0 || evidence.watching(callId)) return;
57983
- const named = tool === "TaskOutput" ? input2?.task_id : tool === "Read" ? input2?.file_path : tool === "Bash" ? input2?.command : void 0;
57984
- if (typeof named !== "string" || tool === "Bash" && RUNS_GH.test(named)) return;
57985
- const read = new Set(
57986
- [...tasks.started].filter(([task]) => tool === "TaskOutput" ? named === task : named.includes(`/${task}.output`)).map(([, followed2]) => followed2)
57987
- );
57988
- if (read.size !== 1) return;
57989
- const [followed] = read;
57990
- evidence.follow(callId, followed);
57991
- if (evidence.watching(callId)) keepBounded(tasks.reads, callId, followed);
57992
- }
57993
- var RUNS_GH = /(?:^|[\s;&|(])gh\s/;
57994
- function toolResults(record2, evidence, tasks, line) {
57995
- const content = isRecord(record2.message) ? record2.message.content : void 0;
57996
- if (!Array.isArray(content)) return;
57997
- const result = isRecord(record2.toolUseResult) ? record2.toolUseResult : {};
57998
- const file2 = isRecord(result.file) ? result.file : {};
57999
- const task = isRecord(result.task) ? result.task : {};
58000
- for (const block2 of content) {
58001
- if (!isRecord(block2) || block2.type !== "tool_result" || typeof block2.tool_use_id !== "string") continue;
58002
- if (!evidence.watching(block2.tool_use_id)) continue;
58003
- const reads = tasks.reads.get(block2.tool_use_id);
58004
- tasks.reads.delete(block2.tool_use_id);
58005
- const started = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId : null;
58006
- if (started !== null) keepBounded(tasks.started, started, reads ?? started);
58007
- const failed2 = block2.is_error === true || result.interrupted === true;
58008
- const taskExited = typeof task.exitCode === "number" && task.task_id === reads;
58009
- const status = reads !== void 0 ? { succeeded: taskExited ? task.exitCode === 0 : null, running: taskExited ? null : reads } : { succeeded: failed2 ? false : started !== null ? null : true, running: started };
58010
- evidence.result(block2.tool_use_id, {
58011
- ...status,
58012
- text: [result.stdout, result.stderr, file2.content, task.output].filter((part) => typeof part === "string").concat(contentText(block2.content)).join("\n"),
58013
- at: recordTime(record2),
58014
- line
58015
- });
58016
- }
58017
- }
58018
- function contentText(content) {
58019
- if (typeof content === "string") return content;
58020
- if (!Array.isArray(content)) return "";
58021
- return content.map((block2) => isRecord(block2) && typeof block2.text === "string" ? block2.text : "").join("\n");
58022
- }
58023
- function messageIdOf(record2, message2) {
58024
- if (typeof message2.id === "string") return message2.id;
58025
- if (typeof record2.requestId === "string") return record2.requestId;
58026
- if (typeof record2.uuid === "string") return record2.uuid;
58027
- return null;
58028
- }
58029
- function keepRecordedFacts(later, recorded, laterGeo) {
58030
- if ((later.serviceTier === void 0 || later.serviceTier === "unknown") && recorded.serviceTier !== void 0) {
58031
- later.serviceTier = recorded.serviceTier;
58032
- }
58033
- if (later.cacheWrite1hTokens === null && recorded.cacheWriteTokens === later.cacheWriteTokens) {
58034
- later.cacheWrite1hTokens = recorded.cacheWrite1hTokens;
58035
- }
58036
- if (GEOGRAPHY_SAYS_NOTHING.has(laterGeo) && recorded.usOnlyInference === true) later.usOnlyInference = true;
58037
- }
58038
- var GEOGRAPHY_SAYS_NOTHING = /* @__PURE__ */ new Set([void 0, null, "not_available"]);
58039
- function recordTurnUsage(message2) {
58040
- const usage = message2.usage;
58041
- if (!usage || typeof usage !== "object") return null;
58042
- const count3 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
58043
- const input2 = count3(usage.input_tokens);
58044
- const output2 = count3(usage.output_tokens);
58045
- if (input2 === null && output2 === null) return null;
58046
- const cacheCreation = isRecord(usage.cache_creation) ? usage.cache_creation : null;
58047
- const speed = usage.speed;
58048
- return {
58049
- inputTokens: input2 ?? 0,
58050
- outputTokens: output2 ?? 0,
58051
- cacheReadTokens: count3(usage.cache_read_input_tokens),
58052
- cacheWriteTokens: count3(usage.cache_creation_input_tokens),
58053
- cacheWrite1hTokens: cacheCreation === null ? null : count3(cacheCreation.ephemeral_1h_input_tokens),
58054
- model: typeof message2.model === "string" ? message2.model : null,
58055
- // The same speed values the collector reads for the session's Fast
58056
- // split; a speed it does not recognize is unknown (standard rate), and
58057
- // a null speed is no speed, as the collector reads it.
58058
- ...speed !== void 0 && speed !== null && {
58059
- serviceTier: speed === "fast" || speed === "standard" ? speed : "unknown"
58060
- },
58061
- ...usage.inference_geo === "us" && { usOnlyInference: true }
58062
- };
58063
- }
58064
- function zeroUsage(model) {
58065
- return { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, cacheWrite1hTokens: 0, model };
58066
- }
58067
- function sameUsage(a, b2) {
58068
- return a.inputTokens === b2.inputTokens && a.outputTokens === b2.outputTokens && a.cacheReadTokens === b2.cacheReadTokens && a.cacheWriteTokens === b2.cacheWriteTokens && a.cacheWrite1hTokens === b2.cacheWrite1hTokens && a.model === b2.model && a.serviceTier === b2.serviceTier && a.usOnlyInference === b2.usOnlyInference;
58069
- }
58070
- function mergeUsage(a, b2) {
58071
- if (!a) return b2;
58072
- if (!b2) return a;
58073
- const cache = (x, y) => x === null || y === null ? null : x + y;
58074
- const serviceTier = a.serviceTier === b2.serviceTier ? a.serviceTier : "unknown";
58075
- return {
58076
- inputTokens: a.inputTokens + b2.inputTokens,
58077
- outputTokens: a.outputTokens + b2.outputTokens,
58078
- cacheReadTokens: cache(a.cacheReadTokens, b2.cacheReadTokens),
58079
- cacheWriteTokens: cache(a.cacheWriteTokens, b2.cacheWriteTokens),
58080
- cacheWrite1hTokens: cache(a.cacheWrite1hTokens, b2.cacheWrite1hTokens),
58081
- model: a.model ?? b2.model,
58082
- ...serviceTier !== void 0 && { serviceTier },
58083
- ...a.usOnlyInference === true && b2.usOnlyInference === true && { usOnlyInference: true }
58084
- };
58085
- }
58086
- function userText(record2) {
58087
- const message2 = record2.message;
58088
- const content = message2?.content;
58089
- if (typeof content === "string") return content.trim() === "" ? null : content;
58090
- if (!Array.isArray(content)) return null;
58091
- const parts = [];
58092
- for (const block2 of content) {
58093
- if (!isRecord(block2)) continue;
58094
- if (block2.type === "text" && typeof block2.text === "string" && block2.text.trim() !== "") {
58095
- parts.push(block2.text);
58096
- continue;
58097
- }
58098
- const image = describeImageBlock(block2);
58099
- if (image) parts.push(imageLabel(image));
58100
- }
58101
- return parts.length > 0 ? parts.join("\n") : null;
58102
- }
58103
- function toolFilePath(input2) {
58104
- const candidate = input2?.file_path ?? input2?.path ?? input2?.notebook_path;
58105
- return typeof candidate === "string" ? { filePath: candidate } : {};
58106
- }
58107
57128
 
58108
57129
  // ../core/src/collectorDiagnostics.ts
58109
57130
  var count = external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
@@ -58176,6 +57197,8 @@ var collectorPassDiagnosticSchema = external_exports.strictObject({
58176
57197
  "codex",
58177
57198
  "cursor",
58178
57199
  "metadata",
57200
+ // Sent only by collectors released before preview registration was
57201
+ // removed. Accepted until the supported-version floor passes them.
58179
57202
  "previews",
58180
57203
  "raw",
58181
57204
  "complete"
@@ -58304,7 +57327,7 @@ function excludeImageCarriers(record2) {
58304
57327
  return withoutImages(item, itemPath);
58305
57328
  });
58306
57329
  }
58307
- if (!isRecord2(value)) return value;
57330
+ if (!isRecord(value)) return value;
58308
57331
  const kept = [];
58309
57332
  for (const [key, item] of Object.entries(value)) {
58310
57333
  const keyPath = path55 === "" ? key : `${path55}.${key}`;
@@ -58346,64 +57369,14 @@ function retainFieldsBounded(record2, maxBytes) {
58346
57369
  function nativeTypeLabel(value) {
58347
57370
  return typeof value === "string" && /^[A-Za-z0-9_.:/-]{1,64}$/.test(value) ? value : void 0;
58348
57371
  }
58349
- function createCursorTurnParser(options = {}) {
58350
- const turns = [];
58351
- let pendingTools = [];
58352
- let pendingAt = null;
58353
- const flushPendingTools = () => {
58354
- if (pendingTools.length === 0) return;
58355
- turns.push({ kind: "agent_text", text: "", origin: "agent", toolCalls: pendingTools, usage: null, at: pendingAt });
58356
- pendingTools = [];
58357
- pendingAt = null;
58358
- };
58359
- return {
58360
- pushLine(line) {
58361
- const trimmed = line.trim();
58362
- if (trimmed === "") return;
58363
- let record2;
58364
- try {
58365
- const parsed = JSON.parse(trimmed);
58366
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return;
58367
- record2 = parsed;
58368
- } catch {
58369
- return;
58370
- }
58371
- const at = typeof record2.createdAt === "string" && record2.createdAt !== "" ? record2.createdAt : null;
58372
- if (record2.type === "user" && typeof record2.text === "string" && record2.text.trim() !== "") {
58373
- flushPendingTools();
58374
- turns.push({ kind: "human_prompt", text: record2.text, origin: "unknown", toolCalls: [], usage: null, at });
58375
- return;
58376
- }
58377
- if (record2.type === "tool" && typeof record2.name === "string") {
58378
- const call = { name: record2.name };
58379
- if (typeof record2.filePath === "string") call.filePath = record2.filePath;
58380
- if (options.keepToolInputs === true && isRecord2(record2.args)) {
58381
- call.input = boundedToolInput(record2.args);
58382
- }
58383
- pendingTools.push(call);
58384
- pendingAt ??= at;
58385
- return;
58386
- }
58387
- if (record2.type === "agent" && typeof record2.text === "string" && record2.text.trim() !== "") {
58388
- turns.push({ kind: "agent_text", text: record2.text, origin: "agent", toolCalls: pendingTools, usage: null, at: pendingAt ?? at });
58389
- pendingTools = [];
58390
- pendingAt = null;
58391
- }
58392
- },
58393
- finish() {
58394
- flushPendingTools();
58395
- return turns;
58396
- }
58397
- };
58398
- }
58399
- function isRecord2(value) {
57372
+ function isRecord(value) {
58400
57373
  return value !== null && typeof value === "object" && !Array.isArray(value);
58401
57374
  }
58402
57375
 
58403
57376
  // ../core/src/codexResponseUsage.ts
58404
57377
  var count2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
58405
57378
  function readTotals(value) {
58406
- if (!isRecord2(value)) return null;
57379
+ if (!isRecord(value)) return null;
58407
57380
  const inputTokens = count2(value.input_tokens);
58408
57381
  const outputTokens = count2(value.output_tokens);
58409
57382
  if (inputTokens === null || outputTokens === null) return null;
@@ -58486,11 +57459,11 @@ function createCodexUsageReader(options = {}) {
58486
57459
  return {
58487
57460
  startPage,
58488
57461
  pushRecord(record2) {
58489
- if (!isRecord2(record2) || typeof record2.type !== "string") return;
58490
- const payload = isRecord2(record2.payload) ? record2.payload : null;
57462
+ if (!isRecord(record2) || typeof record2.type !== "string") return;
57463
+ const payload = isRecord(record2.payload) ? record2.payload : null;
58491
57464
  const at = typeof record2.timestamp === "string" && record2.timestamp !== "" ? record2.timestamp : null;
58492
57465
  if (record2.type === "session_meta") {
58493
- if (payload !== null && isRecord2(payload.history_base)) startPage();
57466
+ if (payload !== null && isRecord(payload.history_base)) startPage();
58494
57467
  return;
58495
57468
  }
58496
57469
  if (payload === null) return;
@@ -58521,7 +57494,7 @@ function createCodexUsageReader(options = {}) {
58521
57494
  }
58522
57495
  if (record2.type !== "event_msg") return;
58523
57496
  if (payload.type === "thread_settings_applied") {
58524
- const settings = isRecord2(payload.thread_settings) ? payload.thread_settings : null;
57497
+ const settings = isRecord(payload.thread_settings) ? payload.thread_settings : null;
58525
57498
  if (settings !== null && settings.service_tier !== void 0) {
58526
57499
  tier = codexServiceTier(settings.service_tier) ?? "unknown";
58527
57500
  nativeTier = typeof settings.service_tier === "string" ? settings.service_tier : null;
@@ -58531,7 +57504,7 @@ function createCodexUsageReader(options = {}) {
58531
57504
  }
58532
57505
  if (payload.type !== "token_count") return;
58533
57506
  if (payload.info === null || payload.info === void 0) return;
58534
- if (!isRecord2(payload.info)) {
57507
+ if (!isRecord(payload.info)) {
58535
57508
  summary.malformedRecords += 1;
58536
57509
  return;
58537
57510
  }
@@ -58560,17 +57533,6 @@ function createCodexUsageReader(options = {}) {
58560
57533
  }
58561
57534
  };
58562
57535
  }
58563
- function codexResponseTurnUsage(entry) {
58564
- return {
58565
- inputTokens: Math.max(0, entry.counts.inputTokens - entry.counts.cachedInputTokens),
58566
- outputTokens: entry.counts.outputTokens,
58567
- cacheReadTokens: entry.counts.cachedInputTokens,
58568
- cacheWriteTokens: null,
58569
- cacheWrite1hTokens: null,
58570
- model: entry.model,
58571
- serviceTier: entry.serviceTier
58572
- };
58573
- }
58574
57536
  function codexPageTotals(read) {
58575
57537
  if (read.entries.length === 0 && read.uncounted.length === 0) return null;
58576
57538
  const totals = { input: 0, cached: 0, output: 0 };
@@ -58616,39 +57578,6 @@ var MACHINE_ENROLL_CALLBACK_PORT = 41999;
58616
57578
  var MACHINE_ENROLL_CALLBACK_PATH = "/callback";
58617
57579
  var MACHINE_ENROLL_CALLBACK_URL = `http://127.0.0.1:${MACHINE_ENROLL_CALLBACK_PORT}${MACHINE_ENROLL_CALLBACK_PATH}`;
58618
57580
 
58619
- // ../core/src/sessionRooms.ts
58620
- var RECENT_ACTIVITY_WINDOW_MS = 5 * 24 * 36e5;
58621
- function capturedSessionEvents(turns, anchor2) {
58622
- const events = [];
58623
- const base = {
58624
- actor: null,
58625
- member: null,
58626
- deliveryState: null,
58627
- occurredAt: null,
58628
- observedAt: anchor2.observedAt
58629
- };
58630
- turns.forEach((turn, index) => {
58631
- turn.toolCalls.forEach((call, callIndex) => {
58632
- events.push({
58633
- ...base,
58634
- id: `${anchor2.sessionId}:${index}:tool:${callIndex}`,
58635
- kind: "tool_activity",
58636
- text: null,
58637
- toolName: call.name
58638
- });
58639
- });
58640
- if (turn.text.trim() === "") return;
58641
- events.push({
58642
- ...base,
58643
- id: `${anchor2.sessionId}:${index}:${turn.kind}`,
58644
- kind: turn.kind === "human_prompt" ? "agent_prompt" : "agent_response",
58645
- text: turn.text,
58646
- toolName: null
58647
- });
58648
- });
58649
- return events;
58650
- }
58651
-
58652
57581
  // ../core/src/workspaceClaims.ts
58653
57582
  function workspaceClaimsRepo(repoFullName, policy) {
58654
57583
  const repo = repoFullName.toLowerCase();
@@ -58660,716 +57589,8 @@ function workspaceClaimsAnyRepo(policy) {
58660
57589
  return policy.repos !== null ? policy.repos.length > 0 : policy.owners.length > 0;
58661
57590
  }
58662
57591
 
58663
- // ../core/src/codexRollout.ts
58664
- function toolCallName(item) {
58665
- switch (item.type) {
58666
- case "function_call":
58667
- case "custom_tool_call":
58668
- return typeof item.name === "string" ? item.name : null;
58669
- case "local_shell_call":
58670
- return "shell";
58671
- case "web_search_call":
58672
- return "web_search";
58673
- default:
58674
- return null;
58675
- }
58676
- }
58677
- function toolCallArguments(item) {
58678
- switch (item.type) {
58679
- case "function_call": {
58680
- if (typeof item.arguments !== "string") return null;
58681
- const parsed = safeJsonRecord(item.arguments);
58682
- return parsed ?? { arguments: item.arguments };
58683
- }
58684
- case "custom_tool_call":
58685
- return typeof item.input === "string" ? { input: item.input } : null;
58686
- case "local_shell_call":
58687
- case "web_search_call":
58688
- return asRecord2(item.action);
58689
- default:
58690
- return null;
58691
- }
58692
- }
58693
- function asRecord2(value) {
58694
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
58695
- }
58696
- function safeJsonRecord(text) {
58697
- try {
58698
- return asRecord2(JSON.parse(text));
58699
- } catch {
58700
- return null;
58701
- }
58702
- }
58703
- function outputTextBlocks(content) {
58704
- if (!Array.isArray(content)) return [];
58705
- return content.filter(
58706
- (block2) => typeof block2 === "object" && block2 !== null && block2.type === "output_text" && typeof block2.text === "string"
58707
- ).map((block2) => block2.text);
58708
- }
58709
- function promptText(content) {
58710
- if (!Array.isArray(content)) return null;
58711
- const kept = [];
58712
- const textOrigins = [];
58713
- for (const raw of content) {
58714
- const block2 = asRecord2(raw);
58715
- if (!block2) continue;
58716
- if (block2.type === "input_image") {
58717
- kept.push(imageLabel(describeImageUrl(block2.image_url)));
58718
- continue;
58719
- }
58720
- if (block2.type !== "input_text" || typeof block2.text !== "string") continue;
58721
- const parsed = codexPromptBlock(block2.text);
58722
- if (parsed.origin === "harness") continue;
58723
- textOrigins.push(parsed.origin);
58724
- if (parsed.ask !== "") kept.push(parsed.ask);
58725
- }
58726
- return kept.length === 0 ? null : { text: kept.join("\n"), origin: codexPromptOrigin(textOrigins) };
58727
- }
58728
- function createCodexTurnParser(options = {}) {
58729
- const turns = [];
58730
- let pendingTools = [];
58731
- let pendingAt = null;
58732
- const evidence = new PrEvidenceCollector();
58733
- const scripts = /* @__PURE__ */ new Map();
58734
- const runningScripts = /* @__PURE__ */ new Map();
58735
- let line = -1;
58736
- const envelopes = [];
58737
- let pendingEnvelopes = [];
58738
- let turnsAtLastEntry = 0;
58739
- const landPending = (turnIndex) => {
58740
- const turn = turns[turnIndex];
58741
- for (const envelope of pendingEnvelopes) {
58742
- envelope.turn = turnIndex;
58743
- envelopes.push(envelope);
58744
- turn.usage = mergeUsage(turn.usage, envelope.usage);
58745
- }
58746
- pendingEnvelopes = [];
58747
- };
58748
- const usage = createCodexUsageReader({
58749
- keepEntries: false,
58750
- onEntry(entry) {
58751
- const turnUsage = codexResponseTurnUsage(entry);
58752
- const newest = turns.length - 1;
58753
- const fresh = turns.length > turnsAtLastEntry;
58754
- turnsAtLastEntry = turns.length;
58755
- if (fresh && newest >= 0 && turns[newest].kind === "agent_text") {
58756
- turns[newest].usage = mergeUsage(turns[newest].usage, turnUsage);
58757
- envelopes.push({ turn: newest, at: entry.at, usage: turnUsage, branch: null });
58758
- return;
58759
- }
58760
- pendingEnvelopes.push({ turn: -1, at: entry.at, usage: turnUsage, branch: null });
58761
- }
58762
- });
58763
- const pushAgentTurn = (turn) => {
58764
- turns.push(turn);
58765
- if (pendingEnvelopes.length > 0) landPending(turns.length - 1);
58766
- };
58767
- const flushPendingTools = () => {
58768
- if (pendingTools.length === 0) return;
58769
- pushAgentTurn({ kind: "agent_text", text: "", origin: "agent", toolCalls: pendingTools, usage: null, at: pendingAt });
58770
- pendingTools = [];
58771
- pendingAt = null;
58772
- };
58773
- return {
58774
- pushLine(raw) {
58775
- line += 1;
58776
- const trimmed = raw.trim();
58777
- if (trimmed === "") return;
58778
- let record2;
58779
- try {
58780
- const parsed = JSON.parse(trimmed);
58781
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return;
58782
- record2 = parsed;
58783
- } catch {
58784
- return;
58785
- }
58786
- usage.pushRecord(record2);
58787
- if (record2.type !== "response_item") return;
58788
- const at = typeof record2.timestamp === "string" && record2.timestamp !== "" ? record2.timestamp : null;
58789
- const item = record2.payload;
58790
- if (item === null || typeof item !== "object" || Array.isArray(item)) return;
58791
- const responseItem = item;
58792
- const callId = typeof responseItem.call_id === "string" ? responseItem.call_id : null;
58793
- if (callId !== null && isToolOutput(responseItem)) {
58794
- const script = scripts.get(callId);
58795
- scripts.delete(callId);
58796
- if (script !== void 0) {
58797
- const [header = "", ...blocks] = outputBlocks(responseItem.output);
58798
- const cell = SCRIPT_STILL_RUNNING.exec(header)?.[1];
58799
- if (cell === void 0) scriptResult(evidence, script, header, blocks, at, line);
58800
- else keepBounded(runningScripts, cell, script);
58801
- } else if (evidence.watching(callId)) {
58802
- const text2 = contentText(responseItem.output);
58803
- evidence.result(callId, { succeeded: codexExitStatus(text2), text: text2, running: codexRunningProcess(text2), at, line });
58804
- } else if (runningScripts.size > 0 || evidence.following()) {
58805
- const [header = "", ...blocks] = outputBlocks(responseItem.output);
58806
- const cell = SCRIPT_STILL_RUNNING.exec(header)?.[1];
58807
- if (cell !== void 0) runningScripts.delete(cell);
58808
- for (const text2 of [header, ...blocks]) {
58809
- const process2 = codexRunningProcess(text2);
58810
- if (process2 !== null) evidence.forget(process2);
58811
- }
58812
- }
58813
- return;
58814
- }
58815
- const tool = toolCallName(responseItem);
58816
- if (tool !== null) {
58817
- const call = { name: tool };
58818
- if (options.keepToolInputs === true) {
58819
- const args = toolCallArguments(responseItem);
58820
- if (args !== null) call.input = boundedToolInput(args);
58821
- }
58822
- pendingTools.push(call);
58823
- pendingAt ??= at;
58824
- if (callId !== null) {
58825
- const script = watchCodexCall(evidence, callId, responseItem, at, runningScripts);
58826
- if (script !== null) keepBounded(scripts, callId, script);
58827
- }
58828
- return;
58829
- }
58830
- if (responseItem.type !== "message") return;
58831
- if (responseItem.role === "user") {
58832
- const prompt = promptText(responseItem.content);
58833
- if (prompt !== null) {
58834
- flushPendingTools();
58835
- turns.push({ kind: "human_prompt", text: prompt.text, origin: prompt.origin, toolCalls: [], usage: null, at });
58836
- }
58837
- return;
58838
- }
58839
- if (responseItem.role !== "assistant") return;
58840
- const text = outputTextBlocks(responseItem.content).join("\n");
58841
- if (text.trim() === "") return;
58842
- pushAgentTurn({ kind: "agent_text", text, origin: "agent", toolCalls: pendingTools, usage: null, at: pendingAt ?? at });
58843
- pendingTools = [];
58844
- pendingAt = null;
58845
- },
58846
- finish() {
58847
- flushPendingTools();
58848
- if (pendingEnvelopes.length > 0) {
58849
- const lastAgentTurn = turns.findLastIndex((turn) => turn.kind === "agent_text");
58850
- if (lastAgentTurn === -1) {
58851
- turns.push({ kind: "agent_text", text: "", origin: "agent", toolCalls: [], usage: null, at: pendingEnvelopes[0].at });
58852
- landPending(turns.length - 1);
58853
- } else {
58854
- landPending(lastAgentTurn);
58855
- }
58856
- }
58857
- return turns;
58858
- },
58859
- usageEnvelopes() {
58860
- return envelopes;
58861
- },
58862
- prEvidence() {
58863
- return evidence.finish();
58864
- },
58865
- prEvidenceDroppedPushes() {
58866
- return evidence.droppedPushes();
58867
- }
58868
- };
58869
- }
58870
- var stepKey = (callId, step) => `${callId}#${step}`;
58871
- function watchCodexCall(evidence, callId, item, at, runningScripts) {
58872
- if (item.type === "custom_tool_call" && item.name === "exec" && typeof item.input === "string") {
58873
- const steps = execScriptSteps(item.input);
58874
- const commands = [];
58875
- let seen = { pushes: 0, pullRequestCreates: 0 };
58876
- steps.forEach((step, i) => {
58877
- if (step.polls !== null) evidence.follow(stepKey(callId, i), step.polls);
58878
- if (step.command === null) return;
58879
- commands.push(step.command);
58880
- const read = readCodeHostCommands(commands.join("\n"), null);
58881
- evidence.watch(
58882
- stepKey(callId, i),
58883
- {
58884
- pushes: read.pushes.slice(seen.pushes),
58885
- pullRequestCreates: read.pullRequestCreates.slice(seen.pullRequestCreates)
58886
- },
58887
- at
58888
- );
58889
- seen = { pushes: read.pushes.length, pullRequestCreates: read.pullRequestCreates.length };
58890
- });
58891
- const watched = steps.some((_, i) => evidence.watching(stepKey(callId, i)));
58892
- return watched ? { callId, polls: steps.map((step) => step.polls), printsEachStep: printsEachStep(item.input, steps) } : null;
58893
- }
58894
- if (item.type === "local_shell_call") {
58895
- const command = argvCommand(asRecord2(item.action)?.command);
58896
- if (command !== null) evidence.command(callId, command, null, at);
58897
- return null;
58898
- }
58899
- if (item.type !== "function_call" || typeof item.arguments !== "string") return null;
58900
- const args = safeJsonRecord(item.arguments);
58901
- if (item.name === "exec_command" && typeof args?.cmd === "string") {
58902
- evidence.command(callId, args.cmd, null, at);
58903
- } else if (item.name === "shell") {
58904
- const command = argvCommand(args?.command);
58905
- if (command !== null) evidence.command(callId, command, null, at);
58906
- } else if (item.name === "write_stdin" && typeof args?.session_id === "number") {
58907
- evidence.follow(callId, String(args.session_id));
58908
- } else if (item.name === "wait" && (typeof args?.cell_id === "string" || typeof args?.cell_id === "number")) {
58909
- const script = runningScripts.get(String(args.cell_id)) ?? null;
58910
- runningScripts.delete(String(args.cell_id));
58911
- return script;
58912
- } else if (item.name === "_create_pull_request") {
58913
- const head = typeof args?.head === "string" ? args.head : null;
58914
- evidence.watch(callId, { pushes: [], pullRequestCreates: [{ head, ownExitStatus: true }] }, at);
58915
- }
58916
- return null;
58917
- }
58918
- function scriptResult(evidence, script, header, blocks, at, line) {
58919
- const paired = script.printsEachStep && blocks.length === script.polls.length;
58920
- const keys = script.polls.map((_, i) => stepKey(script.callId, i));
58921
- if (!paired) {
58922
- evidence.merge(keys.filter((_, i) => script.polls[i] === null), script.callId);
58923
- evidence.result(script.callId, { succeeded: null, text: [header, ...blocks].join("\n"), running: null, at, line });
58924
- }
58925
- script.polls.forEach((polls, i) => {
58926
- if (!evidence.watching(keys[i])) return;
58927
- const text = paired ? blocks[i] : "";
58928
- const succeeded = paired ? codexExitStatus(text) : null;
58929
- const running = (paired ? codexRunningProcess(text) : null) ?? (succeeded === null ? polls : null);
58930
- evidence.result(keys[i], { succeeded, text, running, at, line });
58931
- });
58932
- }
58933
- function outputBlocks(output2) {
58934
- if (typeof output2 === "string") return [output2];
58935
- if (!Array.isArray(output2)) return [];
58936
- return output2.map((block2) => {
58937
- const text = asRecord2(block2)?.text;
58938
- return typeof text === "string" ? text : "";
58939
- });
58940
- }
58941
- function argvCommand(argv) {
58942
- if (typeof argv === "string") return argv;
58943
- if (!Array.isArray(argv) || !argv.every((word) => typeof word === "string")) return null;
58944
- const [shell, flag, script] = argv;
58945
- if (argv.length === 3 && /(?:^|\/)(?:ba|z|da|k)?sh$/.test(shell) && /^-[a-z]*c[a-z]*$/.test(flag)) return script;
58946
- return argv.map((word) => /^[A-Za-z0-9._/:=@+-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`).join(" ");
58947
- }
58948
- var SCRIPT_TOOL_CALL = /tools\.(\w+)\(/g;
58949
- var COMMAND_ARGUMENT = /\{\s*"?cmd"?\s*:\s*("(?:[^"\\]|\\.)*")/y;
58950
- var SESSION_ARGUMENT = /\{\s*"?session_id"?\s*:\s*(\d+)/y;
58951
- function execScriptSteps(script) {
58952
- const steps = [];
58953
- const call = new RegExp(SCRIPT_TOOL_CALL);
58954
- for (let match = call.exec(script); match !== null; match = call.exec(script)) {
58955
- const argument = match[1] === "exec_command" ? COMMAND_ARGUMENT : match[1] === "write_stdin" ? SESSION_ARGUMENT : null;
58956
- if (argument !== null) argument.lastIndex = call.lastIndex;
58957
- const value = argument?.exec(script) ?? null;
58958
- if (value !== null) call.lastIndex += value[0].length;
58959
- steps.push({
58960
- command: value !== null && match[1] === "exec_command" ? jsonString(value[1]) : null,
58961
- polls: value !== null && match[1] === "write_stdin" ? value[1] : null
58962
- });
58963
- }
58964
- return steps;
58965
- }
58966
- var STRING_LITERAL = /"(?:[^"\\]|\\.)*"/g;
58967
- var TEXT_CALL = /\btext\(/g;
58968
- var TEXT_OF_TOOL_CALL = /\btext\(\s*await\s+tools\.\w+\(/g;
58969
- var DEFERRED_CODE = /\bfunction\b|=>|\.then\(/;
58970
- function printsEachStep(script, steps) {
58971
- if (steps.length === 1) return true;
58972
- const code = script.replace(STRING_LITERAL, '""');
58973
- if (DEFERRED_CODE.test(code)) return false;
58974
- const printed = [...code.matchAll(TEXT_OF_TOOL_CALL)].length;
58975
- return printed === steps.length && [...code.matchAll(TEXT_CALL)].length === steps.length;
58976
- }
58977
- function jsonString(literal2) {
58978
- try {
58979
- const parsed = JSON.parse(literal2);
58980
- return typeof parsed === "string" ? parsed : null;
58981
- } catch {
58982
- return null;
58983
- }
58984
- }
58985
- function isToolOutput(item) {
58986
- return item.type === "custom_tool_call_output" || item.type === "function_call_output" || item.type === "local_shell_call_output";
58987
- }
58988
- var SCRIPT_STILL_RUNNING = /^Script running with cell ID (\d+)/;
58989
- var RUNNING_CHUNK = /^\s*\{[^\n]*?"session_id"\s*:\s*(\d+)/;
58990
- var RUNNING_PROCESS_LINE = /^Process running with session ID (\d+)$/m;
58991
- function codexRunningProcess(output2) {
58992
- const chunk = RUNNING_CHUNK.exec(output2);
58993
- if (chunk !== null) return chunk[1];
58994
- const outputLine = output2.search(/^Output:/m);
58995
- const header = outputLine === -1 ? output2 : output2.slice(0, outputLine);
58996
- return RUNNING_PROCESS_LINE.exec(header)?.[1] ?? null;
58997
- }
58998
- var EXIT_STATUS = /"exit_code"\s*:\s*(\d+)|Process exited with code (\d+)/g;
58999
- function codexExitStatus(output2) {
59000
- const codes = [...output2.matchAll(EXIT_STATUS)].map((match) => Number(match[1] ?? match[2]));
59001
- if (codes.length === 0) return null;
59002
- return codes.every((code) => code === 0);
59003
- }
59004
-
59005
- // ../core/src/cursorRunEvents.ts
59006
- var API_TOOL_NAMES = {
59007
- read_file: "Read",
59008
- run_terminal_cmd: "Shell",
59009
- grep_search: "Grep",
59010
- edit_file: "StrReplace",
59011
- get_mcp_tools: "GetMcpTools",
59012
- mcp: "CallMcpTool",
59013
- await: "Await",
59014
- pr_management: "ManagePullRequest",
59015
- file_search: "Glob",
59016
- task: "Subagent",
59017
- todo_write: "TodoWrite"
59018
- };
59019
- var READ_TOOLS = /* @__PURE__ */ new Set(["Read", "ReadFile"]);
59020
- var ARTIFACT_PATH_RE = /(^|\/)(agent-tools\/[0-9a-f-]{8,}|terminals\/\d+)\.txt$/;
59021
- function primaryArg(args) {
59022
- for (const key of ["path", "command", "query", "pattern"]) {
59023
- const v = args[key];
59024
- if (typeof v === "string" && v.length > 0) return v;
59025
- }
59026
- const firstString = Object.values(args).find((v) => typeof v === "string" && v.length > 0);
59027
- return firstString ?? null;
59028
- }
59029
- function readFilePath(name, primary) {
59030
- if (!primary || !READ_TOOLS.has(name)) return null;
59031
- if (ARTIFACT_PATH_RE.test(primary)) return null;
59032
- const path55 = primary.startsWith("/workspace/") ? primary.slice("/workspace/".length) : primary;
59033
- return path55.length > 0 ? path55 : null;
59034
- }
59035
- function asRecord3(value) {
59036
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
59037
- }
59038
- function stringField(value, key) {
59039
- const v = value?.[key];
59040
- return typeof v === "string" && v.length > 0 ? v : null;
59041
- }
59042
- function asRawEvent(value) {
59043
- const record2 = asRecord3(value);
59044
- const event = stringField(record2, "event");
59045
- return event ? { event, data: record2?.data } : null;
59046
- }
59047
- function parseCursorRunEvents(runs, options = {}) {
59048
- return parseCursorRunEventsDetailed(runs, options).turns;
59049
- }
59050
- function parseCursorRunEventsDetailed(runs, options = {}) {
59051
- const turns = [];
59052
- const turnTokens = [];
59053
- let pendingTools = [];
59054
- let pendingTokens = 0;
59055
- let text = "";
59056
- const flush2 = () => {
59057
- if (text !== "" || pendingTools.length > 0 || pendingTokens > 0) {
59058
- turns.push({ kind: "agent_text", text, origin: "agent", toolCalls: pendingTools, usage: null, at: null });
59059
- turnTokens.push(pendingTokens);
59060
- }
59061
- text = "";
59062
- pendingTools = [];
59063
- pendingTokens = 0;
59064
- };
59065
- for (const run2 of runs) {
59066
- const openCalls = /* @__PURE__ */ new Map();
59067
- for (const raw of run2.events) {
59068
- const evt = asRawEvent(raw);
59069
- if (!evt) continue;
59070
- if (evt.event === "tool_call") {
59071
- const call = asRecord3(evt.data);
59072
- const callId = stringField(call, "callId");
59073
- const rawName = stringField(call, "name");
59074
- if (!callId || !rawName) continue;
59075
- let entry = openCalls.get(callId);
59076
- if (!entry) {
59077
- if (text !== "") flush2();
59078
- entry = { name: API_TOOL_NAMES[rawName] ?? rawName };
59079
- openCalls.set(callId, entry);
59080
- pendingTools.push(entry);
59081
- }
59082
- const args = asRecord3(call?.args);
59083
- if (args) {
59084
- const filePath = readFilePath(entry.name, primaryArg(args));
59085
- if (filePath) entry.filePath = filePath;
59086
- else delete entry.filePath;
59087
- if (options.keepToolInputs === true) entry.input = boundedToolInput(args);
59088
- }
59089
- continue;
59090
- }
59091
- if (evt.event === "thinking" || evt.event === "assistant") {
59092
- const delta = stringField(asRecord3(evt.data), "text");
59093
- if (delta) text += delta;
59094
- continue;
59095
- }
59096
- if (evt.event === "interaction_update") {
59097
- const data = asRecord3(evt.data);
59098
- const type = stringField(data, "type");
59099
- if (type === "token-delta") {
59100
- const tokens = Number(data?.tokens);
59101
- if (Number.isFinite(tokens) && tokens > 0) pendingTokens += tokens;
59102
- continue;
59103
- }
59104
- if (type !== "user-message-appended") continue;
59105
- const prompt = stringField(asRecord3(data?.userMessage), "text");
59106
- if (!prompt) continue;
59107
- if (text !== "") flush2();
59108
- turns.push({ kind: "human_prompt", text: prompt, origin: "unknown", toolCalls: [], usage: null, at: null });
59109
- turnTokens.push(0);
59110
- continue;
59111
- }
59112
- }
59113
- }
59114
- flush2();
59115
- return { turns, turnTokens };
59116
- }
59117
-
59118
- // ../core/src/cursorRunRedaction.ts
59119
- var REDACTED2 = "[REDACTED]";
59120
- var SECRET_REST = /^[^\s\\"',;]+/;
59121
- var CUT_PRIVATE_KEY_BODY = /\[REDACTED\][A-Za-z0-9+/=\s\\]*-----END [A-Z0-9 ]*PRIVATE KEY-----/g;
59122
- function asRecord4(value) {
59123
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
59124
- }
59125
- function nonEmptyString(value) {
59126
- return typeof value === "string" && value !== "";
59127
- }
59128
- function streamedText(event) {
59129
- const data = asRecord4(event.data);
59130
- if (data === null) return null;
59131
- if (event.event === "assistant" || event.event === "thinking") {
59132
- if (typeof data.text !== "string") return null;
59133
- return {
59134
- stream: event.event,
59135
- served: true,
59136
- text: data.text,
59137
- withText: (text) => ({ ...event, data: { ...data, text } })
59138
- };
59139
- }
59140
- if (event.event !== "interaction_update") return null;
59141
- if (data.type === "text-delta" || data.type === "thinking-delta") {
59142
- if (typeof data.text !== "string") return null;
59143
- return {
59144
- stream: data.type,
59145
- served: false,
59146
- text: data.text,
59147
- withText: (text) => ({ ...event, data: { ...data, text } })
59148
- };
59149
- }
59150
- const update = asRecord4(data.taskUpdate);
59151
- if (data.type !== "tool-call-delta" || !nonEmptyString(data.callId) || update?.type !== "text-delta" && update?.type !== "thinking-delta" || typeof update.text !== "string") {
59152
- return null;
59153
- }
59154
- return {
59155
- stream: `${data.callId}/${update.type}`,
59156
- served: false,
59157
- text: update.text,
59158
- withText: (text) => ({ ...event, data: { ...data, taskUpdate: { ...update, text } } })
59159
- };
59160
- }
59161
- function endsTurnText(event, callIds) {
59162
- const data = asRecord4(event.data);
59163
- if (event.event === "tool_call") {
59164
- if (!nonEmptyString(data?.callId) || !nonEmptyString(data.name) || callIds.has(data.callId)) return false;
59165
- callIds.add(data.callId);
59166
- return true;
59167
- }
59168
- return event.event === "interaction_update" && data?.type === "user-message-appended" && nonEmptyString(asRecord4(data.userMessage)?.text);
59169
- }
59170
- function splitLikeParts(parts, redacted) {
59171
- const joined = parts.join("");
59172
- if (joined === redacted) return [...parts];
59173
- const shorter = Math.min(joined.length, redacted.length);
59174
- let start = 0;
59175
- while (start < shorter && joined[start] === redacted[start]) start += 1;
59176
- let same = 0;
59177
- while (same < shorter - start && joined.at(-1 - same) === redacted.at(-1 - same)) same += 1;
59178
- const changedEnd = joined.length - same;
59179
- const changed = redacted.slice(start, redacted.length - same);
59180
- let at = 0;
59181
- let placed = false;
59182
- return parts.map((part, index) => {
59183
- const end = at + part.length;
59184
- let text = joined.slice(at, Math.min(end, start));
59185
- if (!placed && (end > start || index === parts.length - 1)) {
59186
- text += changed;
59187
- placed = true;
59188
- }
59189
- text += joined.slice(Math.max(at, changedEnd), end);
59190
- at = end;
59191
- return text;
59192
- });
59193
- }
59194
- function removeCutSecretRests(texts) {
59195
- let cut = false;
59196
- return texts.map((text) => {
59197
- const part = cut ? text.replace(SECRET_REST, "") : text;
59198
- if (part !== "") cut = part.endsWith(REDACTED2);
59199
- return part;
59200
- });
59201
- }
59202
- function keepTextAfterRedactions(parts) {
59203
- const out = [...parts];
59204
- let open3 = null;
59205
- for (const k2 of out.keys()) {
59206
- if (open3 !== null) {
59207
- const rest = SECRET_REST.exec(out[k2])?.[0] ?? "";
59208
- out[open3] += rest;
59209
- out[k2] = out[k2].slice(rest.length);
59210
- if (out[k2] === "") continue;
59211
- }
59212
- open3 = out[k2].endsWith(REDACTED2) ? k2 : null;
59213
- }
59214
- return out;
59215
- }
59216
- function redactStreamTexts(texts) {
59217
- const parts = removeCutSecretRests(texts);
59218
- const joined = parts.join("");
59219
- const redacted = redactText(joined.replace(CUT_PRIVATE_KEY_BODY, REDACTED2));
59220
- const alone = redacted === joined ? parts : parts.map(redactText);
59221
- const split = alone.join("") === redacted ? alone : splitLikeParts(parts, redacted);
59222
- return keepTextAfterRedactions(split);
59223
- }
59224
- function mapStreams(events, servedOnly, map2) {
59225
- const out = [...events];
59226
- const callIds = /* @__PURE__ */ new Set();
59227
- let streams = /* @__PURE__ */ new Map();
59228
- const mapStreamsSoFar = () => {
59229
- for (const indices of streams.values()) {
59230
- const deltas = indices.map((index) => streamedText(out[index]));
59231
- const texts = map2(deltas.map((delta) => delta.text));
59232
- for (const [k2, delta] of deltas.entries()) {
59233
- if (texts[k2] !== delta.text) out[indices[k2]] = delta.withText(texts[k2]);
59234
- }
59235
- }
59236
- streams = /* @__PURE__ */ new Map();
59237
- };
59238
- for (const [index, event] of events.entries()) {
59239
- if (endsTurnText(event, callIds)) mapStreamsSoFar();
59240
- const delta = streamedText(event);
59241
- if (delta === null || servedOnly && !delta.served) continue;
59242
- const indices = streams.get(delta.stream);
59243
- if (indices) indices.push(index);
59244
- else streams.set(delta.stream, [index]);
59245
- }
59246
- mapStreamsSoFar();
59247
- return out;
59248
- }
59249
- function redactCursorRunEvents(events, { servedOnly = false } = {}) {
59250
- return mapStreams(events, servedOnly, redactStreamTexts);
59251
- }
59252
-
59253
- // ../core/src/previewLinks.ts
59254
- var SKILL_LINE = /^(?:[-*+]\s+)?[*`]*PREVIEW:\s+(\S+)\s+(https?:\/\/\S+)\s*$/gm;
59255
- var MARKDOWN_LINE = (
59256
- // eslint-disable-next-line security/detect-unsafe-regex
59257
- /\*\*([^*]{1,60})\*\*:?\s*:?\s*(https?:\/\/[\w.:-]+(?:\/[\w./\-~%]*)?(?:\?[\w./\-~%&=+]*)?)/g
59258
- );
59259
- function extractPreviewLinks(events, kinds = ["agent_response"], options) {
59260
- let guardIndex = -1;
59261
- if (options?.unsettledTail === true) {
59262
- for (let index = events.length - 1; index >= 0; index -= 1) {
59263
- const event = events[index];
59264
- if (kinds.includes(event.kind) && event.text) {
59265
- guardIndex = index;
59266
- break;
59267
- }
59268
- }
59269
- }
59270
- const byUrl = /* @__PURE__ */ new Map();
59271
- for (const [index, event] of events.entries()) {
59272
- if (!kinds.includes(event.kind)) continue;
59273
- const text = event.text;
59274
- if (!text) continue;
59275
- const guardTail = index === guardIndex;
59276
- for (const pattern of [SKILL_LINE, MARKDOWN_LINE]) {
59277
- pattern.lastIndex = 0;
59278
- for (const match of text.matchAll(pattern)) {
59279
- const matchEnd = match.index + match[0].replace(/\s+$/, "").length;
59280
- if (guardTail && matchEnd === text.length) continue;
59281
- const raw = match[1].trim().replace(/[:*]+$/, "").trim();
59282
- const url2 = normalizeUrl(match[2]);
59283
- const building = /\(building\)$/i.test(raw);
59284
- const label2 = building ? raw.replace(/\s*\(building\)$/i, "").trim() : raw;
59285
- if (!url2 || label2 === "") continue;
59286
- byUrl.set(trimTrailingSlash(url2), building ? { label: label2, url: url2, building } : { label: label2, url: url2 });
59287
- }
59288
- }
59289
- }
59290
- return [...byUrl.values()];
59291
- }
59292
- var trimTrailingSlash = (url2) => url2.replace(/\/+$/, "");
59293
- function normalizeUrl(raw) {
59294
- const trimmed = raw.replace(/[.,)\]`*]+$/, "");
59295
- return /^https?:\/\/[\w.-]+(:\d+)?(\/[\w./\-~%]*)?(\?[\w./\-~%&=+]*)?$/.test(trimmed) ? trimmed : null;
59296
- }
59297
-
59298
- // ../core/src/sessionTurns.ts
59299
- function parseSessionTurns(source, transcript, options = {}) {
59300
- return parseSessionTurnsDetailed(source, transcript, options).turns;
59301
- }
59302
- function parseSessionTurnsDetailed(source, transcript, options = {}) {
59303
- if (source === "cursor-cloud") {
59304
- return {
59305
- turns: parseCursorRunEvents(envelopeRuns(transcript), options),
59306
- envelopes: [],
59307
- prEvidence: [],
59308
- droppedPushes: 0
59309
- };
59310
- }
59311
- const parser = createSessionTurnParser(source, options);
59312
- for (const line of transcript.split("\n")) parser.pushLine(line);
59313
- const turns = parser.finish();
59314
- return {
59315
- turns,
59316
- envelopes: parser.usageEnvelopes?.() ?? [],
59317
- prEvidence: parser.prEvidence?.() ?? [],
59318
- droppedPushes: parser.prEvidenceDroppedPushes?.() ?? 0
59319
- };
59320
- }
59321
- function createSessionTurnParser(source, options = {}) {
59322
- if (source === "codex") return createCodexTurnParser(options);
59323
- if (source === "cursor") return createCursorTurnParser(options);
59324
- return createDigestTurnParser(options);
59325
- }
59326
- function announcedPreviewsFromEvents(events) {
59327
- return extractPreviewLinks(events, ["agent_prompt", "agent_response"]);
59328
- }
59329
- function announcedPreviewsFromTurns(turns) {
59330
- return announcedPreviewsFromEvents(
59331
- capturedSessionEvents(turns, { sessionId: "announced", observedAt: "" })
59332
- );
59333
- }
59334
- function parseSseEvents(text) {
59335
- const events = [];
59336
- let type = "";
59337
- let dataLines = [];
59338
- const flush2 = () => {
59339
- if (dataLines.length === 0) return;
59340
- events.push({ event: type, data: safeJson(dataLines.join("\n")) });
59341
- type = "";
59342
- dataLines = [];
59343
- };
59344
- for (const line of text.split("\n")) {
59345
- if (line.startsWith("event:")) type = line.slice("event:".length).trim();
59346
- else if (line.startsWith("data:")) dataLines.push(line.slice("data:".length).trimStart());
59347
- else if (line.trim() === "") flush2();
59348
- }
59349
- flush2();
59350
- return events;
59351
- }
59352
- function envelopeRuns(transcript) {
59353
- const parsed = safeJson(transcript);
59354
- if (!parsed || !Array.isArray(parsed.runs)) return [];
59355
- const runs = [];
59356
- for (const item of parsed.runs) {
59357
- const run2 = item;
59358
- if (typeof run2?.runId !== "string" || typeof run2.sse !== "string") continue;
59359
- runs.push({ runId: run2.runId, events: redactCursorRunEvents(parseSseEvents(run2.sse), { servedOnly: true }) });
59360
- }
59361
- return runs;
59362
- }
59363
- function safeJson(text) {
59364
- try {
59365
- return JSON.parse(text);
59366
- } catch {
59367
- return null;
59368
- }
59369
- }
59370
-
59371
57592
  // ../core/src/scrubSentryEvent.ts
59372
- var REDACTED3 = "[Filtered]";
57593
+ var REDACTED2 = "[Filtered]";
59373
57594
  var SECRET_KEY_PATTERN = /^(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|x-csrf-token|x-supabase-auth|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|client[_-]?secret|password|passwd|secret|signature|token|jwt)$/i;
59374
57595
  var SECRET_QUERY_PARAM_PATTERN = /^(?:token|access_token|refresh_token|id_token|api_key|apikey|key|code|signature|password|secret|client_secret|state)$/i;
59375
57596
  var BEARER_TOKEN_PATTERN = /\bBearer\s+[\w\-._~+/=]+/gi;
@@ -59444,7 +57665,7 @@ var OUTGOING_URL_FIELD_NAMES = ["url", "url.full", "http.url"];
59444
57665
  var OUTGOING_PATH_FIELD_NAMES = ["url.path", "http.target"];
59445
57666
  var MAX_DEPTH = 10;
59446
57667
  function scrubString(value) {
59447
- return scrubUserInfo(value).replace(POWERPLANT_TOKEN_PATTERN, REDACTED3).replace(BEARER_TOKEN_PATTERN, `Bearer ${REDACTED3}`).replace(JWT_PATTERN, REDACTED3).replace(EMBEDDED_QUERY_SECRET_PATTERN, `$1${REDACTED3}`);
57668
+ return scrubUserInfo(value).replace(POWERPLANT_TOKEN_PATTERN, REDACTED2).replace(BEARER_TOKEN_PATTERN, `Bearer ${REDACTED2}`).replace(JWT_PATTERN, REDACTED2).replace(EMBEDDED_QUERY_SECRET_PATTERN, `$1${REDACTED2}`);
59448
57669
  }
59449
57670
  function scrubUrl(url2) {
59450
57671
  const scrubbed = scrubUserInfo(url2);
@@ -59452,11 +57673,11 @@ function scrubUrl(url2) {
59452
57673
  return queryStart === -1 ? scrubbed : scrubbed.slice(0, queryStart);
59453
57674
  }
59454
57675
  function scrubUserInfo(value) {
59455
- return value.replace(URL_USER_INFO_PATTERN, `$1${REDACTED3}@`);
57676
+ return value.replace(URL_USER_INFO_PATTERN, `$1${REDACTED2}@`);
59456
57677
  }
59457
57678
  function scrubOutgoingUrl(url2) {
59458
57679
  const parts = URL_PARTS.exec(url2);
59459
- if (!parts) return REDACTED3;
57680
+ if (!parts) return REDACTED2;
59460
57681
  const [, scheme = "", authority = "", path55 = ""] = parts;
59461
57682
  const host = authority.slice(authority.lastIndexOf("@") + 1);
59462
57683
  const origin = `${scheme}${host}`;
@@ -59483,7 +57704,7 @@ function scrubValue(value, depth = 0) {
59483
57704
  for (const [key, child] of Object.entries(value)) {
59484
57705
  const name = key.toLowerCase();
59485
57706
  if (SECRET_KEY_PATTERN.test(key) || SECRET_QUERY_PARAM_PATTERN.test(key) || HTTP_ATTRIBUTE_PREFIX.test(name) && !KEPT_HTTP_ATTRIBUTES.has(name)) {
59486
- out[key] = REDACTED3;
57707
+ out[key] = REDACTED2;
59487
57708
  } else if (URL_FIELD_NAMES.has(name) && typeof child === "string") {
59488
57709
  out[key] = scrubUrl(child);
59489
57710
  } else {
@@ -59498,20 +57719,20 @@ function scrubSentryEvent(event) {
59498
57719
  event.request.url = scrubUrl(event.request.url);
59499
57720
  }
59500
57721
  if (event.request.query_string !== void 0) {
59501
- event.request.query_string = REDACTED3;
57722
+ event.request.query_string = REDACTED2;
59502
57723
  }
59503
57724
  if (event.request.headers) {
59504
57725
  const headers = Object.entries(event.request.headers).map(([name, value]) => [
59505
57726
  name,
59506
- KEPT_HEADER_NAMES.has(name.toLowerCase()) ? value : REDACTED3
57727
+ KEPT_HEADER_NAMES.has(name.toLowerCase()) ? value : REDACTED2
59507
57728
  ]);
59508
57729
  event.request.headers = scrubValue(Object.fromEntries(headers));
59509
57730
  }
59510
57731
  if (event.request.cookies !== void 0) {
59511
- event.request.cookies = REDACTED3;
57732
+ event.request.cookies = REDACTED2;
59512
57733
  }
59513
57734
  if (event.request.data !== void 0) {
59514
- event.request.data = REDACTED3;
57735
+ event.request.data = REDACTED2;
59515
57736
  }
59516
57737
  }
59517
57738
  if (event.exception?.values) {
@@ -59560,7 +57781,7 @@ function scrubOutgoingRequestSpan(span) {
59560
57781
  if (typeof value === "string") data[name] = scrubOutgoingUrl(value);
59561
57782
  }
59562
57783
  for (const name of OUTGOING_PATH_FIELD_NAMES) {
59563
- if (name in data) data[name] = REDACTED3;
57784
+ if (name in data) data[name] = REDACTED2;
59564
57785
  }
59565
57786
  }
59566
57787
  function scrubBreadcrumb(breadcrumb) {
@@ -86915,7 +85136,7 @@ import { createHmac } from "node:crypto";
86915
85136
  import tls2 from "node:tls";
86916
85137
  var import_undici = __toESM(require_undici(), 1);
86917
85138
  var CLI_VERSION_HEADER = "x-powerplant-cli-version";
86918
- var cliVersion = true ? "0.4.25" : "0.0.0-checkout";
85139
+ var cliVersion = true ? "0.4.27" : "0.0.0-checkout";
86919
85140
  function cliVersionHeaders() {
86920
85141
  return { [CLI_VERSION_HEADER]: cliVersion, "user-agent": `powerplant-cli/${cliVersion}` };
86921
85142
  }
@@ -88014,10 +86235,10 @@ function readFirstSessionMeta(rolloutPath) {
88014
86235
  } catch {
88015
86236
  record2 = void 0;
88016
86237
  }
88017
- if (!isRecord2(record2)) {
86238
+ if (!isRecord(record2)) {
88018
86239
  return first.complete ? { state: "fault", reason: "the first line is not a JSON object (expected a session_meta record)" } : { state: "pending" };
88019
86240
  }
88020
- if (record2.type !== "session_meta" || !isRecord2(record2.payload)) {
86241
+ if (record2.type !== "session_meta" || !isRecord(record2.payload)) {
88021
86242
  return { state: "fault", reason: "the first record is not a session_meta record with a payload object" };
88022
86243
  }
88023
86244
  return { state: "session_meta", timestamp: record2.timestamp, meta: record2.payload };
@@ -88026,7 +86247,7 @@ function rolloutLocation(rolloutPath, first = readFirstSessionMeta(rolloutPath))
88026
86247
  const unknown2 = { kind: "session", codexClient: "unknown", totals: null, fastTotals: null };
88027
86248
  if (first.state === "session_meta") return locationOf(first.timestamp, first.meta);
88028
86249
  if (first.state === "pending") return unknown2;
88029
- const record2 = readFirstRecord(rolloutPath, (candidate) => candidate.type === "session_meta" && isRecord2(candidate.payload));
86250
+ const record2 = readFirstRecord(rolloutPath, (candidate) => candidate.type === "session_meta" && isRecord(candidate.payload));
88030
86251
  return record2 === null ? unknown2 : locationOf(record2.timestamp, record2.payload);
88031
86252
  }
88032
86253
  function locationOf(startedAt, meta3) {
@@ -89042,10 +87263,10 @@ async function openLocalDatabase(dbPath) {
89042
87263
  const sqlite = await loadSqlite();
89043
87264
  return new sqlite.DatabaseSync(dbPath, { readOnly: true });
89044
87265
  }
89045
- function safeJsonRecord2(text) {
87266
+ function safeJsonRecord(text) {
89046
87267
  try {
89047
87268
  const parsed = JSON.parse(text);
89048
- return isRecord2(parsed) ? parsed : null;
87269
+ return isRecord(parsed) ? parsed : null;
89049
87270
  } catch {
89050
87271
  return null;
89051
87272
  }
@@ -89080,7 +87301,7 @@ function workspaceFolderOf(cursorUserDir, workspaceId) {
89080
87301
  }
89081
87302
  const text = readIfExists(path6.join(cursorUserDir, "workspaceStorage", workspaceId, "workspace.json"));
89082
87303
  if (text === null) return void 0;
89083
- const record2 = safeJsonRecord2(text);
87304
+ const record2 = safeJsonRecord(text);
89084
87305
  const folder = record2?.folder;
89085
87306
  if (typeof folder !== "string") return void 0;
89086
87307
  try {
@@ -89090,19 +87311,19 @@ function workspaceFolderOf(cursorUserDir, workspaceId) {
89090
87311
  }
89091
87312
  }
89092
87313
  function headerFactsOf(value) {
89093
- const location = isRecord2(value.agentLocation) ? value.agentLocation : null;
89094
- const workspaceUri = isRecord2(value.workspaceIdentifier) ? value.workspaceIdentifier.uri : void 0;
87314
+ const location = isRecord(value.agentLocation) ? value.agentLocation : null;
87315
+ const workspaceUri = isRecord(value.workspaceIdentifier) ? value.workspaceIdentifier.uri : void 0;
89095
87316
  const repos = Array.isArray(value.trackedGitRepos) ? value.trackedGitRepos : [];
89096
87317
  const branchStamps = [];
89097
87318
  let repoPath;
89098
87319
  for (const repo of repos) {
89099
- if (!isRecord2(repo)) continue;
87320
+ if (!isRecord(repo)) continue;
89100
87321
  if (repoPath === void 0 && typeof repo.repoPath === "string" && repo.repoPath !== "") {
89101
87322
  repoPath = repo.repoPath;
89102
87323
  }
89103
87324
  if (!Array.isArray(repo.branches)) continue;
89104
87325
  for (const branch of repo.branches) {
89105
- if (!isRecord2(branch) || typeof branch.branchName !== "string" || branch.branchName === "")
87326
+ if (!isRecord(branch) || typeof branch.branchName !== "string" || branch.branchName === "")
89106
87327
  continue;
89107
87328
  branchStamps.push({
89108
87329
  name: branch.branchName,
@@ -89232,7 +87453,7 @@ function unfamiliarLine(fields, position, recorder) {
89232
87453
  function promptContext(context2, recorder) {
89233
87454
  const present = Object.entries(context2).filter(([, value]) => {
89234
87455
  if (Array.isArray(value)) return value.length > 0;
89235
- if (isRecord2(value)) return Object.keys(value).length > 0;
87456
+ if (isRecord(value)) return Object.keys(value).length > 0;
89236
87457
  return value !== void 0 && value !== null;
89237
87458
  });
89238
87459
  const { kept, excludedKeys, omitted } = retainFieldsBounded(Object.fromEntries(present), PROMPT_CONTEXT_MAX_BYTES);
@@ -89247,7 +87468,7 @@ function promptContext(context2, recorder) {
89247
87468
  function boundedJsonText(raw, maxBytes) {
89248
87469
  const bytes = Buffer.byteLength(raw);
89249
87470
  if (bytes > maxBytes) return { kind: "over", bytes };
89250
- const value = safeJsonRecord2(raw);
87471
+ const value = safeJsonRecord(raw);
89251
87472
  return value === null ? { kind: "text", bytes } : { kind: "object", value };
89252
87473
  }
89253
87474
  var TOOL_JSON_TEXT_FIELDS = ["rawArgs", "params", "result"];
@@ -89256,7 +87477,7 @@ function hasCallEvidence(tool) {
89256
87477
  }
89257
87478
  function retainedCallField(key, value) {
89258
87479
  if (!TOOL_JSON_TEXT_FIELDS.includes(key) || typeof value !== "string") return value;
89259
- return safeJsonRecord2(value) ?? value;
87480
+ return safeJsonRecord(value) ?? value;
89260
87481
  }
89261
87482
  function toolLine(tool, recorder, formatVersion) {
89262
87483
  const rawArgs = typeof tool.rawArgs === "string" && tool.rawArgs !== "" ? tool.rawArgs : typeof tool.params === "string" ? tool.params : "";
@@ -89265,7 +87486,7 @@ function toolLine(tool, recorder, formatVersion) {
89265
87486
  if (args?.kind === "over") recorder.count("truncated");
89266
87487
  const result = typeof tool.result === "string" ? boundedJsonText(tool.result, TOOL_RESULT_MAX_BYTES) : null;
89267
87488
  if (result?.kind === "over") recorder.count("truncated");
89268
- const parsedArgs = args?.kind === "object" ? args.value : args?.kind === "over" ? safeJsonRecord2(rawArgs) : null;
87489
+ const parsedArgs = args?.kind === "object" ? args.value : args?.kind === "over" ? safeJsonRecord(rawArgs) : null;
89269
87490
  const filePath = parsedArgs === null ? void 0 : toolFilePathOf(parsedArgs);
89270
87491
  return {
89271
87492
  name: tool.name,
@@ -89311,13 +87532,13 @@ function bubbleLines(bubble, at, recorder) {
89311
87532
  const text = typeof bubble.text === "string" ? bubble.text : "";
89312
87533
  if (bubble.type === 1) {
89313
87534
  collectUnfamiliar(bubble, USER_BUBBLE_FIELDS, BUBBLE_FIELDS_EXCLUDED, "", unfamiliar, recorder, formatVersion);
89314
- const context2 = isRecord2(bubble.context) ? promptContext(bubble.context, recorder) : {};
87535
+ const context2 = isRecord(bubble.context) ? promptContext(bubble.context, recorder) : {};
89315
87536
  if (text.trim() !== "" || Object.keys(context2).length > 0) {
89316
87537
  lines.push({ type: "user", text, ...createdAt, ...context2, ...position });
89317
87538
  }
89318
87539
  } else {
89319
87540
  collectUnfamiliar(bubble, ASSISTANT_BUBBLE_FIELDS, BUBBLE_FIELDS_EXCLUDED, "", unfamiliar, recorder, formatVersion);
89320
- const tool = isRecord2(bubble.toolFormerData) ? bubble.toolFormerData : null;
87541
+ const tool = isRecord(bubble.toolFormerData) ? bubble.toolFormerData : null;
89321
87542
  if (tool !== null) {
89322
87543
  collectUnfamiliar(tool, TOOL_FIELDS_INTERPRETED, TOOL_FIELDS_EXCLUDED, "toolFormerData", unfamiliar, recorder, formatVersion);
89323
87544
  if (typeof tool.name === "string" && tool.name !== "") {
@@ -89330,7 +87551,7 @@ function bubbleLines(bubble, at, recorder) {
89330
87551
  }
89331
87552
  }
89332
87553
  if (bubble.thinking !== void 0 && bubble.thinking !== null) {
89333
- if (isRecord2(bubble.thinking)) {
87554
+ if (isRecord(bubble.thinking)) {
89334
87555
  collectUnfamiliar(bubble.thinking, THINKING_FIELDS_INTERPRETED, THINKING_FIELDS_EXCLUDED, "thinking", unfamiliar, recorder, formatVersion);
89335
87556
  }
89336
87557
  const thinkingText = cursorThinkingText(bubble.thinking);
@@ -89342,7 +87563,7 @@ function bubbleLines(bubble, at, recorder) {
89342
87563
  ...position
89343
87564
  });
89344
87565
  }
89345
- const modelInfo = isRecord2(bubble.modelInfo) ? bubble.modelInfo : null;
87566
+ const modelInfo = isRecord(bubble.modelInfo) ? bubble.modelInfo : null;
89346
87567
  if (modelInfo !== null) {
89347
87568
  collectUnfamiliar(modelInfo, MODEL_INFO_FIELDS_INTERPRETED, /* @__PURE__ */ new Set(), "modelInfo", unfamiliar, recorder, formatVersion);
89348
87569
  }
@@ -89371,8 +87592,8 @@ var CONTENT_LINE_TYPES = /* @__PURE__ */ new Set([
89371
87592
  function extractTranscript(db, composerId, maxBytes) {
89372
87593
  const valueByKey = db.prepare("select value from cursorDiskKV where key = ?");
89373
87594
  const dataRow = valueByKey.get(`composerData:${composerId}`);
89374
- const dataText = isRecord2(dataRow) && typeof dataRow.value === "string" ? dataRow.value : null;
89375
- const data = dataText === null ? null : safeJsonRecord2(dataText);
87595
+ const dataText = isRecord(dataRow) && typeof dataRow.value === "string" ? dataRow.value : null;
87596
+ const data = dataText === null ? null : safeJsonRecord(dataText);
89376
87597
  const spine = Array.isArray(data?.fullConversationHeadersOnly) ? data.fullConversationHeadersOnly : [];
89377
87598
  if (spine.length === 0) return null;
89378
87599
  const recorder = createOmissionRecorder();
@@ -89386,14 +87607,14 @@ function extractTranscript(db, composerId, maxBytes) {
89386
87607
  for (const [spineIndex, entry] of spine.entries()) {
89387
87608
  const entryRecorder = createOmissionRecorder();
89388
87609
  let bubbleLinesOut;
89389
- if (!isRecord2(entry) || typeof entry.bubbleId !== "string") {
89390
- entryRecorder.note("malformed", "spine[]", jsonValueType(isRecord2(entry) ? entry.bubbleId : entry));
87610
+ if (!isRecord(entry) || typeof entry.bubbleId !== "string") {
87611
+ entryRecorder.note("malformed", "spine[]", jsonValueType(isRecord(entry) ? entry.bubbleId : entry));
89391
87612
  bubbleLinesOut = [{ type: "malformed", spineIndex, bytes: Buffer.byteLength(JSON.stringify(entry) ?? "") }];
89392
87613
  } else {
89393
87614
  const at = { spineIndex, bubbleId: entry.bubbleId };
89394
87615
  const row = valueByKey.get(`bubbleId:${composerId}:${entry.bubbleId}`);
89395
- const text = isRecord2(row) && typeof row.value === "string" ? row.value : null;
89396
- const bubble = text === null ? null : safeJsonRecord2(text);
87616
+ const text = isRecord(row) && typeof row.value === "string" ? row.value : null;
87617
+ const bubble = text === null ? null : safeJsonRecord(text);
89397
87618
  if (text === null) {
89398
87619
  entryRecorder.note("unavailable", "bubble", "missing");
89399
87620
  bubbleLinesOut = [{ type: "unavailable", ...at }];
@@ -89475,7 +87696,7 @@ function collectFromStore(db, userDir, options, result, knownIds) {
89475
87696
  const maxBytes = options.maxTranscriptBytes ?? MAX_TRANSCRIPT_FILE_BYTES;
89476
87697
  let extractedTranscriptsDirReady = false;
89477
87698
  const columns = new Set(
89478
- db.prepare("pragma table_info(composerHeaders)").all().map((row) => isRecord2(row) ? row.name : void 0)
87699
+ db.prepare("pragma table_info(composerHeaders)").all().map((row) => isRecord(row) ? row.name : void 0)
89479
87700
  );
89480
87701
  const archiveColumn = columns.has("isArchived") ? "isArchived, " : "";
89481
87702
  const headerRows = db.prepare(
@@ -89483,11 +87704,11 @@ function collectFromStore(db, userDir, options, result, knownIds) {
89483
87704
  ).all(options.sinceMs ?? 0);
89484
87705
  for (const raw of headerRows) {
89485
87706
  try {
89486
- if (!isRecord2(raw) || typeof raw.composerId !== "string" || raw.composerId === "") continue;
87707
+ if (!isRecord(raw) || typeof raw.composerId !== "string" || raw.composerId === "") continue;
89487
87708
  knownIds.add(raw.composerId);
89488
87709
  const lastUpdatedAt = typeof raw.lastUpdatedAt === "number" ? raw.lastUpdatedAt : typeof raw.createdAt === "number" ? raw.createdAt : null;
89489
87710
  if (lastUpdatedAt === null) continue;
89490
- const value = typeof raw.value === "string" ? safeJsonRecord2(raw.value) : null;
87711
+ const value = typeof raw.value === "string" ? safeJsonRecord(raw.value) : null;
89491
87712
  if (value === null) {
89492
87713
  result.skippedUnreadable += 1;
89493
87714
  continue;
@@ -89662,7 +87883,7 @@ function parseCursorTranscriptFile(text) {
89662
87883
  } catch {
89663
87884
  value = void 0;
89664
87885
  }
89665
- if (!isRecord2(value)) {
87886
+ if (!isRecord(value)) {
89666
87887
  lines.push({ type: "malformed", recordIndex, bytes: Buffer.byteLength(row) });
89667
87888
  recorder.note("malformed", "record", jsonValueType(value));
89668
87889
  return;
@@ -89681,7 +87902,7 @@ function parseCursorTranscriptFile(text) {
89681
87902
  const role = record2.data.role;
89682
87903
  record2.data.message.content.forEach((content, blockIndex) => {
89683
87904
  const at = { recordIndex, blockIndex };
89684
- if (!isRecord2(content)) {
87905
+ if (!isRecord(content)) {
89685
87906
  lines.push({ type: "malformed", ...at, bytes: Buffer.byteLength(JSON.stringify(content)) });
89686
87907
  recorder.note("malformed", "message.content[]", jsonValueType(content));
89687
87908
  return;
@@ -92385,22 +90606,38 @@ var DELETE_CODES = /* @__PURE__ */ new Set([...LOCKED_CODES, "ENOTEMPTY", "EMFIL
92385
90606
  var RETRY_LIMIT_MS = 5e3;
92386
90607
  var FIRST_WAIT_MS = 50;
92387
90608
  var LONGEST_WAIT_MS = 1e3;
90609
+ var LOCK_WAIT_LABEL = "Waiting for Windows to release Powerplant's files\u2026";
92388
90610
  var sleeper = new Int32Array(new SharedArrayBuffer(4));
92389
90611
  var systemClock = { now: () => performance.now(), sleep: (ms) => void Atomics.wait(sleeper, 0, 0, ms) };
92390
90612
  function retryWhileLocked(what, change, retry, codes = LOCKED_CODES) {
92391
90613
  const clock = retry.clock ?? systemClock;
92392
90614
  const started = clock.now();
92393
90615
  let first = null;
92394
- for (let wait = FIRST_WAIT_MS; ; wait = Math.min(wait * 2, LONGEST_WAIT_MS)) {
92395
- try {
92396
- return change();
92397
- } catch (error63) {
92398
- first ??= { error: error63 };
92399
- const code = errorCode(error63, codes);
92400
- if (code === null || clock.now() - started + wait > RETRY_LIMIT_MS) throw first.error;
92401
- retry.log(`${what}: Windows refused it (${code}), which it can do while it holds a new file; trying again in ${wait} ms`);
92402
- clock.sleep(wait);
90616
+ let stopWaiting = null;
90617
+ try {
90618
+ for (let wait = FIRST_WAIT_MS; ; wait = Math.min(wait * 2, LONGEST_WAIT_MS)) {
90619
+ try {
90620
+ return change();
90621
+ } catch (error63) {
90622
+ first ??= { error: error63 };
90623
+ const code = errorCode(error63, codes);
90624
+ const waited = clock.now() - started;
90625
+ if (code === null || waited + wait > RETRY_LIMIT_MS) {
90626
+ if (stopWaiting !== null) {
90627
+ stopWaiting();
90628
+ stopWaiting = null;
90629
+ const reason = code === null ? "a retry failed another way" : `Windows still held the file (${code})`;
90630
+ retry.log(`${what}: gave up after ${Math.round(waited)} ms of retries: ${reason}`);
90631
+ }
90632
+ throw first.error;
90633
+ }
90634
+ stopWaiting ??= retry.waiting?.(LOCK_WAIT_LABEL) ?? (() => {
90635
+ });
90636
+ clock.sleep(wait);
90637
+ }
92403
90638
  }
90639
+ } finally {
90640
+ stopWaiting?.();
92404
90641
  }
92405
90642
  }
92406
90643
  function errorCode(error63, codes) {
@@ -92936,7 +91173,7 @@ function listNames(dir) {
92936
91173
  }
92937
91174
  async function installRelease(options) {
92938
91175
  const { location, recordFile } = options;
92939
- const retry = { log: options.log, ...options.clock !== void 0 && { clock: options.clock } };
91176
+ const retry = { log: options.log, waiting: options.waiting, ...options.clock !== void 0 && { clock: options.clock } };
92940
91177
  const record2 = readRecordForInstall(recordFile);
92941
91178
  const running = versionHolding(location, options.runningProgram);
92942
91179
  const keep = record2 === null ? listNames(location) : [record2.version, record2.previousVersion, running].filter((version2) => version2 !== null);
@@ -93899,22 +92136,6 @@ async function uploadBranchFacts(apiUrl, machineToken, facts) {
93899
92136
  }
93900
92137
  return { recorded };
93901
92138
  }
93902
- async function uploadPreviewRegistration(apiUrl, machineToken, registration) {
93903
- const response = await fetchWithRetry("registering previews", `${apiUrl}/api/ingest/previews`, {
93904
- method: "POST",
93905
- headers: { authorization: `Bearer ${machineToken}`, "content-type": "application/json" },
93906
- body: JSON.stringify(registration)
93907
- });
93908
- if (response.status === 401) {
93909
- throw tokenRejected("The ingest API", response);
93910
- }
93911
- if (response.status === 403) return "foreign-owner";
93912
- if (response.status === 423) return "previews-off";
93913
- if (!response.ok) {
93914
- throw await failedResponse("preview registration failed", response);
93915
- }
93916
- return "registered";
93917
- }
93918
92139
  var gzipAsync = promisify2(gzip);
93919
92140
  var REDACT_SLICE_CHARS = 64 * 1024;
93920
92141
  async function encodeRawTranscript(text) {
@@ -94165,7 +92386,9 @@ async function runEnrollment(config2, options) {
94165
92386
  email: options.email,
94166
92387
  password: options.password,
94167
92388
  capture: { mode: captureMode, folderCount: scopePaths.length },
94168
- log: log3
92389
+ log: log3,
92390
+ confirmOpen: options.confirmOpen,
92391
+ onWaiting: options.onWaiting
94169
92392
  });
94170
92393
  let orgPolicy = captureMode === "org-repos" ? await fetchCapturePolicy(config2.apiUrl, result.token) : void 0;
94171
92394
  const anyWorkspaceClaims = (orgPolicy?.workspaces ?? []).some(workspaceClaimsAnyRepo);
@@ -94241,7 +92464,13 @@ async function enroll(config2, options, createAuthClient = gotrueAuthClient, lis
94241
92464
  capture: options.capture
94242
92465
  }),
94243
92466
  state,
94244
- { ...listener, log: options.log, redeem: (code) => redeemApproval(config2.apiUrl, code, verifier) }
92467
+ {
92468
+ ...listener,
92469
+ log: options.log,
92470
+ confirmOpen: options.confirmOpen,
92471
+ onWaiting: options.onWaiting,
92472
+ redeem: (code) => redeemApproval(config2.apiUrl, code, verifier)
92473
+ }
94245
92474
  );
94246
92475
  }
94247
92476
  var challengeFor = (verifier) => createHash7("sha256").update(verifier).digest("hex");
@@ -94319,7 +92548,9 @@ function waitForApproval(approvalUrl, state, options) {
94319
92548
  port = MACHINE_ENROLL_CALLBACK_PORT,
94320
92549
  onListening,
94321
92550
  timeoutMs = APPROVAL_TIMEOUT_MS,
94322
- log: log3 = console.log
92551
+ log: log3 = console.log,
92552
+ confirmOpen,
92553
+ onWaiting
94323
92554
  } = options;
94324
92555
  const open3 = options.open ?? ((url2) => openUrl(url2, (reason) => log3(`Could not open a browser (${reason}). Open the link above to approve.`)));
94325
92556
  return new Promise((resolve2, reject) => {
@@ -94386,18 +92617,35 @@ function waitForApproval(approvalUrl, state, options) {
94386
92617
  )
94387
92618
  );
94388
92619
  });
94389
- const timeout = setTimeout(
94390
- () => finish(
94391
- () => reject(
94392
- new ExpectedCliError(
94393
- "enrollment approval timed out after 5 minutes, run the same command again to retry"
94394
- )
94395
- )
94396
- ),
94397
- timeoutMs
94398
- );
92620
+ let timeout;
92621
+ const settled = new AbortController();
92622
+ const startWaiting = () => {
92623
+ if (settled.signal.aborted) return;
92624
+ if (!redeeming) {
92625
+ timeout = setTimeout(
92626
+ () => finish(
92627
+ () => reject(
92628
+ new ExpectedCliError(
92629
+ "enrollment approval timed out after 5 minutes, run the same command again to retry"
92630
+ )
92631
+ )
92632
+ ),
92633
+ timeoutMs
92634
+ );
92635
+ }
92636
+ onWaiting?.();
92637
+ };
92638
+ const presentPage = async () => {
92639
+ if (confirmOpen === void 0) {
92640
+ log3(`Opening approval page\u2026 ${approvalUrl}`);
92641
+ open3(approvalUrl);
92642
+ return;
92643
+ }
92644
+ if (await confirmOpen(approvalUrl, settled.signal)) open3(approvalUrl);
92645
+ };
94399
92646
  const finish = (settle2) => {
94400
92647
  clearTimeout(timeout);
92648
+ settled.abort();
94401
92649
  server.close();
94402
92650
  server.closeAllConnections();
94403
92651
  settle2();
@@ -94406,8 +92654,10 @@ function waitForApproval(approvalUrl, state, options) {
94406
92654
  server.listen(port, "127.0.0.1", () => {
94407
92655
  const address = server.address();
94408
92656
  if (onListening && address !== null && typeof address === "object") onListening(address.port);
94409
- log3(`Opening approval page\u2026 ${approvalUrl}`);
94410
- open3(approvalUrl);
92657
+ presentPage().then(
92658
+ startWaiting,
92659
+ (cause) => finish(() => reject(cause instanceof Error ? cause : new Error(String(cause))))
92660
+ );
94411
92661
  });
94412
92662
  });
94413
92663
  }
@@ -96229,68 +94479,6 @@ function readIfExists2(p) {
96229
94479
  }
96230
94480
  }
96231
94481
 
96232
- // ../../apps/syncservice/src/previewRegistration.ts
96233
- import { setImmediate as yieldToEventLoop4 } from "node:timers/promises";
96234
- async function registerAnnouncedPreviews(apiUrl, machineToken, collected, memo2, deps = {}) {
96235
- const readTranscript = deps.readTranscript ?? readIfExists;
96236
- const upload = deps.upload ?? uploadPreviewRegistration;
96237
- const summary = {
96238
- registered: 0,
96239
- foreignOwned: [],
96240
- previewsOff: [],
96241
- failed: []
96242
- };
96243
- for (const session of collected) {
96244
- if (session.item.status !== "active") continue;
96245
- const key = sessionKey(session.item);
96246
- const state = memo2.get(key);
96247
- if (state?.foreignOwner || state?.previewsOff) continue;
96248
- if (state?.examinedMtimeMs === session.mtimeMs) continue;
96249
- await yieldToEventLoop4();
96250
- try {
96251
- const text = readTranscript(session.transcriptPath);
96252
- if (text === null) continue;
96253
- const legacyIdentity = legacySessionSourceFromHarness(session.item.harness);
96254
- if (legacyIdentity.kind === "unsupported") {
96255
- throw new Error(`Transcript parsing does not support ${session.item.harness}`);
96256
- }
96257
- const previews = announcedPreviewsFromTurns(parseSessionTurns(legacyIdentity.source, text)).filter(
96258
- (preview) => preview.url.length <= MAX_PREVIEW_URL_LENGTH && redactText(preview.url) === preview.url
96259
- ).slice(-MAX_REGISTERED_PREVIEWS).map((preview) => ({
96260
- ...preview,
96261
- label: redactText(preview.label).slice(0, MAX_PREVIEW_LABEL_LENGTH)
96262
- }));
96263
- const registeredJson = JSON.stringify(previews);
96264
- if (previews.length === 0 || state?.registeredJson === registeredJson) {
96265
- memo2.set(key, { ...state, examinedMtimeMs: session.mtimeMs });
96266
- continue;
96267
- }
96268
- const outcome = await upload(apiUrl, machineToken, {
96269
- harness: session.item.harness,
96270
- harnessSessionId: session.item.harnessSessionId,
96271
- previews
96272
- });
96273
- if (outcome === "foreign-owner") {
96274
- memo2.set(key, { examinedMtimeMs: session.mtimeMs, foreignOwner: true });
96275
- summary.foreignOwned.push(session.item.harnessSessionId);
96276
- continue;
96277
- }
96278
- if (outcome === "previews-off") {
96279
- memo2.set(key, { examinedMtimeMs: session.mtimeMs, previewsOff: true });
96280
- summary.previewsOff.push(session.item.harnessSessionId);
96281
- continue;
96282
- }
96283
- memo2.set(key, { examinedMtimeMs: session.mtimeMs, registeredJson });
96284
- summary.registered += 1;
96285
- } catch (error63) {
96286
- summary.failed.push(
96287
- `${session.item.harnessSessionId}: ${error63 instanceof Error ? error63.message : String(error63)}`
96288
- );
96289
- }
96290
- }
96291
- return summary;
96292
- }
96293
-
96294
94482
  // ../../apps/syncservice/src/sync.ts
96295
94483
  var RecordTurns = class {
96296
94484
  last = Promise.resolve();
@@ -96578,26 +94766,6 @@ async function runSyncPassInternal(config2, options, diagnostic, turn) {
96578
94766
  );
96579
94767
  }
96580
94768
  if (options.isNewSession) return { sessions: collected, upserted };
96581
- diagnostic.stage = "previews";
96582
- const registerPreviews = options.registerPreviews ?? registerAnnouncedPreviews;
96583
- const previewSummary = await registerPreviews(
96584
- credentials.apiUrl,
96585
- credentials.token,
96586
- writable,
96587
- options.previewRegistrations ?? /* @__PURE__ */ new Map()
96588
- );
96589
- if (previewSummary.registered > 0) {
96590
- log3(`Previews: ${previewSummary.registered} registration(s) updated.`);
96591
- }
96592
- for (const externalId of previewSummary.foreignOwned) {
96593
- log3(
96594
- `Previews for ${externalId} are registered by another machine, leaving its list in place.`
96595
- );
96596
- }
96597
- for (const externalId of previewSummary.previewsOff) {
96598
- log3(`Previews for ${externalId} refused, this organization has previews switched off.`);
96599
- }
96600
- for (const failure2 of previewSummary.failed) log3(` preview registration failed, ${failure2}`);
96601
94769
  try {
96602
94770
  const observe = options.observeBranch ? options.observeBranch() : branchObserver({ allowedProtectedRoots: credentials.repoDiscoveryRoots ?? [] });
96603
94771
  const facts = branchFactsOf(writable, observe);
@@ -97703,7 +95871,6 @@ function startWatch(config2, homeDir, runtime = { version: "checkout" }) {
97703
95871
  onChecked: () => menu?.changed()
97704
95872
  });
97705
95873
  const rawShipped = /* @__PURE__ */ new Map();
97706
- const previewRegistrations = /* @__PURE__ */ new Map();
97707
95874
  const codexThreadLinks = new CodexThreadLinks();
97708
95875
  const codexThreadReads = new CodexThreadReads();
97709
95876
  const recordTurns = new RecordTurns();
@@ -97715,7 +95882,6 @@ function startWatch(config2, homeDir, runtime = { version: "checkout" }) {
97715
95882
  let lastCatchupReportAt = -Infinity;
97716
95883
  const shared = {
97717
95884
  rawShipped,
97718
- previewRegistrations,
97719
95885
  codexThreadLinks,
97720
95886
  codexThreadReads,
97721
95887
  lifecycleJournal: journal,
@@ -98506,7 +96672,7 @@ import { accessSync, constants as constants4, readFileSync as readFileSync22 } f
98506
96672
  import path42 from "node:path";
98507
96673
 
98508
96674
  // src/version.ts
98509
- var CLI_VERSION = true ? "0.4.25" : "0.0.0-checkout";
96675
+ var CLI_VERSION = true ? "0.4.27" : "0.0.0-checkout";
98510
96676
  var CLI_RELEASE_BUILD = true ? true : false;
98511
96677
  var CLI_PACKAGE_NAME = "@usepowerplant/cli";
98512
96678
 
@@ -99705,7 +97871,7 @@ function cursorAppVersion(applicationsDirs, seams) {
99705
97871
  }
99706
97872
  return newest?.text ?? null;
99707
97873
  }
99708
- function runConnect(clients, deps) {
97874
+ async function runConnect(clients, deps) {
99709
97875
  const agents = groupByAgent(clients);
99710
97876
  const outcome = {
99711
97877
  found: agents.size,
@@ -99721,9 +97887,10 @@ function runConnect(clients, deps) {
99721
97887
  return outcome;
99722
97888
  }
99723
97889
  for (const [agent, candidates] of agents) {
99724
- const results = [...groupByConnectionTarget(candidates).values()].map(
99725
- (targetCandidates) => connectTarget(agent, targetCandidates, clients, deps)
99726
- );
97890
+ const results = [];
97891
+ for (const targetCandidates of groupByConnectionTarget(candidates).values()) {
97892
+ results.push(await connectTarget(agent, targetCandidates, clients, deps));
97893
+ }
99727
97894
  const result = aggregateConnectionTargets(results);
99728
97895
  outcome[result.state] += 1;
99729
97896
  if (result.unchanged) outcome.unchanged += 1;
@@ -99753,7 +97920,7 @@ function aggregateConnectionTargets(results) {
99753
97920
  const state = results.some((result) => result.state === "failed") ? "failed" : results.some((result) => result.state === "pending") ? "pending" : results.some((result) => result.state === "configured") ? "configured" : "connected";
99754
97921
  return { state, unchanged: results.every((result) => result.unchanged) };
99755
97922
  }
99756
- function connectTarget(agent, candidates, all, deps) {
97923
+ async function connectTarget(agent, candidates, all, deps) {
99757
97924
  let last = failed("no installation to try");
99758
97925
  for (const [index, candidate] of candidates.entries()) {
99759
97926
  const name = displayName(candidate, all);
@@ -99762,7 +97929,7 @@ function connectTarget(agent, candidates, all, deps) {
99762
97929
  const tooOld = refusal === null ? belowVersionFloor(candidate.client, deps.agentVersion(candidate)) : null;
99763
97930
  last = refusal !== null ? failed(refusal) : tooOld !== null ? failed(
99764
97931
  `version ${tooOld.version} is older than ${tooOld.floor}, the oldest ${AGENT_DISPLAY_NAMES[agent]} Powerplant supports. Update it, then re-run ${deps.connectCommand}.`
99765
- ) : connectCandidate(candidate, name, deps);
97932
+ ) : await connectCandidate(candidate, name, deps);
99766
97933
  } catch (error63) {
99767
97934
  last = failed(error63 instanceof Error ? error63.message : String(error63));
99768
97935
  }
@@ -99908,7 +98075,7 @@ function claudeAddArgs(deps) {
99908
98075
  function claudeEnv(client) {
99909
98076
  return { CLAUDE_CONFIG_DIR: client.configDir };
99910
98077
  }
99911
- function connectClaude(client, name, deps) {
98078
+ async function connectClaude(client, name, deps) {
99912
98079
  const { bin } = client;
99913
98080
  const env = claudeEnv(client);
99914
98081
  const probe = parseClaudeProbe(deps.run(bin, ["mcp", "get", deps.serverName], env));
@@ -100109,7 +98276,7 @@ function connectInCodexHome(install, deps) {
100109
98276
  runInteractive: (bin, args, overrides) => deps.runInteractive(bin, args, env(overrides))
100110
98277
  };
100111
98278
  }
100112
- function connectCodex(install, name, unscoped) {
98279
+ async function connectCodex(install, name, unscoped) {
100113
98280
  const { bin } = install;
100114
98281
  const deps = connectInCodexHome(install, unscoped);
100115
98282
  healOrphanCodexOauthTable(name, deps);
@@ -100124,7 +98291,7 @@ function connectCodex(install, name, unscoped) {
100124
98291
  if (wrongUrl) deps.log(`${name} was registered against ${registeredUrl}, re-registering for ${deps.mcpUrl}.`);
100125
98292
  if (codexAddLogsIn(bin, deps)) {
100126
98293
  ensureCodexCallbackPort(name, deps);
100127
- const outcome = login(bin, name, codexAddArgs(deps, { withOfficialClientId: true }), deps);
98294
+ const outcome = await login(bin, name, codexAddArgs(deps, { withOfficialClientId: true }), deps);
100128
98295
  if (outcome.state === "connected") ensureCodexOfficialClient(name, deps);
100129
98296
  return outcome;
100130
98297
  }
@@ -100171,7 +98338,7 @@ function ensureCodexOfficialClient(name, deps) {
100171
98338
  )
100172
98339
  );
100173
98340
  }
100174
- function connectCursor(mcpJsonPath, name, deps) {
98341
+ async function connectCursor(mcpJsonPath, name, deps) {
100175
98342
  const official = deps.officialClients?.cursor;
100176
98343
  const patch = patchCursorMcpJson(
100177
98344
  deps.readTextFile(mcpJsonPath),
@@ -100185,6 +98352,7 @@ function connectCursor(mcpJsonPath, name, deps) {
100185
98352
  );
100186
98353
  }
100187
98354
  if (patch.changed) deps.writeTextFile(mcpJsonPath, patch.content);
98355
+ await deps.pressEnter?.("open Cursor");
100188
98356
  if (deps.openUrl(cursorInstallDeeplink(deps.serverName, patch.entry))) {
100189
98357
  deps.log(`\u2192 ${name}: approve inside Cursor when it asks`);
100190
98358
  return { state: "configured", unchanged: !patch.changed };
@@ -100194,8 +98362,9 @@ function connectCursor(mcpJsonPath, name, deps) {
100194
98362
  );
100195
98363
  return { state: "pending", unchanged: false };
100196
98364
  }
100197
- function login(bin, name, args, deps, env) {
100198
- deps.log(`\u2192 ${name}: approve in your browser\u2026`);
98365
+ async function login(bin, name, args, deps, env) {
98366
+ if (deps.pressEnter) await deps.pressEnter(`sign in to ${name} in your browser`);
98367
+ else deps.log(`\u2192 ${name}: approve in your browser\u2026`);
100199
98368
  const status = deps.runInteractive(bin, args, env);
100200
98369
  if (status === 0) {
100201
98370
  deps.log(`\u2713 ${name}: MCP connected`);
@@ -101365,6 +99534,14 @@ function initExitCode(summary) {
101365
99534
  function enrolledLine(credentials) {
101366
99535
  return `\u2713 ${credentials.machineName} enrolled${credentials.orgName ? ` in ${credentials.orgName}` : ""}`;
101367
99536
  }
99537
+ async function waitForEnrollment(output2, enroll2) {
99538
+ let startSpinner = () => {
99539
+ };
99540
+ const waiting = new Promise((resolve2) => startSpinner = resolve2);
99541
+ const enrolling = enroll2(startSpinner);
99542
+ await Promise.race([waiting, enrolling]);
99543
+ return output2.activity("Waiting for approval in your browser\u2026", () => enrolling);
99544
+ }
101368
99545
  async function runInit(deps) {
101369
99546
  if (deps.setupRefusal !== null) throw new ExpectedCliError(deps.setupRefusal);
101370
99547
  const { command, stage } = deps.terminal;
@@ -101381,7 +99558,7 @@ async function runInit(deps) {
101381
99558
  );
101382
99559
  credentials = existing;
101383
99560
  } else {
101384
- credentials = await stage.activity("Waiting for approval in your browser\u2026", deps.enroll);
99561
+ credentials = await waitForEnrollment(stage, deps.enroll);
101385
99562
  stage.log(enrolledLine(credentials));
101386
99563
  enrolled = true;
101387
99564
  }
@@ -101583,6 +99760,25 @@ function logProtectedSessionsStayLocal(stage, found) {
101583
99760
  );
101584
99761
  stage.detail("Sessions outside folders you explicitly added will stay local.");
101585
99762
  }
99763
+ function realPressEnter(question, signal) {
99764
+ return new Promise((resolve2) => {
99765
+ const prompt = createInterface2({ input: process.stdin, output: process.stdout });
99766
+ let interrupted = false;
99767
+ prompt.once("SIGINT", () => {
99768
+ interrupted = true;
99769
+ prompt.close();
99770
+ process.stdout.write("\n");
99771
+ process.kill(process.pid, "SIGINT");
99772
+ });
99773
+ prompt.question(question, signal ? { signal } : {}).then(
99774
+ () => resolve2(true),
99775
+ () => {
99776
+ if (interrupted) return;
99777
+ resolve2(!(signal?.aborted ?? false));
99778
+ }
99779
+ ).finally(() => prompt.close());
99780
+ });
99781
+ }
101586
99782
  async function realPromptLine(question) {
101587
99783
  const prompt = createInterface2({ input: process.stdin, output: process.stdout });
101588
99784
  try {
@@ -101986,7 +100182,6 @@ function createTerminalOutput(options) {
101986
100182
  let activityLabel = null;
101987
100183
  let activityIndent = "";
101988
100184
  let frameIndex = 0;
101989
- let timer = null;
101990
100185
  const renderActivity = () => {
101991
100186
  if (activityLabel === null) return;
101992
100187
  const frame = SPINNER_FRAMES[frameIndex % SPINNER_FRAMES.length];
@@ -102004,25 +100199,31 @@ function createTerminalOutput(options) {
102004
100199
  `);
102005
100200
  if (rerender) renderActivity();
102006
100201
  };
102007
- const activity = async (place, label2, work) => {
100202
+ const startActivity = (place, label2) => {
102008
100203
  const indent = " ".repeat(COLUMNS[place.level].line);
102009
100204
  if (!interactive) {
102010
100205
  log3(`${indent}\u2026 ${label2}`, place);
102011
- return await work();
100206
+ return () => {
100207
+ };
102012
100208
  }
102013
100209
  activityLabel = label2;
102014
100210
  activityIndent = indent;
102015
100211
  frameIndex = 0;
102016
100212
  renderActivity();
102017
- timer = setInterval(renderActivity, 80);
100213
+ const timer = setInterval(renderActivity, 80);
102018
100214
  timer.unref();
100215
+ return () => {
100216
+ clearInterval(timer);
100217
+ clearActivity();
100218
+ activityLabel = null;
100219
+ };
100220
+ };
100221
+ const activity = async (place, label2, work) => {
100222
+ const stop = startActivity(place, label2);
102019
100223
  try {
102020
100224
  return await work();
102021
100225
  } finally {
102022
- if (timer !== null) clearInterval(timer);
102023
- timer = null;
102024
- clearActivity();
102025
- activityLabel = null;
100226
+ stop();
102026
100227
  }
102027
100228
  };
102028
100229
  const writer = (level) => {
@@ -102036,7 +100237,9 @@ function createTerminalOutput(options) {
102036
100237
  // A blank line separates stages; it carries no indentation.
102037
100238
  log: (text) => log3(text === "" ? "" : `${indent}${text}`, line),
102038
100239
  detail: (text) => log3(`${detailIndent}${text}`, detail),
102039
- activity: (label2, work) => activity(line, label2, work)
100240
+ activity: (label2, work) => activity(line, label2, work),
100241
+ startActivity: (label2) => startActivity(line, label2),
100242
+ pressEnterPrompt: (action) => color ? `${indent}${ANSI.bold}Press Enter${ANSI.resetDim} to ${styleUrls(action)}\u2026 ` : `${indent}Press Enter to ${action}\u2026 `
102040
100243
  };
102041
100244
  };
102042
100245
  return { command: writer("command"), stage: writer("stage") };
@@ -102124,7 +100327,8 @@ async function runWindowsUpdate(run2) {
102124
100327
  await handOff(newCopy);
102125
100328
  },
102126
100329
  pointServiceAt: run2.pointServiceAt,
102127
- log: run2.log
100330
+ log: run2.log,
100331
+ waiting: run2.waiting
102128
100332
  });
102129
100333
  try {
102130
100334
  write("up-to-date", installed.version, { finishedAt: new Date(run2.now()).toISOString() });
@@ -102310,7 +100514,7 @@ async function runInstallRelease(appEnv, options, env = process.env, isProcessAl
102310
100514
  setupRefusal: () => setupRefusal(retry)
102311
100515
  });
102312
100516
  if (!ownersLock && lock === null) {
102313
- if (askService !== void 0) return askService({ file: path50.resolve(tarball), sha256: sha2562 });
100517
+ if (askService !== void 0) return { line: `\u2713 ${(await askService({ file: path50.resolve(tarball), sha256: sha2562 })).replace(/\.$/, "")}`, details: [] };
102314
100518
  throw new ExpectedCliError("Another Powerplant install or update is running on this computer. Run the installer again after it finishes.");
102315
100519
  }
102316
100520
  const service = options.update === true ? hostBackgroundService(appEnv) : null;
@@ -102333,19 +100537,19 @@ async function runInstallRelease(appEnv, options, env = process.env, isProcessAl
102333
100537
  healthCheck: (command, version2) => checkNewVersionStarts(command, version2, { appEnv }),
102334
100538
  pointServiceAt: (command) => service?.pointAt?.({ appEnv, command })
102335
100539
  },
102336
- log: console.log
100540
+ log: console.log,
100541
+ waiting: options.waiting
102337
100542
  });
102338
- const current = installed.currentError === void 0 ? "" : `
102339
- The current folder could not be pointed at it (${installed.currentError}). Run the installer again.`;
102340
- if (typeof installed.path === "object") {
102341
- return `Installed Powerplant ${installed.version}.${current}
102342
- ${installed.path.failed} To run Powerplant, use "${installed.command[0]}".`;
102343
- }
102344
- return `Installed Powerplant ${installed.version}.${current}`;
100543
+ return installedResult(installed, windowsInstallCommand(appEnv));
102345
100544
  } finally {
102346
100545
  lock?.release();
102347
100546
  }
102348
100547
  }
100548
+ function installedResult(installed, installCommand) {
100549
+ const pathFailed = typeof installed.path === "object" ? installed.path.failed : null;
100550
+ const details = installed.currentError !== void 0 ? [`The current folder could not be pointed at it (${installed.currentError}). Run \`${installCommand}\` again.`, ...pathFailed === null ? [] : [pathFailed]] : pathFailed === null ? [] : [`${pathFailed} To run Powerplant, use \`& "${installed.command[0]}"\`.`];
100551
+ return { line: `${details.length === 0 ? "\u2713" : "!"} Installed Powerplant ${installed.version}`, details };
100552
+ }
102349
100553
  function processIsAlive(pid) {
102350
100554
  try {
102351
100555
  process.kill(pid, 0);
@@ -102436,7 +100640,8 @@ async function installPerUserCopy(deps, fetched) {
102436
100640
  run: (program, args) => deps.runNewCopy(program, args, deps.log),
102437
100641
  args: ["--env", deps.appEnv]
102438
100642
  }),
102439
- log: deps.log
100643
+ log: deps.log,
100644
+ waiting: deps.waiting
102440
100645
  });
102441
100646
  if (installed.currentError !== void 0) {
102442
100647
  deps.log(`! The current folder could not be pointed at Powerplant ${installed.version} (${installed.currentError}). Hooks and PATH use it, so fix it and run \`${deps.retryCommand}\` again.`);
@@ -103134,14 +101339,6 @@ ${USAGE}`);
103134
101339
  }
103135
101340
  }
103136
101341
  const withEnv = (cmd) => config2.appEnv === "production" ? cmd : `${cmd} --env ${config2.appEnv}`;
103137
- const enroll2 = (log3) => runEnrollment(config2, {
103138
- name: values.name,
103139
- email: values.email,
103140
- password: values.password,
103141
- scope: values.scope,
103142
- enrollCommand: withEnv("powerplant enroll"),
103143
- log: log3
103144
- });
103145
101342
  const connectCommand = withEnv("powerplant connect");
103146
101343
  const disconnectCommand = withEnv("powerplant disconnect");
103147
101344
  const clientFilter = parseClientFilter(values.client);
@@ -103150,6 +101347,19 @@ ${USAGE}`);
103150
101347
  stdinIsTty: process.stdin.isTTY === true,
103151
101348
  stdoutIsTty: process.stdout.isTTY === true
103152
101349
  });
101350
+ const pressEnter = (output2, action, signal) => pickerOn ? realPressEnter(output2.pressEnterPrompt(action), signal) : Promise.resolve(true);
101351
+ const enroll2 = (output2, onWaiting) => runEnrollment(config2, {
101352
+ name: values.name,
101353
+ email: values.email,
101354
+ password: values.password,
101355
+ scope: values.scope,
101356
+ enrollCommand: withEnv("powerplant enroll"),
101357
+ log: output2.detail,
101358
+ ...pickerOn && {
101359
+ confirmOpen: (url2, signal) => pressEnter(output2, `open ${url2} in your browser`, signal)
101360
+ },
101361
+ onWaiting
101362
+ });
103153
101363
  const pause = realPauseDeps(config2.appEnv, withEnv("powerplant resume"), realPromptLine);
103154
101364
  const terminalEffects = terminalUsesEffects(process.stdout.isTTY === true, process.env);
103155
101365
  const terminal = createTerminalOutput({
@@ -103233,6 +101443,7 @@ ${USAGE}`);
103233
101443
  url2,
103234
101444
  (reason) => log3(`! Cursor: could not open Cursor (${reason}), enable the ${mcpServerNameFor(config2.appEnv)} server in Cursor's MCP settings and sign in`)
103235
101445
  ),
101446
+ pressEnter: pickerOn ? (action) => pressEnter(output2, action) : null,
103236
101447
  codexConfigPath: codexConfigPath({}),
103237
101448
  verifySignature: verifyBundleSignatureSync
103238
101449
  }),
@@ -103243,7 +101454,7 @@ ${USAGE}`);
103243
101454
  case "init": {
103244
101455
  const setupRefusal = hostBackgroundService(config2.appEnv)?.setupRefusal?.("init") ?? null;
103245
101456
  if (isNpmCopyOnWindows(process.platform, entryPath())) {
103246
- const code = await initFromNpmCopy({ ...npmInitDeps(config2), args: process.argv.slice(2), entryPath: entryPath(), setupRefusal });
101457
+ const code = await initFromNpmCopy({ ...npmInitDeps(config2, terminal.command), args: process.argv.slice(2), entryPath: entryPath(), setupRefusal });
103247
101458
  if (code !== null) {
103248
101459
  process.exitCode = code;
103249
101460
  return;
@@ -103255,7 +101466,7 @@ ${USAGE}`);
103255
101466
  // Enrollment's own lines (approval URL, token location) are detail
103256
101467
  // lines under stage 1's spinner; init prints the result line, and
103257
101468
  // stage 2 states the capture boundary.
103258
- enroll: () => enroll2(terminal.stage.detail),
101469
+ enroll: (onWaiting) => enroll2(terminal.stage, onWaiting),
103259
101470
  // Discovery may read a worktree pointer under a root the store
103260
101471
  // already allows, so a revoked checkout root still surfaces.
103261
101472
  findProtectedSessions: () => findRecentProtectedSessions({
@@ -103336,9 +101547,9 @@ The access you granted these agents stays on your Powerplant account until you r
103336
101547
  return;
103337
101548
  }
103338
101549
  case "enroll": {
103339
- const credentials = await terminal.command.activity(
103340
- "Waiting for approval in your browser\u2026",
103341
- () => enroll2(terminal.command.detail)
101550
+ const credentials = await waitForEnrollment(
101551
+ terminal.command,
101552
+ (onWaiting) => enroll2(terminal.command, onWaiting)
103342
101553
  );
103343
101554
  terminal.command.log(enrolledLine(credentials));
103344
101555
  terminal.command.detail(`Syncing: ${describeStoredCapture(credentials)}`);
@@ -103494,13 +101705,13 @@ The access you granted these agents stays on your Powerplant account until you r
103494
101705
  }
103495
101706
  const windowsInstall = thisWindowsInstall(config2);
103496
101707
  if (windowsInstall !== null) {
103497
- await updateWindowsInstall(config2, windowsInstall, values.background === true, tarballOption(values.tarball, values.sha256));
101708
+ await updateWindowsInstall(config2, terminal.command, windowsInstall, values.background === true, tarballOption(values.tarball, values.sha256));
103498
101709
  return;
103499
101710
  }
103500
101711
  if (values.tarball !== void 0) throw new ExpectedCliError("--tarball updates a per-user Windows install only.");
103501
101712
  if (isNpmCopyOnWindows(process.platform, entryPath()) && values.background !== true) {
103502
101713
  await updateFromNpmCopy({
103503
- ...npmInitDeps(config2),
101714
+ ...npmInitDeps(config2, terminal.command),
103504
101715
  retryCommand: withEnv("powerplant update"),
103505
101716
  setupRefusal: hostBackgroundService(config2.appEnv)?.setupRefusal?.("update") ?? null,
103506
101717
  cliVersion: CLI_VERSION,
@@ -103554,15 +101765,15 @@ The access you granted these agents stays on your Powerplant account until you r
103554
101765
  if (process.platform !== "win32") {
103555
101766
  throw new ExpectedCliError("powerplant install-release installs the Windows release of Powerplant, so it runs only on Windows.");
103556
101767
  }
103557
- console.log(
103558
- await runInstallRelease(
103559
- config2.appEnv,
103560
- { tarball: values.tarball, sha256: values.sha256, update: values.update },
103561
- process.env,
103562
- processIsAlive2,
103563
- (tarball) => updateThroughService(serviceUpdateDeps(config2, tarball), true).then((line) => line ?? "")
103564
- )
101768
+ const installed = await runInstallRelease(
101769
+ config2.appEnv,
101770
+ { tarball: values.tarball, sha256: values.sha256, update: values.update, waiting: (label2) => terminal.command.startActivity(label2) },
101771
+ process.env,
101772
+ processIsAlive2,
101773
+ (tarball) => updateThroughService(serviceUpdateDeps(config2, tarball), true).then((line) => line ?? "")
103565
101774
  );
101775
+ terminal.command.log(installed.line);
101776
+ for (const detail of installed.details) terminal.command.detail(detail);
103566
101777
  return;
103567
101778
  }
103568
101779
  case "restart": {
@@ -103739,13 +101950,13 @@ function watchCommand(config2) {
103739
101950
  function thisWindowsInstall(config2) {
103740
101951
  return windowsInstallOwning(readInstallRecord(installRecordPath(config2.appEnv)), process.execPath);
103741
101952
  }
103742
- function npmInitDeps(config2) {
101953
+ function npmInitDeps(config2, terminal) {
103743
101954
  const localAppData = process.env.LOCALAPPDATA;
103744
101955
  if (localAppData === void 0 || localAppData === "") {
103745
101956
  throw new ExpectedCliError("LOCALAPPDATA is not set, so Powerplant cannot find your program folder.");
103746
101957
  }
103747
101958
  return {
103748
- ...windowsUpdateContext(config2, "terminal"),
101959
+ ...windowsUpdateContext(config2, terminal),
103749
101960
  location: windowsInstallFolder(config2.appEnv, localAppData),
103750
101961
  lockFile: installLockPath(config2.appEnv),
103751
101962
  // Only production goes on PATH, so a typed `powerplant` is always production.
@@ -103754,7 +101965,7 @@ function npmInitDeps(config2) {
103754
101965
  retryCommand: ["powerplant init", ...envArgsFor(config2)].join(" ")
103755
101966
  };
103756
101967
  }
103757
- function windowsUpdateContext(config2, newCopyOutput) {
101968
+ function windowsUpdateContext(config2, output2) {
103758
101969
  return {
103759
101970
  appEnv: config2.appEnv,
103760
101971
  apiUrl: config2.apiUrl,
@@ -103763,7 +101974,8 @@ function windowsUpdateContext(config2, newCopyOutput) {
103763
101974
  tar: path54.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe"),
103764
101975
  signedByPowerplant: (file2) => verifyBundleSignatureSync(file2, POWERPLANT_SIGNER),
103765
101976
  reportedVersion: programVersion,
103766
- runNewCopy: startNewCopy(newCopyOutput),
101977
+ runNewCopy: startNewCopy(output2 === "log" ? "log" : "terminal"),
101978
+ waiting: output2 === "log" ? void 0 : (label2) => output2.startActivity(label2),
103767
101979
  progress: updateProgress,
103768
101980
  now: Date.now,
103769
101981
  pid: process.pid
@@ -103799,7 +102011,7 @@ function tarballOption(tarball, sha2562) {
103799
102011
  }
103800
102012
  return { file: path54.resolve(tarball), sha256: sha2562 };
103801
102013
  }
103802
- async function updateWindowsInstall(config2, install, background, tarball) {
102014
+ async function updateWindowsInstall(config2, terminal, install, background, tarball) {
103803
102015
  const lock = lockInstallForChange(changeLockDeps(config2, install.location));
103804
102016
  if (lock === null) {
103805
102017
  if (!background) console.log("Background sync is installing the update\u2026");
@@ -103814,7 +102026,7 @@ async function updateWindowsInstall(config2, install, background, tarball) {
103814
102026
  }
103815
102027
  try {
103816
102028
  await runWindowsUpdate({
103817
- ...windowsUpdateContext(config2, "terminal"),
102029
+ ...windowsUpdateContext(config2, terminal),
103818
102030
  record: install,
103819
102031
  target: null,
103820
102032
  tarball,
@@ -104001,4 +102213,4 @@ undici/lib/web/websocket/frame.js:
104001
102213
  (*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *)
104002
102214
  */
104003
102215
 
104004
- //# debugId=d8a10efc-d51d-5eaf-94f5-f1daf8755a2a
102216
+ //# debugId=c205f968-8b28-5dc5-9420-5b3fae8d2c6f