@ascenda-one/agent-mcp 0.1.41 → 0.1.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -182,12 +182,27 @@ var require_gitActionClassifier = __commonJS({
182
182
  }
183
183
  if (i >= words.length)
184
184
  return void 0;
185
- return { verb: words[i], args: words.slice(i + 1) };
185
+ return { verb: words[i], args: withoutRedirects(words.slice(i + 1)) };
186
+ }
187
+ function withoutRedirects(words) {
188
+ const kept = [];
189
+ for (let i = 0; i < words.length; i++) {
190
+ const redirect = /^\d*(>>?|<)(.*)$/.exec(words[i]);
191
+ if (!redirect) {
192
+ kept.push(words[i]);
193
+ } else if (redirect[2] === "") {
194
+ i += 1;
195
+ }
196
+ }
197
+ return kept;
198
+ }
199
+ function isHeadRef(ref) {
200
+ return /^(head([~^@]|$)|@([~^]|$))/.test(ref);
186
201
  }
187
202
  function discardsWork({ verb, args }) {
188
203
  switch (verb) {
189
204
  case "restore":
190
- return !args.includes("--staged");
205
+ return restoreDiscards(args);
191
206
  case "switch":
192
207
  return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
193
208
  case "clean": {
@@ -201,18 +216,43 @@ var require_gitActionClassifier = __commonJS({
201
216
  return false;
202
217
  }
203
218
  }
219
+ function restoreDiscards(args) {
220
+ if (args.includes("--staged"))
221
+ return false;
222
+ if (args.includes("--ours") || args.includes("--theirs"))
223
+ return false;
224
+ const source = optionValue(args, "--source", "-s");
225
+ return source === void 0 || isHeadRef(source);
226
+ }
227
+ function optionValue(args, long, short) {
228
+ for (let i = 0; i < args.length; i++) {
229
+ if (args[i].startsWith(`${long}=`))
230
+ return args[i].slice(long.length + 1);
231
+ if (args[i] === long || args[i] === short)
232
+ return args[i + 1];
233
+ }
234
+ return void 0;
235
+ }
204
236
  function checkoutDiscards(args) {
205
- if (args.includes("--"))
206
- return true;
237
+ if (args.includes("--ours") || args.includes("--theirs"))
238
+ return false;
239
+ const separator = args.indexOf("--");
240
+ if (separator !== -1) {
241
+ const source = args.slice(0, separator).find((a) => !a.startsWith("-"));
242
+ return source === void 0 || isHeadRef(source);
243
+ }
207
244
  if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
208
245
  return false;
209
246
  const words = args.filter((a) => !a.startsWith("-"));
210
247
  if (words.length >= 2)
211
- return true;
248
+ return isHeadRef(words[0]) || looksLikePath(words[0]);
212
249
  if (words.length === 1)
213
- return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
250
+ return looksLikePath(words[0]);
214
251
  return false;
215
252
  }
253
+ function looksLikePath(word) {
254
+ return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(word);
255
+ }
216
256
  }
217
257
  });
218
258
 
@@ -313,7 +353,13 @@ var require_modelClassifier = __commonJS({
313
353
  "../packages/tool-kit/out/modelClassifier.js"(exports) {
314
354
  "use strict";
315
355
  Object.defineProperty(exports, "__esModule", { value: true });
356
+ exports.PREMIUM_MODEL_CLASSES = void 0;
357
+ exports.isPremiumModelClass = isPremiumModelClass;
316
358
  exports.classifyModelClass = classifyModelClass;
359
+ exports.PREMIUM_MODEL_CLASSES = /* @__PURE__ */ new Set(["anthropic:opus", "anthropic:fable"]);
360
+ function isPremiumModelClass(modelClass) {
361
+ return modelClass !== void 0 && exports.PREMIUM_MODEL_CLASSES.has(modelClass);
362
+ }
317
363
  function classifyModelClass(raw) {
318
364
  const candidate = raw;
319
365
  if (candidate === void 0 || candidate === null)
@@ -325,6 +371,8 @@ var require_modelClassifier = __commonJS({
325
371
  return void 0;
326
372
  if (ROUTER_SENTINEL.test(value))
327
373
  return "router:auto";
374
+ if (LOCAL_RUNTIME.test(value))
375
+ return "local:on_device";
328
376
  const vendor = readModelVendor(value);
329
377
  if (vendor === void 0)
330
378
  return "unknown";
@@ -342,14 +390,22 @@ var require_modelClassifier = __commonJS({
342
390
  return void 0;
343
391
  }
344
392
  var ROUTER_SENTINEL = /^(?:[a-z0-9][a-z0-9._-]*\/)?(?:auto|default)$/;
393
+ var LOCAL_RUNTIME = /\b(ollama|llamacpp|llama\.cpp|lmstudio|lm-studio|on[-_]?device)\b/;
345
394
  var VENDOR_PATTERNS = [
346
395
  [/\b(anthropic|claude|opus|sonnet|haiku|fable)\b/, "anthropic"],
347
396
  [/\b(openai|gpt|o[1-9])\b/, "openai"],
348
- [/\b(google|gemini|vertex)\b/, "google"],
397
+ [/\b(google|gemini)\b/, "google"],
349
398
  // xAI carries no corporate prefix in any observed id — the family name is
350
399
  // the whole marker, exactly as `claude` and `gemini` are for theirs.
351
400
  [/\b(xai|grok)\b/, "xai"],
352
- [/\b(ollama|llamacpp|on[-_]?device|local)\b/, "local"]
401
+ [/\bdeepseek(?:-ai)?(?![a-z])/, "deepseek"],
402
+ [/\b(moonshot(?:ai)?|kimi)(?![a-z])/, "moonshot"],
403
+ [/\b(zhipu(?:ai)?|z-ai|zai-org|chatglm|glm)(?![a-z])/, "zhipu"],
404
+ [/\bminimax(?:ai)?(?![a-z])/, "minimax"],
405
+ [/\b(alibaba|qwen|qwq)(?![a-z])/, "alibaba"],
406
+ [/\b(mistral(?:ai)?|mixtral|codestral|devstral|magistral|ministral|pixtral)(?![a-z])/, "mistral"],
407
+ [/\b(meta-llama|meta|llama|codellama)(?![a-z])/, "meta"],
408
+ [/\blocal\b/, "local"]
353
409
  ];
354
410
  var TIER_PATTERNS_BY_VENDOR = {
355
411
  anthropic: [
@@ -365,127 +421,511 @@ var require_modelClassifier = __commonJS({
365
421
  // distinction the ids do not yet draw — `<vendor>:unknown` is waiting for
366
422
  // the day one does.
367
423
  xai: [[/\bgrok\b/, "xai:grok"]],
368
- local: [[/\b(ollama|llamacpp|on[-_]?device)\b/, "local:on_device"]]
424
+ deepseek: [],
425
+ moonshot: [],
426
+ zhipu: [],
427
+ minimax: [],
428
+ alibaba: [],
429
+ mistral: [],
430
+ meta: [],
431
+ // The runtime words are read before any vendor, so only a bare `local`
432
+ // reaches here, and it names no runtime.
433
+ local: []
369
434
  };
370
435
  var UNKNOWN_TIER_BY_VENDOR = {
371
436
  anthropic: "anthropic:unknown",
372
437
  openai: "openai:unknown",
373
438
  google: "google:unknown",
374
439
  xai: "xai:unknown",
440
+ deepseek: "deepseek:unknown",
441
+ moonshot: "moonshot:unknown",
442
+ zhipu: "zhipu:unknown",
443
+ minimax: "minimax:unknown",
444
+ alibaba: "alibaba:unknown",
445
+ mistral: "mistral:unknown",
446
+ meta: "meta:unknown",
375
447
  local: "local:unknown"
376
448
  };
377
449
  }
378
450
  });
379
451
 
380
- // ../packages/tool-kit/out/buckets.js
381
- var require_buckets = __commonJS({
382
- "../packages/tool-kit/out/buckets.js"(exports) {
452
+ // ../packages/tool-kit/out/effortClassifier.js
453
+ var require_effortClassifier = __commonJS({
454
+ "../packages/tool-kit/out/effortClassifier.js"(exports) {
383
455
  "use strict";
384
456
  Object.defineProperty(exports, "__esModule", { value: true });
385
- exports.bucketLinesChanged = bucketLinesChanged;
386
- exports.bucketDurationMs = bucketDurationMs2;
387
- function bucketLinesChanged(count) {
388
- if (count <= 0)
389
- return "0";
390
- if (count <= 10)
391
- return "1-10";
392
- if (count <= 50)
393
- return "10-50";
394
- if (count <= 200)
395
- return "50-200";
396
- return "200+";
397
- }
398
- function bucketDurationMs2(durationMs) {
399
- if (typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs < 0)
457
+ exports.classifyEffortClass = classifyEffortClass;
458
+ function classifyEffortClass(raw) {
459
+ const candidate = raw;
460
+ if (candidate === void 0 || candidate === null)
400
461
  return void 0;
401
- const minutes = durationMs / 6e4;
402
- if (minutes <= 1)
403
- return "0-1m";
404
- if (minutes <= 5)
405
- return "1-5m";
406
- if (minutes <= 10)
407
- return "5-10m";
408
- if (minutes <= 30)
409
- return "10-30m";
410
- if (minutes <= 60)
411
- return "30-60m";
412
- return "60m+";
413
- }
462
+ if (typeof candidate !== "string")
463
+ return "unknown";
464
+ const value = candidate.trim().toLowerCase();
465
+ if (!value)
466
+ return void 0;
467
+ return EFFORT_CLASS_BY_LEVEL[value] ?? "unknown";
468
+ }
469
+ var EFFORT_CLASS_BY_LEVEL = {
470
+ none: "low",
471
+ minimal: "low",
472
+ low: "low",
473
+ medium: "medium",
474
+ high: "high",
475
+ xhigh: "xhigh",
476
+ max: "max"
477
+ };
414
478
  }
415
479
  });
416
480
 
417
- // ../packages/tool-kit/out/afterHours.js
418
- var require_afterHours = __commonJS({
419
- "../packages/tool-kit/out/afterHours.js"(exports) {
481
+ // ../packages/tool-kit/out/modelRoute.js
482
+ var require_modelRoute = __commonJS({
483
+ "../packages/tool-kit/out/modelRoute.js"(exports) {
420
484
  "use strict";
421
485
  Object.defineProperty(exports, "__esModule", { value: true });
422
- exports.BUSINESS_DAY = void 0;
423
- exports.isOutsideBusinessHours = isOutsideBusinessHours;
424
- exports.isAfterHours = isAfterHours;
425
- exports.utcOffsetMinutesAt = utcOffsetMinutesAt;
426
- exports.localHourAt = localHourAt;
427
- exports.BUSINESS_DAY = {
428
- /** 0 = Sunday … 6 = Saturday. */
429
- days: [1, 2, 3, 4, 5],
430
- start: "09:00",
431
- end: "17:00"
486
+ exports.modelRouteFromSlug = modelRouteFromSlug;
487
+ exports.modelRouteFromCodexProvider = modelRouteFromCodexProvider;
488
+ exports.claudeCodeModelRoute = claudeCodeModelRoute;
489
+ function modelRouteFromSlug(raw) {
490
+ if (typeof raw !== "string")
491
+ return void 0;
492
+ const value = raw.trim().toLowerCase();
493
+ if (!value)
494
+ return void 0;
495
+ for (const [pattern, route] of SLUG_ROUTES) {
496
+ if (pattern.test(value))
497
+ return route;
498
+ }
499
+ return void 0;
500
+ }
501
+ var BEDROCK_VENDORS = "anthropic|amazon|meta|mistral|cohere|ai21|deepseek|qwen|openai|writer|moonshot|minimax|stability";
502
+ var SLUG_ROUTES = [
503
+ // Local runtimes first: `ollama/…` says where the weights ran whatever the
504
+ // rest of the id says.
505
+ [/^(ollama|ollama_chat|lmstudio|lm_studio|lm-studio|llamacpp|llama\.cpp)\//, "local"],
506
+ [/\b(ollama|llamacpp|lmstudio)\b/, "local"],
507
+ [/^(bedrock|bedrock_converse|amazon-bedrock|aws-bedrock)\//, "bedrock"],
508
+ [/^arn:aws[a-z-]*:bedrock:/, "bedrock"],
509
+ // `us.anthropic.claude-…-v1:0`, `eu.meta.llama3-…`, `anthropic.claude-…`.
510
+ // The vendor dot is what makes it Bedrock's form: no other surface writes
511
+ // `vendor.model`.
512
+ [new RegExp(`^(?:(?:us|eu|apac|us-gov|global|jp|au|ca)\\.)?(?:${BEDROCK_VENDORS})\\.[a-z0-9]`), "bedrock"],
513
+ [/^(vertex_ai|vertex|vertex_ai_beta|google-vertex|vertexai)\//, "vertex"],
514
+ [/(^|\/)publishers\/[a-z0-9-]+\/models\//, "vertex"],
515
+ [/^(azure|azure_ai|azure-openai|azureai)\//, "azure"],
516
+ [/^(openrouter|litellm|litellm_proxy|portkey|helicone|together_ai|together|fireworks_ai|fireworks|groq|deepinfra|cloudflare)\//, "gateway"]
517
+ ];
518
+ function modelRouteFromCodexProvider(raw) {
519
+ if (typeof raw !== "string")
520
+ return void 0;
521
+ const value = raw.trim().toLowerCase();
522
+ if (!value)
523
+ return void 0;
524
+ return CODEX_PROVIDER_ROUTES[value] ?? "custom_endpoint";
525
+ }
526
+ var CODEX_PROVIDER_ROUTES = {
527
+ openai: "direct",
528
+ azure: "azure",
529
+ "azure-openai": "azure",
530
+ oss: "local",
531
+ ollama: "local",
532
+ lmstudio: "local",
533
+ "lm-studio": "local",
534
+ bedrock: "bedrock",
535
+ "amazon-bedrock": "bedrock",
536
+ vertex: "vertex",
537
+ vertexai: "vertex",
538
+ openrouter: "gateway",
539
+ litellm: "gateway",
540
+ portkey: "gateway"
432
541
  };
433
- function isOutsideBusinessHours(at = /* @__PURE__ */ new Date(), opts = {}) {
434
- const days = opts.days ?? exports.BUSINESS_DAY.days;
435
- if (!days.includes(at.getDay()))
436
- return true;
437
- const minutes = at.getHours() * 60 + at.getMinutes();
438
- const start = parseTimeToMinutes(opts.start ?? exports.BUSINESS_DAY.start, 9 * 60);
439
- const end = parseTimeToMinutes(opts.end ?? exports.BUSINESS_DAY.end, 17 * 60);
440
- if (start >= end)
542
+ function claudeCodeModelRoute(env, slug) {
543
+ if (isTruthySetting(env.CLAUDE_CODE_USE_BEDROCK))
544
+ return "bedrock";
545
+ if (isTruthySetting(env.CLAUDE_CODE_USE_VERTEX))
546
+ return "vertex";
547
+ if (isTruthySetting(env.CLAUDE_CODE_USE_FOUNDRY))
548
+ return "azure";
549
+ const fromSlug = modelRouteFromSlug(slug);
550
+ if (fromSlug)
551
+ return fromSlug;
552
+ if (typeof env.ANTHROPIC_BASE_URL === "string" && env.ANTHROPIC_BASE_URL.trim() !== "")
553
+ return "custom_endpoint";
554
+ return "direct";
555
+ }
556
+ function isTruthySetting(value) {
557
+ if (value === void 0)
441
558
  return false;
442
- return minutes < start || minutes >= end;
559
+ const v = value.trim().toLowerCase();
560
+ return v !== "" && v !== "0" && v !== "false" && v !== "no" && v !== "off";
443
561
  }
444
- function isAfterHours(now = /* @__PURE__ */ new Date(), start = "19:00", end = "07:00") {
445
- const currentMinutes = now.getHours() * 60 + now.getMinutes();
446
- const startMinutes = parseTimeToMinutes(start, 19 * 60);
447
- const endMinutes = parseTimeToMinutes(end, 7 * 60);
448
- if (startMinutes === endMinutes)
449
- return false;
450
- if (startMinutes < endMinutes)
451
- return currentMinutes >= startMinutes && currentMinutes < endMinutes;
452
- return currentMinutes >= startMinutes || currentMinutes < endMinutes;
562
+ }
563
+ });
564
+
565
+ // ../packages/tool-kit/out/tokenStore.js
566
+ var require_tokenStore = __commonJS({
567
+ "../packages/tool-kit/out/tokenStore.js"(exports) {
568
+ "use strict";
569
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
570
+ if (k2 === void 0) k2 = k;
571
+ var desc = Object.getOwnPropertyDescriptor(m, k);
572
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
573
+ desc = { enumerable: true, get: function() {
574
+ return m[k];
575
+ } };
576
+ }
577
+ Object.defineProperty(o, k2, desc);
578
+ } : function(o, m, k, k2) {
579
+ if (k2 === void 0) k2 = k;
580
+ o[k2] = m[k];
581
+ });
582
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
583
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
584
+ } : function(o, v) {
585
+ o["default"] = v;
586
+ });
587
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
588
+ var ownKeys = function(o) {
589
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
590
+ var ar = [];
591
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
592
+ return ar;
593
+ };
594
+ return ownKeys(o);
595
+ };
596
+ return function(mod) {
597
+ if (mod && mod.__esModule) return mod;
598
+ var result = {};
599
+ if (mod != null) {
600
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
601
+ }
602
+ __setModuleDefault(result, mod);
603
+ return result;
604
+ };
605
+ }();
606
+ Object.defineProperty(exports, "__esModule", { value: true });
607
+ exports.EVENT_TOKEN_TTL_MS = void 0;
608
+ exports.ascendaHome = ascendaHome;
609
+ exports.defaultTokenFilePath = defaultTokenFilePath2;
610
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
611
+ exports.persistEventWriteToken = persistEventWriteToken2;
612
+ exports.readTokenExpiry = readTokenExpiry;
613
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
614
+ exports.readTokenFile = readTokenFile2;
615
+ exports.sanitizeFilePart = sanitizeFilePart;
616
+ var fs = __importStar(__require("fs"));
617
+ var os = __importStar(__require("os"));
618
+ var path = __importStar(__require("path"));
619
+ function ascendaHome(home = os.homedir()) {
620
+ return process.env.ASCENDA_HOME ?? path.join(home, ".ascenda");
453
621
  }
454
- function parseTimeToMinutes(value, fallback) {
455
- const match = /^(\d{1,2}):(\d{2})$/.exec(value.trim());
456
- if (!match)
457
- return fallback;
458
- const hours = Number(match[1]);
459
- const minutes = Number(match[2]);
460
- if (Number.isNaN(hours) || Number.isNaN(minutes))
461
- return fallback;
462
- return Math.max(0, Math.min(23, hours)) * 60 + Math.max(0, Math.min(59, minutes));
622
+ function defaultTokenFilePath2(toolInstallationId) {
623
+ return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
463
624
  }
464
- function utcOffsetMinutesAt(at) {
465
- return -at.getTimezoneOffset();
625
+ function tokenExpiryFilePath(tokenFilePath) {
626
+ return path.join(path.dirname(tokenFilePath), "expiry", path.basename(tokenFilePath));
466
627
  }
467
- function localHourAt(at, utcOffsetMinutes) {
468
- const shifted = new Date(at.getTime() + utcOffsetMinutes * 6e4);
469
- return shifted.getUTCHours();
628
+ function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
629
+ const dir = path.dirname(tokenFilePath);
630
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
631
+ fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
632
+ if (process.platform !== "win32") {
633
+ fs.chmodSync(dir, 448);
634
+ fs.chmodSync(tokenFilePath, 384);
635
+ }
636
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
637
+ try {
638
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
639
+ fs.mkdirSync(path.dirname(expiryFile), { recursive: true, mode: 448 });
640
+ fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
641
+ } else {
642
+ fs.rmSync(expiryFile, { force: true });
643
+ }
644
+ } catch {
645
+ }
646
+ }
647
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
648
+ function readTokenExpiry(tokenFilePath) {
649
+ try {
650
+ const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
651
+ if (Number.isFinite(recorded))
652
+ return recorded;
653
+ } catch {
654
+ }
655
+ try {
656
+ return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
657
+ } catch {
658
+ return void 0;
659
+ }
660
+ }
661
+ function listPersistedToolInstallationIds(toolType) {
662
+ const prefix = `${sanitizeFilePart(toolType)}_`;
663
+ const dir = path.join(ascendaHome(), "tokens");
664
+ let names;
665
+ try {
666
+ names = fs.readdirSync(dir);
667
+ } catch {
668
+ return [];
669
+ }
670
+ const ids = [];
671
+ for (const name of names.sort()) {
672
+ if (!name.startsWith(prefix) || name.length === prefix.length)
673
+ continue;
674
+ const file = path.join(dir, name);
675
+ try {
676
+ if (!fs.statSync(file).isFile())
677
+ continue;
678
+ } catch {
679
+ continue;
680
+ }
681
+ if (readTokenFile2(file) === void 0)
682
+ continue;
683
+ ids.push(`${toolType}:${name.slice(prefix.length)}`);
684
+ }
685
+ return ids;
686
+ }
687
+ function readTokenFile2(tokenFilePath) {
688
+ try {
689
+ if (!fs.existsSync(tokenFilePath))
690
+ return void 0;
691
+ const value = fs.readFileSync(tokenFilePath, "utf8").trim();
692
+ return value || void 0;
693
+ } catch {
694
+ return void 0;
695
+ }
696
+ }
697
+ function sanitizeFilePart(value) {
698
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_");
470
699
  }
471
700
  }
472
701
  });
473
702
 
474
- // ../packages/tool-contract/out/metricKeys.js
475
- var require_metricKeys = __commonJS({
476
- "../packages/tool-contract/out/metricKeys.js"(exports) {
703
+ // ../packages/tool-kit/out/modelState.js
704
+ var require_modelState = __commonJS({
705
+ "../packages/tool-kit/out/modelState.js"(exports) {
477
706
  "use strict";
478
- Object.defineProperty(exports, "__esModule", { value: true });
479
- exports.METRIC_KEYS = void 0;
480
- exports.backendMetricKeys = backendMetricKeys;
481
- var CONTEXT_WINDOW_CANONICAL_ALIASES = [
482
- "contextWindowPeakPct",
707
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
708
+ if (k2 === void 0) k2 = k;
709
+ var desc = Object.getOwnPropertyDescriptor(m, k);
710
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
711
+ desc = { enumerable: true, get: function() {
712
+ return m[k];
713
+ } };
714
+ }
715
+ Object.defineProperty(o, k2, desc);
716
+ } : function(o, m, k, k2) {
717
+ if (k2 === void 0) k2 = k;
718
+ o[k2] = m[k];
719
+ });
720
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
721
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
722
+ } : function(o, v) {
723
+ o["default"] = v;
724
+ });
725
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
726
+ var ownKeys = function(o) {
727
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
728
+ var ar = [];
729
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
730
+ return ar;
731
+ };
732
+ return ownKeys(o);
733
+ };
734
+ return function(mod) {
735
+ if (mod && mod.__esModule) return mod;
736
+ var result = {};
737
+ if (mod != null) {
738
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
739
+ }
740
+ __setModuleDefault(result, mod);
741
+ return result;
742
+ };
743
+ }();
744
+ Object.defineProperty(exports, "__esModule", { value: true });
745
+ exports.readSentModelId = readSentModelId;
746
+ exports.recordSentModelId = recordSentModelId;
747
+ exports.clearSentModelId = clearSentModelId;
748
+ exports.modelFieldsFor = modelFieldsFor;
749
+ exports.withModelOnChange = withModelOnChange;
750
+ var fs = __importStar(__require("fs"));
751
+ var path = __importStar(__require("path"));
752
+ var tokenStore_1 = require_tokenStore();
753
+ var modelClassifier_1 = require_modelClassifier();
754
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join((0, tokenStore_1.ascendaHome)(), "state");
755
+ function modelFile(agent, sessionId) {
756
+ return path.join(stateDir(), `${sanitize(agent)}-model-${sanitize(sessionId)}`);
757
+ }
758
+ function sanitize(value) {
759
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_");
760
+ }
761
+ function readSentModelId(agent, sessionId) {
762
+ if (!sessionId)
763
+ return void 0;
764
+ try {
765
+ const id = fs.readFileSync(modelFile(agent, sessionId), "utf8").trim();
766
+ return id || void 0;
767
+ } catch {
768
+ return void 0;
769
+ }
770
+ }
771
+ function recordSentModelId(agent, sessionId, modelId) {
772
+ if (!sessionId || !modelId)
773
+ return;
774
+ try {
775
+ fs.mkdirSync(stateDir(), { recursive: true });
776
+ fs.writeFileSync(modelFile(agent, sessionId), modelId, { encoding: "utf8", mode: 384 });
777
+ } catch {
778
+ }
779
+ }
780
+ function clearSentModelId(agent, sessionId) {
781
+ if (!sessionId)
782
+ return;
783
+ try {
784
+ fs.rmSync(modelFile(agent, sessionId), { force: true });
785
+ } catch {
786
+ }
787
+ }
788
+ function modelFieldsFor(raw, route) {
789
+ if (typeof raw !== "string")
790
+ return void 0;
791
+ const modelId = raw.trim();
792
+ if (!modelId || modelId.length > 200)
793
+ return void 0;
794
+ const modelClass = (0, modelClassifier_1.classifyModelClass)(modelId);
795
+ if (modelClass === void 0)
796
+ return void 0;
797
+ return { modelId, modelClass, ...route ? { modelRoute: route } : {} };
798
+ }
799
+ function withModelOnChange(events, fields, lastSentModelId, force = false) {
800
+ if (events.length === 0 || !fields)
801
+ return { events };
802
+ if (!force && fields.modelId === lastSentModelId)
803
+ return { events };
804
+ const [first, ...rest] = events;
805
+ return {
806
+ events: [{ ...first, metadata: { ...first.metadata ?? {}, ...fields } }, ...rest],
807
+ sent: fields.modelId
808
+ };
809
+ }
810
+ }
811
+ });
812
+
813
+ // ../packages/tool-kit/out/buckets.js
814
+ var require_buckets = __commonJS({
815
+ "../packages/tool-kit/out/buckets.js"(exports) {
816
+ "use strict";
817
+ Object.defineProperty(exports, "__esModule", { value: true });
818
+ exports.bucketLinesChanged = bucketLinesChanged;
819
+ exports.bucketDurationMs = bucketDurationMs2;
820
+ function bucketLinesChanged(count) {
821
+ if (count <= 0)
822
+ return "0";
823
+ if (count <= 10)
824
+ return "1-10";
825
+ if (count <= 50)
826
+ return "10-50";
827
+ if (count <= 200)
828
+ return "50-200";
829
+ return "200+";
830
+ }
831
+ function bucketDurationMs2(durationMs) {
832
+ if (typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs < 0)
833
+ return void 0;
834
+ const minutes = durationMs / 6e4;
835
+ if (minutes <= 1)
836
+ return "0-1m";
837
+ if (minutes <= 5)
838
+ return "1-5m";
839
+ if (minutes <= 10)
840
+ return "5-10m";
841
+ if (minutes <= 30)
842
+ return "10-30m";
843
+ if (minutes <= 60)
844
+ return "30-60m";
845
+ return "60m+";
846
+ }
847
+ }
848
+ });
849
+
850
+ // ../packages/tool-kit/out/afterHours.js
851
+ var require_afterHours = __commonJS({
852
+ "../packages/tool-kit/out/afterHours.js"(exports) {
853
+ "use strict";
854
+ Object.defineProperty(exports, "__esModule", { value: true });
855
+ exports.BUSINESS_DAY = void 0;
856
+ exports.isOutsideBusinessHours = isOutsideBusinessHours;
857
+ exports.isAfterHours = isAfterHours;
858
+ exports.utcOffsetMinutesAt = utcOffsetMinutesAt;
859
+ exports.localHourAt = localHourAt;
860
+ exports.BUSINESS_DAY = {
861
+ /** 0 = Sunday … 6 = Saturday. */
862
+ days: [1, 2, 3, 4, 5],
863
+ start: "09:00",
864
+ end: "17:00"
865
+ };
866
+ function isOutsideBusinessHours(at = /* @__PURE__ */ new Date(), opts = {}) {
867
+ const days = opts.days ?? exports.BUSINESS_DAY.days;
868
+ if (!days.includes(at.getDay()))
869
+ return true;
870
+ const minutes = at.getHours() * 60 + at.getMinutes();
871
+ const start = parseTimeToMinutes(opts.start ?? exports.BUSINESS_DAY.start, 9 * 60);
872
+ const end = parseTimeToMinutes(opts.end ?? exports.BUSINESS_DAY.end, 17 * 60);
873
+ if (start >= end)
874
+ return false;
875
+ return minutes < start || minutes >= end;
876
+ }
877
+ function isAfterHours(now = /* @__PURE__ */ new Date(), start = "19:00", end = "07:00") {
878
+ const currentMinutes = now.getHours() * 60 + now.getMinutes();
879
+ const startMinutes = parseTimeToMinutes(start, 19 * 60);
880
+ const endMinutes = parseTimeToMinutes(end, 7 * 60);
881
+ if (startMinutes === endMinutes)
882
+ return false;
883
+ if (startMinutes < endMinutes)
884
+ return currentMinutes >= startMinutes && currentMinutes < endMinutes;
885
+ return currentMinutes >= startMinutes || currentMinutes < endMinutes;
886
+ }
887
+ function parseTimeToMinutes(value, fallback) {
888
+ const match = /^(\d{1,2}):(\d{2})$/.exec(value.trim());
889
+ if (!match)
890
+ return fallback;
891
+ const hours = Number(match[1]);
892
+ const minutes = Number(match[2]);
893
+ if (Number.isNaN(hours) || Number.isNaN(minutes))
894
+ return fallback;
895
+ return Math.max(0, Math.min(23, hours)) * 60 + Math.max(0, Math.min(59, minutes));
896
+ }
897
+ function utcOffsetMinutesAt(at) {
898
+ return -at.getTimezoneOffset();
899
+ }
900
+ function localHourAt(at, utcOffsetMinutes) {
901
+ const shifted = new Date(at.getTime() + utcOffsetMinutes * 6e4);
902
+ return shifted.getUTCHours();
903
+ }
904
+ }
905
+ });
906
+
907
+ // ../packages/tool-contract/out/metricKeys.js
908
+ var require_metricKeys = __commonJS({
909
+ "../packages/tool-contract/out/metricKeys.js"(exports) {
910
+ "use strict";
911
+ Object.defineProperty(exports, "__esModule", { value: true });
912
+ exports.METRIC_KEYS = void 0;
913
+ exports.localMetricKeys = localMetricKeys;
914
+ exports.backendMetricKeys = backendMetricKeys;
915
+ var CONTEXT_WINDOW_CANONICAL_ALIASES = [
916
+ "contextWindowPeakPct",
483
917
  "context_window_peak_pct",
484
918
  "contextWindowPct",
485
919
  "context_window_pct"
486
920
  ];
487
921
  var CONTEXT_WINDOW_CURSOR_PERCENT_ALIASES = ["contextUsagePercent"];
488
922
  exports.METRIC_KEYS = {
923
+ extractorRevision: {
924
+ family: "transport",
925
+ readBy: ["backend"],
926
+ backendAliases: ["extractorRevision"],
927
+ note: "Which rung of the store's extractor produced the row; the backend replaces a stored row when a higher one arrives under the same importKey."
928
+ },
489
929
  // ── Read by a backend reader ────────────────────────────────────────────
490
930
  contextWindowPeakPct: {
491
931
  family: "context",
@@ -505,8 +945,12 @@ var require_metricKeys = __commonJS({
505
945
  sessionMinutes: { family: "session", readBy: ["backend"], backendAliases: ["sessionMinutes", "session_minutes"], unit: "minutes" },
506
946
  durationBucket: { family: "session", readBy: ["backend", "handoff"], backendAliases: ["durationBucket", "duration_bucket"] },
507
947
  afterHoursPrompts: { family: "clock", readBy: ["backend", "handoff"], backendAliases: ["afterHoursPrompts", "after_hours_prompts"] },
948
+ /** Input tokens billed at the full rate: cache reads and cache writes
949
+ * excluded. Every extractor ships it on this definition, so
950
+ * `inputTokens + cacheReadTokens + cacheCreationTokens` is the whole input. */
508
951
  inputTokens: { family: "context", readBy: ["backend"], backendAliases: ["inputTokens", "input_tokens"], unit: "tokens" },
509
952
  outputTokens: { family: "context", readBy: ["backend"], backendAliases: ["outputTokens", "output_tokens"], unit: "tokens" },
953
+ /** Input tokens served from the prompt cache. Not part of `inputTokens`. */
510
954
  cacheReadTokens: { family: "context", readBy: ["backend"], backendAliases: ["cacheReadTokens", "cache_read_tokens"], unit: "tokens" },
511
955
  queuedPrompts: { family: "counts", readBy: ["backend"], backendAliases: ["queuedPrompts", "queued_prompts"] },
512
956
  linesChangedBucket: { family: "edits", readBy: ["backend"], backendAliases: ["linesChangedBucket", "lines_changed_bucket"] },
@@ -528,6 +972,57 @@ var require_metricKeys = __commonJS({
528
972
  backendAliases: ["branchKey", "branch_key"],
529
973
  note: "forgeBranchKey of the repository and the branch a commit is reachable from. Absent on the default branch, like the live hooks."
530
974
  },
975
+ // Codex's own usage-limit readings: `rate_limits` on its token_count lines,
976
+ // main thread only. The limit's id and name, the plan and the credit
977
+ // balance on the same object are never read. A session whose rollouts
978
+ // carried no readings has none of these keys.
979
+ //
980
+ // `family: "local"`, all seven. They say how much of an allowance was left
981
+ // on an account with the provider, which is a fact about the account and
982
+ // not about how the work went, so they are read on the machine and never
983
+ // sent. `ship.ts` leaves a `local` key out of the wire payload, and
984
+ // `localMetricKeys.test.mjs` holds it to that.
985
+ usageLimitShortPeakPct: {
986
+ family: "local",
987
+ readBy: ["handoff"],
988
+ unit: "percent (0\u2013100), whole number",
989
+ note: "Stays on the machine: an account's allowance, not the work. The largest used_percent of the short (primary) window the session saw. Five hours on every build seen; usageLimitShortWindowMinutes says. Each day slice carries that day's own peak under the same name."
990
+ },
991
+ usageLimitLongPeakPct: {
992
+ family: "local",
993
+ readBy: ["handoff"],
994
+ unit: "percent (0\u2013100), whole number",
995
+ note: "Stays on the machine, as the short window does. The same for the long (secondary) window. Weekly on every build seen."
996
+ },
997
+ usageLimitShortWindowMinutes: {
998
+ family: "local",
999
+ readBy: ["handoff"],
1000
+ unit: "minutes",
1001
+ note: "Stays on the machine. The short window's size as the rollout reported it, never assumed."
1002
+ },
1003
+ usageLimitLongWindowMinutes: {
1004
+ family: "local",
1005
+ readBy: ["handoff"],
1006
+ unit: "minutes",
1007
+ note: "Stays on the machine. The long window's size as the rollout reported it."
1008
+ },
1009
+ usageLimitReached: {
1010
+ family: "local",
1011
+ readBy: ["handoff"],
1012
+ unit: "boolean",
1013
+ note: "Stays on the machine. True when a reading carried a non-null rate_limit_reached_type. Present only beside the peaks."
1014
+ },
1015
+ usageLimitReachedType: {
1016
+ family: "local",
1017
+ readBy: ["handoff"],
1018
+ note: "Stays on the machine. Which limit was hit: primary, secondary, or other for any value outside that list."
1019
+ },
1020
+ usageLimitFirstReachedAt: {
1021
+ family: "local",
1022
+ readBy: ["handoff"],
1023
+ unit: "ISO 8601 instant",
1024
+ note: "Stays on the machine. The first reading that carried a reached type."
1025
+ },
531
1026
  // ── Read by the local handoff only ──────────────────────────────────────
532
1027
  activeMinutes: { family: "session", readBy: ["handoff"], unit: "minutes" },
533
1028
  syntheticPromptLines: {
@@ -536,6 +1031,12 @@ var require_metricKeys = __commonJS({
536
1031
  unit: "lines",
537
1032
  note: "Main-thread user lines the runtime wrote on the person's behalf (notifications, its own bookkeeping, slash-command wrappers, interrupt markers) and promptCount left out. Claude Code only; the receipt for the handoff's promptBasis. Counted per transcript, so a resumed transcript's copies count again."
538
1033
  },
1034
+ repeatedLines: {
1035
+ family: "reading",
1036
+ readBy: ["diagnostic"],
1037
+ unit: "lines",
1038
+ note: "Lines read but left out of every count because they repeat one already read: a uuid seen earlier in the same transcript (a resume can write the same lines twice), or, in a forked subagent's transcript, a line its parent's main transcript holds. Claude Code only; shipped when above 0."
1039
+ },
539
1040
  dispatchedPromptLines: {
540
1041
  family: "reading",
541
1042
  readBy: ["handoff"],
@@ -622,6 +1123,36 @@ var require_metricKeys = __commonJS({
622
1123
  backendAliases: ["primaryModel", "primary_model"],
623
1124
  note: "Read twice: the desktop's local handoff folds it, and a server-side reader resolves it to group a bucket's sessions by the model that served them. Declared handoff-only until 23 Sep 2026 \u2014 see toolName for why that direction of mistake has no symptom."
624
1125
  },
1126
+ primaryEffort: {
1127
+ family: "model",
1128
+ readBy: ["handoff"],
1129
+ note: "Claude Code and Codex: the effort level on most of the session's main-thread model turns, as the store wrote it (low, medium, high, xhigh). Absent where the store wrote none, which older Claude Code builds didn't. ship.ts adds effortClass beside it on the way out. The ordered switches ride beside metrics as effortChanges, since a list can't be a metric. The backend reader arrives in its own change."
1130
+ },
1131
+ modelRoute: {
1132
+ family: "model",
1133
+ readBy: ["handoff"],
1134
+ note: "Who served the session's model, one word: direct, bedrock, vertex, azure, gateway, custom_endpoint, local. Codex reads session_meta.model_provider (a provider not built into Codex reads as custom_endpoint, never its name); Claude Code and the other stores read only the slug's own prefix, so a plain slug leaves it off. Never a URL, host or region. ship.ts derives it from primaryModel where the extractor set none. The backend reader arrives in its own change."
1135
+ },
1136
+ modelTurns: {
1137
+ family: "model",
1138
+ readBy: ["handoff"],
1139
+ note: "Claude Code and Codex: the session's model mix as a JSON object in a string, raw slug to count, at most 8 entries, largest first. The counts are the ones primaryModel is chosen from (Claude Code: main-thread API messages plus advisor iterations; Codex: turn_context lines on every thread), so its largest entry is primaryModel unless two models tie. Turns past the cap are in modelTurnsOmitted. See modelTurns.ts."
1140
+ },
1141
+ modelTurnsOmitted: {
1142
+ family: "model",
1143
+ readBy: ["handoff"],
1144
+ note: "Turns on models left out of modelTurns by its cap, or on a slug too long to be a model id. Absent when nothing was left out."
1145
+ },
1146
+ mainThreadToolCallCount: {
1147
+ family: "tools",
1148
+ readBy: ["handoff"],
1149
+ note: "Claude Code and Codex: tool calls the session's own thread issued, subagents excluded. The denominator for mainThreadToolFailureCount. Equal to toolCallCount on Claude Code, which already counts the main thread only; Codex's toolCallCount includes subagent threads."
1150
+ },
1151
+ mainThreadToolFailureCount: {
1152
+ family: "outcome",
1153
+ readBy: ["handoff"],
1154
+ note: "Claude Code and Codex: main-thread tool calls whose result was an error, one per call. Same basis as mainThreadToolCallCount, so the two divide. toolFailureCount keeps its meaning (it adds subagent failures and API errors) and is not a numerator for toolCallCount."
1155
+ },
625
1156
  requestCount: { family: "counts", readBy: ["handoff"] },
626
1157
  sessionStartedAt: { family: "session", readBy: ["handoff"] },
627
1158
  subagentComposers: { family: "counts", readBy: ["handoff"] },
@@ -689,6 +1220,76 @@ var require_metricKeys = __commonJS({
689
1220
  subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
690
1221
  subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
691
1222
  subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
1223
+ // ── Cost-finding evidence (Claude Code). Counts only: skill, MCP server and
1224
+ // agent names stay on the machine. Each family ships behind its own seen
1225
+ // flag, so an absent key means "not measured", never zero.
1226
+ skillListingSeen: {
1227
+ family: "tools",
1228
+ readBy: ["diagnostic"],
1229
+ note: "Claude Code only: true when the transcript listed the skills in context (a skill_listing attachment). Without it the session ships no skill keys, since a skill can't be called unused off a list nobody saw. The backend reader arrives in its own change."
1230
+ },
1231
+ skillsListed: {
1232
+ family: "tools",
1233
+ readBy: ["diagnostic"],
1234
+ note: "Claude Code only: how many skills were in the session's context at the end, from its skill_listing attachments (an initial listing replaces the set, a later one adds to it). A count; the names aren't read past the fold. Shipped with skillListingSeen. The backend reader arrives in its own change."
1235
+ },
1236
+ skillsInvoked: {
1237
+ family: "tools",
1238
+ readBy: ["diagnostic"],
1239
+ note: "Claude Code only: distinct listed skills the session loaded, from invoked_skills attachments and Skill tool calls, main thread and subagents. Shipped with skillListingSeen. The backend reader arrives in its own change."
1240
+ },
1241
+ mcpListingSeen: {
1242
+ family: "tools",
1243
+ readBy: ["diagnostic"],
1244
+ note: "Claude Code only: true when the transcript recorded which MCP servers were in context (mcp_instructions_delta or deferred_tools_delta). Without it the session ships no MCP keys. The backend reader arrives in its own change."
1245
+ },
1246
+ mcpServersLoaded: {
1247
+ family: "tools",
1248
+ readBy: ["diagnostic"],
1249
+ note: "Claude Code only: distinct MCP servers in context at the end: servers with instructions, servers with deferred tools, and any server whose tool was called. Shipped with mcpListingSeen. The backend reader arrives in its own change."
1250
+ },
1251
+ mcpServersUsed: {
1252
+ family: "tools",
1253
+ readBy: ["diagnostic"],
1254
+ note: "Claude Code only: distinct MCP servers whose tools the session called, main thread and subagents, read from the raw mcp__<server>__<tool> name before toolName truncation. Shipped with mcpListingSeen. The backend reader arrives in its own change."
1255
+ },
1256
+ mcpServersFailed: {
1257
+ family: "tools",
1258
+ readBy: ["diagnostic"],
1259
+ note: "Claude Code only: distinct MCP servers a deferred_tools_delta reported as failed and that never loaded later in the session. Shipped with mcpListingSeen. The backend reader arrives in its own change."
1260
+ },
1261
+ speedSeen: {
1262
+ family: "model",
1263
+ readBy: ["diagnostic"],
1264
+ note: "Claude Code only: true once any owned assistant line carried usage.speed. Without it fastTurns and subagentFastTurns are absent, because the build didn't record the field. The backend reader arrives in its own change."
1265
+ },
1266
+ fastTurns: {
1267
+ family: "model",
1268
+ readBy: ["diagnostic"],
1269
+ note: "Claude Code only: main-thread API messages (one per message, however many lines it spans) whose usage.speed was fast. Shipped with speedSeen. The backend reader arrives in its own change."
1270
+ },
1271
+ subagentFastTurns: {
1272
+ family: "subagents",
1273
+ readBy: ["diagnostic"],
1274
+ note: "Claude Code only: subagent API messages whose usage.speed was fast, counted like fastTurns. Shipped with speedSeen. The backend reader arrives in its own change."
1275
+ },
1276
+ deepTurns200k: {
1277
+ family: "context",
1278
+ readBy: ["diagnostic"],
1279
+ unit: "messages",
1280
+ note: "Claude Code only: main-thread API messages whose context (input + cache read + cache write tokens) was above 200,000. A fixed cut point, so sessions compare without the raw series. The backend reader arrives in its own change."
1281
+ },
1282
+ deepTurns400k: {
1283
+ family: "context",
1284
+ readBy: ["diagnostic"],
1285
+ unit: "messages",
1286
+ note: "Claude Code only: the same count above 400,000 tokens. The backend reader arrives in its own change."
1287
+ },
1288
+ premiumSubagents: {
1289
+ family: "subagents",
1290
+ readBy: ["diagnostic"],
1291
+ note: "Claude Code only: subagents whose receipt modelClass is in PREMIUM_MODEL_CLASSES (tool-kit: anthropic:opus, anthropic:fable). 0 for a session with no subagents. The backend reader arrives in its own change."
1292
+ },
692
1293
  advisorMessageCount: {
693
1294
  family: "counts",
694
1295
  readBy: ["diagnostic"],
@@ -700,6 +1301,8 @@ var require_metricKeys = __commonJS({
700
1301
  unit: "tokens",
701
1302
  note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
702
1303
  },
1304
+ /** Input tokens written to the prompt cache. Not part of `inputTokens`.
1305
+ * Absent, never 0, where the store doesn't record the figure. */
703
1306
  cacheCreationTokens: {
704
1307
  family: "context",
705
1308
  readBy: ["diagnostic"],
@@ -753,7 +1356,7 @@ var require_metricKeys = __commonJS({
753
1356
  clientName: {
754
1357
  family: "session",
755
1358
  readBy: ["diagnostic"],
756
- note: "Copilot CLI only: workspace.yaml's client_name, one constant word naming what started the CLI (vscode, vscode-agent-host). Absent on sessions written before the field existed, which were the standalone CLI."
1359
+ note: "Copilot CLI: workspace.yaml's client_name, one constant word naming what started the CLI (vscode, vscode-agent-host); absent on sessions written before the field existed, which were the standalone CLI. Claude Code: claude-desktop-cowork on sessions read from Claude Desktop's Cowork config dirs, absent on the rest."
757
1360
  },
758
1361
  totalApiDurationMs: {
759
1362
  family: "session",
@@ -811,7 +1414,12 @@ var require_metricKeys = __commonJS({
811
1414
  unparsedBubbles: { family: "reading", readBy: ["diagnostic"] },
812
1415
  unparsedChatSessionFiles: { family: "reading", readBy: ["diagnostic"] },
813
1416
  unparsedHistoryFiles: { family: "reading", readBy: ["diagnostic"] },
814
- unparsedLines: { family: "reading", readBy: ["diagnostic"] },
1417
+ duplicateRolloutFiles: {
1418
+ family: "reading",
1419
+ readBy: ["diagnostic"],
1420
+ note: "Codex only: rollout files skipped because the same rollout sat under both sessions/ and archived_sessions/. One copy is read; the other would have counted its prompts and tool calls twice."
1421
+ },
1422
+ unparsedLines: { family: "reading", readBy: ["diagnostic"] },
815
1423
  unreadableChatSessionFiles: { family: "reading", readBy: ["diagnostic"] },
816
1424
  unreadableHistoryFiles: { family: "reading", readBy: ["diagnostic"] },
817
1425
  unreadableRolloutFiles: {
@@ -821,6 +1429,9 @@ var require_metricKeys = __commonJS({
821
1429
  },
822
1430
  unrecognisedChatSessionFiles: { family: "reading", readBy: ["diagnostic"] }
823
1431
  };
1432
+ function localMetricKeys() {
1433
+ return new Set(Object.entries(exports.METRIC_KEYS).filter(([, spec]) => spec.family === "local").map(([key]) => key));
1434
+ }
824
1435
  function backendMetricKeys() {
825
1436
  return Object.entries(exports.METRIC_KEYS).filter(([, spec]) => spec.readBy.includes("backend")).map(([key, spec]) => [key, spec.backendAliases ?? [key]]);
826
1437
  }
@@ -832,7 +1443,7 @@ var require_out = __commonJS({
832
1443
  "../packages/tool-contract/out/index.js"(exports) {
833
1444
  "use strict";
834
1445
  Object.defineProperty(exports, "__esModule", { value: true });
835
- exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.DELIVERY_ENVELOPE_KEYS = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
1446
+ exports.localMetricKeys = exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.DELIVERY_ENVELOPE_KEYS = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
836
1447
  exports.combineDisjointHalves = combineDisjointHalves;
837
1448
  exports.requireComparableQuantities = requireComparableQuantities;
838
1449
  exports.joinEventPayload = joinEventPayload;
@@ -924,10 +1535,19 @@ var require_out = __commonJS({
924
1535
  autonomyMode: "posture",
925
1536
  modelClass: "model",
926
1537
  modelId: "model",
1538
+ // The effort setting is a model setting, so it shares the model family:
1539
+ // the same consent covers it, and the pairing sentence names it.
1540
+ effortLevel: "model",
1541
+ effortClass: "model",
1542
+ // Who served the model, one word from a closed list. Never a host.
1543
+ modelRoute: "model",
927
1544
  userModified: "edits",
928
1545
  outcome: "outcome",
929
1546
  trigger: "outcome",
930
1547
  promptClass: "counts",
1548
+ // One letter for how long the prompt was, worked out on this machine.
1549
+ // Never the text or its length.
1550
+ promptSizeBucket: "counts",
931
1551
  reason: "outcome",
932
1552
  afterHours: "clock",
933
1553
  activity: "counts",
@@ -956,6 +1576,9 @@ var require_out = __commonJS({
956
1576
  importKey: "transport",
957
1577
  extractionId: "transport",
958
1578
  importSchema: "transport",
1579
+ // A whole number naming which rung of a store's extractor produced the row.
1580
+ // Says nothing about the work itself.
1581
+ extractorRevision: "transport",
959
1582
  // The version of the Ascenda collector that sent this event. Names the
960
1583
  // build, and nothing about the work it observed.
961
1584
  collectorVersion: "transport",
@@ -983,10 +1606,14 @@ var require_out = __commonJS({
983
1606
  "autonomyMode",
984
1607
  "modelClass",
985
1608
  "modelId",
1609
+ "effortLevel",
1610
+ "effortClass",
1611
+ "modelRoute",
986
1612
  "userModified",
987
1613
  "outcome",
988
1614
  "trigger",
989
1615
  "promptClass",
1616
+ "promptSizeBucket",
990
1617
  "reason",
991
1618
  "afterHours",
992
1619
  "activity",
@@ -1005,6 +1632,7 @@ var require_out = __commonJS({
1005
1632
  "importKey",
1006
1633
  "extractionId",
1007
1634
  "importSchema",
1635
+ "extractorRevision",
1008
1636
  "collectorVersion",
1009
1637
  "collectorPlatform"
1010
1638
  ];
@@ -1115,6 +1743,9 @@ var require_out = __commonJS({
1115
1743
  Object.defineProperty(exports, "backendMetricKeys", { enumerable: true, get: function() {
1116
1744
  return metricKeys_1.backendMetricKeys;
1117
1745
  } });
1746
+ Object.defineProperty(exports, "localMetricKeys", { enumerable: true, get: function() {
1747
+ return metricKeys_1.localMetricKeys;
1748
+ } });
1118
1749
  }
1119
1750
  });
1120
1751
 
@@ -1291,151 +1922,13 @@ var require_collectorVersion = __commonJS({
1291
1922
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
1292
1923
  exports.describeCollectorVersion = describeCollectorVersion;
1293
1924
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
1294
- exports.COLLECTOR_VERSION = "0.1.41" ? "0.1.41" : exports.UNRELEASED_COLLECTOR_VERSION;
1925
+ exports.COLLECTOR_VERSION = "0.1.43" ? "0.1.43" : exports.UNRELEASED_COLLECTOR_VERSION;
1295
1926
  function describeCollectorVersion(version2 = exports.COLLECTOR_VERSION) {
1296
1927
  return version2 === exports.UNRELEASED_COLLECTOR_VERSION ? `${version2} (built from a checkout, not a release)` : version2;
1297
1928
  }
1298
1929
  }
1299
1930
  });
1300
1931
 
1301
- // ../packages/tool-kit/out/tokenStore.js
1302
- var require_tokenStore = __commonJS({
1303
- "../packages/tool-kit/out/tokenStore.js"(exports) {
1304
- "use strict";
1305
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1306
- if (k2 === void 0) k2 = k;
1307
- var desc = Object.getOwnPropertyDescriptor(m, k);
1308
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1309
- desc = { enumerable: true, get: function() {
1310
- return m[k];
1311
- } };
1312
- }
1313
- Object.defineProperty(o, k2, desc);
1314
- } : function(o, m, k, k2) {
1315
- if (k2 === void 0) k2 = k;
1316
- o[k2] = m[k];
1317
- });
1318
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1319
- Object.defineProperty(o, "default", { enumerable: true, value: v });
1320
- } : function(o, v) {
1321
- o["default"] = v;
1322
- });
1323
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1324
- var ownKeys = function(o) {
1325
- ownKeys = Object.getOwnPropertyNames || function(o2) {
1326
- var ar = [];
1327
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1328
- return ar;
1329
- };
1330
- return ownKeys(o);
1331
- };
1332
- return function(mod) {
1333
- if (mod && mod.__esModule) return mod;
1334
- var result = {};
1335
- if (mod != null) {
1336
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1337
- }
1338
- __setModuleDefault(result, mod);
1339
- return result;
1340
- };
1341
- }();
1342
- Object.defineProperty(exports, "__esModule", { value: true });
1343
- exports.EVENT_TOKEN_TTL_MS = void 0;
1344
- exports.ascendaHome = ascendaHome;
1345
- exports.defaultTokenFilePath = defaultTokenFilePath2;
1346
- exports.tokenExpiryFilePath = tokenExpiryFilePath;
1347
- exports.persistEventWriteToken = persistEventWriteToken2;
1348
- exports.readTokenExpiry = readTokenExpiry;
1349
- exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1350
- exports.readTokenFile = readTokenFile2;
1351
- exports.sanitizeFilePart = sanitizeFilePart;
1352
- var fs = __importStar(__require("fs"));
1353
- var os = __importStar(__require("os"));
1354
- var path = __importStar(__require("path"));
1355
- function ascendaHome(home = os.homedir()) {
1356
- return process.env.ASCENDA_HOME ?? path.join(home, ".ascenda");
1357
- }
1358
- function defaultTokenFilePath2(toolInstallationId) {
1359
- return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1360
- }
1361
- function tokenExpiryFilePath(tokenFilePath) {
1362
- return path.join(path.dirname(tokenFilePath), "expiry", path.basename(tokenFilePath));
1363
- }
1364
- function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
1365
- const dir = path.dirname(tokenFilePath);
1366
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1367
- fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1368
- if (process.platform !== "win32") {
1369
- fs.chmodSync(dir, 448);
1370
- fs.chmodSync(tokenFilePath, 384);
1371
- }
1372
- const expiryFile = tokenExpiryFilePath(tokenFilePath);
1373
- try {
1374
- if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1375
- fs.mkdirSync(path.dirname(expiryFile), { recursive: true, mode: 448 });
1376
- fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1377
- } else {
1378
- fs.rmSync(expiryFile, { force: true });
1379
- }
1380
- } catch {
1381
- }
1382
- }
1383
- exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1384
- function readTokenExpiry(tokenFilePath) {
1385
- try {
1386
- const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1387
- if (Number.isFinite(recorded))
1388
- return recorded;
1389
- } catch {
1390
- }
1391
- try {
1392
- return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1393
- } catch {
1394
- return void 0;
1395
- }
1396
- }
1397
- function listPersistedToolInstallationIds(toolType) {
1398
- const prefix = `${sanitizeFilePart(toolType)}_`;
1399
- const dir = path.join(ascendaHome(), "tokens");
1400
- let names;
1401
- try {
1402
- names = fs.readdirSync(dir);
1403
- } catch {
1404
- return [];
1405
- }
1406
- const ids = [];
1407
- for (const name of names.sort()) {
1408
- if (!name.startsWith(prefix) || name.length === prefix.length)
1409
- continue;
1410
- const file = path.join(dir, name);
1411
- try {
1412
- if (!fs.statSync(file).isFile())
1413
- continue;
1414
- } catch {
1415
- continue;
1416
- }
1417
- if (readTokenFile2(file) === void 0)
1418
- continue;
1419
- ids.push(`${toolType}:${name.slice(prefix.length)}`);
1420
- }
1421
- return ids;
1422
- }
1423
- function readTokenFile2(tokenFilePath) {
1424
- try {
1425
- if (!fs.existsSync(tokenFilePath))
1426
- return void 0;
1427
- const value = fs.readFileSync(tokenFilePath, "utf8").trim();
1428
- return value || void 0;
1429
- } catch {
1430
- return void 0;
1431
- }
1432
- }
1433
- function sanitizeFilePart(value) {
1434
- return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1435
- }
1436
- }
1437
- });
1438
-
1439
1932
  // ../packages/tool-kit/out/stateStore.js
1440
1933
  var require_stateStore = __commonJS({
1441
1934
  "../packages/tool-kit/out/stateStore.js"(exports) {
@@ -1815,9 +2308,9 @@ var require_outbox = __commonJS({
1815
2308
  }
1816
2309
  });
1817
2310
 
1818
- // ../packages/tool-kit/out/backgroundDelivery.js
1819
- var require_backgroundDelivery = __commonJS({
1820
- "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
2311
+ // ../packages/tool-kit/out/hookRunner.js
2312
+ var require_hookRunner = __commonJS({
2313
+ "../packages/tool-kit/out/hookRunner.js"(exports) {
1821
2314
  "use strict";
1822
2315
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1823
2316
  if (k2 === void 0) k2 = k;
@@ -1857,94 +2350,615 @@ var require_backgroundDelivery = __commonJS({
1857
2350
  };
1858
2351
  }();
1859
2352
  Object.defineProperty(exports, "__esModule", { value: true });
1860
- exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
1861
- exports.hookDeliveryInline = hookDeliveryInline;
1862
- exports.flushLockPath = flushLockPath;
1863
- exports.startBackgroundFlush = startBackgroundFlush;
1864
- exports.runOutboxFlush = runOutboxFlush;
1865
- var fs = __importStar(__require("fs"));
2353
+ exports.hookRunnerPaths = hookRunnerPaths;
2354
+ exports.hookLauncherScript = hookLauncherScript;
2355
+ exports.isDowngrade = isDowngrade;
2356
+ exports.installHookRunner = installHookRunner;
2357
+ exports.removeHookRunner = removeHookRunner;
2358
+ exports.hookRunnerCommand = hookRunnerCommand;
2359
+ exports.writeAtomically = writeAtomically;
2360
+ exports.lastHookPath = lastHookPath;
2361
+ exports.stampLastHook = stampLastHook;
2362
+ exports.readLastHook = readLastHook;
2363
+ exports.describeAge = describeAge;
2364
+ exports.resolveHookNode = resolveHookNode;
2365
+ exports.tidyHomePath = tidyHomePath;
1866
2366
  var child_process_1 = __require("child_process");
1867
- var outbox_1 = require_outbox();
1868
- exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
1869
- exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
1870
- exports.FLUSH_LOCK_FRESH_MS = 2e4;
1871
- var FLUSH_MAX_PASSES = 20;
1872
- var FLUSH_MAX_RUN_MS = 6e4;
1873
- function hookDeliveryInline(env = process.env) {
1874
- return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
1875
- }
1876
- function flushLockPath(outboxFilePath) {
1877
- return `${outboxFilePath}.flushing`;
1878
- }
1879
- function lockIsFresh(lockPath, now) {
1880
- try {
1881
- return now - fs.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1882
- } catch {
1883
- return false;
1884
- }
1885
- }
1886
- function touchLock(lockPath) {
1887
- try {
1888
- fs.writeFileSync(lockPath, `${process.pid}
1889
- `, { encoding: "utf8", mode: 384 });
1890
- } catch {
1891
- }
1892
- }
1893
- function removeLock(lockPath) {
1894
- try {
1895
- fs.unlinkSync(lockPath);
1896
- } catch {
1897
- }
1898
- }
1899
- function outboxHasEntries(outboxFilePath) {
1900
- try {
1901
- return fs.statSync(outboxFilePath).size > 0;
1902
- } catch {
1903
- return false;
1904
- }
1905
- }
1906
- function startBackgroundFlush(options) {
1907
- const lockPath = flushLockPath(options.outboxFilePath);
1908
- const now = options.now ?? Date.now();
1909
- if (lockIsFresh(lockPath, now))
1910
- return false;
1911
- const script = options.script ?? process.argv[1];
1912
- if (!script)
1913
- return false;
1914
- try {
1915
- touchLock(lockPath);
1916
- const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
1917
- detached: true,
1918
- stdio: "ignore",
1919
- windowsHide: true,
1920
- env: process.env
1921
- });
1922
- child.on("error", () => removeLock(lockPath));
1923
- child.unref();
1924
- return true;
1925
- } catch {
1926
- removeLock(lockPath);
1927
- return false;
1928
- }
2367
+ var fs = __importStar(__require("fs"));
2368
+ var path = __importStar(__require("path"));
2369
+ var collectorVersion_1 = require_collectorVersion();
2370
+ var tokenStore_1 = require_tokenStore();
2371
+ function hookRunnerPaths(binaryName) {
2372
+ const launcher = path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
2373
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
1929
2374
  }
1930
- async function runOutboxFlush(sender, now = Date.now) {
1931
- const outboxFilePath = sender.outboxFilePath();
1932
- const lockPath = flushLockPath(outboxFilePath);
1933
- const started = now();
1934
- let last;
1935
- let passes = 0;
1936
- const drain = async () => {
1937
- while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
1938
- passes += 1;
1939
- touchLock(lockPath);
1940
- last = await sender.flushOutbox();
1941
- if (!last || last.found === 0 || last.halted || !last.sendEnabled)
1942
- return;
1943
- if (last.delivered === 0 && last.discarded === 0)
1944
- return;
1945
- }
1946
- };
1947
- try {
2375
+ var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
2376
+ function hookLauncherScript(options) {
2377
+ const { binaryName, setupCommand, loudEvent } = options;
2378
+ return [
2379
+ "#!/bin/sh",
2380
+ `# Ascenda hook launcher (${binaryName}). Written by \`setup\`, replaced by the`,
2381
+ "# next one; edits here are lost. Finds a Node to run the hook bundle beside it.",
2382
+ "",
2383
+ 'dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 0',
2384
+ `bundle="$dir/${binaryName}.mjs"`,
2385
+ `record="$dir/${binaryName}.node"`,
2386
+ `missing="$dir/${binaryName}.no-node"`,
2387
+ "",
2388
+ 'runs() { [ -n "$1" ] && [ -f "$1" ] && [ -x "$1" ]; }',
2389
+ "",
2390
+ "# The hook bundle needs Node 20 or newer. Checked only while searching, so",
2391
+ "# the recorded path costs nothing to reuse.",
2392
+ "recent() {",
2393
+ ` runs "$1" && "$1" -e 'process.exit(parseInt(process.versions.node, 10) >= 20 ? 0 : 1)' >/dev/null 2>&1`,
2394
+ "}",
2395
+ "",
2396
+ "newest_nvm() {",
2397
+ ' [ -d "$HOME/.nvm/versions/node" ] || return 0',
2398
+ ` ls "$HOME/.nvm/versions/node" 2>/dev/null | sed 's/^v//' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1 | sed 's/^/v/'`,
2399
+ "}",
2400
+ "",
2401
+ 'node=""',
2402
+ "how=recorded",
2403
+ '[ -r "$record" ] && IFS= read -r node < "$record"',
2404
+ "",
2405
+ 'if ! runs "$node"; then',
2406
+ ' node=""',
2407
+ " how=found",
2408
+ ' nvm_default=""',
2409
+ ' if [ -r "$HOME/.nvm/alias/default" ]; then',
2410
+ ' IFS= read -r wanted < "$HOME/.nvm/alias/default"',
2411
+ " wanted=${wanted#v}",
2412
+ ' for candidate in "$HOME/.nvm/versions/node/v$wanted"*; do',
2413
+ ' [ -x "$candidate/bin/node" ] && nvm_default="$candidate/bin/node"',
2414
+ " done",
2415
+ " fi",
2416
+ " nvm_newest=$(newest_nvm)",
2417
+ " for candidate in \\",
2418
+ ' "$(command -v node 2>/dev/null)" \\',
2419
+ " /opt/homebrew/bin/node \\",
2420
+ " /usr/local/bin/node \\",
2421
+ ' "$HOME/.volta/bin/node" \\',
2422
+ ' "$nvm_default" \\',
2423
+ ' "$HOME/.local/share/fnm/aliases/default/bin/node" \\',
2424
+ ' "$HOME/Library/Application Support/fnm/aliases/default/bin/node" \\',
2425
+ ' "$HOME/.asdf/shims/node" \\',
2426
+ ' "$HOME/.local/share/mise/shims/node" \\',
2427
+ ' "$HOME/.nvm/versions/node/$nvm_newest/bin/node"',
2428
+ " do",
2429
+ ' if recent "$candidate"; then node=$candidate; break; fi',
2430
+ " done",
2431
+ ' if [ -n "$node" ]; then',
2432
+ ` printf '%s\\n' "$node" > "$record.$$" 2>/dev/null && mv -f "$record.$$" "$record" 2>/dev/null`,
2433
+ ' rm -f "$missing" 2>/dev/null',
2434
+ " fi",
2435
+ "fi",
2436
+ "",
2437
+ 'if [ -n "$ASCENDA_HOOK_LAUNCHER_PROBE" ]; then',
2438
+ ' [ -n "$node" ] || { echo "no Node 20 or newer found on PATH or in the usual install locations" >&2; exit 1; }',
2439
+ ` printf '%s\\t%s\\n' "$node" "$how"`,
2440
+ " exit 0",
2441
+ "fi",
2442
+ "",
2443
+ 'if [ -z "$node" ]; then',
2444
+ ' date -u +%Y-%m-%dT%H:%M:%SZ > "$missing" 2>/dev/null',
2445
+ ' case "$1" in',
2446
+ ...loudEvent ? [
2447
+ ` ${loudEvent})`,
2448
+ " cat >/dev/null 2>&1",
2449
+ ` echo "Ascenda hooks cannot find Node 20 or newer, so none of them are running. Install Node, then run: ${setupCommand}" >&2`,
2450
+ " exit 1 ;;"
2451
+ ] : [],
2452
+ ` ${LAUNCHER_MANAGEMENT_COMMANDS.join("|")})`,
2453
+ ` echo "${binaryName}: no Node 20 or newer found on PATH or in the usual install locations." >&2`,
2454
+ " exit 1 ;;",
2455
+ " *)",
2456
+ " # A hook: say nothing per tool call. status and doctor read the",
2457
+ " # file written above.",
2458
+ " cat >/dev/null 2>&1",
2459
+ " exit 0 ;;",
2460
+ " esac",
2461
+ "fi",
2462
+ "",
2463
+ 'exec "$node" "$bundle" "$@"',
2464
+ ""
2465
+ ].join("\n");
2466
+ }
2467
+ function releaseOf(version2) {
2468
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version2 ?? "").trim());
2469
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
2470
+ }
2471
+ function isDowngrade(installed, incoming) {
2472
+ const have = releaseOf(installed);
2473
+ const want = releaseOf(incoming);
2474
+ if (!have || !want)
2475
+ return false;
2476
+ for (let i = 0; i < 3; i++) {
2477
+ if (have[i] !== want[i])
2478
+ return have[i] > want[i];
2479
+ }
2480
+ return false;
2481
+ }
2482
+ function readInstalledVersion(file) {
2483
+ try {
2484
+ return fs.readFileSync(file, "utf8").trim() || void 0;
2485
+ } catch {
2486
+ return void 0;
2487
+ }
2488
+ }
2489
+ function installHookRunner(options) {
2490
+ const paths = hookRunnerPaths(options.binaryName);
2491
+ if (options.dryRun)
2492
+ return paths.launcher;
2493
+ const source = path.resolve(options.source ?? process.argv[1]);
2494
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
2495
+ const installed = readInstalledVersion(paths.version);
2496
+ const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
2497
+ if (installed && fs.existsSync(installedFile) && isDowngrade(installed, incoming)) {
2498
+ options.onKeptNewer?.(installed, incoming);
2499
+ if (process.platform !== "win32" && !fs.existsSync(paths.launcher))
2500
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
2501
+ return paths.launcher;
2502
+ }
2503
+ fs.mkdirSync(path.dirname(paths.launcher), { recursive: true });
2504
+ if (process.platform === "win32") {
2505
+ if (source !== path.resolve(paths.launcher))
2506
+ fs.copyFileSync(source, paths.launcher);
2507
+ writeAtomically(paths.version, `${incoming}
2508
+ `, 420);
2509
+ return paths.launcher;
2510
+ }
2511
+ if (source !== path.resolve(paths.bundle))
2512
+ writeAtomically(paths.bundle, fs.readFileSync(source), 493);
2513
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
2514
+ writeAtomically(paths.record, `${process.execPath}
2515
+ `, 420);
2516
+ if (source !== path.resolve(paths.bundle))
2517
+ writeAtomically(paths.version, `${incoming}
2518
+ `, 420);
2519
+ fs.rmSync(paths.noNode, { force: true });
2520
+ return paths.launcher;
2521
+ }
2522
+ function removeHookRunner(binaryName) {
2523
+ const removed = [];
2524
+ for (const file of Object.values(hookRunnerPaths(binaryName))) {
2525
+ if (!fs.existsSync(file))
2526
+ continue;
2527
+ fs.rmSync(file, { force: true });
2528
+ removed.push(file);
2529
+ }
2530
+ return removed;
2531
+ }
2532
+ function hookRunnerCommand(launcher, platform = process.platform) {
2533
+ return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
2534
+ }
2535
+ function writeAtomically(target, contents, mode) {
2536
+ const tmp = `${target}.${process.pid}.tmp`;
2537
+ fs.writeFileSync(tmp, contents, { mode });
2538
+ fs.chmodSync(tmp, mode);
2539
+ fs.renameSync(tmp, target);
2540
+ }
2541
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join((0, tokenStore_1.ascendaHome)(), "state");
2542
+ function lastHookPath(tool) {
2543
+ return path.join(stateDir(), `${tool}-last-hook.json`);
2544
+ }
2545
+ function stampLastHook(tool, event, now = /* @__PURE__ */ new Date()) {
2546
+ try {
2547
+ fs.mkdirSync(stateDir(), { recursive: true });
2548
+ const file = lastHookPath(tool);
2549
+ const tmp = `${file}.${process.pid}.tmp`;
2550
+ fs.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
2551
+ `, { mode: 384 });
2552
+ fs.renameSync(tmp, file);
2553
+ } catch {
2554
+ }
2555
+ }
2556
+ function readLastHook(tool) {
2557
+ try {
2558
+ const parsed = JSON.parse(fs.readFileSync(lastHookPath(tool), "utf8"));
2559
+ if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
2560
+ return void 0;
2561
+ return { event: parsed.event, at: parsed.at };
2562
+ } catch {
2563
+ return void 0;
2564
+ }
2565
+ }
2566
+ function describeAge(ms) {
2567
+ if (!Number.isFinite(ms) || ms < 0)
2568
+ return "just now";
2569
+ const seconds = Math.round(ms / 1e3);
2570
+ if (seconds < 60)
2571
+ return `${seconds} s ago`;
2572
+ const minutes = Math.round(seconds / 60);
2573
+ if (minutes < 60)
2574
+ return `${minutes} min ago`;
2575
+ const hours = Math.round(minutes / 60);
2576
+ if (hours < 48)
2577
+ return `${hours} h ago`;
2578
+ return `${Math.round(hours / 24)} days ago`;
2579
+ }
2580
+ function resolveHookNode(launcher) {
2581
+ if (!fs.existsSync(launcher))
2582
+ return { problem: "the hook launcher is not installed" };
2583
+ const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
2584
+ encoding: "utf8",
2585
+ timeout: 5e3,
2586
+ env: { HOME: process.env.HOME ?? "", PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ASCENDA_HOOK_LAUNCHER_PROBE: "1" }
2587
+ });
2588
+ const [node, how] = (probe.stdout ?? "").trim().split(" ");
2589
+ if (probe.status !== 0 || !node) {
2590
+ return { problem: (probe.stderr ?? "").trim() || "the launcher found no Node it can run" };
2591
+ }
2592
+ const version2 = (0, child_process_1.spawnSync)(node, ["--version"], { encoding: "utf8", timeout: 5e3 });
2593
+ if (version2.status !== 0)
2594
+ return { node, how, problem: `${node} did not run` };
2595
+ return { node, how, version: version2.stdout.trim() };
2596
+ }
2597
+ function tidyHomePath(file, home = process.env.HOME ?? "") {
2598
+ return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
2599
+ }
2600
+ }
2601
+ });
2602
+
2603
+ // ../packages/tool-kit/out/releaseCheck.js
2604
+ var require_releaseCheck = __commonJS({
2605
+ "../packages/tool-kit/out/releaseCheck.js"(exports) {
2606
+ "use strict";
2607
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2608
+ if (k2 === void 0) k2 = k;
2609
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2610
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2611
+ desc = { enumerable: true, get: function() {
2612
+ return m[k];
2613
+ } };
2614
+ }
2615
+ Object.defineProperty(o, k2, desc);
2616
+ } : function(o, m, k, k2) {
2617
+ if (k2 === void 0) k2 = k;
2618
+ o[k2] = m[k];
2619
+ });
2620
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2621
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2622
+ } : function(o, v) {
2623
+ o["default"] = v;
2624
+ });
2625
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2626
+ var ownKeys = function(o) {
2627
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2628
+ var ar = [];
2629
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2630
+ return ar;
2631
+ };
2632
+ return ownKeys(o);
2633
+ };
2634
+ return function(mod) {
2635
+ if (mod && mod.__esModule) return mod;
2636
+ var result = {};
2637
+ if (mod != null) {
2638
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2639
+ }
2640
+ __setModuleDefault(result, mod);
2641
+ return result;
2642
+ };
2643
+ }();
2644
+ Object.defineProperty(exports, "__esModule", { value: true });
2645
+ exports.RELEASE_CHECK_RETRY_MS = exports.RELEASE_CHECK_INTERVAL_MS = exports.RELEASE_CHECK_ENV_VAR = exports.RELEASE_MANIFEST_URL = void 0;
2646
+ exports.releaseCheckDisabled = releaseCheckDisabled;
2647
+ exports.releaseCheckPath = releaseCheckPath;
2648
+ exports.readReleaseCheck = readReleaseCheck;
2649
+ exports.compareReleases = compareReleases;
2650
+ exports.releaseStanding = releaseStanding;
2651
+ exports.refreshReleaseCheck = refreshReleaseCheck;
2652
+ exports.runsFromInstalledBundle = runsFromInstalledBundle;
2653
+ exports.pendingReleaseNotice = pendingReleaseNotice;
2654
+ exports.describeReleaseCheck = describeReleaseCheck;
2655
+ exports.installedBundleVersion = installedBundleVersion;
2656
+ var fs = __importStar(__require("fs"));
2657
+ var path = __importStar(__require("path"));
2658
+ var collectorVersion_1 = require_collectorVersion();
2659
+ var hookRunner_1 = require_hookRunner();
2660
+ var tokenStore_1 = require_tokenStore();
2661
+ exports.RELEASE_MANIFEST_URL = "https://github.com/ascendaone-com/ai-engineer-tools/releases/latest/download/manifest.json";
2662
+ exports.RELEASE_CHECK_ENV_VAR = "ASCENDA_DISABLE_UPDATE_CHECK";
2663
+ exports.RELEASE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2664
+ exports.RELEASE_CHECK_RETRY_MS = 60 * 60 * 1e3;
2665
+ var FETCH_TIMEOUT_MS = 3e3;
2666
+ var SUMMARY_MAX_CHARS = 200;
2667
+ function releaseCheckDisabled(env = process.env) {
2668
+ return env[exports.RELEASE_CHECK_ENV_VAR]?.trim().toLowerCase() === "true";
2669
+ }
2670
+ function releaseCheckPath() {
2671
+ return path.join((0, tokenStore_1.ascendaHome)(), "state", "release-check.json");
2672
+ }
2673
+ function readReleaseCheck(file = releaseCheckPath()) {
2674
+ try {
2675
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
2676
+ return parsed && typeof parsed === "object" ? parsed : void 0;
2677
+ } catch {
2678
+ return void 0;
2679
+ }
2680
+ }
2681
+ function writeReleaseCheck(file, check2) {
2682
+ try {
2683
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2684
+ (0, hookRunner_1.writeAtomically)(file, `${JSON.stringify(check2, null, 2)}
2685
+ `, 384);
2686
+ } catch {
2687
+ }
2688
+ }
2689
+ function parseRelease(version2) {
2690
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec((version2 ?? "").trim());
2691
+ if (!match)
2692
+ return void 0;
2693
+ return { core: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] };
2694
+ }
2695
+ function compareReleases(a, b) {
2696
+ const left = parseRelease(a);
2697
+ const right = parseRelease(b);
2698
+ if (!left || !right)
2699
+ return void 0;
2700
+ for (let i = 0; i < 3; i++) {
2701
+ if (left.core[i] !== right.core[i])
2702
+ return left.core[i] - right.core[i];
2703
+ }
2704
+ if (left.pre === right.pre)
2705
+ return 0;
2706
+ if (left.pre === void 0)
2707
+ return 1;
2708
+ if (right.pre === void 0)
2709
+ return -1;
2710
+ return left.pre < right.pre ? -1 : 1;
2711
+ }
2712
+ function releaseStanding(installed, check2) {
2713
+ const latest = check2?.latestVersion;
2714
+ if (!latest)
2715
+ return void 0;
2716
+ const floor = check2.minCollectorVersion;
2717
+ const belowFloor = floor !== void 0 && (compareReleases(installed, floor) ?? 0) < 0;
2718
+ if (belowFloor)
2719
+ return { kind: "unsupported", latest, floor };
2720
+ const behind = compareReleases(installed, latest);
2721
+ if (behind === void 0)
2722
+ return void 0;
2723
+ return behind < 0 ? { kind: "behind", latest } : { kind: "current", latest };
2724
+ }
2725
+ async function refreshReleaseCheck(options = {}) {
2726
+ const file = options.file ?? releaseCheckPath();
2727
+ const now = options.now ?? Date.now();
2728
+ const installed = options.installed ?? collectorVersion_1.COLLECTOR_VERSION;
2729
+ const previous = readReleaseCheck(file);
2730
+ if (releaseCheckDisabled(options.env) || installed === collectorVersion_1.UNRELEASED_COLLECTOR_VERSION)
2731
+ return previous;
2732
+ const since = (stamp) => {
2733
+ const at = stamp ? Date.parse(stamp) : NaN;
2734
+ return Number.isFinite(at) ? now - at : Infinity;
2735
+ };
2736
+ if (since(previous?.checkedAt) < exports.RELEASE_CHECK_INTERVAL_MS)
2737
+ return previous;
2738
+ if (since(previous?.attemptedAt) < exports.RELEASE_CHECK_RETRY_MS)
2739
+ return previous;
2740
+ const attemptedAt = new Date(now).toISOString();
2741
+ const fetched = await fetchManifest(options.fetchImpl ?? fetch);
2742
+ const next = fetched ? { ...previous, ...fetched, checkedAt: attemptedAt, attemptedAt } : { ...previous, attemptedAt };
2743
+ writeReleaseCheck(file, next);
2744
+ return next;
2745
+ }
2746
+ async function fetchManifest(fetchImpl) {
2747
+ try {
2748
+ const response = await fetchImpl(exports.RELEASE_MANIFEST_URL, {
2749
+ headers: { accept: "application/json" },
2750
+ redirect: "follow",
2751
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
2752
+ });
2753
+ if (!response.ok)
2754
+ return void 0;
2755
+ const manifest = await response.json();
2756
+ const latestVersion = typeof manifest.version === "string" && parseRelease(manifest.version) ? manifest.version : void 0;
2757
+ if (!latestVersion)
2758
+ return void 0;
2759
+ const floor = manifest.compatibility?.minCollectorVersion;
2760
+ const summary = typeof manifest.summary === "string" ? manifest.summary.trim() : "";
2761
+ return {
2762
+ latestVersion,
2763
+ ...summary && summary.length <= SUMMARY_MAX_CHARS ? { latestSummary: summary } : {},
2764
+ ...typeof floor === "string" && parseRelease(floor) ? { minCollectorVersion: floor } : {},
2765
+ ...typeof manifest.minNode === "number" ? { minNode: manifest.minNode } : {}
2766
+ };
2767
+ } catch {
2768
+ return void 0;
2769
+ }
2770
+ }
2771
+ function runsFromInstalledBundle(script = process.argv[1]) {
2772
+ if (!script)
2773
+ return false;
2774
+ return path.dirname(path.resolve(script)) === path.join((0, tokenStore_1.ascendaHome)(), "bin");
2775
+ }
2776
+ function pendingReleaseNotice(options) {
2777
+ if (releaseCheckDisabled(options.env))
2778
+ return void 0;
2779
+ const installed = options.installed ?? collectorVersion_1.COLLECTOR_VERSION;
2780
+ if (installed === collectorVersion_1.UNRELEASED_COLLECTOR_VERSION)
2781
+ return void 0;
2782
+ const file = options.file ?? releaseCheckPath();
2783
+ const check2 = readReleaseCheck(file);
2784
+ const standing = releaseStanding(installed, check2);
2785
+ if (!check2 || !standing || standing.kind === "current")
2786
+ return void 0;
2787
+ if (standing.kind === "behind" && check2.notifiedFor === standing.latest)
2788
+ return void 0;
2789
+ const nodeMajor = options.nodeMajor ?? Number(process.versions.node.split(".")[0]);
2790
+ const node = check2.minNode !== void 0 && nodeMajor < check2.minNode ? ` ${standing.latest} needs Node ${check2.minNode} or newer and these hooks run on Node ${nodeMajor}, so update Node first.` : "";
2791
+ const run = `Run \`${options.setupCommand}\`, then restart ${options.agentName}.`;
2792
+ const news = standing.kind === "behind" && check2.latestSummary ? ` What's new: ${check2.latestSummary}` : "";
2793
+ const text = standing.kind === "unsupported" ? `Ascenda note: the Ascenda hooks here are ${installed}, older than the oldest supported release (${standing.floor}). ${run}${node} This note repeats each session until they're updated.` : `Ascenda note: the Ascenda hooks here are ${installed}, and ${standing.latest} is out.${news} ${run}${node} This note appears once per release.`;
2794
+ return {
2795
+ text,
2796
+ markShown: () => {
2797
+ if (standing.kind !== "behind")
2798
+ return;
2799
+ writeReleaseCheck(file, { ...readReleaseCheck(file), notifiedFor: standing.latest });
2800
+ }
2801
+ };
2802
+ }
2803
+ function describeReleaseCheck(options) {
2804
+ if (options.localOnly)
2805
+ return "\u2014 not checked: an unpaired install makes no network requests";
2806
+ if (releaseCheckDisabled(options.env))
2807
+ return `\u2014 not checked: ${exports.RELEASE_CHECK_ENV_VAR} is set`;
2808
+ const check2 = readReleaseCheck(options.file);
2809
+ if (!check2?.latestVersion || !check2.checkedAt)
2810
+ return "\u2014 not checked yet; the background sender checks once a day";
2811
+ const age = (0, hookRunner_1.describeAge)((options.now ?? Date.now()) - Date.parse(check2.checkedAt));
2812
+ const standing = releaseStanding(options.installed, check2);
2813
+ if (!standing)
2814
+ return `${check2.latestVersion} (checked ${age})`;
2815
+ if (standing.kind === "current")
2816
+ return `${check2.latestVersion}, up to date (checked ${age})`;
2817
+ const below = standing.kind === "unsupported" ? `, and ${options.installed} is below the oldest supported release (${standing.floor})` : "";
2818
+ const news = check2.latestSummary ? ` What's new: ${check2.latestSummary}` : "";
2819
+ return `${check2.latestVersion} (checked ${age})${below}.${news} Update: ${options.setupCommand}`;
2820
+ }
2821
+ function installedBundleVersion(versionFile) {
2822
+ try {
2823
+ return fs.readFileSync(versionFile, "utf8").trim() || void 0;
2824
+ } catch {
2825
+ return void 0;
2826
+ }
2827
+ }
2828
+ }
2829
+ });
2830
+
2831
+ // ../packages/tool-kit/out/backgroundDelivery.js
2832
+ var require_backgroundDelivery = __commonJS({
2833
+ "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
2834
+ "use strict";
2835
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2836
+ if (k2 === void 0) k2 = k;
2837
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2838
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2839
+ desc = { enumerable: true, get: function() {
2840
+ return m[k];
2841
+ } };
2842
+ }
2843
+ Object.defineProperty(o, k2, desc);
2844
+ } : function(o, m, k, k2) {
2845
+ if (k2 === void 0) k2 = k;
2846
+ o[k2] = m[k];
2847
+ });
2848
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2849
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2850
+ } : function(o, v) {
2851
+ o["default"] = v;
2852
+ });
2853
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2854
+ var ownKeys = function(o) {
2855
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2856
+ var ar = [];
2857
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2858
+ return ar;
2859
+ };
2860
+ return ownKeys(o);
2861
+ };
2862
+ return function(mod) {
2863
+ if (mod && mod.__esModule) return mod;
2864
+ var result = {};
2865
+ if (mod != null) {
2866
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2867
+ }
2868
+ __setModuleDefault(result, mod);
2869
+ return result;
2870
+ };
2871
+ }();
2872
+ Object.defineProperty(exports, "__esModule", { value: true });
2873
+ exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
2874
+ exports.hookDeliveryInline = hookDeliveryInline;
2875
+ exports.flushLockPath = flushLockPath;
2876
+ exports.startBackgroundFlush = startBackgroundFlush;
2877
+ exports.runOutboxFlush = runOutboxFlush;
2878
+ var fs = __importStar(__require("fs"));
2879
+ var child_process_1 = __require("child_process");
2880
+ var outbox_1 = require_outbox();
2881
+ var releaseCheck_1 = require_releaseCheck();
2882
+ exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
2883
+ exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
2884
+ exports.FLUSH_LOCK_FRESH_MS = 2e4;
2885
+ var FLUSH_MAX_PASSES = 20;
2886
+ var FLUSH_MAX_RUN_MS = 6e4;
2887
+ function hookDeliveryInline(env = process.env) {
2888
+ return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
2889
+ }
2890
+ function flushLockPath(outboxFilePath) {
2891
+ return `${outboxFilePath}.flushing`;
2892
+ }
2893
+ function lockIsFresh(lockPath, now) {
2894
+ try {
2895
+ return now - fs.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
2896
+ } catch {
2897
+ return false;
2898
+ }
2899
+ }
2900
+ function touchLock(lockPath) {
2901
+ try {
2902
+ fs.writeFileSync(lockPath, `${process.pid}
2903
+ `, { encoding: "utf8", mode: 384 });
2904
+ } catch {
2905
+ }
2906
+ }
2907
+ function removeLock(lockPath) {
2908
+ try {
2909
+ fs.unlinkSync(lockPath);
2910
+ } catch {
2911
+ }
2912
+ }
2913
+ function outboxHasEntries(outboxFilePath) {
2914
+ try {
2915
+ return fs.statSync(outboxFilePath).size > 0;
2916
+ } catch {
2917
+ return false;
2918
+ }
2919
+ }
2920
+ function startBackgroundFlush(options) {
2921
+ const lockPath = flushLockPath(options.outboxFilePath);
2922
+ const now = options.now ?? Date.now();
2923
+ if (lockIsFresh(lockPath, now))
2924
+ return false;
2925
+ const script = options.script ?? process.argv[1];
2926
+ if (!script)
2927
+ return false;
2928
+ try {
2929
+ touchLock(lockPath);
2930
+ const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
2931
+ detached: true,
2932
+ stdio: "ignore",
2933
+ windowsHide: true,
2934
+ env: process.env
2935
+ });
2936
+ child.on("error", () => removeLock(lockPath));
2937
+ child.unref();
2938
+ return true;
2939
+ } catch {
2940
+ removeLock(lockPath);
2941
+ return false;
2942
+ }
2943
+ }
2944
+ async function runOutboxFlush(sender, now = Date.now) {
2945
+ const outboxFilePath = sender.outboxFilePath();
2946
+ const lockPath = flushLockPath(outboxFilePath);
2947
+ const started = now();
2948
+ let last;
2949
+ let passes = 0;
2950
+ const drain = async () => {
2951
+ while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
2952
+ passes += 1;
2953
+ touchLock(lockPath);
2954
+ last = await sender.flushOutbox();
2955
+ if (!last || last.found === 0 || last.halted || !last.sendEnabled)
2956
+ return;
2957
+ if (last.delivered === 0 && last.discarded === 0)
2958
+ return;
2959
+ }
2960
+ };
2961
+ try {
1948
2962
  await drain();
1949
2963
  removeLock(lockPath);
1950
2964
  if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
@@ -1955,6 +2969,7 @@ var require_backgroundDelivery = __commonJS({
1955
2969
  } catch {
1956
2970
  removeLock(lockPath);
1957
2971
  }
2972
+ await (0, releaseCheck_1.refreshReleaseCheck)();
1958
2973
  return last;
1959
2974
  }
1960
2975
  }
@@ -2397,6 +3412,8 @@ var require_http = __commonJS({
2397
3412
  exports.createPairingSession = createPairingSession;
2398
3413
  exports.getPairingStatus = getPairingStatus;
2399
3414
  exports.startStudyJoin = startStudyJoin;
3415
+ exports.previewJoinCode = previewJoinCode;
3416
+ exports.startSquadronJoin = startSquadronJoin;
2400
3417
  exports.getStudyJoinStatus = getStudyJoinStatus;
2401
3418
  exports.readInitiatives = readInitiatives;
2402
3419
  exports.readStudyNotices = readStudyNotices;
@@ -2422,27 +3439,52 @@ var require_http = __commonJS({
2422
3439
  async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName, orgJoinCode) {
2423
3440
  const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
2424
3441
  method: "POST",
2425
- headers: { "Content-Type": "application/json" },
2426
- body: JSON.stringify({ toolInstallationId, toolType, displayName, ...orgJoinCode ? { orgJoinCode, mode: "report" } : {} })
3442
+ headers: { "Content-Type": "application/json" },
3443
+ body: JSON.stringify({ toolInstallationId, toolType, displayName, ...orgJoinCode ? { orgJoinCode, mode: "report" } : {} })
3444
+ });
3445
+ if (!response.ok)
3446
+ throw await apiError(response);
3447
+ return await response.json();
3448
+ }
3449
+ async function getPairingStatus(apiBaseUrl, pairingSessionId) {
3450
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
3451
+ method: "GET",
3452
+ headers: { Accept: "application/json" }
3453
+ });
3454
+ if (!response.ok)
3455
+ throw new AscendaApiError(response.status, void 0, await response.text());
3456
+ return await response.json();
3457
+ }
3458
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
3459
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
3460
+ method: "POST",
3461
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
3462
+ body: JSON.stringify({ joinCode, mode })
2427
3463
  });
2428
3464
  if (!response.ok)
2429
3465
  throw await apiError(response);
2430
3466
  return await response.json();
2431
3467
  }
2432
- async function getPairingStatus(apiBaseUrl, pairingSessionId) {
2433
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
3468
+ async function previewJoinCode(apiBaseUrl, joinCode) {
3469
+ const response = await fetch(`${apiBaseUrl}/api/share/join/${encodeURIComponent(joinCode)}`, {
2434
3470
  method: "GET",
2435
3471
  headers: { Accept: "application/json" }
2436
3472
  });
2437
3473
  if (!response.ok)
2438
- throw new AscendaApiError(response.status, void 0, await response.text());
3474
+ throw await apiError(response);
2439
3475
  return await response.json();
2440
3476
  }
2441
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
3477
+ async function startSquadronJoin(apiBaseUrl, eventWriteToken, seat) {
2442
3478
  const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2443
3479
  method: "POST",
2444
3480
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2445
- body: JSON.stringify({ joinCode, mode })
3481
+ body: JSON.stringify({
3482
+ joinCode: seat.joinCode,
3483
+ mode: "jam",
3484
+ handle: seat.handle,
3485
+ ...seat.aircraft ? { aircraft: seat.aircraft } : {},
3486
+ ...seat.colour ? { colour: seat.colour } : {}
3487
+ })
2446
3488
  });
2447
3489
  if (!response.ok)
2448
3490
  throw await apiError(response);
@@ -3944,421 +4986,152 @@ var require_hookAdapter = __commonJS({
3944
4986
  const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
3945
4987
  if (logFile)
3946
4988
  logUnsent(logFile, events, options);
3947
- return;
3948
- }
3949
- let config2;
3950
- try {
3951
- config2 = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
3952
- } catch (error2) {
3953
- if (error2 instanceof MissingInstallationIdError)
3954
- journalSkippedSend(options.host, error2);
3955
- const logFile = (0, eventLog_1.resolveEventLogPath)();
3956
- if (!logFile)
3957
- throw error2;
3958
- logUnsent(logFile, events, options);
3959
- if (!(error2 instanceof MissingInstallationIdError))
3960
- throw error2;
3961
- return;
3962
- }
3963
- const sender = new eventSender_1.AscendaEventSender({
3964
- apiBaseUrl: config2.apiBaseUrl,
3965
- toolInstallationId: config2.toolInstallationId,
3966
- source: options.source,
3967
- eventWriteToken: config2.eventWriteToken,
3968
- tokenFilePath: config2.tokenFilePath,
3969
- sessionId: config2.sessionId,
3970
- workspaceHash: config2.workspaceHash,
3971
- projectHash: config2.projectHash,
3972
- timeoutMs: config2.timeoutMs
3973
- });
3974
- if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
3975
- for (const event of events) {
3976
- const result = await sender.send(event);
3977
- if (result === "accepted")
3978
- continue;
3979
- const message2 = noticeFor(result);
3980
- if (message2)
3981
- notice(message2);
3982
- return;
3983
- }
3984
- return;
3985
- }
3986
- for (const event of events)
3987
- sender.queue(event);
3988
- (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
3989
- const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
3990
- const message = last ? noticeFor(last) : void 0;
3991
- if (message)
3992
- notice(message);
3993
- }
3994
- function noticeFor(result) {
3995
- if (result === "accepted" || result === "duplicate")
3996
- return void 0;
3997
- if (result === "consent_missing")
3998
- return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
3999
- if (result === "auth_failed")
4000
- return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
4001
- if (result === "transport_error")
4002
- return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
4003
- if (result === "outbox_discarded")
4004
- return void 0;
4005
- return `Ascenda telemetry rejected: ${result}`;
4006
- }
4007
- async function flushHookOutbox(options) {
4008
- let config2;
4009
- try {
4010
- config2 = loadCliAgentPairing(options.toolType, options);
4011
- } catch {
4012
- return;
4013
- }
4014
- const sender = new eventSender_1.AscendaEventSender({
4015
- apiBaseUrl: config2.apiBaseUrl,
4016
- toolInstallationId: config2.toolInstallationId,
4017
- source: options.source,
4018
- eventWriteToken: config2.eventWriteToken,
4019
- tokenFilePath: config2.tokenFilePath,
4020
- timeoutMs: config2.timeoutMs
4021
- });
4022
- await (0, backgroundDelivery_1.runOutboxFlush)(sender);
4023
- }
4024
- function logUnsent(logFile, events, options) {
4025
- const contextHashes = resolveContextHashes(options.cwd);
4026
- for (const event of events) {
4027
- (0, eventLog_1.appendEventLog)(logFile, {
4028
- loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
4029
- delivery: "not_sent",
4030
- payload: (0, eventSender_1.buildEventPayload)({
4031
- toolInstallationId: `${options.toolType}:unpaired`,
4032
- source: options.source,
4033
- sessionId: process.env.ASCENDA_SESSION_ID?.trim() || options.sessionId || null,
4034
- workspaceHash: contextHashes.workspaceHash,
4035
- projectHash: contextHashes.projectHash
4036
- }, event)
4037
- });
4038
- }
4039
- }
4040
- function journalSkippedSend(host, error2) {
4041
- const who = host ? `${host}: ` : "";
4042
- (0, stateStore_1.recordSendOutcome)((0, stateStore_1.unresolvedStateFilePath)(error2.toolType), (0, stateStore_1.unresolvedToolInstallationId)(error2.toolType), "skipped_no_installation_id", {
4043
- detail: error2.candidates.length === 0 ? `${who}no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, no ${error2.toolType} token file` : `${who}no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, ${error2.candidates.length} ${error2.toolType} token files (${error2.candidates.join(", ")})`
4044
- });
4045
- }
4046
- function parsePositiveInt(value) {
4047
- const n = Number(value);
4048
- return Number.isInteger(n) && n > 0 ? n : void 0;
4049
- }
4050
- }
4051
- });
4052
-
4053
- // ../packages/tool-kit/out/confirmLinks.js
4054
- var require_confirmLinks = __commonJS({
4055
- "../packages/tool-kit/out/confirmLinks.js"(exports) {
4056
- "use strict";
4057
- Object.defineProperty(exports, "__esModule", { value: true });
4058
- exports.pairingConfirmUrl = pairingConfirmUrl;
4059
- exports.pairingConfirmLines = pairingConfirmLines;
4060
- exports.studyJoinConfirmUrl = studyJoinConfirmUrl;
4061
- function pairingConfirmUrl(qrUrl) {
4062
- return isHttps(qrUrl) ? qrUrl : void 0;
4063
- }
4064
- function pairingConfirmLines(qrUrl, code) {
4065
- const url = pairingConfirmUrl(qrUrl);
4066
- if (!url)
4067
- return [`Confirm in the Ascenda app \u2014 code ${code}`];
4068
- return [`Open this link to confirm: ${url}`, `Or paste code ${code} in the Ascenda app.`];
4069
- }
4070
- function studyJoinConfirmUrl(apiBaseUrl, deviceCode) {
4071
- if (!isHttps(apiBaseUrl))
4072
- return void 0;
4073
- return `${apiBaseUrl.replace(/\/+$/, "")}/join/${encodeURIComponent(deviceCode)}`;
4074
- }
4075
- function isHttps(value) {
4076
- if (!value)
4077
- return false;
4078
- try {
4079
- return new URL(value).protocol === "https:";
4080
- } catch {
4081
- return false;
4082
- }
4083
- }
4084
- }
4085
- });
4086
-
4087
- // ../packages/tool-kit/out/studyJoin.js
4088
- var require_studyJoin = __commonJS({
4089
- "../packages/tool-kit/out/studyJoin.js"(exports) {
4090
- "use strict";
4091
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4092
- if (k2 === void 0) k2 = k;
4093
- var desc = Object.getOwnPropertyDescriptor(m, k);
4094
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4095
- desc = { enumerable: true, get: function() {
4096
- return m[k];
4097
- } };
4098
- }
4099
- Object.defineProperty(o, k2, desc);
4100
- } : function(o, m, k, k2) {
4101
- if (k2 === void 0) k2 = k;
4102
- o[k2] = m[k];
4103
- });
4104
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4105
- Object.defineProperty(o, "default", { enumerable: true, value: v });
4106
- } : function(o, v) {
4107
- o["default"] = v;
4108
- });
4109
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4110
- var ownKeys = function(o) {
4111
- ownKeys = Object.getOwnPropertyNames || function(o2) {
4112
- var ar = [];
4113
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4114
- return ar;
4115
- };
4116
- return ownKeys(o);
4117
- };
4118
- return function(mod) {
4119
- if (mod && mod.__esModule) return mod;
4120
- var result = {};
4121
- if (mod != null) {
4122
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4123
- }
4124
- __setModuleDefault(result, mod);
4125
- return result;
4126
- };
4127
- }();
4128
- Object.defineProperty(exports, "__esModule", { value: true });
4129
- exports.gitOfferLine = gitOfferLine;
4130
- exports.runStudyJoin = runStudyJoin;
4131
- exports.formatWindow = formatWindow;
4132
- exports.describeStudyGrant = describeStudyGrant;
4133
- exports.describeStudyKind = describeStudyKind;
4134
- exports.describeRefusal = describeRefusal;
4135
- var readline = __importStar(__require("node:readline"));
4136
- var confirmLinks_1 = require_confirmLinks();
4137
- var http_1 = require_http();
4138
- function gitOfferLine(optionalImportStores) {
4139
- if (!optionalImportStores?.includes("git"))
4140
- return void 0;
4141
- return "The page also has an unticked box for git history: commit times, size buckets, files changed and whether each is a merge. No messages, paths, names or emails.";
4142
- }
4143
- var STUDY_JOIN_MODE = "report";
4144
- var POLL_INTERVAL_MS = 3e3;
4145
- var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
4146
- async function runStudyJoin(ctx) {
4147
- const report = (outcome) => ctx.onOutcome?.(outcome);
4148
- const stdin = ctx.stdin ?? process.stdin;
4149
- const stdout = ctx.stdout ?? process.stdout;
4150
- const stderr = ctx.stderr ?? process.stderr;
4151
- const print = (line) => stdout.write(`${line}
4152
- `);
4153
- if (!stdin.isTTY || !stdout.isTTY) {
4154
- stderr.write("join needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
4155
- report({ status: "no_terminal", granted: [] });
4156
- return 0;
4157
- }
4158
- if (!ctx.joinCode) {
4159
- stderr.write("Usage: join <code>\n");
4160
- report({ status: "failed", granted: [], message: "No join code given." });
4161
- return 1;
4162
- }
4163
- let start;
4164
- try {
4165
- start = await (0, http_1.startStudyJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, ctx.joinCode, STUDY_JOIN_MODE);
4166
- } catch (error2) {
4167
- stderr.write(`${describeStartError(error2)}
4168
- `);
4169
- report({ status: "failed", granted: [], message: describeStartError(error2) });
4170
- return 1;
4171
- }
4172
- print("");
4173
- print(`${start.organisationName}: ${describeStudyKind(start.studyKind)}`);
4174
- print(formatWindow(start.windowStartUtc, start.windowEndUtc));
4175
- print("");
4176
- print("Report (30 days) grants:");
4177
- for (const grant of start.grants)
4178
- print(` ${describeStudyGrant(grant)}`);
4179
- const gitOffer = gitOfferLine(start.optionalImportStores);
4180
- if (gitOffer)
4181
- print(gitOffer);
4182
- print("");
4183
- print("Study mode needs the Ascenda app. Open the app to join that way instead.");
4184
- print("");
4185
- print("Join in:");
4186
- print(" 1) Report (30 days)");
4187
- print(" 2) Not now");
4188
- print("");
4189
- const answer = await askChoice(stdin, stdout);
4190
- if (!/^(1|report)$/i.test(answer)) {
4191
- print("Not now.");
4192
- report({ status: "not_now", start, granted: [] });
4193
- return 0;
4989
+ return;
4194
4990
  }
4195
- print("");
4196
- const confirmUrl = (0, confirmLinks_1.studyJoinConfirmUrl)(ctx.apiBaseUrl, start.deviceCode);
4197
- if (confirmUrl) {
4198
- print(`Open this link to confirm: ${confirmUrl}`);
4199
- print(`Or confirm in the Ascenda app with code ${start.deviceCode}.`);
4200
- } else {
4201
- print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
4991
+ let config2;
4992
+ try {
4993
+ config2 = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
4994
+ } catch (error2) {
4995
+ if (error2 instanceof MissingInstallationIdError)
4996
+ journalSkippedSend(options.host, error2);
4997
+ const logFile = (0, eventLog_1.resolveEventLogPath)();
4998
+ if (!logFile)
4999
+ throw error2;
5000
+ logUnsent(logFile, events, options);
5001
+ if (!(error2 instanceof MissingInstallationIdError))
5002
+ throw error2;
5003
+ return;
4202
5004
  }
4203
- print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
4204
- const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
4205
- const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
4206
- while (Date.now() < deadline) {
4207
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
4208
- let poll;
4209
- try {
4210
- poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
4211
- } catch (error2) {
4212
- if (isRetryablePollError(error2))
5005
+ const sender = new eventSender_1.AscendaEventSender({
5006
+ apiBaseUrl: config2.apiBaseUrl,
5007
+ toolInstallationId: config2.toolInstallationId,
5008
+ source: options.source,
5009
+ eventWriteToken: config2.eventWriteToken,
5010
+ tokenFilePath: config2.tokenFilePath,
5011
+ sessionId: config2.sessionId,
5012
+ workspaceHash: config2.workspaceHash,
5013
+ projectHash: config2.projectHash,
5014
+ timeoutMs: config2.timeoutMs
5015
+ });
5016
+ if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
5017
+ for (const event of events) {
5018
+ const result = await sender.send(event);
5019
+ if (result === "accepted")
4213
5020
  continue;
4214
- stderr.write(`${describeStartError(error2)}
4215
- `);
4216
- report({ status: "failed", start, granted: [], message: describeStartError(error2) });
4217
- return 1;
4218
- }
4219
- if (poll.status === "pending")
4220
- continue;
4221
- if (poll.status === "confirmed") {
4222
- const granted = poll.granted ?? [];
4223
- if (granted.length === 0) {
4224
- print("");
4225
- print("Nothing was granted. Run join again, or check with your organisation.");
4226
- report({ status: "refused", start, granted: [], message: "Nothing was granted." });
4227
- return 1;
4228
- }
4229
- print("");
4230
- print("Joined. Granted:");
4231
- for (const grant of granted)
4232
- print(` ${describeStudyGrant(grant)}`);
4233
- print("");
4234
- print("Each of these can be turned off separately, in the app's consent settings.");
4235
- print("The organisation sees group counts, never who joined.");
4236
- report({ status: "joined", start, granted, importStores: poll.importStores ?? null });
4237
- return 0;
4238
- }
4239
- if (poll.status === "expired") {
4240
- print("");
4241
- print("This code expired before it was confirmed. Run join again for a fresh code.");
4242
- report({ status: "expired", start, granted: [] });
4243
- return 1;
4244
- }
4245
- if (poll.refusedReason === "grant_failed") {
4246
- print("");
4247
- print("Join failed partway through. Some grants may not have gone through.");
4248
- const granted = poll.granted ?? [];
4249
- if (granted.length > 0) {
4250
- print("");
4251
- print("Granted before the failure:");
4252
- for (const grant of granted)
4253
- print(` ${describeStudyGrant(grant)}`);
4254
- print("");
4255
- print("Each of these can be turned off separately, in the app's consent settings.");
4256
- }
4257
- print("Run join again, or check with your organisation.");
4258
- report({ status: "refused", start, granted, refusedReason: poll.refusedReason, message: describeRefusal(poll.refusedReason), importStores: poll.importStores ?? null });
4259
- return 1;
5021
+ const message2 = noticeFor(result);
5022
+ if (message2)
5023
+ notice(message2);
5024
+ return;
4260
5025
  }
4261
- print("");
4262
- print(describeRefusal(poll.refusedReason));
4263
- report({ status: "refused", start, granted: [], refusedReason: poll.refusedReason, message: describeRefusal(poll.refusedReason) });
4264
- return 1;
5026
+ return;
4265
5027
  }
4266
- print("");
4267
- print("Timed out waiting for confirmation. Run join again for a fresh code.");
4268
- report({ status: "expired", start, granted: [] });
4269
- return 1;
5028
+ for (const event of events)
5029
+ sender.queue(event);
5030
+ (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
5031
+ const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
5032
+ const message = last ? noticeFor(last) : void 0;
5033
+ if (message)
5034
+ notice(message);
4270
5035
  }
4271
- function isRetryablePollError(error2) {
4272
- if (error2 instanceof http_1.AscendaApiError)
4273
- return error2.status >= 500 && error2.status <= 599;
4274
- return true;
5036
+ function noticeFor(result) {
5037
+ if (result === "accepted" || result === "duplicate")
5038
+ return void 0;
5039
+ if (result === "consent_missing")
5040
+ return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
5041
+ if (result === "auth_failed")
5042
+ return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
5043
+ if (result === "transport_error")
5044
+ return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
5045
+ if (result === "outbox_discarded")
5046
+ return void 0;
5047
+ return `Ascenda telemetry rejected: ${result}`;
4275
5048
  }
4276
- function askChoice(stdin, stdout) {
4277
- return new Promise((resolve) => {
4278
- const rl = readline.createInterface({ input: stdin, output: stdout });
4279
- let settled = false;
4280
- const finish = (value) => {
4281
- if (settled)
4282
- return;
4283
- settled = true;
4284
- rl.close();
4285
- resolve(value.trim());
4286
- };
4287
- rl.question("Choice [Not now]: ", finish);
4288
- rl.once("close", () => finish(""));
5049
+ async function flushHookOutbox(options) {
5050
+ let config2;
5051
+ try {
5052
+ config2 = loadCliAgentPairing(options.toolType, options);
5053
+ } catch {
5054
+ return;
5055
+ }
5056
+ const sender = new eventSender_1.AscendaEventSender({
5057
+ apiBaseUrl: config2.apiBaseUrl,
5058
+ toolInstallationId: config2.toolInstallationId,
5059
+ source: options.source,
5060
+ eventWriteToken: config2.eventWriteToken,
5061
+ tokenFilePath: config2.tokenFilePath,
5062
+ timeoutMs: config2.timeoutMs
4289
5063
  });
5064
+ await (0, backgroundDelivery_1.runOutboxFlush)(sender);
4290
5065
  }
4291
- function formatLocalTime(iso) {
4292
- const date3 = new Date(iso);
4293
- if (Number.isNaN(date3.getTime()))
4294
- return iso;
4295
- return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date3);
4296
- }
4297
- function formatWindow(startUtc, endUtc) {
4298
- const start = new Date(startUtc);
4299
- const end = new Date(endUtc);
4300
- const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
4301
- const dayMonth = { day: "numeric", month: "short", timeZone: "UTC" };
4302
- const withYear = { ...dayMonth, year: "numeric" };
4303
- const startFmt = new Intl.DateTimeFormat("en-GB", sameYear ? dayMonth : withYear);
4304
- const endFmt = new Intl.DateTimeFormat("en-GB", withYear);
4305
- return `${startFmt.format(start)} \u2013 ${endFmt.format(end)}`;
5066
+ function logUnsent(logFile, events, options) {
5067
+ const contextHashes = resolveContextHashes(options.cwd);
5068
+ for (const event of events) {
5069
+ (0, eventLog_1.appendEventLog)(logFile, {
5070
+ loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
5071
+ delivery: "not_sent",
5072
+ payload: (0, eventSender_1.buildEventPayload)({
5073
+ toolInstallationId: `${options.toolType}:unpaired`,
5074
+ source: options.source,
5075
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || options.sessionId || null,
5076
+ workspaceHash: contextHashes.workspaceHash,
5077
+ projectHash: contextHashes.projectHash
5078
+ }, event)
5079
+ });
5080
+ }
4306
5081
  }
4307
- var GRANT_SENTENCES = {
4308
- 501: "AI assistant data processing consent",
4309
- 507: "Import of the AI-work history already on your machine"
4310
- };
4311
- function describeStudyGrant(grant) {
4312
- return GRANT_SENTENCES[grant.code] ?? humanise(grant.name);
5082
+ function journalSkippedSend(host, error2) {
5083
+ const who = host ? `${host}: ` : "";
5084
+ (0, stateStore_1.recordSendOutcome)((0, stateStore_1.unresolvedStateFilePath)(error2.toolType), (0, stateStore_1.unresolvedToolInstallationId)(error2.toolType), "skipped_no_installation_id", {
5085
+ detail: error2.candidates.length === 0 ? `${who}no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, no ${error2.toolType} token file` : `${who}no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, ${error2.candidates.length} ${error2.toolType} token files (${error2.candidates.join(", ")})`
5086
+ });
4313
5087
  }
4314
- var STUDY_KIND_SENTENCES = {
4315
- Report30: "a 30-day report",
4316
- Study90: "a 90-day study"
4317
- };
4318
- function describeStudyKind(studyKind) {
4319
- return STUDY_KIND_SENTENCES[studyKind] ?? humanise(studyKind);
5088
+ function parsePositiveInt(value) {
5089
+ const n = Number(value);
5090
+ return Number.isInteger(n) && n > 0 ? n : void 0;
4320
5091
  }
4321
- function humanise(name) {
4322
- return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim() || name;
5092
+ }
5093
+ });
5094
+
5095
+ // ../packages/tool-kit/out/confirmLinks.js
5096
+ var require_confirmLinks = __commonJS({
5097
+ "../packages/tool-kit/out/confirmLinks.js"(exports) {
5098
+ "use strict";
5099
+ Object.defineProperty(exports, "__esModule", { value: true });
5100
+ exports.WEEKLY_POSTER_CONNECT_URL = void 0;
5101
+ exports.pairingConfirmUrl = pairingConfirmUrl;
5102
+ exports.pairingConfirmLines = pairingConfirmLines;
5103
+ exports.studyJoinConfirmUrl = studyJoinConfirmUrl;
5104
+ exports.WEEKLY_POSTER_CONNECT_URL = "https://me.ascendaflow.com/connect";
5105
+ function pairingConfirmUrl(qrUrl) {
5106
+ return isHttps(qrUrl) ? qrUrl : void 0;
4323
5107
  }
4324
- var REFUSED_REASON_MESSAGES = {
4325
- study_no_longer_live: "That study is no longer open to join.",
4326
- withdrawn: "You're no longer an active participant in that study.",
4327
- // Handled as its own branch above, with its granted list, before this
4328
- // table is ever consulted — present so the type stays exhaustive, and as
4329
- // a plain fallback should something call this function with it directly.
4330
- grant_failed: "Join failed partway through. Some grants may not have gone through.",
4331
- declined: "You declined the join. Nothing was granted.",
4332
- not_enrolled: "That study couldn't enrol you, so nothing was granted."
4333
- };
4334
- function describeRefusal(refusedReason) {
4335
- if (refusedReason && REFUSED_REASON_MESSAGES[refusedReason])
4336
- return REFUSED_REASON_MESSAGES[refusedReason];
4337
- return "The join didn't go through. Nothing new was granted.";
5108
+ function pairingConfirmLines(qrUrl, code) {
5109
+ const url = pairingConfirmUrl(qrUrl);
5110
+ const where = [" Ascenda Flow, under Connections \u2192 Ingest telemetry", ` ${exports.WEEKLY_POSTER_CONNECT_URL}, for the weekly poster`];
5111
+ if (!url)
5112
+ return [`Confirm code ${code} in either place:`, ...where];
5113
+ return [`Open this link to confirm: ${url}`, `Or enter code ${code} in either place:`, ...where];
4338
5114
  }
4339
- var START_ERROR_MESSAGES = {
4340
- join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
4341
- unknown_mode: "This tool only offers Report mode from the command line.",
4342
- no_live_study: "There's nothing open to join with that code right now.",
4343
- too_many_open_sessions: "This tool has too many joins waiting to be confirmed. Confirm one, or let one expire, then try again.",
4344
- unknown_session: "That join can no longer be found. Run join again for a fresh code."
4345
- };
4346
- function describeStartError(error2) {
4347
- if (error2 instanceof http_1.AscendaApiError) {
4348
- if (error2.errorCode && START_ERROR_MESSAGES[error2.errorCode])
4349
- return START_ERROR_MESSAGES[error2.errorCode];
4350
- if (error2.status === 401)
4351
- return "This tool's pairing was rejected. Re-pair it, then try again.";
4352
- return `Could not reach the join code (HTTP ${error2.status}).`;
5115
+ function studyJoinConfirmUrl(apiBaseUrl, deviceCode) {
5116
+ if (!isHttps(apiBaseUrl))
5117
+ return void 0;
5118
+ return `${apiBaseUrl.replace(/\/+$/, "")}/join/${encodeURIComponent(deviceCode)}`;
5119
+ }
5120
+ function isHttps(value) {
5121
+ if (!value)
5122
+ return false;
5123
+ try {
5124
+ return new URL(value).protocol === "https:";
5125
+ } catch {
5126
+ return false;
4353
5127
  }
4354
- return error2 instanceof Error ? error2.message : String(error2);
4355
5128
  }
4356
5129
  }
4357
5130
  });
4358
5131
 
4359
- // ../packages/tool-kit/out/pairingStudyJoin.js
4360
- var require_pairingStudyJoin = __commonJS({
4361
- "../packages/tool-kit/out/pairingStudyJoin.js"(exports) {
5132
+ // ../packages/tool-kit/out/studyJoin.js
5133
+ var require_studyJoin = __commonJS({
5134
+ "../packages/tool-kit/out/studyJoin.js"(exports) {
4362
5135
  "use strict";
4363
5136
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4364
5137
  if (k2 === void 0) k2 = k;
@@ -4398,319 +5171,239 @@ var require_pairingStudyJoin = __commonJS({
4398
5171
  };
4399
5172
  }();
4400
5173
  Object.defineProperty(exports, "__esModule", { value: true });
4401
- exports.PAIR_JOIN_OUTCOME_FILE_ENV = exports.PAIR_ORG_JOIN_CODE_ENV = void 0;
4402
- exports.createPairingAttempt = createPairingAttempt;
4403
- exports.pairingAttemptLines = pairingAttemptLines;
4404
- exports.settleStudyJoin = settleStudyJoin;
4405
- exports.writePairingJoinOutcome = writePairingJoinOutcome;
4406
- exports.pairingJoinOutcome = pairingJoinOutcome;
4407
- var fs = __importStar(__require("node:fs"));
5174
+ exports.gitOfferLine = gitOfferLine;
5175
+ exports.runStudyJoin = runStudyJoin;
5176
+ exports.formatWindow = formatWindow;
5177
+ exports.describeStudyGrant = describeStudyGrant;
5178
+ exports.describeStudyKind = describeStudyKind;
5179
+ exports.describeRefusal = describeRefusal;
5180
+ var readline = __importStar(__require("node:readline"));
4408
5181
  var confirmLinks_1 = require_confirmLinks();
4409
- var studyJoin_1 = require_studyJoin();
4410
5182
  var http_1 = require_http();
4411
- exports.PAIR_ORG_JOIN_CODE_ENV = "ASCENDA_PAIR_ORG_JOIN_CODE";
4412
- exports.PAIR_JOIN_OUTCOME_FILE_ENV = "ASCENDA_PAIR_JOIN_OUTCOME_FILE";
4413
- var CREATE_REFUSALS = {
4414
- join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
4415
- no_live_study: "There's nothing open to join with that code right now.",
4416
- unknown_mode: "This tool only offers Report mode from the command line."
4417
- };
4418
- var JOIN_SETTLE_MS = 6e4;
4419
- async function createPairingAttempt(apiBaseUrl, toolInstallationId, toolType, displayName, env = process.env) {
4420
- const orgJoinCode = env[exports.PAIR_ORG_JOIN_CODE_ENV]?.trim();
4421
- if (!orgJoinCode)
4422
- return { session: await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName), carriesJoin: false };
4423
- let refusal;
4424
- try {
4425
- const session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName, orgJoinCode);
4426
- return { session, carriesJoin: session.studyJoin !== void 0 };
4427
- } catch (error2) {
4428
- if (!(error2 instanceof http_1.AscendaApiError) || error2.status >= 500)
4429
- throw error2;
4430
- refusal = error2.errorCode ? CREATE_REFUSALS[error2.errorCode] : void 0;
4431
- }
4432
- return { session: await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName), carriesJoin: false, refusal };
4433
- }
4434
- function pairingAttemptLines(attempt) {
4435
- const { session } = attempt;
4436
- const join = attempt.carriesJoin ? session.studyJoin : void 0;
4437
- if (!join)
4438
- return (0, confirmLinks_1.pairingConfirmLines)(session.qrUrl, session.code);
4439
- const gitOffer = (0, studyJoin_1.gitOfferLine)(join.optionalImportStores);
4440
- return [
4441
- `This also joins ${join.organisationName} (${(0, studyJoin_1.formatWindow)(join.windowStartUtc, join.windowEndUtc)}). The page shows what you'd share before you confirm.`,
4442
- ...gitOffer ? [gitOffer] : [],
4443
- `Open this link to confirm: ${session.qrUrl}`
4444
- ];
4445
- }
4446
- async function settleStudyJoin(apiBaseUrl, pairingSessionId, last, wait = 1e3) {
4447
- let current = last;
4448
- const deadline = Date.now() + JOIN_SETTLE_MS;
4449
- while (current && current.status === "pending" && Date.now() < deadline) {
4450
- await new Promise((resolve) => setTimeout(resolve, wait));
4451
- let status;
4452
- try {
4453
- status = await (0, http_1.getPairingStatus)(apiBaseUrl, pairingSessionId);
4454
- } catch {
4455
- continue;
4456
- }
4457
- current = status.studyJoin ?? current;
4458
- }
4459
- return current;
4460
- }
4461
- function writePairingJoinOutcome(outcome, env = process.env) {
4462
- const file = env[exports.PAIR_JOIN_OUTCOME_FILE_ENV]?.trim();
4463
- if (!file)
4464
- return;
4465
- try {
4466
- fs.writeFileSync(file, `${JSON.stringify(outcome)}
4467
- `, { mode: 384 });
4468
- } catch {
4469
- }
4470
- }
4471
- function pairingJoinOutcome(attempt, pairing, studyJoin) {
4472
- if (!attempt)
4473
- return { join: "none", pairing };
4474
- if (attempt.refusal)
4475
- return { join: "refused", pairing, message: attempt.refusal };
4476
- return { join: attempt.carriesJoin ? "carried" : "not_carried", pairing, studyJoin };
4477
- }
4478
- }
4479
- });
4480
-
4481
- // ../packages/tool-kit/out/hookSet.js
4482
- var require_hookSet = __commonJS({
4483
- "../packages/tool-kit/out/hookSet.js"(exports) {
4484
- "use strict";
4485
- Object.defineProperty(exports, "__esModule", { value: true });
4486
- exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = void 0;
4487
- exports.hookSetArgument = hookSetArgument;
4488
- exports.readHookSet = readHookSet;
4489
- exports.isHookSet = isHookSet;
4490
- exports.readViaPlugin = readViaPlugin;
4491
- exports.hookSetOfCommand = hookSetOfCommand;
4492
- exports.hookSetChanges = hookSetChanges;
4493
- exports.describeHookSetChanges = describeHookSetChanges;
4494
- exports.HOOK_SET_FLAG = "--hook-set";
4495
- exports.UNVERSIONED_HOOK_SET = 1;
4496
- function hookSetArgument(hookSet) {
4497
- return hookSet === void 0 ? "" : ` ${exports.HOOK_SET_FLAG} ${hookSet}`;
4498
- }
4499
- function readHookSet(argv) {
4500
- const index = argv.indexOf(exports.HOOK_SET_FLAG);
4501
- if (index === -1)
4502
- return void 0;
4503
- const raw = argv[index + 1];
4504
- if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
4505
- return void 0;
4506
- const value = Number(raw);
4507
- return isHookSet(value) ? value : void 0;
4508
- }
4509
- function isHookSet(value) {
4510
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
4511
- }
4512
- function readViaPlugin(env) {
4513
- return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
4514
- }
4515
- function hookSetOfCommand(command) {
4516
- const match = command.match(/--hook-set\s+(\d+)/);
4517
- return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
4518
- }
4519
- function hookSetChanges(before, events) {
4520
- const added = events.filter((event) => !before.has(event));
4521
- const sets = [...before.values()];
4522
- return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
4523
- }
4524
- function describeHookSetChanges(changes, hookSet) {
4525
- if (changes.previousSet === void 0)
5183
+ function gitOfferLine(optionalImportStores) {
5184
+ if (!optionalImportStores?.includes("git"))
4526
5185
  return void 0;
4527
- const parts = [];
4528
- if (changes.added.length)
4529
- parts.push(`added ${changes.added.join(", ")}`);
4530
- if (changes.previousSet < hookSet)
4531
- parts.push(`hook set ${changes.previousSet} \u2192 ${hookSet}`);
4532
- return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
5186
+ return "The page also has an unticked box for git history: commit times, size buckets, files changed and whether each is a merge. No messages, paths, names or emails.";
4533
5187
  }
4534
- }
4535
- });
4536
-
4537
- // ../packages/tool-kit/out/initiatives.js
4538
- var require_initiatives = __commonJS({
4539
- "../packages/tool-kit/out/initiatives.js"(exports) {
4540
- "use strict";
4541
- Object.defineProperty(exports, "__esModule", { value: true });
4542
- exports.INITIATIVE_COPY = void 0;
4543
- exports.initiativesStatusLines = initiativesStatusLines;
4544
- exports.renderInitiatives = renderInitiatives;
4545
- var http_1 = require_http();
4546
- var studyJoin_1 = require_studyJoin();
4547
- var READ_TIMEOUT_MS = 5e3;
4548
- exports.INITIATIVE_COPY = {
4549
- outcomes: {
4550
- moved_as_declared: "Moved the way declared, beyond the cohort's own variation",
4551
- moved_against_declared: "Moved the other way, beyond the cohort's own variation",
4552
- moved_no_direction_declared: "Moved beyond the cohort's own variation; no direction was declared",
4553
- within_own_variation: "No further from the baseline than the cohort's own week-to-week variation",
4554
- withheld: "Withheld"
4555
- },
4556
- withheldReasons: {
4557
- cohort_below_minimum: "the cohort was too small to report on when the scoring window closed",
4558
- below_minimum_cohort: "the cohort was too small to report on when the scoring window closed",
4559
- below_minimum_cohort_size: "the cohort was too small to report on when the scoring window closed",
4560
- baseline_withheld: "the baseline was withheld"
5188
+ var STUDY_JOIN_MODE = "report";
5189
+ var POLL_INTERVAL_MS = 3e3;
5190
+ var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
5191
+ async function runStudyJoin(ctx) {
5192
+ const report = (outcome) => ctx.onOutcome?.(outcome);
5193
+ const stdin = ctx.stdin ?? process.stdin;
5194
+ const stdout = ctx.stdout ?? process.stdout;
5195
+ const stderr = ctx.stderr ?? process.stderr;
5196
+ const print = (line) => stdout.write(`${line}
5197
+ `);
5198
+ if (!stdin.isTTY || !stdout.isTTY) {
5199
+ stderr.write("join needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
5200
+ report({ status: "no_terminal", granted: [] });
5201
+ return 0;
4561
5202
  }
4562
- };
4563
- var OUTCOME_EMPTY = "Not stated";
4564
- var OUTCOME_UNKNOWN = "An outcome this app does not recognise";
4565
- var WITHHELD_UNKNOWN = "Withheld, for a reason this version of the app doesn't name yet.";
4566
- var DIRECTION_WORDS = {
4567
- up: "Expected to rise",
4568
- down: "Expected to fall",
4569
- none_declared: "No direction declared"
4570
- };
4571
- var DIRECTION_UNKNOWN = "A direction this app does not recognise";
4572
- async function initiativesStatusLines(ctx) {
4573
- const heading = "Changes your organisation has published to you";
4574
- if (!ctx.eventWriteToken) {
4575
- return [heading, " Not checked: this install holds no token, so nothing was fetched."];
5203
+ if (!ctx.joinCode) {
5204
+ stderr.write("Usage: join <code>\n");
5205
+ report({ status: "failed", granted: [], message: "No join code given." });
5206
+ return 1;
4576
5207
  }
4577
- const read = await (0, http_1.readInitiatives)(ctx.apiBaseUrl, ctx.eventWriteToken, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
4578
- if (read.kind === "rejected") {
4579
- return [
4580
- heading,
4581
- ` Couldn't check: the server turned this install's request down. If that keeps happening, pair again with \`${ctx.pairCommand}\`.`
4582
- ];
5208
+ let start;
5209
+ try {
5210
+ start = await (0, http_1.startStudyJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, ctx.joinCode, STUDY_JOIN_MODE);
5211
+ } catch (error2) {
5212
+ stderr.write(`${describeStartError(error2)}
5213
+ `);
5214
+ report({ status: "failed", granted: [], message: describeStartError(error2) });
5215
+ return 1;
4583
5216
  }
4584
- if (read.kind === "failed") {
4585
- return [heading, ` Couldn't check: ${read.reason}. Run status again to retry.`];
5217
+ print("");
5218
+ print(`${start.organisationName}: ${describeStudyKind(start.studyKind)}`);
5219
+ print(formatWindow(start.windowStartUtc, start.windowEndUtc));
5220
+ print("");
5221
+ print("Report (30 days) grants:");
5222
+ for (const grant of start.grants)
5223
+ print(` ${describeStudyGrant(grant)}`);
5224
+ const gitOffer = gitOfferLine(start.optionalImportStores);
5225
+ if (gitOffer)
5226
+ print(gitOffer);
5227
+ print("");
5228
+ print("Study mode needs the Ascenda app. Open the app to join that way instead.");
5229
+ print("");
5230
+ print("Join in:");
5231
+ print(" 1) Report (30 days)");
5232
+ print(" 2) Not now");
5233
+ print("");
5234
+ const answer = await askChoice(stdin, stdout);
5235
+ if (!/^(1|report)$/i.test(answer)) {
5236
+ print("Not now.");
5237
+ report({ status: "not_now", start, granted: [] });
5238
+ return 0;
5239
+ }
5240
+ print("");
5241
+ const confirmUrl = (0, confirmLinks_1.studyJoinConfirmUrl)(ctx.apiBaseUrl, start.deviceCode);
5242
+ if (confirmUrl) {
5243
+ print(`Open this link to confirm: ${confirmUrl}`);
5244
+ print(`Or confirm in the Ascenda app with code ${start.deviceCode}.`);
5245
+ } else {
5246
+ print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
4586
5247
  }
4587
- return [heading, ...renderInitiatives(read.initiatives)];
4588
- }
4589
- function renderInitiatives(entries, copy = exports.INITIATIVE_COPY) {
4590
- if (entries.length === 0)
4591
- return [" None published to you."];
4592
- const lines = [];
4593
- let unreadable = 0;
4594
- for (const entry of entries) {
4595
- const initiative = asInitiative(entry);
4596
- if (!initiative) {
4597
- unreadable += 1;
5248
+ print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
5249
+ const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
5250
+ const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
5251
+ while (Date.now() < deadline) {
5252
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
5253
+ let poll;
5254
+ try {
5255
+ poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
5256
+ } catch (error2) {
5257
+ if (isRetryablePollError(error2))
5258
+ continue;
5259
+ stderr.write(`${describeStartError(error2)}
5260
+ `);
5261
+ report({ status: "failed", start, granted: [], message: describeStartError(error2) });
5262
+ return 1;
5263
+ }
5264
+ if (poll.status === "pending")
4598
5265
  continue;
5266
+ if (poll.status === "confirmed") {
5267
+ const granted = poll.granted ?? [];
5268
+ if (granted.length === 0) {
5269
+ print("");
5270
+ print("Nothing was granted. Run join again, or check with your organisation.");
5271
+ report({ status: "refused", start, granted: [], message: "Nothing was granted." });
5272
+ return 1;
5273
+ }
5274
+ print("");
5275
+ print("Joined. Granted:");
5276
+ for (const grant of granted)
5277
+ print(` ${describeStudyGrant(grant)}`);
5278
+ print("");
5279
+ print("Each of these can be turned off separately, in the app's consent settings.");
5280
+ print("The organisation sees group counts, never who joined.");
5281
+ report({ status: "joined", start, granted, importStores: poll.importStores ?? null });
5282
+ return 0;
4599
5283
  }
4600
- lines.push(...renderOne(initiative, copy));
4601
- }
4602
- if (unreadable > 0) {
4603
- lines.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
5284
+ if (poll.status === "expired") {
5285
+ print("");
5286
+ print("This code expired before it was confirmed. Run join again for a fresh code.");
5287
+ report({ status: "expired", start, granted: [] });
5288
+ return 1;
5289
+ }
5290
+ if (poll.refusedReason === "grant_failed") {
5291
+ print("");
5292
+ print("Join failed partway through. Some grants may not have gone through.");
5293
+ const granted = poll.granted ?? [];
5294
+ if (granted.length > 0) {
5295
+ print("");
5296
+ print("Granted before the failure:");
5297
+ for (const grant of granted)
5298
+ print(` ${describeStudyGrant(grant)}`);
5299
+ print("");
5300
+ print("Each of these can be turned off separately, in the app's consent settings.");
5301
+ }
5302
+ print("Run join again, or check with your organisation.");
5303
+ report({ status: "refused", start, granted, refusedReason: poll.refusedReason, message: describeRefusal(poll.refusedReason), importStores: poll.importStores ?? null });
5304
+ return 1;
5305
+ }
5306
+ print("");
5307
+ print(describeRefusal(poll.refusedReason));
5308
+ report({ status: "refused", start, granted: [], refusedReason: poll.refusedReason, message: describeRefusal(poll.refusedReason) });
5309
+ return 1;
4604
5310
  }
4605
- return lines;
5311
+ print("");
5312
+ print("Timed out waiting for confirmation. Run join again for a fresh code.");
5313
+ report({ status: "expired", start, granted: [] });
5314
+ return 1;
4606
5315
  }
4607
- function renderOne(initiative, copy) {
4608
- const lines = [` ${initiative.organisationName}: ${initiative.title}`];
4609
- lines.push(` ${describeStatus(initiative)}`);
4610
- if (initiative.summaryForCohort) {
4611
- for (const line of initiative.summaryForCohort.split(/\r?\n/))
4612
- lines.push(` ${line}`);
4613
- }
4614
- if (initiative.direction)
4615
- lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
4616
- lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
4617
- if (initiative.result)
4618
- lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
4619
- lines.push("");
4620
- return lines;
5316
+ function isRetryablePollError(error2) {
5317
+ if (error2 instanceof http_1.AscendaApiError)
5318
+ return error2.status >= 500 && error2.status <= 599;
5319
+ return true;
4621
5320
  }
4622
- function describeStatus(initiative) {
4623
- switch (initiative.status) {
4624
- case "published":
4625
- return "Published, not scored yet.";
4626
- case "scored":
4627
- return "Scored.";
4628
- case "withdrawn":
4629
- return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
4630
- default:
4631
- return "Status not recognised.";
4632
- }
5321
+ function askChoice(stdin, stdout) {
5322
+ return new Promise((resolve) => {
5323
+ const rl = readline.createInterface({ input: stdin, output: stdout });
5324
+ let settled = false;
5325
+ const finish = (value) => {
5326
+ if (settled)
5327
+ return;
5328
+ settled = true;
5329
+ rl.close();
5330
+ resolve(value.trim());
5331
+ };
5332
+ rl.question("Choice [Not now]: ", finish);
5333
+ rl.once("close", () => finish(""));
5334
+ });
4633
5335
  }
4634
- function renderResult(result, unit, copy) {
4635
- const lines = [];
4636
- const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
4637
- if (result.value === null) {
4638
- const why = copy.withheldReasons[result.withheldReason ?? ""];
4639
- lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
4640
- return lines;
4641
- }
4642
- lines.push(` Result: ${show(result.value)}`);
4643
- lines.push(` ${movementLine(result)}`);
4644
- lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
4645
- return lines;
5336
+ function formatLocalTime(iso) {
5337
+ const date3 = new Date(iso);
5338
+ if (Number.isNaN(date3.getTime()))
5339
+ return iso;
5340
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date3);
4646
5341
  }
4647
- function movementLine(result) {
4648
- if (result.outcome === "within_own_variation")
4649
- return "No material change against frozen baseline";
4650
- if (result.delta === null)
4651
- return "No reading";
4652
- if (result.delta > 0)
4653
- return `Up ${figure(result.delta)} against frozen baseline`;
4654
- if (result.delta < 0)
4655
- return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
4656
- return "No change against frozen baseline";
5342
+ function formatWindow(startUtc, endUtc) {
5343
+ const start = new Date(startUtc);
5344
+ const end = new Date(endUtc);
5345
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
5346
+ const dayMonth = { day: "numeric", month: "short", timeZone: "UTC" };
5347
+ const withYear = { ...dayMonth, year: "numeric" };
5348
+ const startFmt = new Intl.DateTimeFormat("en-GB", sameYear ? dayMonth : withYear);
5349
+ const endFmt = new Intl.DateTimeFormat("en-GB", withYear);
5350
+ return `${startFmt.format(start)} \u2013 ${endFmt.format(end)}`;
4657
5351
  }
4658
- function figure(n) {
4659
- return String(Number(n.toPrecision(12)));
5352
+ var GRANT_SENTENCES = {
5353
+ 501: "AI assistant data processing consent",
5354
+ 507: "Import of the AI-work history already on your machine"
5355
+ };
5356
+ function describeStudyGrant(grant) {
5357
+ return GRANT_SENTENCES[grant.code] ?? humanise(grant.name);
4660
5358
  }
4661
- function asInitiative(value) {
4662
- if (!value || typeof value !== "object")
4663
- return void 0;
4664
- const o = value;
4665
- if (typeof o.title !== "string" || typeof o.status !== "string")
4666
- return void 0;
4667
- return {
4668
- id: typeof o.id === "string" ? o.id : "",
4669
- organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
4670
- title: o.title,
4671
- summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
4672
- measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
4673
- scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
4674
- scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
4675
- withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
4676
- status: o.status,
4677
- direction: typeof o.direction === "string" ? o.direction : null,
4678
- result: asResult(o.result)
4679
- };
5359
+ var STUDY_KIND_SENTENCES = {
5360
+ Report30: "a 30-day report",
5361
+ Study90: "a 90-day study"
5362
+ };
5363
+ function describeStudyKind(studyKind) {
5364
+ return STUDY_KIND_SENTENCES[studyKind] ?? humanise(studyKind);
4680
5365
  }
4681
- function asResult(value) {
4682
- if (!value || typeof value !== "object")
4683
- return null;
4684
- const r = value;
4685
- const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
4686
- return {
4687
- scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
4688
- value: num(r.value),
4689
- baselineValue: num(r.baselineValue),
4690
- delta: num(r.delta),
4691
- movement: typeof r.movement === "string" ? r.movement : null,
4692
- outcome: typeof r.outcome === "string" ? r.outcome : "",
4693
- withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
4694
- basis: typeof r.basis === "string" ? r.basis : null
4695
- };
5366
+ function humanise(name) {
5367
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim() || name;
4696
5368
  }
4697
- function formatWindowOrRaw(startUtc, endUtc) {
4698
- if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
4699
- return "not given";
4700
- return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
5369
+ var REFUSED_REASON_MESSAGES = {
5370
+ study_no_longer_live: "That study is no longer open to join.",
5371
+ withdrawn: "You're no longer an active participant in that study.",
5372
+ // Handled as its own branch above, with its granted list, before this
5373
+ // table is ever consulted — present so the type stays exhaustive, and as
5374
+ // a plain fallback should something call this function with it directly.
5375
+ grant_failed: "Join failed partway through. Some grants may not have gone through.",
5376
+ declined: "You declined the join. Nothing was granted.",
5377
+ not_enrolled: "That study couldn't enrol you, so nothing was granted."
5378
+ };
5379
+ function describeRefusal(refusedReason) {
5380
+ if (refusedReason && REFUSED_REASON_MESSAGES[refusedReason])
5381
+ return REFUSED_REASON_MESSAGES[refusedReason];
5382
+ return "The join didn't go through. Nothing new was granted.";
4701
5383
  }
4702
- function formatDay(iso) {
4703
- const date3 = new Date(iso);
4704
- if (Number.isNaN(date3.getTime()))
4705
- return iso;
4706
- return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date3);
5384
+ var START_ERROR_MESSAGES = {
5385
+ join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
5386
+ unknown_mode: "This tool only offers Report mode from the command line.",
5387
+ no_live_study: "There's nothing open to join with that code right now.",
5388
+ too_many_open_sessions: "This tool has too many joins waiting to be confirmed. Confirm one, or let one expire, then try again.",
5389
+ unknown_session: "That join can no longer be found. Run join again for a fresh code."
5390
+ };
5391
+ function describeStartError(error2) {
5392
+ if (error2 instanceof http_1.AscendaApiError) {
5393
+ if (error2.errorCode && START_ERROR_MESSAGES[error2.errorCode])
5394
+ return START_ERROR_MESSAGES[error2.errorCode];
5395
+ if (error2.status === 401)
5396
+ return "This tool's pairing was rejected. Re-pair it, then try again.";
5397
+ return `Could not reach the join code (HTTP ${error2.status}).`;
5398
+ }
5399
+ return error2 instanceof Error ? error2.message : String(error2);
4707
5400
  }
4708
5401
  }
4709
5402
  });
4710
5403
 
4711
- // ../packages/tool-kit/out/hookRunner.js
4712
- var require_hookRunner = __commonJS({
4713
- "../packages/tool-kit/out/hookRunner.js"(exports) {
5404
+ // ../packages/tool-kit/out/pairingStudyJoin.js
5405
+ var require_pairingStudyJoin = __commonJS({
5406
+ "../packages/tool-kit/out/pairingStudyJoin.js"(exports) {
4714
5407
  "use strict";
4715
5408
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4716
5409
  if (k2 === void 0) k2 = k;
@@ -4750,252 +5443,312 @@ var require_hookRunner = __commonJS({
4750
5443
  };
4751
5444
  }();
4752
5445
  Object.defineProperty(exports, "__esModule", { value: true });
4753
- exports.hookRunnerPaths = hookRunnerPaths;
4754
- exports.hookLauncherScript = hookLauncherScript;
4755
- exports.isDowngrade = isDowngrade;
4756
- exports.installHookRunner = installHookRunner;
4757
- exports.removeHookRunner = removeHookRunner;
4758
- exports.hookRunnerCommand = hookRunnerCommand;
4759
- exports.writeAtomically = writeAtomically;
4760
- exports.lastHookPath = lastHookPath;
4761
- exports.stampLastHook = stampLastHook;
4762
- exports.readLastHook = readLastHook;
4763
- exports.describeAge = describeAge;
4764
- exports.resolveHookNode = resolveHookNode;
4765
- exports.tidyHomePath = tidyHomePath;
4766
- var child_process_1 = __require("child_process");
4767
- var fs = __importStar(__require("fs"));
4768
- var path = __importStar(__require("path"));
4769
- var collectorVersion_1 = require_collectorVersion();
4770
- var tokenStore_1 = require_tokenStore();
4771
- function hookRunnerPaths(binaryName) {
4772
- const launcher = path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
4773
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
5446
+ exports.PAIR_JOIN_OUTCOME_FILE_ENV = exports.PAIR_ORG_JOIN_CODE_ENV = void 0;
5447
+ exports.createPairingAttempt = createPairingAttempt;
5448
+ exports.pairingAttemptLines = pairingAttemptLines;
5449
+ exports.settleStudyJoin = settleStudyJoin;
5450
+ exports.writePairingJoinOutcome = writePairingJoinOutcome;
5451
+ exports.pairingJoinOutcome = pairingJoinOutcome;
5452
+ var fs = __importStar(__require("node:fs"));
5453
+ var confirmLinks_1 = require_confirmLinks();
5454
+ var studyJoin_1 = require_studyJoin();
5455
+ var http_1 = require_http();
5456
+ exports.PAIR_ORG_JOIN_CODE_ENV = "ASCENDA_PAIR_ORG_JOIN_CODE";
5457
+ exports.PAIR_JOIN_OUTCOME_FILE_ENV = "ASCENDA_PAIR_JOIN_OUTCOME_FILE";
5458
+ var CREATE_REFUSALS = {
5459
+ join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
5460
+ no_live_study: "There's nothing open to join with that code right now.",
5461
+ unknown_mode: "This tool only offers Report mode from the command line."
5462
+ };
5463
+ var JOIN_SETTLE_MS = 6e4;
5464
+ async function createPairingAttempt(apiBaseUrl, toolInstallationId, toolType, displayName, env = process.env) {
5465
+ const orgJoinCode = env[exports.PAIR_ORG_JOIN_CODE_ENV]?.trim();
5466
+ if (!orgJoinCode)
5467
+ return { session: await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName), carriesJoin: false };
5468
+ let refusal;
5469
+ try {
5470
+ const session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName, orgJoinCode);
5471
+ return { session, carriesJoin: session.studyJoin !== void 0 };
5472
+ } catch (error2) {
5473
+ if (!(error2 instanceof http_1.AscendaApiError) || error2.status >= 500)
5474
+ throw error2;
5475
+ refusal = error2.errorCode ? CREATE_REFUSALS[error2.errorCode] : void 0;
5476
+ }
5477
+ return { session: await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName), carriesJoin: false, refusal };
4774
5478
  }
4775
- var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
4776
- function hookLauncherScript(options) {
4777
- const { binaryName, setupCommand, loudEvent } = options;
5479
+ function pairingAttemptLines(attempt) {
5480
+ const { session } = attempt;
5481
+ const join = attempt.carriesJoin ? session.studyJoin : void 0;
5482
+ if (!join)
5483
+ return (0, confirmLinks_1.pairingConfirmLines)(session.qrUrl, session.code);
5484
+ const gitOffer = (0, studyJoin_1.gitOfferLine)(join.optionalImportStores);
4778
5485
  return [
4779
- "#!/bin/sh",
4780
- `# Ascenda hook launcher (${binaryName}). Written by \`setup\`, replaced by the`,
4781
- "# next one; edits here are lost. Finds a Node to run the hook bundle beside it.",
4782
- "",
4783
- 'dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 0',
4784
- `bundle="$dir/${binaryName}.mjs"`,
4785
- `record="$dir/${binaryName}.node"`,
4786
- `missing="$dir/${binaryName}.no-node"`,
4787
- "",
4788
- 'runs() { [ -n "$1" ] && [ -f "$1" ] && [ -x "$1" ]; }',
4789
- "",
4790
- "# The hook bundle needs Node 20 or newer. Checked only while searching, so",
4791
- "# the recorded path costs nothing to reuse.",
4792
- "recent() {",
4793
- ` runs "$1" && "$1" -e 'process.exit(parseInt(process.versions.node, 10) >= 20 ? 0 : 1)' >/dev/null 2>&1`,
4794
- "}",
4795
- "",
4796
- "newest_nvm() {",
4797
- ' [ -d "$HOME/.nvm/versions/node" ] || return 0',
4798
- ` ls "$HOME/.nvm/versions/node" 2>/dev/null | sed 's/^v//' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1 | sed 's/^/v/'`,
4799
- "}",
4800
- "",
4801
- 'node=""',
4802
- "how=recorded",
4803
- '[ -r "$record" ] && IFS= read -r node < "$record"',
4804
- "",
4805
- 'if ! runs "$node"; then',
4806
- ' node=""',
4807
- " how=found",
4808
- ' nvm_default=""',
4809
- ' if [ -r "$HOME/.nvm/alias/default" ]; then',
4810
- ' IFS= read -r wanted < "$HOME/.nvm/alias/default"',
4811
- " wanted=${wanted#v}",
4812
- ' for candidate in "$HOME/.nvm/versions/node/v$wanted"*; do',
4813
- ' [ -x "$candidate/bin/node" ] && nvm_default="$candidate/bin/node"',
4814
- " done",
4815
- " fi",
4816
- " nvm_newest=$(newest_nvm)",
4817
- " for candidate in \\",
4818
- ' "$(command -v node 2>/dev/null)" \\',
4819
- " /opt/homebrew/bin/node \\",
4820
- " /usr/local/bin/node \\",
4821
- ' "$HOME/.volta/bin/node" \\',
4822
- ' "$nvm_default" \\',
4823
- ' "$HOME/.local/share/fnm/aliases/default/bin/node" \\',
4824
- ' "$HOME/Library/Application Support/fnm/aliases/default/bin/node" \\',
4825
- ' "$HOME/.asdf/shims/node" \\',
4826
- ' "$HOME/.local/share/mise/shims/node" \\',
4827
- ' "$HOME/.nvm/versions/node/$nvm_newest/bin/node"',
4828
- " do",
4829
- ' if recent "$candidate"; then node=$candidate; break; fi',
4830
- " done",
4831
- ' if [ -n "$node" ]; then',
4832
- ` printf '%s\\n' "$node" > "$record.$$" 2>/dev/null && mv -f "$record.$$" "$record" 2>/dev/null`,
4833
- ' rm -f "$missing" 2>/dev/null',
4834
- " fi",
4835
- "fi",
4836
- "",
4837
- 'if [ -n "$ASCENDA_HOOK_LAUNCHER_PROBE" ]; then',
4838
- ' [ -n "$node" ] || { echo "no Node 20 or newer found on PATH or in the usual install locations" >&2; exit 1; }',
4839
- ` printf '%s\\t%s\\n' "$node" "$how"`,
4840
- " exit 0",
4841
- "fi",
4842
- "",
4843
- 'if [ -z "$node" ]; then',
4844
- ' date -u +%Y-%m-%dT%H:%M:%SZ > "$missing" 2>/dev/null',
4845
- ' case "$1" in',
4846
- ...loudEvent ? [
4847
- ` ${loudEvent})`,
4848
- " cat >/dev/null 2>&1",
4849
- ` echo "Ascenda hooks cannot find Node 20 or newer, so none of them are running. Install Node, then run: ${setupCommand}" >&2`,
4850
- " exit 1 ;;"
4851
- ] : [],
4852
- ` ${LAUNCHER_MANAGEMENT_COMMANDS.join("|")})`,
4853
- ` echo "${binaryName}: no Node 20 or newer found on PATH or in the usual install locations." >&2`,
4854
- " exit 1 ;;",
4855
- " *)",
4856
- " # A hook: say nothing per tool call. status and doctor read the",
4857
- " # file written above.",
4858
- " cat >/dev/null 2>&1",
4859
- " exit 0 ;;",
4860
- " esac",
4861
- "fi",
4862
- "",
4863
- 'exec "$node" "$bundle" "$@"',
4864
- ""
4865
- ].join("\n");
5486
+ `This also joins ${join.organisationName} (${(0, studyJoin_1.formatWindow)(join.windowStartUtc, join.windowEndUtc)}). The page shows what you'd share before you confirm.`,
5487
+ ...gitOffer ? [gitOffer] : [],
5488
+ `Open this link to confirm: ${session.qrUrl}`
5489
+ ];
4866
5490
  }
4867
- function releaseOf(version2) {
4868
- const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version2 ?? "").trim());
4869
- return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
5491
+ async function settleStudyJoin(apiBaseUrl, pairingSessionId, last, wait = 1e3) {
5492
+ let current = last;
5493
+ const deadline = Date.now() + JOIN_SETTLE_MS;
5494
+ while (current && current.status === "pending" && Date.now() < deadline) {
5495
+ await new Promise((resolve) => setTimeout(resolve, wait));
5496
+ let status;
5497
+ try {
5498
+ status = await (0, http_1.getPairingStatus)(apiBaseUrl, pairingSessionId);
5499
+ } catch {
5500
+ continue;
5501
+ }
5502
+ current = status.studyJoin ?? current;
5503
+ }
5504
+ return current;
4870
5505
  }
4871
- function isDowngrade(installed, incoming) {
4872
- const have = releaseOf(installed);
4873
- const want = releaseOf(incoming);
4874
- if (!have || !want)
4875
- return false;
4876
- for (let i = 0; i < 3; i++) {
4877
- if (have[i] !== want[i])
4878
- return have[i] > want[i];
5506
+ function writePairingJoinOutcome(outcome, env = process.env) {
5507
+ const file = env[exports.PAIR_JOIN_OUTCOME_FILE_ENV]?.trim();
5508
+ if (!file)
5509
+ return;
5510
+ try {
5511
+ fs.writeFileSync(file, `${JSON.stringify(outcome)}
5512
+ `, { mode: 384 });
5513
+ } catch {
5514
+ }
5515
+ }
5516
+ function pairingJoinOutcome(attempt, pairing, studyJoin) {
5517
+ if (!attempt)
5518
+ return { join: "none", pairing };
5519
+ if (attempt.refusal)
5520
+ return { join: "refused", pairing, message: attempt.refusal };
5521
+ return { join: attempt.carriesJoin ? "carried" : "not_carried", pairing, studyJoin };
5522
+ }
5523
+ }
5524
+ });
5525
+
5526
+ // ../packages/tool-kit/out/hookSet.js
5527
+ var require_hookSet = __commonJS({
5528
+ "../packages/tool-kit/out/hookSet.js"(exports) {
5529
+ "use strict";
5530
+ Object.defineProperty(exports, "__esModule", { value: true });
5531
+ exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = void 0;
5532
+ exports.hookSetArgument = hookSetArgument;
5533
+ exports.readHookSet = readHookSet;
5534
+ exports.isHookSet = isHookSet;
5535
+ exports.readViaPlugin = readViaPlugin;
5536
+ exports.hookSetOfCommand = hookSetOfCommand;
5537
+ exports.hookSetChanges = hookSetChanges;
5538
+ exports.describeHookSetChanges = describeHookSetChanges;
5539
+ exports.HOOK_SET_FLAG = "--hook-set";
5540
+ exports.UNVERSIONED_HOOK_SET = 1;
5541
+ function hookSetArgument(hookSet) {
5542
+ return hookSet === void 0 ? "" : ` ${exports.HOOK_SET_FLAG} ${hookSet}`;
5543
+ }
5544
+ function readHookSet(argv) {
5545
+ const index = argv.indexOf(exports.HOOK_SET_FLAG);
5546
+ if (index === -1)
5547
+ return void 0;
5548
+ const raw = argv[index + 1];
5549
+ if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
5550
+ return void 0;
5551
+ const value = Number(raw);
5552
+ return isHookSet(value) ? value : void 0;
5553
+ }
5554
+ function isHookSet(value) {
5555
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
5556
+ }
5557
+ function readViaPlugin(env) {
5558
+ return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
5559
+ }
5560
+ function hookSetOfCommand(command) {
5561
+ const match = command.match(/--hook-set\s+(\d+)/);
5562
+ return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
5563
+ }
5564
+ function hookSetChanges(before, events) {
5565
+ const added = events.filter((event) => !before.has(event));
5566
+ const sets = [...before.values()];
5567
+ return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
5568
+ }
5569
+ function describeHookSetChanges(changes, hookSet) {
5570
+ if (changes.previousSet === void 0)
5571
+ return void 0;
5572
+ const parts = [];
5573
+ if (changes.added.length)
5574
+ parts.push(`added ${changes.added.join(", ")}`);
5575
+ if (changes.previousSet < hookSet)
5576
+ parts.push(`hook set ${changes.previousSet} \u2192 ${hookSet}`);
5577
+ return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
5578
+ }
5579
+ }
5580
+ });
5581
+
5582
+ // ../packages/tool-kit/out/initiatives.js
5583
+ var require_initiatives = __commonJS({
5584
+ "../packages/tool-kit/out/initiatives.js"(exports) {
5585
+ "use strict";
5586
+ Object.defineProperty(exports, "__esModule", { value: true });
5587
+ exports.INITIATIVE_COPY = void 0;
5588
+ exports.initiativesStatusLines = initiativesStatusLines;
5589
+ exports.renderInitiatives = renderInitiatives;
5590
+ var http_1 = require_http();
5591
+ var studyJoin_1 = require_studyJoin();
5592
+ var READ_TIMEOUT_MS = 5e3;
5593
+ exports.INITIATIVE_COPY = {
5594
+ outcomes: {
5595
+ moved_as_declared: "Moved the way declared, beyond the cohort's own variation",
5596
+ moved_against_declared: "Moved the other way, beyond the cohort's own variation",
5597
+ moved_no_direction_declared: "Moved beyond the cohort's own variation; no direction was declared",
5598
+ within_own_variation: "No further from the baseline than the cohort's own week-to-week variation",
5599
+ withheld: "Withheld"
5600
+ },
5601
+ withheldReasons: {
5602
+ cohort_below_minimum: "the cohort was too small to report on when the scoring window closed",
5603
+ below_minimum_cohort: "the cohort was too small to report on when the scoring window closed",
5604
+ below_minimum_cohort_size: "the cohort was too small to report on when the scoring window closed",
5605
+ baseline_withheld: "the baseline was withheld"
4879
5606
  }
4880
- return false;
4881
- }
4882
- function readInstalledVersion(file) {
4883
- try {
4884
- return fs.readFileSync(file, "utf8").trim() || void 0;
4885
- } catch {
4886
- return void 0;
5607
+ };
5608
+ var OUTCOME_EMPTY = "Not stated";
5609
+ var OUTCOME_UNKNOWN = "An outcome this app does not recognise";
5610
+ var WITHHELD_UNKNOWN = "Withheld, for a reason this version of the app doesn't name yet.";
5611
+ var DIRECTION_WORDS = {
5612
+ up: "Expected to rise",
5613
+ down: "Expected to fall",
5614
+ none_declared: "No direction declared"
5615
+ };
5616
+ var DIRECTION_UNKNOWN = "A direction this app does not recognise";
5617
+ async function initiativesStatusLines(ctx) {
5618
+ const heading = "Changes your organisation has published to you";
5619
+ if (!ctx.eventWriteToken) {
5620
+ return [heading, " Not checked: this install holds no token, so nothing was fetched."];
4887
5621
  }
4888
- }
4889
- function installHookRunner(options) {
4890
- const paths = hookRunnerPaths(options.binaryName);
4891
- if (options.dryRun)
4892
- return paths.launcher;
4893
- const source = path.resolve(options.source ?? process.argv[1]);
4894
- const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
4895
- const installed = readInstalledVersion(paths.version);
4896
- const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
4897
- if (installed && fs.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4898
- options.onKeptNewer?.(installed, incoming);
4899
- if (process.platform !== "win32" && !fs.existsSync(paths.launcher))
4900
- writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4901
- return paths.launcher;
5622
+ const read = await (0, http_1.readInitiatives)(ctx.apiBaseUrl, ctx.eventWriteToken, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
5623
+ if (read.kind === "rejected") {
5624
+ return [
5625
+ heading,
5626
+ ` Couldn't check: the server turned this install's request down. If that keeps happening, pair again with \`${ctx.pairCommand}\`.`
5627
+ ];
4902
5628
  }
4903
- fs.mkdirSync(path.dirname(paths.launcher), { recursive: true });
4904
- if (process.platform === "win32") {
4905
- if (source !== path.resolve(paths.launcher))
4906
- fs.copyFileSync(source, paths.launcher);
4907
- writeAtomically(paths.version, `${incoming}
4908
- `, 420);
4909
- return paths.launcher;
5629
+ if (read.kind === "failed") {
5630
+ return [heading, ` Couldn't check: ${read.reason}. Run status again to retry.`];
4910
5631
  }
4911
- if (source !== path.resolve(paths.bundle))
4912
- writeAtomically(paths.bundle, fs.readFileSync(source), 493);
4913
- writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4914
- writeAtomically(paths.record, `${process.execPath}
4915
- `, 420);
4916
- if (source !== path.resolve(paths.bundle))
4917
- writeAtomically(paths.version, `${incoming}
4918
- `, 420);
4919
- fs.rmSync(paths.noNode, { force: true });
4920
- return paths.launcher;
5632
+ return [heading, ...renderInitiatives(read.initiatives)];
4921
5633
  }
4922
- function removeHookRunner(binaryName) {
4923
- const removed = [];
4924
- for (const file of Object.values(hookRunnerPaths(binaryName))) {
4925
- if (!fs.existsSync(file))
5634
+ function renderInitiatives(entries, copy = exports.INITIATIVE_COPY) {
5635
+ if (entries.length === 0)
5636
+ return [" None published to you."];
5637
+ const lines = [];
5638
+ let unreadable = 0;
5639
+ for (const entry of entries) {
5640
+ const initiative = asInitiative(entry);
5641
+ if (!initiative) {
5642
+ unreadable += 1;
4926
5643
  continue;
4927
- fs.rmSync(file, { force: true });
4928
- removed.push(file);
5644
+ }
5645
+ lines.push(...renderOne(initiative, copy));
4929
5646
  }
4930
- return removed;
4931
- }
4932
- function hookRunnerCommand(launcher, platform = process.platform) {
4933
- return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
5647
+ if (unreadable > 0) {
5648
+ lines.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
5649
+ }
5650
+ return lines;
4934
5651
  }
4935
- function writeAtomically(target, contents, mode) {
4936
- const tmp = `${target}.${process.pid}.tmp`;
4937
- fs.writeFileSync(tmp, contents, { mode });
4938
- fs.chmodSync(tmp, mode);
4939
- fs.renameSync(tmp, target);
5652
+ function renderOne(initiative, copy) {
5653
+ const lines = [` ${initiative.organisationName}: ${initiative.title}`];
5654
+ lines.push(` ${describeStatus(initiative)}`);
5655
+ if (initiative.summaryForCohort) {
5656
+ for (const line of initiative.summaryForCohort.split(/\r?\n/))
5657
+ lines.push(` ${line}`);
5658
+ }
5659
+ if (initiative.direction)
5660
+ lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
5661
+ lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
5662
+ if (initiative.result)
5663
+ lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
5664
+ lines.push("");
5665
+ return lines;
4940
5666
  }
4941
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join((0, tokenStore_1.ascendaHome)(), "state");
4942
- function lastHookPath(tool) {
4943
- return path.join(stateDir(), `${tool}-last-hook.json`);
5667
+ function describeStatus(initiative) {
5668
+ switch (initiative.status) {
5669
+ case "published":
5670
+ return "Published, not scored yet.";
5671
+ case "scored":
5672
+ return "Scored.";
5673
+ case "withdrawn":
5674
+ return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
5675
+ default:
5676
+ return "Status not recognised.";
5677
+ }
4944
5678
  }
4945
- function stampLastHook(tool, event, now = /* @__PURE__ */ new Date()) {
4946
- try {
4947
- fs.mkdirSync(stateDir(), { recursive: true });
4948
- const file = lastHookPath(tool);
4949
- const tmp = `${file}.${process.pid}.tmp`;
4950
- fs.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
4951
- `, { mode: 384 });
4952
- fs.renameSync(tmp, file);
4953
- } catch {
5679
+ function renderResult(result, unit, copy) {
5680
+ const lines = [];
5681
+ const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
5682
+ if (result.value === null) {
5683
+ const why = copy.withheldReasons[result.withheldReason ?? ""];
5684
+ lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
5685
+ return lines;
4954
5686
  }
5687
+ lines.push(` Result: ${show(result.value)}`);
5688
+ lines.push(` ${movementLine(result)}`);
5689
+ lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
5690
+ return lines;
4955
5691
  }
4956
- function readLastHook(tool) {
4957
- try {
4958
- const parsed = JSON.parse(fs.readFileSync(lastHookPath(tool), "utf8"));
4959
- if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
4960
- return void 0;
4961
- return { event: parsed.event, at: parsed.at };
4962
- } catch {
5692
+ function movementLine(result) {
5693
+ if (result.outcome === "within_own_variation")
5694
+ return "No material change against frozen baseline";
5695
+ if (result.delta === null)
5696
+ return "No reading";
5697
+ if (result.delta > 0)
5698
+ return `Up ${figure(result.delta)} against frozen baseline`;
5699
+ if (result.delta < 0)
5700
+ return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
5701
+ return "No change against frozen baseline";
5702
+ }
5703
+ function figure(n) {
5704
+ return String(Number(n.toPrecision(12)));
5705
+ }
5706
+ function asInitiative(value) {
5707
+ if (!value || typeof value !== "object")
4963
5708
  return void 0;
4964
- }
5709
+ const o = value;
5710
+ if (typeof o.title !== "string" || typeof o.status !== "string")
5711
+ return void 0;
5712
+ return {
5713
+ id: typeof o.id === "string" ? o.id : "",
5714
+ organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
5715
+ title: o.title,
5716
+ summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
5717
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
5718
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
5719
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
5720
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
5721
+ status: o.status,
5722
+ direction: typeof o.direction === "string" ? o.direction : null,
5723
+ result: asResult(o.result)
5724
+ };
4965
5725
  }
4966
- function describeAge(ms) {
4967
- if (!Number.isFinite(ms) || ms < 0)
4968
- return "just now";
4969
- const seconds = Math.round(ms / 1e3);
4970
- if (seconds < 60)
4971
- return `${seconds} s ago`;
4972
- const minutes = Math.round(seconds / 60);
4973
- if (minutes < 60)
4974
- return `${minutes} min ago`;
4975
- const hours = Math.round(minutes / 60);
4976
- if (hours < 48)
4977
- return `${hours} h ago`;
4978
- return `${Math.round(hours / 24)} days ago`;
5726
+ function asResult(value) {
5727
+ if (!value || typeof value !== "object")
5728
+ return null;
5729
+ const r = value;
5730
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
5731
+ return {
5732
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
5733
+ value: num(r.value),
5734
+ baselineValue: num(r.baselineValue),
5735
+ delta: num(r.delta),
5736
+ movement: typeof r.movement === "string" ? r.movement : null,
5737
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
5738
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
5739
+ basis: typeof r.basis === "string" ? r.basis : null
5740
+ };
4979
5741
  }
4980
- function resolveHookNode(launcher) {
4981
- if (!fs.existsSync(launcher))
4982
- return { problem: "the hook launcher is not installed" };
4983
- const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
4984
- encoding: "utf8",
4985
- timeout: 5e3,
4986
- env: { HOME: process.env.HOME ?? "", PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ASCENDA_HOOK_LAUNCHER_PROBE: "1" }
4987
- });
4988
- const [node, how] = (probe.stdout ?? "").trim().split(" ");
4989
- if (probe.status !== 0 || !node) {
4990
- return { problem: (probe.stderr ?? "").trim() || "the launcher found no Node it can run" };
4991
- }
4992
- const version2 = (0, child_process_1.spawnSync)(node, ["--version"], { encoding: "utf8", timeout: 5e3 });
4993
- if (version2.status !== 0)
4994
- return { node, how, problem: `${node} did not run` };
4995
- return { node, how, version: version2.stdout.trim() };
5742
+ function formatWindowOrRaw(startUtc, endUtc) {
5743
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
5744
+ return "not given";
5745
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
4996
5746
  }
4997
- function tidyHomePath(file, home = process.env.HOME ?? "") {
4998
- return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
5747
+ function formatDay(iso) {
5748
+ const date3 = new Date(iso);
5749
+ if (Number.isNaN(date3.getTime()))
5750
+ return iso;
5751
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date3);
4999
5752
  }
5000
5753
  }
5001
5754
  });
@@ -5070,12 +5823,12 @@ var require_setupDisclosure = __commonJS({
5070
5823
  exports.renderSetupDisclosure = renderSetupDisclosure;
5071
5824
  exports.FAMILY_SENTENCES = {
5072
5825
  session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
5073
- counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
5826
+ counts: "how many prompts you sent and roughly how long each was, as one of four sizes, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
5074
5827
  tools: "the name of each tool your agent calls",
5075
5828
  outcome: "whether a call succeeded, failed, or was interrupted",
5076
5829
  clock: "your machine's offset from UTC, so an evening is read as an evening",
5077
5830
  repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
5078
- model: "which model served the session, by name and by tier",
5831
+ model: "which model served the session, by name and by tier, whether it came through the vendor, a cloud platform, a gateway or this machine (one word, never an address), and the effort level it was set to where your agent records one",
5079
5832
  posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
5080
5833
  git: "that a commit, push or revert happened, and when a pull request opened or merged",
5081
5834
  edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
@@ -5323,6 +6076,7 @@ var require_liveBus = __commonJS({
5323
6076
  exports.existingSocketCandidates = existingSocketCandidates;
5324
6077
  exports.liveBusSocketPath = liveBusSocketPath;
5325
6078
  exports.bucketPromptSize = bucketPromptSize;
6079
+ exports.promptSizeMetadata = promptSizeMetadata;
5326
6080
  exports.emitLiveSignal = emitLiveSignal;
5327
6081
  exports.deliverLine = deliverLine;
5328
6082
  var fs = __importStar(__require("fs"));
@@ -5371,6 +6125,9 @@ var require_liveBus = __commonJS({
5371
6125
  return "l";
5372
6126
  return "xl";
5373
6127
  }
6128
+ function promptSizeMetadata(text) {
6129
+ return text === void 0 ? {} : { promptSizeBucket: bucketPromptSize(text) };
6130
+ }
5374
6131
  var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
5375
6132
  function onTheWire(signal) {
5376
6133
  const out = { ...signal };
@@ -5883,6 +6640,7 @@ var require_cliAgentSetup = __commonJS({
5883
6640
  var os = __importStar(__require("os"));
5884
6641
  var path = __importStar(__require("path"));
5885
6642
  var collectorVersion_1 = require_collectorVersion();
6643
+ var releaseCheck_1 = require_releaseCheck();
5886
6644
  var credentials_1 = require_credentials();
5887
6645
  var eventLog_1 = require_eventLog();
5888
6646
  var hookAdapter_1 = require_hookAdapter();
@@ -6036,7 +6794,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
6036
6794
  const next = (label, value) => console.log(` ${ui.bold(label.padEnd(6))} ${value}`);
6037
6795
  console.log("");
6038
6796
  if (chosenLocal) {
6039
- console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
6797
+ console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and Ascenda Flow's live view work now.`);
6040
6798
  console.log(" They run on this machine and need no account or pairing.");
6041
6799
  if (eventLog.path)
6042
6800
  console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os.homedir())}, for you or any tool to read.`);
@@ -6053,9 +6811,9 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
6053
6811
  next(chosenLocal ? "Pair" : "Retry", `${ui.cyan(`${self} setup`)}${chosenLocal ? ui.dim(" (optional)") : ""}`);
6054
6812
  if (chosenLocal) {
6055
6813
  console.log("");
6056
- console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account the"));
6057
- console.log(ui.dim(" Ascenda app is signed in to when you confirm the code, so your sessions appear"));
6058
- console.log(ui.dim(" in the app. Until you pair, nothing leaves this machine."));
6814
+ console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account you"));
6815
+ console.log(ui.dim(" confirm the code with, in Ascenda Flow or at me.ascendaflow.com."));
6816
+ console.log(ui.dim(" Until you pair, nothing leaves this machine."));
6059
6817
  console.log("");
6060
6818
  console.log(ui.dim((0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName }).split("\n").map((line) => ` ${line}`).join("\n")));
6061
6819
  }
@@ -6474,6 +7232,11 @@ ${serialised}`);
6474
7232
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
6475
7233
  console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
6476
7234
  console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
7235
+ console.log(`latest ${(0, releaseCheck_1.describeReleaseCheck)({
7236
+ installed: (0, releaseCheck_1.installedBundleVersion)((0, hookRunner_1.hookRunnerPaths)(spec.binaryName).version) ?? collectorVersion_1.COLLECTOR_VERSION,
7237
+ setupCommand: `npx -y ${spec.packageName} setup`,
7238
+ localOnly
7239
+ })}`);
6477
7240
  const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
6478
7241
  if (node) {
6479
7242
  console.log(node.problem ? `node \u2014 ${node.problem}. Install Node 20 or newer, then run setup again` : `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
@@ -6774,6 +7537,480 @@ var require_turnState = __commonJS({
6774
7537
  }
6775
7538
  });
6776
7539
 
7540
+ // ../packages/tool-kit/out/effortState.js
7541
+ var require_effortState = __commonJS({
7542
+ "../packages/tool-kit/out/effortState.js"(exports) {
7543
+ "use strict";
7544
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
7545
+ if (k2 === void 0) k2 = k;
7546
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7547
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7548
+ desc = { enumerable: true, get: function() {
7549
+ return m[k];
7550
+ } };
7551
+ }
7552
+ Object.defineProperty(o, k2, desc);
7553
+ } : function(o, m, k, k2) {
7554
+ if (k2 === void 0) k2 = k;
7555
+ o[k2] = m[k];
7556
+ });
7557
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
7558
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
7559
+ } : function(o, v) {
7560
+ o["default"] = v;
7561
+ });
7562
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
7563
+ var ownKeys = function(o) {
7564
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
7565
+ var ar = [];
7566
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
7567
+ return ar;
7568
+ };
7569
+ return ownKeys(o);
7570
+ };
7571
+ return function(mod) {
7572
+ if (mod && mod.__esModule) return mod;
7573
+ var result = {};
7574
+ if (mod != null) {
7575
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
7576
+ }
7577
+ __setModuleDefault(result, mod);
7578
+ return result;
7579
+ };
7580
+ }();
7581
+ Object.defineProperty(exports, "__esModule", { value: true });
7582
+ exports.readSentEffortLevel = readSentEffortLevel;
7583
+ exports.recordSentEffortLevel = recordSentEffortLevel;
7584
+ exports.clearSentEffortLevel = clearSentEffortLevel;
7585
+ var fs = __importStar(__require("fs"));
7586
+ var path = __importStar(__require("path"));
7587
+ var tokenStore_1 = require_tokenStore();
7588
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join((0, tokenStore_1.ascendaHome)(), "state");
7589
+ function effortFile(agent, sessionId) {
7590
+ return path.join(stateDir(), `${sanitize(agent)}-effort-${sanitize(sessionId)}`);
7591
+ }
7592
+ function sanitize(value) {
7593
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_");
7594
+ }
7595
+ function readSentEffortLevel(agent, sessionId) {
7596
+ if (!sessionId)
7597
+ return void 0;
7598
+ try {
7599
+ const level = fs.readFileSync(effortFile(agent, sessionId), "utf8").trim();
7600
+ return level || void 0;
7601
+ } catch {
7602
+ return void 0;
7603
+ }
7604
+ }
7605
+ function recordSentEffortLevel(agent, sessionId, level) {
7606
+ if (!sessionId || !level)
7607
+ return;
7608
+ try {
7609
+ fs.mkdirSync(stateDir(), { recursive: true });
7610
+ fs.writeFileSync(effortFile(agent, sessionId), level, { encoding: "utf8", mode: 384 });
7611
+ } catch {
7612
+ }
7613
+ }
7614
+ function clearSentEffortLevel(agent, sessionId) {
7615
+ if (!sessionId)
7616
+ return;
7617
+ try {
7618
+ fs.rmSync(effortFile(agent, sessionId), { force: true });
7619
+ } catch {
7620
+ }
7621
+ }
7622
+ }
7623
+ });
7624
+
7625
+ // ../packages/tool-kit/out/squadronJoin.js
7626
+ var require_squadronJoin = __commonJS({
7627
+ "../packages/tool-kit/out/squadronJoin.js"(exports) {
7628
+ "use strict";
7629
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
7630
+ if (k2 === void 0) k2 = k;
7631
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7632
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7633
+ desc = { enumerable: true, get: function() {
7634
+ return m[k];
7635
+ } };
7636
+ }
7637
+ Object.defineProperty(o, k2, desc);
7638
+ } : function(o, m, k, k2) {
7639
+ if (k2 === void 0) k2 = k;
7640
+ o[k2] = m[k];
7641
+ });
7642
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
7643
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
7644
+ } : function(o, v) {
7645
+ o["default"] = v;
7646
+ });
7647
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
7648
+ var ownKeys = function(o) {
7649
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
7650
+ var ar = [];
7651
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
7652
+ return ar;
7653
+ };
7654
+ return ownKeys(o);
7655
+ };
7656
+ return function(mod) {
7657
+ if (mod && mod.__esModule) return mod;
7658
+ var result = {};
7659
+ if (mod != null) {
7660
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
7661
+ }
7662
+ __setModuleDefault(result, mod);
7663
+ return result;
7664
+ };
7665
+ }();
7666
+ Object.defineProperty(exports, "__esModule", { value: true });
7667
+ exports.SQUADRON_COLOURS = exports.SQUADRON_AIRCRAFT = void 0;
7668
+ exports.generateCallsign = generateCallsign;
7669
+ exports.normaliseBookingReference = normaliseBookingReference;
7670
+ exports.callsignProblem = callsignProblem;
7671
+ exports.runSquadronJoin = runSquadronJoin;
7672
+ exports.leaseEnd = leaseEnd;
7673
+ exports.describeGate = describeGate;
7674
+ exports.describeSquadronRefusal = describeSquadronRefusal;
7675
+ var readline = __importStar(__require("node:readline"));
7676
+ var node_crypto_1 = __require("node:crypto");
7677
+ var confirmLinks_1 = require_confirmLinks();
7678
+ var http_1 = require_http();
7679
+ exports.SQUADRON_AIRCRAFT = ["trainer", "airliner", "glider", "fighter", "stealth", "floatplane"];
7680
+ exports.SQUADRON_COLOURS = ["orange", "yellow", "ivory", "charcoal", "grey", "red"];
7681
+ var CALLSIGN_WORDS = ["Kestrel", "Falcon", "Heron", "Swift", "Osprey", "Raven", "Merlin", "Puffin", "Condor", "Harrier", "Kite", "Tern"];
7682
+ function generateCallsign() {
7683
+ return `${CALLSIGN_WORDS[(0, node_crypto_1.randomInt)(CALLSIGN_WORDS.length)]} ${String((0, node_crypto_1.randomInt)(10, 100))}`;
7684
+ }
7685
+ function normaliseBookingReference(raw) {
7686
+ const cleaned = (raw ?? "").replace(/[\s-]/g, "").toUpperCase();
7687
+ return /^[A-Z0-9]{6}$/.test(cleaned) ? cleaned : void 0;
7688
+ }
7689
+ function callsignProblem(callsign) {
7690
+ const trimmed = callsign.trim();
7691
+ if (trimmed.length === 0)
7692
+ return "A callsign can't be empty.";
7693
+ if (trimmed.length > 40)
7694
+ return "A callsign is 40 characters at most.";
7695
+ if (/[\u0000-\u001f\u007f]/.test(trimmed))
7696
+ return "A callsign can't contain control characters.";
7697
+ return void 0;
7698
+ }
7699
+ var POLL_INTERVAL_MS = 3e3;
7700
+ var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
7701
+ async function runSquadronJoin(ctx) {
7702
+ const stdin = ctx.stdin ?? process.stdin;
7703
+ const stdout = ctx.stdout ?? process.stdout;
7704
+ const stderr = ctx.stderr ?? process.stderr;
7705
+ const print = (line = "") => stdout.write(`${line}
7706
+ `);
7707
+ if (!stdin.isTTY || !stdout.isTTY) {
7708
+ stderr.write("squadron needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
7709
+ return 0;
7710
+ }
7711
+ const reference = normaliseBookingReference(ctx.bookingReference);
7712
+ if (!reference) {
7713
+ stderr.write("A booking reference is six letters or digits, like FEFBDH.\n");
7714
+ return 1;
7715
+ }
7716
+ let preview;
7717
+ try {
7718
+ preview = await (0, http_1.previewJoinCode)(ctx.apiBaseUrl, reference);
7719
+ } catch (error2) {
7720
+ stderr.write(`${describeSquadronError(error2)}
7721
+ `);
7722
+ return 1;
7723
+ }
7724
+ const jam = preview.jam;
7725
+ if (preview.labRole !== "Jam" || !jam) {
7726
+ stderr.write(`${reference} isn't a Squadron booking reference. If it's a study code, run join instead.
7727
+ `);
7728
+ return 1;
7729
+ }
7730
+ if (jam.acceptsJoins === false) {
7731
+ stderr.write(jam.isLocked ? "This sortie's gate is closed. Ask the host to open it.\n" : "This sortie isn't taking new pilots.\n");
7732
+ return 1;
7733
+ }
7734
+ const aircraftList = jam.aircraft?.length ? jam.aircraft : [...exports.SQUADRON_AIRCRAFT];
7735
+ const colourList = jam.colours?.length ? jam.colours : [...exports.SQUADRON_COLOURS];
7736
+ for (const [flag, value, list] of [["--aircraft", ctx.aircraft, aircraftList], ["--colour", ctx.colour, colourList]]) {
7737
+ if (value !== void 0 && !list.includes(value.trim().toLowerCase())) {
7738
+ stderr.write(`${flag} must be one of: ${list.join(", ")}.
7739
+ `);
7740
+ return 1;
7741
+ }
7742
+ }
7743
+ if (ctx.callsign !== void 0) {
7744
+ const problem = callsignProblem(ctx.callsign);
7745
+ if (problem) {
7746
+ stderr.write(`${problem}
7747
+ `);
7748
+ return 1;
7749
+ }
7750
+ }
7751
+ print();
7752
+ print(`Squadron: ${jam.name ?? preview.labName ?? reference}`);
7753
+ if (jam.mission)
7754
+ print(`Mission: ${jam.mission}`);
7755
+ print(describeGate(jam));
7756
+ print();
7757
+ const prompt = createPrompter(stdin, stdout);
7758
+ try {
7759
+ let callsign = ctx.callsign?.trim();
7760
+ if (callsign === void 0) {
7761
+ const suggested = (ctx.generateCallsign ?? generateCallsign)();
7762
+ for (; ; ) {
7763
+ const answer = await prompt.ask(`Callsign [${suggested}]: `);
7764
+ if (answer === void 0)
7765
+ return notNow(print);
7766
+ const chosen = answer === "" ? suggested : answer;
7767
+ const problem = callsignProblem(chosen);
7768
+ if (!problem) {
7769
+ callsign = chosen.trim();
7770
+ break;
7771
+ }
7772
+ print(problem);
7773
+ }
7774
+ }
7775
+ let aircraft = ctx.aircraft?.trim().toLowerCase();
7776
+ if (aircraft === void 0) {
7777
+ const suggested = aircraftList[(0, node_crypto_1.randomInt)(aircraftList.length)];
7778
+ aircraft = await askFromList(prompt, print, "Aircraft", aircraftList, suggested);
7779
+ if (aircraft === void 0)
7780
+ return notNow(print);
7781
+ }
7782
+ let colour = ctx.colour?.trim().toLowerCase();
7783
+ if (colour === void 0) {
7784
+ const picked = await askFromList(prompt, print, "Colour", colourList, "", "dealt for you");
7785
+ if (picked === void 0)
7786
+ return notNow(print);
7787
+ colour = picked === "" ? void 0 : picked;
7788
+ }
7789
+ print();
7790
+ print(`You'll confirm as ${callsign}, ${aircraft}${colour ? `, ${colour}` : ""}. The confirm page lets you change any of them.`);
7791
+ print();
7792
+ print("Joining shares, with this squadron only:");
7793
+ print(` your activity counts from ${ctx.displayName}: prompts, tool calls, turns and edits, as numbers`);
7794
+ print(" your callsign and aircraft, which the other pilots see");
7795
+ print("Never your prompts, code, file names or project names.");
7796
+ print("Sharing stops on the date the server gives when you join. It's printed then.");
7797
+ print();
7798
+ print(" 1) Join");
7799
+ print(" 2) Not now");
7800
+ print();
7801
+ const choice = await prompt.ask("Choice [Not now]: ");
7802
+ if (choice === void 0 || !/^(1|join|y|yes)$/i.test(choice))
7803
+ return notNow(print);
7804
+ prompt.close();
7805
+ let start;
7806
+ try {
7807
+ start = await (0, http_1.startSquadronJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, { joinCode: reference, handle: callsign, aircraft, colour });
7808
+ } catch (error2) {
7809
+ const doorClosed = error2 instanceof http_1.AscendaApiError && error2.status === 404 && !error2.errorCode?.startsWith("jam_");
7810
+ stderr.write(doorClosed ? "This server can't seat you in a sortie from the command line yet. Join from the Ascenda app instead.\n" : `${describeSquadronError(error2)}
7811
+ `);
7812
+ return 1;
7813
+ }
7814
+ if (start.kind !== void 0 && start.kind !== "jam") {
7815
+ stderr.write(`${reference} opened a study join, not a sortie. Run join instead.
7816
+ `);
7817
+ return 1;
7818
+ }
7819
+ print();
7820
+ const confirmUrl = (0, confirmLinks_1.studyJoinConfirmUrl)(ctx.apiBaseUrl, start.deviceCode);
7821
+ if (confirmUrl) {
7822
+ print(`Open this link to confirm: ${confirmUrl}`);
7823
+ print(`Or confirm in the Ascenda app with code ${start.deviceCode}.`);
7824
+ } else {
7825
+ print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
7826
+ }
7827
+ print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
7828
+ const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
7829
+ const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
7830
+ while (Date.now() < deadline) {
7831
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
7832
+ let poll;
7833
+ try {
7834
+ poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
7835
+ } catch (error2) {
7836
+ if (!(error2 instanceof http_1.AscendaApiError) || error2.status >= 500 && error2.status <= 599)
7837
+ continue;
7838
+ stderr.write(`${describeSquadronError(error2)}
7839
+ `);
7840
+ return 1;
7841
+ }
7842
+ if (poll.status === "pending")
7843
+ continue;
7844
+ if (poll.status === "confirmed") {
7845
+ const until = poll.endUtc ?? poll.jam?.endUtc ?? leaseEnd(poll.jam ?? {});
7846
+ const seat = poll.jam?.handle ? ` as ${poll.jam.handle}` : "";
7847
+ print();
7848
+ print(poll.jam?.alreadyJoined ? `You already have a seat${seat}.` : `Joined${seat}.`);
7849
+ print(until ? `Your activity counts are shared with this squadron until ${formatLocalDate(until)}.` : "Your activity counts are shared with this squadron until the sortie's sharing ends. The server didn't give a date.");
7850
+ print(describeStatusAfterJoin(poll.jam));
7851
+ return 0;
7852
+ }
7853
+ if (poll.status === "expired") {
7854
+ print();
7855
+ print("This code expired before it was confirmed. Run squadron again for a fresh code.");
7856
+ return 1;
7857
+ }
7858
+ print();
7859
+ print(describeSquadronRefusal(poll.refusedReason ?? void 0));
7860
+ return 1;
7861
+ }
7862
+ print();
7863
+ print("Timed out waiting for confirmation. Run squadron again for a fresh code.");
7864
+ return 1;
7865
+ } finally {
7866
+ prompt.close();
7867
+ }
7868
+ }
7869
+ function leaseEnd(jam) {
7870
+ const from = Date.parse(jam.startedAt ?? jam.quorumDeadline ?? "");
7871
+ if (Number.isNaN(from) || typeof jam.durationMinutes !== "number")
7872
+ return void 0;
7873
+ return new Date(from + (jam.durationMinutes + 7 * 24 * 60) * 6e4).toISOString();
7874
+ }
7875
+ function notNow(print) {
7876
+ print("Not now.");
7877
+ return 0;
7878
+ }
7879
+ async function askFromList(prompt, print, label, list, suggested, emptyMeans) {
7880
+ print(`${label === "Aircraft" ? "Aircraft" : `${label}s`}: ${list.join(", ")}`);
7881
+ for (; ; ) {
7882
+ const answer = await prompt.ask(`${label} [${emptyMeans ?? suggested}]: `);
7883
+ if (answer === void 0)
7884
+ return void 0;
7885
+ if (answer === "")
7886
+ return suggested;
7887
+ const value = answer.toLowerCase();
7888
+ const byNumber = /^\d+$/.test(value) ? list[Number(value) - 1] : void 0;
7889
+ if (byNumber)
7890
+ return byNumber;
7891
+ if (list.includes(value))
7892
+ return value;
7893
+ print(`Pick one of: ${list.join(", ")}.`);
7894
+ }
7895
+ }
7896
+ function describeGate(jam) {
7897
+ const length = jam.durationMinutes ? `${jam.durationMinutes}-minute flight plan` : "flight plan";
7898
+ if (jam.status === "live")
7899
+ return `In the air now, ${length}.`;
7900
+ const have = jam.activeParticipants ?? 0;
7901
+ const need = jam.minParticipants ?? 0;
7902
+ const deadline = jam.quorumDeadline ? `, gate closes ${formatLocalTime(jam.quorumDeadline)}` : "";
7903
+ return need > have ? `On the ground: ${have} of ${need} pilots in${deadline}. The ${length} starts when the squadron fills.` : `On the ground${deadline}. ${length[0].toUpperCase()}${length.slice(1)}.`;
7904
+ }
7905
+ function describeStatusAfterJoin(jam) {
7906
+ if (!jam)
7907
+ return "Open the Ascenda app to watch the squadron.";
7908
+ if (jam.status === "live" && jam.expiresAt)
7909
+ return `The squadron is in the air until ${formatLocalTime(jam.expiresAt)}. Open the Ascenda app to watch.`;
7910
+ const have = jam.activeParticipants;
7911
+ const need = jam.minParticipants;
7912
+ if (have !== void 0 && need !== void 0 && need > have)
7913
+ return `${have} of ${need} pilots in. The clock starts when the squadron fills.`;
7914
+ return "Open the Ascenda app to watch the squadron.";
7915
+ }
7916
+ function describeSquadronRefusal(code) {
7917
+ switch (code) {
7918
+ case "join_code_not_found":
7919
+ return "No sortie has that booking reference, or it has ended.";
7920
+ case "jam_closed":
7921
+ return "That sortie has ended.";
7922
+ case "jam_locked":
7923
+ return "This sortie's gate is closed. Ask the host to open it.";
7924
+ case "jam_already_left":
7925
+ return "You left this sortie, and leaving is final. Ask the host for a new one.";
7926
+ case "jam_handle_taken":
7927
+ return "Another pilot has that callsign. Run squadron again and pick another.";
7928
+ case "jam_requires_account":
7929
+ return "A sortie needs a signed-in Ascenda account, not a guest one.";
7930
+ case "jam_handle_required":
7931
+ case "jam_handle_too_long":
7932
+ case "jam_handle_invalid":
7933
+ return "The server didn't accept that callsign. Run squadron again and pick another.";
7934
+ case "jam_aircraft_unknown":
7935
+ return "The server didn't recognise that aircraft.";
7936
+ case "jam_colour_unknown":
7937
+ return "The server didn't recognise that colour.";
7938
+ case "unknown_mode":
7939
+ return "This server's join door didn't accept a sortie. It may be older than this command.";
7940
+ case "too_many_open_sessions":
7941
+ return "Too many joins are waiting to be confirmed. Confirm or let one expire, then try again.";
7942
+ case "jam_not_enabled":
7943
+ return "Squadron isn't switched on for this server yet.";
7944
+ default:
7945
+ return code ? `The server refused the join (${code}).` : "The server refused the join.";
7946
+ }
7947
+ }
7948
+ function describeSquadronError(error2) {
7949
+ if (error2 instanceof http_1.AscendaApiError) {
7950
+ if (error2.status === 401)
7951
+ return "This collector's pairing isn't accepted any more. Run pair, then try again.";
7952
+ if (error2.status === 404 && !error2.errorCode?.startsWith("jam_"))
7953
+ return describeSquadronRefusal("join_code_not_found");
7954
+ return describeSquadronRefusal(error2.errorCode);
7955
+ }
7956
+ return `Couldn't reach Ascenda: ${error2 instanceof Error ? error2.message : String(error2)}`;
7957
+ }
7958
+ function createPrompter(stdin, stdout) {
7959
+ const rl = readline.createInterface({ input: stdin, output: stdout });
7960
+ let closed = false;
7961
+ const lines = [];
7962
+ let waiting;
7963
+ rl.on("line", (line) => {
7964
+ if (waiting) {
7965
+ const resolve = waiting;
7966
+ waiting = void 0;
7967
+ resolve(line.trim());
7968
+ } else {
7969
+ lines.push(line.trim());
7970
+ }
7971
+ });
7972
+ rl.on("close", () => {
7973
+ closed = true;
7974
+ if (waiting) {
7975
+ const resolve = waiting;
7976
+ waiting = void 0;
7977
+ resolve(void 0);
7978
+ }
7979
+ });
7980
+ return {
7981
+ ask(question) {
7982
+ if (lines.length > 0) {
7983
+ stdout.write(question);
7984
+ return Promise.resolve(lines.shift());
7985
+ }
7986
+ if (closed)
7987
+ return Promise.resolve(void 0);
7988
+ stdout.write(question);
7989
+ return new Promise((resolve) => {
7990
+ waiting = resolve;
7991
+ });
7992
+ },
7993
+ close() {
7994
+ if (!closed)
7995
+ rl.close();
7996
+ }
7997
+ };
7998
+ }
7999
+ function formatLocalTime(iso) {
8000
+ const date3 = new Date(iso);
8001
+ if (Number.isNaN(date3.getTime()))
8002
+ return iso;
8003
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date3);
8004
+ }
8005
+ function formatLocalDate(iso) {
8006
+ const date3 = new Date(iso);
8007
+ if (Number.isNaN(date3.getTime()))
8008
+ return iso;
8009
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", year: "numeric" }).format(date3);
8010
+ }
8011
+ }
8012
+ });
8013
+
6777
8014
  // ../packages/tool-kit/out/pluginBundle.js
6778
8015
  var require_pluginBundle = __commonJS({
6779
8016
  "../packages/tool-kit/out/pluginBundle.js"(exports) {
@@ -7012,11 +8249,12 @@ var require_out3 = __commonJS({
7012
8249
  "../packages/tool-kit/out/index.js"(exports) {
7013
8250
  "use strict";
7014
8251
  Object.defineProperty(exports, "__esModule", { value: true });
7015
- exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.startBackgroundFlush = exports.runOutboxFlush = exports.hookDeliveryInline = exports.flushLockPath = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = exports.FLUSH_LOCK_FRESH_MS = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.detectCollectorPlatform = exports.COLLECTOR_PLATFORM = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.shellCommandFacts = exports.invitesDebrief = exports.classifyMcpWorkMilestone = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
7016
- exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.readTurnPromptId = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeRepoKeysSetting = exports.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.trustProblemLines = exports.runCliAgentSetup = exports.registeredHookSets = exports.ourHookPositions = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.withPromptId = exports.withForgeKeys = exports.loadCliAgentConfig = exports.flushHookOutbox = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.resolveEventLog = exports.parseEventLogFlag = void 0;
7017
- exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.repoKeysEnabled = exports.deriveForgeKeysForCwd = exports.REPO_KEYS_ENV_VAR = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeBranchKey = exports.forgeRepoKey = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = void 0;
7018
- exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.pluginBundlePaths = exports.installPluginBundle = exports.describePluginBundleOutcome = exports.replaceSettingsFile = exports.writeAtomically = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.isDowngrade = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = exports.saverSupportDir = exports.saverStatusDir = void 0;
7019
- exports.writePairingJoinOutcome = exports.settleStudyJoin = exports.pairingJoinOutcome = exports.pairingAttemptLines = exports.createPairingAttempt = exports.PAIR_ORG_JOIN_CODE_ENV = exports.PAIR_JOIN_OUTCOME_FILE_ENV = exports.studyJoinConfirmUrl = exports.pairingConfirmUrl = exports.pairingConfirmLines = exports.runStudyJoin = exports.gitOfferLine = exports.formatWindow = exports.describeStudyGrant = exports.describeStudyKind = exports.describeStudyJoinRefusal = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = void 0;
8252
+ exports.RELEASE_CHECK_ENV_VAR = exports.startBackgroundFlush = exports.runOutboxFlush = exports.hookDeliveryInline = exports.flushLockPath = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = exports.FLUSH_LOCK_FRESH_MS = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.detectCollectorPlatform = exports.COLLECTOR_PLATFORM = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.withModelOnChange = exports.modelFieldsFor = exports.clearSentModelId = exports.recordSentModelId = exports.readSentModelId = exports.claudeCodeModelRoute = exports.modelRouteFromCodexProvider = exports.modelRouteFromSlug = exports.classifyEffortClass = exports.isPremiumModelClass = exports.PREMIUM_MODEL_CLASSES = exports.classifyModelClass = exports.autonomyBand = exports.shellCommandFacts = exports.invitesDebrief = exports.classifyMcpWorkMilestone = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
8253
+ exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.trustProblemLines = exports.runCliAgentSetup = exports.registeredHookSets = exports.ourHookPositions = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.withPromptId = exports.withForgeKeys = exports.loadCliAgentConfig = exports.flushHookOutbox = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.resolveEventLog = exports.parseEventLogFlag = exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.runsFromInstalledBundle = exports.releaseStanding = exports.releaseCheckPath = exports.refreshReleaseCheck = exports.readReleaseCheck = exports.pendingReleaseNotice = exports.installedBundleVersion = exports.describeReleaseCheck = exports.compareReleases = exports.RELEASE_MANIFEST_URL = void 0;
8254
+ exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordSentEffortLevel = exports.readSentEffortLevel = exports.clearSentEffortLevel = exports.recordTurnStart = exports.readTurnPromptId = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeRepoKeysSetting = exports.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = void 0;
8255
+ exports.readLastHook = exports.lastHookPath = exports.isDowngrade = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.promptSizeMetadata = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.startSquadronJoin = exports.previewJoinCode = exports.SQUADRON_COLOURS = exports.SQUADRON_AIRCRAFT = exports.describeSquadronRefusal = exports.describeGate = exports.callsignProblem = exports.normaliseBookingReference = exports.generateCallsign = exports.leaseEnd = exports.runSquadronJoin = exports.repoKeysEnabled = exports.deriveForgeKeysForCwd = exports.REPO_KEYS_ENV_VAR = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeBranchKey = exports.forgeRepoKey = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = void 0;
8256
+ exports.describeStudyJoinRefusal = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.pluginBundlePaths = exports.installPluginBundle = exports.describePluginBundleOutcome = exports.replaceSettingsFile = exports.writeAtomically = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = void 0;
8257
+ exports.writePairingJoinOutcome = exports.settleStudyJoin = exports.pairingJoinOutcome = exports.pairingAttemptLines = exports.createPairingAttempt = exports.PAIR_ORG_JOIN_CODE_ENV = exports.PAIR_JOIN_OUTCOME_FILE_ENV = exports.studyJoinConfirmUrl = exports.pairingConfirmUrl = exports.pairingConfirmLines = exports.WEEKLY_POSTER_CONNECT_URL = exports.runStudyJoin = exports.gitOfferLine = exports.formatWindow = exports.describeStudyGrant = exports.describeStudyKind = void 0;
7020
8258
  var commandClassifier_1 = require_commandClassifier();
7021
8259
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
7022
8260
  return commandClassifier_1.classifyCommand;
@@ -7053,6 +8291,42 @@ var require_out3 = __commonJS({
7053
8291
  Object.defineProperty(exports, "classifyModelClass", { enumerable: true, get: function() {
7054
8292
  return modelClassifier_1.classifyModelClass;
7055
8293
  } });
8294
+ Object.defineProperty(exports, "PREMIUM_MODEL_CLASSES", { enumerable: true, get: function() {
8295
+ return modelClassifier_1.PREMIUM_MODEL_CLASSES;
8296
+ } });
8297
+ Object.defineProperty(exports, "isPremiumModelClass", { enumerable: true, get: function() {
8298
+ return modelClassifier_1.isPremiumModelClass;
8299
+ } });
8300
+ var effortClassifier_1 = require_effortClassifier();
8301
+ Object.defineProperty(exports, "classifyEffortClass", { enumerable: true, get: function() {
8302
+ return effortClassifier_1.classifyEffortClass;
8303
+ } });
8304
+ var modelRoute_1 = require_modelRoute();
8305
+ Object.defineProperty(exports, "modelRouteFromSlug", { enumerable: true, get: function() {
8306
+ return modelRoute_1.modelRouteFromSlug;
8307
+ } });
8308
+ Object.defineProperty(exports, "modelRouteFromCodexProvider", { enumerable: true, get: function() {
8309
+ return modelRoute_1.modelRouteFromCodexProvider;
8310
+ } });
8311
+ Object.defineProperty(exports, "claudeCodeModelRoute", { enumerable: true, get: function() {
8312
+ return modelRoute_1.claudeCodeModelRoute;
8313
+ } });
8314
+ var modelState_1 = require_modelState();
8315
+ Object.defineProperty(exports, "readSentModelId", { enumerable: true, get: function() {
8316
+ return modelState_1.readSentModelId;
8317
+ } });
8318
+ Object.defineProperty(exports, "recordSentModelId", { enumerable: true, get: function() {
8319
+ return modelState_1.recordSentModelId;
8320
+ } });
8321
+ Object.defineProperty(exports, "clearSentModelId", { enumerable: true, get: function() {
8322
+ return modelState_1.clearSentModelId;
8323
+ } });
8324
+ Object.defineProperty(exports, "modelFieldsFor", { enumerable: true, get: function() {
8325
+ return modelState_1.modelFieldsFor;
8326
+ } });
8327
+ Object.defineProperty(exports, "withModelOnChange", { enumerable: true, get: function() {
8328
+ return modelState_1.withModelOnChange;
8329
+ } });
7056
8330
  var buckets_1 = require_buckets();
7057
8331
  Object.defineProperty(exports, "bucketLinesChanged", { enumerable: true, get: function() {
7058
8332
  return buckets_1.bucketLinesChanged;
@@ -7143,6 +8417,40 @@ var require_out3 = __commonJS({
7143
8417
  Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
7144
8418
  return backgroundDelivery_1.startBackgroundFlush;
7145
8419
  } });
8420
+ var releaseCheck_1 = require_releaseCheck();
8421
+ Object.defineProperty(exports, "RELEASE_CHECK_ENV_VAR", { enumerable: true, get: function() {
8422
+ return releaseCheck_1.RELEASE_CHECK_ENV_VAR;
8423
+ } });
8424
+ Object.defineProperty(exports, "RELEASE_MANIFEST_URL", { enumerable: true, get: function() {
8425
+ return releaseCheck_1.RELEASE_MANIFEST_URL;
8426
+ } });
8427
+ Object.defineProperty(exports, "compareReleases", { enumerable: true, get: function() {
8428
+ return releaseCheck_1.compareReleases;
8429
+ } });
8430
+ Object.defineProperty(exports, "describeReleaseCheck", { enumerable: true, get: function() {
8431
+ return releaseCheck_1.describeReleaseCheck;
8432
+ } });
8433
+ Object.defineProperty(exports, "installedBundleVersion", { enumerable: true, get: function() {
8434
+ return releaseCheck_1.installedBundleVersion;
8435
+ } });
8436
+ Object.defineProperty(exports, "pendingReleaseNotice", { enumerable: true, get: function() {
8437
+ return releaseCheck_1.pendingReleaseNotice;
8438
+ } });
8439
+ Object.defineProperty(exports, "readReleaseCheck", { enumerable: true, get: function() {
8440
+ return releaseCheck_1.readReleaseCheck;
8441
+ } });
8442
+ Object.defineProperty(exports, "refreshReleaseCheck", { enumerable: true, get: function() {
8443
+ return releaseCheck_1.refreshReleaseCheck;
8444
+ } });
8445
+ Object.defineProperty(exports, "releaseCheckPath", { enumerable: true, get: function() {
8446
+ return releaseCheck_1.releaseCheckPath;
8447
+ } });
8448
+ Object.defineProperty(exports, "releaseStanding", { enumerable: true, get: function() {
8449
+ return releaseCheck_1.releaseStanding;
8450
+ } });
8451
+ Object.defineProperty(exports, "runsFromInstalledBundle", { enumerable: true, get: function() {
8452
+ return releaseCheck_1.runsFromInstalledBundle;
8453
+ } });
7146
8454
  var eventSender_1 = require_eventSender();
7147
8455
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
7148
8456
  return eventSender_1.AscendaEventSender;
@@ -7301,6 +8609,16 @@ var require_out3 = __commonJS({
7301
8609
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
7302
8610
  return turnState_1.recordTurnStart;
7303
8611
  } });
8612
+ var effortState_1 = require_effortState();
8613
+ Object.defineProperty(exports, "clearSentEffortLevel", { enumerable: true, get: function() {
8614
+ return effortState_1.clearSentEffortLevel;
8615
+ } });
8616
+ Object.defineProperty(exports, "readSentEffortLevel", { enumerable: true, get: function() {
8617
+ return effortState_1.readSentEffortLevel;
8618
+ } });
8619
+ Object.defineProperty(exports, "recordSentEffortLevel", { enumerable: true, get: function() {
8620
+ return effortState_1.recordSentEffortLevel;
8621
+ } });
7304
8622
  var tokenStore_1 = require_tokenStore();
7305
8623
  Object.defineProperty(exports, "EVENT_TOKEN_TTL_MS", { enumerable: true, get: function() {
7306
8624
  return tokenStore_1.EVENT_TOKEN_TTL_MS;
@@ -7460,6 +8778,41 @@ var require_out3 = __commonJS({
7460
8778
  Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
7461
8779
  return forgeKeys_1.repoKeysEnabled;
7462
8780
  } });
8781
+ var squadronJoin_1 = require_squadronJoin();
8782
+ Object.defineProperty(exports, "runSquadronJoin", { enumerable: true, get: function() {
8783
+ return squadronJoin_1.runSquadronJoin;
8784
+ } });
8785
+ Object.defineProperty(exports, "leaseEnd", { enumerable: true, get: function() {
8786
+ return squadronJoin_1.leaseEnd;
8787
+ } });
8788
+ Object.defineProperty(exports, "generateCallsign", { enumerable: true, get: function() {
8789
+ return squadronJoin_1.generateCallsign;
8790
+ } });
8791
+ Object.defineProperty(exports, "normaliseBookingReference", { enumerable: true, get: function() {
8792
+ return squadronJoin_1.normaliseBookingReference;
8793
+ } });
8794
+ Object.defineProperty(exports, "callsignProblem", { enumerable: true, get: function() {
8795
+ return squadronJoin_1.callsignProblem;
8796
+ } });
8797
+ Object.defineProperty(exports, "describeGate", { enumerable: true, get: function() {
8798
+ return squadronJoin_1.describeGate;
8799
+ } });
8800
+ Object.defineProperty(exports, "describeSquadronRefusal", { enumerable: true, get: function() {
8801
+ return squadronJoin_1.describeSquadronRefusal;
8802
+ } });
8803
+ Object.defineProperty(exports, "SQUADRON_AIRCRAFT", { enumerable: true, get: function() {
8804
+ return squadronJoin_1.SQUADRON_AIRCRAFT;
8805
+ } });
8806
+ Object.defineProperty(exports, "SQUADRON_COLOURS", { enumerable: true, get: function() {
8807
+ return squadronJoin_1.SQUADRON_COLOURS;
8808
+ } });
8809
+ var http_1 = require_http();
8810
+ Object.defineProperty(exports, "previewJoinCode", { enumerable: true, get: function() {
8811
+ return http_1.previewJoinCode;
8812
+ } });
8813
+ Object.defineProperty(exports, "startSquadronJoin", { enumerable: true, get: function() {
8814
+ return http_1.startSquadronJoin;
8815
+ } });
7463
8816
  var liveBus_1 = require_liveBus();
7464
8817
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
7465
8818
  return liveBus_1.emitLiveSignal;
@@ -7470,6 +8823,9 @@ var require_out3 = __commonJS({
7470
8823
  Object.defineProperty(exports, "bucketPromptSize", { enumerable: true, get: function() {
7471
8824
  return liveBus_1.bucketPromptSize;
7472
8825
  } });
8826
+ Object.defineProperty(exports, "promptSizeMetadata", { enumerable: true, get: function() {
8827
+ return liveBus_1.promptSizeMetadata;
8828
+ } });
7473
8829
  Object.defineProperty(exports, "liveBusSocketPath", { enumerable: true, get: function() {
7474
8830
  return liveBus_1.liveBusSocketPath;
7475
8831
  } });
@@ -7628,48 +8984,48 @@ var require_out3 = __commonJS({
7628
8984
  Object.defineProperty(exports, "scriptMarkerIn", { enumerable: true, get: function() {
7629
8985
  return agentProcess_1.scriptMarkerIn;
7630
8986
  } });
7631
- var http_1 = require_http();
8987
+ var http_2 = require_http();
7632
8988
  Object.defineProperty(exports, "AscendaApiError", { enumerable: true, get: function() {
7633
- return http_1.AscendaApiError;
8989
+ return http_2.AscendaApiError;
7634
8990
  } });
7635
8991
  Object.defineProperty(exports, "createPairingSession", { enumerable: true, get: function() {
7636
- return http_1.createPairingSession;
8992
+ return http_2.createPairingSession;
7637
8993
  } });
7638
8994
  Object.defineProperty(exports, "getPairingStatus", { enumerable: true, get: function() {
7639
- return http_1.getPairingStatus;
8995
+ return http_2.getPairingStatus;
7640
8996
  } });
7641
8997
  Object.defineProperty(exports, "getStudyJoinStatus", { enumerable: true, get: function() {
7642
- return http_1.getStudyJoinStatus;
8998
+ return http_2.getStudyJoinStatus;
7643
8999
  } });
7644
9000
  Object.defineProperty(exports, "renewToolToken", { enumerable: true, get: function() {
7645
- return http_1.renewToolToken;
9001
+ return http_2.renewToolToken;
7646
9002
  } });
7647
9003
  Object.defineProperty(exports, "postToolEvent", { enumerable: true, get: function() {
7648
- return http_1.postToolEvent;
9004
+ return http_2.postToolEvent;
7649
9005
  } });
7650
9006
  Object.defineProperty(exports, "postToolEventsBatch", { enumerable: true, get: function() {
7651
- return http_1.postToolEventsBatch;
9007
+ return http_2.postToolEventsBatch;
7652
9008
  } });
7653
9009
  Object.defineProperty(exports, "parseIngestResponse", { enumerable: true, get: function() {
7654
- return http_1.parseIngestResponse;
9010
+ return http_2.parseIngestResponse;
7655
9011
  } });
7656
9012
  Object.defineProperty(exports, "isRetryableStatus", { enumerable: true, get: function() {
7657
- return http_1.isRetryableStatus;
9013
+ return http_2.isRetryableStatus;
7658
9014
  } });
7659
9015
  Object.defineProperty(exports, "readInitiatives", { enumerable: true, get: function() {
7660
- return http_1.readInitiatives;
9016
+ return http_2.readInitiatives;
7661
9017
  } });
7662
9018
  Object.defineProperty(exports, "readStudyNotices", { enumerable: true, get: function() {
7663
- return http_1.readStudyNotices;
9019
+ return http_2.readStudyNotices;
7664
9020
  } });
7665
9021
  Object.defineProperty(exports, "markStudyNoticeShown", { enumerable: true, get: function() {
7666
- return http_1.markStudyNoticeShown;
9022
+ return http_2.markStudyNoticeShown;
7667
9023
  } });
7668
9024
  Object.defineProperty(exports, "setStudyObjection", { enumerable: true, get: function() {
7669
- return http_1.setStudyObjection;
9025
+ return http_2.setStudyObjection;
7670
9026
  } });
7671
9027
  Object.defineProperty(exports, "startStudyJoin", { enumerable: true, get: function() {
7672
- return http_1.startStudyJoin;
9028
+ return http_2.startStudyJoin;
7673
9029
  } });
7674
9030
  var initiatives_1 = require_initiatives();
7675
9031
  Object.defineProperty(exports, "INITIATIVE_COPY", { enumerable: true, get: function() {
@@ -7714,6 +9070,9 @@ var require_out3 = __commonJS({
7714
9070
  return studyJoin_1.runStudyJoin;
7715
9071
  } });
7716
9072
  var confirmLinks_1 = require_confirmLinks();
9073
+ Object.defineProperty(exports, "WEEKLY_POSTER_CONNECT_URL", { enumerable: true, get: function() {
9074
+ return confirmLinks_1.WEEKLY_POSTER_CONNECT_URL;
9075
+ } });
7717
9076
  Object.defineProperty(exports, "pairingConfirmLines", { enumerable: true, get: function() {
7718
9077
  return confirmLinks_1.pairingConfirmLines;
7719
9078
  } });
@@ -28894,6 +30253,7 @@ var RESERVED_METADATA_KEYS = /* @__PURE__ */ new Set([
28894
30253
  "outcome",
28895
30254
  "trigger",
28896
30255
  "promptClass",
30256
+ "promptSizeBucket",
28897
30257
  "reason",
28898
30258
  "afterHours",
28899
30259
  "activity",