@ascenda-one/claude-code-hooks 0.1.40 → 0.1.42

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
@@ -611,7 +611,7 @@ var require_metricKeys = __commonJS({
611
611
  family: "context",
612
612
  readBy: ["handoff"],
613
613
  unit: "tokens",
614
- note: "Codex only: the model_context_window the rollout itself recorded \u2014 the real denominator its contextWindowPeakPct was computed against. Claude Code records no window and its ratio assumes 200k; absent here means the store never said."
614
+ note: "Codex: the model_context_window the rollout itself recorded \u2014 the real denominator its contextWindowPeakPct was computed against. VS Code: the largest modelConfiguration.contextSize a Copilot request recorded. Claude Code records no window and its ratio assumes 200k; absent here means the store never said."
615
615
  },
616
616
  date: { family: "clock", readBy: ["handoff"] },
617
617
  errorCount: { family: "outcome", readBy: ["handoff"] },
@@ -727,6 +727,17 @@ var require_metricKeys = __commonJS({
727
727
  unit: "lines",
728
728
  note: "Claude Code only: user lines written by the Agent SDK or a headless run (entrypoint sdk-*). Nobody typed them, so promptCount leaves them out. Counted once per line across the store."
729
729
  },
730
+ copilotCredits: {
731
+ family: "context",
732
+ readBy: ["diagnostic"],
733
+ unit: "Copilot credits",
734
+ note: "VS Code only: the sum of each Copilot request's copilotCredits, rounded to five decimal places. Absent where no request recorded the figure, which Copilot builds before Jun 2026 don't."
735
+ },
736
+ reasoningEffort: {
737
+ family: "model",
738
+ readBy: ["diagnostic"],
739
+ note: "VS Code only: the modelConfiguration.reasoningEffort most of a Copilot session's requests ran with. Absent where no request recorded a model configuration."
740
+ },
730
741
  tokensNotCollected: {
731
742
  family: "context",
732
743
  readBy: ["diagnostic"],
@@ -740,7 +751,28 @@ var require_metricKeys = __commonJS({
740
751
  duplicateChatSessions: {
741
752
  family: "reading",
742
753
  readBy: ["diagnostic"],
743
- note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
754
+ note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once. Copilot CLI uses it for a session written both as a directory and as an older flat file."
755
+ },
756
+ clientName: {
757
+ family: "session",
758
+ readBy: ["diagnostic"],
759
+ 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."
760
+ },
761
+ totalApiDurationMs: {
762
+ family: "session",
763
+ readBy: ["diagnostic"],
764
+ unit: "milliseconds",
765
+ note: "Copilot CLI only: session.shutdown.totalApiDurationMs, the time the session spent waiting on model calls. Absent where the session has no shutdown event."
766
+ },
767
+ selectedModel: {
768
+ family: "model",
769
+ readBy: ["diagnostic"],
770
+ note: "Copilot CLI only: the model the person chose at session start (session.start.selectedModel), which is auto when they let the router pick. primaryModel is the model that served the session, so the two differ exactly when the router chose."
771
+ },
772
+ selectedModelClass: {
773
+ family: "model",
774
+ readBy: ["diagnostic"],
775
+ note: "Copilot CLI only: classifyModelClass of selectedModel, so a session whose person picked auto reads router:auto beside the served model's class."
744
776
  },
745
777
  sessionsStartedFromBubble: {
746
778
  family: "reading",
@@ -899,6 +931,9 @@ var require_out = __commonJS({
899
931
  outcome: "outcome",
900
932
  trigger: "outcome",
901
933
  promptClass: "counts",
934
+ // One letter for how long the prompt was, worked out on this machine.
935
+ // Never the text or its length.
936
+ promptSizeBucket: "counts",
902
937
  reason: "outcome",
903
938
  afterHours: "clock",
904
939
  activity: "counts",
@@ -958,6 +993,7 @@ var require_out = __commonJS({
958
993
  "outcome",
959
994
  "trigger",
960
995
  "promptClass",
996
+ "promptSizeBucket",
961
997
  "reason",
962
998
  "afterHours",
963
999
  "activity",
@@ -1262,7 +1298,7 @@ var require_collectorVersion = __commonJS({
1262
1298
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
1263
1299
  exports.describeCollectorVersion = describeCollectorVersion2;
1264
1300
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
1265
- exports.COLLECTOR_VERSION = "0.1.40" ? "0.1.40" : exports.UNRELEASED_COLLECTOR_VERSION;
1301
+ exports.COLLECTOR_VERSION = "0.1.42" ? "0.1.42" : exports.UNRELEASED_COLLECTOR_VERSION;
1266
1302
  function describeCollectorVersion2(version = exports.COLLECTOR_VERSION) {
1267
1303
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
1268
1304
  }
@@ -2368,6 +2404,8 @@ var require_http = __commonJS({
2368
2404
  exports.createPairingSession = createPairingSession2;
2369
2405
  exports.getPairingStatus = getPairingStatus3;
2370
2406
  exports.startStudyJoin = startStudyJoin;
2407
+ exports.previewJoinCode = previewJoinCode;
2408
+ exports.startSquadronJoin = startSquadronJoin;
2371
2409
  exports.getStudyJoinStatus = getStudyJoinStatus;
2372
2410
  exports.readInitiatives = readInitiatives;
2373
2411
  exports.readStudyNotices = readStudyNotices;
@@ -2419,6 +2457,31 @@ var require_http = __commonJS({
2419
2457
  throw await apiError(response);
2420
2458
  return await response.json();
2421
2459
  }
2460
+ async function previewJoinCode(apiBaseUrl, joinCode) {
2461
+ const response = await fetch(`${apiBaseUrl}/api/share/join/${encodeURIComponent(joinCode)}`, {
2462
+ method: "GET",
2463
+ headers: { Accept: "application/json" }
2464
+ });
2465
+ if (!response.ok)
2466
+ throw await apiError(response);
2467
+ return await response.json();
2468
+ }
2469
+ async function startSquadronJoin(apiBaseUrl, eventWriteToken, seat) {
2470
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2471
+ method: "POST",
2472
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2473
+ body: JSON.stringify({
2474
+ joinCode: seat.joinCode,
2475
+ mode: "jam",
2476
+ handle: seat.handle,
2477
+ ...seat.aircraft ? { aircraft: seat.aircraft } : {},
2478
+ ...seat.colour ? { colour: seat.colour } : {}
2479
+ })
2480
+ });
2481
+ if (!response.ok)
2482
+ throw await apiError(response);
2483
+ return await response.json();
2484
+ }
2422
2485
  async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
2423
2486
  const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
2424
2487
  method: "GET",
@@ -3927,6 +3990,8 @@ var require_hookAdapter = __commonJS({
3927
3990
  if (!logFile)
3928
3991
  throw error;
3929
3992
  logUnsent2(logFile, events, options);
3993
+ if (!(error instanceof MissingInstallationIdError2))
3994
+ throw error;
3930
3995
  return;
3931
3996
  }
3932
3997
  const sender = new eventSender_1.AscendaEventSender({
@@ -4024,17 +4089,20 @@ var require_confirmLinks = __commonJS({
4024
4089
  "../packages/tool-kit/out/confirmLinks.js"(exports) {
4025
4090
  "use strict";
4026
4091
  Object.defineProperty(exports, "__esModule", { value: true });
4092
+ exports.WEEKLY_POSTER_CONNECT_URL = void 0;
4027
4093
  exports.pairingConfirmUrl = pairingConfirmUrl;
4028
4094
  exports.pairingConfirmLines = pairingConfirmLines2;
4029
4095
  exports.studyJoinConfirmUrl = studyJoinConfirmUrl;
4096
+ exports.WEEKLY_POSTER_CONNECT_URL = "https://me.ascendaflow.com/connect";
4030
4097
  function pairingConfirmUrl(qrUrl) {
4031
4098
  return isHttps(qrUrl) ? qrUrl : void 0;
4032
4099
  }
4033
4100
  function pairingConfirmLines2(qrUrl, code) {
4034
4101
  const url = pairingConfirmUrl(qrUrl);
4102
+ const where = [" Ascenda Flow, under Connections \u2192 Ingest telemetry", ` ${exports.WEEKLY_POSTER_CONNECT_URL}, for the weekly poster`];
4035
4103
  if (!url)
4036
- return [`Confirm in the Ascenda app \u2014 code ${code}`];
4037
- return [`Open this link to confirm: ${url}`, `Or paste code ${code} in the Ascenda app.`];
4104
+ return [`Confirm code ${code} in either place:`, ...where];
4105
+ return [`Open this link to confirm: ${url}`, `Or enter code ${code} in either place:`, ...where];
4038
4106
  }
4039
4107
  function studyJoinConfirmUrl(apiBaseUrl, deviceCode) {
4040
4108
  if (!isHttps(apiBaseUrl))
@@ -4095,6 +4163,7 @@ var require_studyJoin = __commonJS({
4095
4163
  };
4096
4164
  }();
4097
4165
  Object.defineProperty(exports, "__esModule", { value: true });
4166
+ exports.gitOfferLine = gitOfferLine;
4098
4167
  exports.runStudyJoin = runStudyJoin2;
4099
4168
  exports.formatWindow = formatWindow;
4100
4169
  exports.describeStudyGrant = describeStudyGrant;
@@ -4103,6 +4172,11 @@ var require_studyJoin = __commonJS({
4103
4172
  var readline = __importStar(__require("node:readline"));
4104
4173
  var confirmLinks_1 = require_confirmLinks();
4105
4174
  var http_1 = require_http();
4175
+ function gitOfferLine(optionalImportStores) {
4176
+ if (!optionalImportStores?.includes("git"))
4177
+ return void 0;
4178
+ 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.";
4179
+ }
4106
4180
  var STUDY_JOIN_MODE = "report";
4107
4181
  var POLL_INTERVAL_MS = 3e3;
4108
4182
  var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
@@ -4139,6 +4213,9 @@ var require_studyJoin = __commonJS({
4139
4213
  print("Report (30 days) grants:");
4140
4214
  for (const grant of start.grants)
4141
4215
  print(` ${describeStudyGrant(grant)}`);
4216
+ const gitOffer = gitOfferLine(start.optionalImportStores);
4217
+ if (gitOffer)
4218
+ print(gitOffer);
4142
4219
  print("");
4143
4220
  print("Study mode needs the Ascenda app. Open the app to join that way instead.");
4144
4221
  print("");
@@ -4193,7 +4270,7 @@ var require_studyJoin = __commonJS({
4193
4270
  print("");
4194
4271
  print("Each of these can be turned off separately, in the app's consent settings.");
4195
4272
  print("The organisation sees group counts, never who joined.");
4196
- report({ status: "joined", start, granted });
4273
+ report({ status: "joined", start, granted, importStores: poll.importStores ?? null });
4197
4274
  return 0;
4198
4275
  }
4199
4276
  if (poll.status === "expired") {
@@ -4215,7 +4292,7 @@ var require_studyJoin = __commonJS({
4215
4292
  print("Each of these can be turned off separately, in the app's consent settings.");
4216
4293
  }
4217
4294
  print("Run join again, or check with your organisation.");
4218
- report({ status: "refused", start, granted, refusedReason: poll.refusedReason, message: describeRefusal(poll.refusedReason) });
4295
+ report({ status: "refused", start, granted, refusedReason: poll.refusedReason, message: describeRefusal(poll.refusedReason), importStores: poll.importStores ?? null });
4219
4296
  return 1;
4220
4297
  }
4221
4298
  print("");
@@ -4396,8 +4473,10 @@ var require_pairingStudyJoin = __commonJS({
4396
4473
  const join4 = attempt.carriesJoin ? session.studyJoin : void 0;
4397
4474
  if (!join4)
4398
4475
  return (0, confirmLinks_1.pairingConfirmLines)(session.qrUrl, session.code);
4476
+ const gitOffer = (0, studyJoin_1.gitOfferLine)(join4.optionalImportStores);
4399
4477
  return [
4400
4478
  `This also joins ${join4.organisationName} (${(0, studyJoin_1.formatWindow)(join4.windowStartUtc, join4.windowEndUtc)}). The page shows what you'd share before you confirm.`,
4479
+ ...gitOffer ? [gitOffer] : [],
4401
4480
  `Open this link to confirm: ${session.qrUrl}`
4402
4481
  ];
4403
4482
  }
@@ -5028,7 +5107,7 @@ var require_setupDisclosure = __commonJS({
5028
5107
  exports.renderSetupDisclosure = renderSetupDisclosure3;
5029
5108
  exports.FAMILY_SENTENCES = {
5030
5109
  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",
5031
- 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",
5110
+ 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",
5032
5111
  tools: "the name of each tool your agent calls",
5033
5112
  outcome: "whether a call succeeded, failed, or was interrupted",
5034
5113
  clock: "your machine's offset from UTC, so an evening is read as an evening",
@@ -5281,6 +5360,7 @@ var require_liveBus = __commonJS({
5281
5360
  exports.existingSocketCandidates = existingSocketCandidates;
5282
5361
  exports.liveBusSocketPath = liveBusSocketPath;
5283
5362
  exports.bucketPromptSize = bucketPromptSize2;
5363
+ exports.promptSizeMetadata = promptSizeMetadata2;
5284
5364
  exports.emitLiveSignal = emitLiveSignal2;
5285
5365
  exports.deliverLine = deliverLine;
5286
5366
  var fs5 = __importStar(__require("fs"));
@@ -5329,6 +5409,9 @@ var require_liveBus = __commonJS({
5329
5409
  return "l";
5330
5410
  return "xl";
5331
5411
  }
5412
+ function promptSizeMetadata2(text) {
5413
+ return text === void 0 ? {} : { promptSizeBucket: bucketPromptSize2(text) };
5414
+ }
5332
5415
  var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
5333
5416
  function onTheWire(signal) {
5334
5417
  const out = { ...signal };
@@ -5967,7 +6050,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5967
6050
  if (options.dryRun) {
5968
6051
  row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())}, so each event runs once`);
5969
6052
  } else if (removeOurHookEntries(otherFile, spec)) {
5970
- row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
6053
+ row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())}, so each event runs once${spec.settings.owned ? "" : ` ${ui.dim("(backup beside it)")}`}`);
5971
6054
  } else {
5972
6055
  row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())} registers these hooks too, so each event runs twice.`);
5973
6056
  detail("", `Remove the ${spec.binaryName} entries from one of the two files.`);
@@ -5994,7 +6077,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5994
6077
  const next = (label, value) => console.log(` ${ui.bold(label.padEnd(6))} ${value}`);
5995
6078
  console.log("");
5996
6079
  if (chosenLocal) {
5997
- console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
6080
+ console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and Ascenda Flow's live view work now.`);
5998
6081
  console.log(" They run on this machine and need no account or pairing.");
5999
6082
  if (eventLog.path)
6000
6083
  console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os4.homedir())}, for you or any tool to read.`);
@@ -6011,9 +6094,9 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
6011
6094
  next(chosenLocal ? "Pair" : "Retry", `${ui.cyan(`${self} setup`)}${chosenLocal ? ui.dim(" (optional)") : ""}`);
6012
6095
  if (chosenLocal) {
6013
6096
  console.log("");
6014
- console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account the"));
6015
- console.log(ui.dim(" Ascenda app is signed in to when you confirm the code, so your sessions appear"));
6016
- console.log(ui.dim(" in the app. Until you pair, nothing leaves this machine."));
6097
+ console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account you"));
6098
+ console.log(ui.dim(" confirm the code with, in Ascenda Flow or at me.ascendaflow.com."));
6099
+ console.log(ui.dim(" Until you pair, nothing leaves this machine."));
6017
6100
  console.log("");
6018
6101
  console.log(ui.dim((0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName }).split("\n").map((line) => ` ${line}`).join("\n")));
6019
6102
  }
@@ -6239,7 +6322,7 @@ Pairing ${status.status}. Run setup again.`);
6239
6322
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
6240
6323
  let settings = { ...spec.settings.scaffold ?? {} };
6241
6324
  const exists = fs5.existsSync(settingsFile);
6242
- if (exists) {
6325
+ if (exists && !spec.settings.owned) {
6243
6326
  const raw = fs5.readFileSync(settingsFile, "utf8").trim();
6244
6327
  if (raw) {
6245
6328
  try {
@@ -6252,7 +6335,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
6252
6335
  }
6253
6336
  }
6254
6337
  const command = hookCommand2(binary, spec);
6255
- const hooks = { ...settings.hooks ?? {} };
6338
+ const hooks = spec.settings.owned ? {} : { ...settings.hooks ?? {} };
6256
6339
  for (const event of spec.hookEvents) {
6257
6340
  hooks[event] = placeOurEntry2(hooks[event] ?? [], spec.settings.entry(command, event), spec);
6258
6341
  }
@@ -6267,6 +6350,11 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
6267
6350
  ${serialised}`);
6268
6351
  return true;
6269
6352
  }
6353
+ if (spec.settings.owned) {
6354
+ fs5.mkdirSync(path4.dirname(settingsFile), { recursive: true });
6355
+ (0, hookRunner_1.writeAtomically)(settingsFile, serialised, 420);
6356
+ return true;
6357
+ }
6270
6358
  (0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
6271
6359
  return true;
6272
6360
  }
@@ -6521,6 +6609,15 @@ ${serialised}`);
6521
6609
  if (found.length)
6522
6610
  lines.push("", ...found);
6523
6611
  }
6612
+ if (spec.doctorExtras) {
6613
+ try {
6614
+ const extra = spec.doctorExtras(ui);
6615
+ if (extra.length)
6616
+ lines.push("", ...extra);
6617
+ } catch (error) {
6618
+ lines.push("", ` ${spec.displayName} checks could not run: ${error instanceof Error ? error.message : String(error)}`);
6619
+ }
6620
+ }
6524
6621
  lines.push("", ...accountLines(ui, spec));
6525
6622
  const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
6526
6623
  lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
@@ -6576,6 +6673,10 @@ ${serialised}`);
6576
6673
  function removeOurHookEntries(settingsFile, spec) {
6577
6674
  if (!fs5.existsSync(settingsFile))
6578
6675
  return true;
6676
+ if (spec.settings.owned) {
6677
+ fs5.rmSync(settingsFile, { force: true });
6678
+ return true;
6679
+ }
6579
6680
  try {
6580
6681
  const settings = JSON.parse(fs5.readFileSync(settingsFile, "utf8"));
6581
6682
  const hooks = { ...settings.hooks ?? {} };
@@ -6603,7 +6704,7 @@ ${serialised}`);
6603
6704
  console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
6604
6705
  return 1;
6605
6706
  }
6606
- console.log(`hooks removed from ${settingsFile}`);
6707
+ console.log(spec.settings.owned ? `removed ${settingsFile}` : `hooks removed from ${settingsFile}`);
6607
6708
  }
6608
6709
  for (const file of (0, hookRunner_1.removeHookRunner)(spec.binaryName)) {
6609
6710
  if (!file.endsWith(".node") && !file.endsWith(".no-node"))
@@ -6714,6 +6815,395 @@ var require_turnState = __commonJS({
6714
6815
  }
6715
6816
  });
6716
6817
 
6818
+ // ../packages/tool-kit/out/squadronJoin.js
6819
+ var require_squadronJoin = __commonJS({
6820
+ "../packages/tool-kit/out/squadronJoin.js"(exports) {
6821
+ "use strict";
6822
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
6823
+ if (k2 === void 0) k2 = k;
6824
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6825
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6826
+ desc = { enumerable: true, get: function() {
6827
+ return m[k];
6828
+ } };
6829
+ }
6830
+ Object.defineProperty(o, k2, desc);
6831
+ } : function(o, m, k, k2) {
6832
+ if (k2 === void 0) k2 = k;
6833
+ o[k2] = m[k];
6834
+ });
6835
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
6836
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
6837
+ } : function(o, v) {
6838
+ o["default"] = v;
6839
+ });
6840
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
6841
+ var ownKeys = function(o) {
6842
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
6843
+ var ar = [];
6844
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
6845
+ return ar;
6846
+ };
6847
+ return ownKeys(o);
6848
+ };
6849
+ return function(mod) {
6850
+ if (mod && mod.__esModule) return mod;
6851
+ var result = {};
6852
+ if (mod != null) {
6853
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
6854
+ }
6855
+ __setModuleDefault(result, mod);
6856
+ return result;
6857
+ };
6858
+ }();
6859
+ Object.defineProperty(exports, "__esModule", { value: true });
6860
+ exports.SQUADRON_COLOURS = exports.SQUADRON_AIRCRAFT = void 0;
6861
+ exports.generateCallsign = generateCallsign;
6862
+ exports.normaliseBookingReference = normaliseBookingReference;
6863
+ exports.callsignProblem = callsignProblem;
6864
+ exports.runSquadronJoin = runSquadronJoin2;
6865
+ exports.leaseEnd = leaseEnd;
6866
+ exports.describeGate = describeGate;
6867
+ exports.describeSquadronRefusal = describeSquadronRefusal;
6868
+ var readline = __importStar(__require("node:readline"));
6869
+ var node_crypto_1 = __require("node:crypto");
6870
+ var confirmLinks_1 = require_confirmLinks();
6871
+ var http_1 = require_http();
6872
+ exports.SQUADRON_AIRCRAFT = ["trainer", "airliner", "glider", "fighter", "stealth", "floatplane"];
6873
+ exports.SQUADRON_COLOURS = ["orange", "yellow", "ivory", "charcoal", "grey", "red"];
6874
+ var CALLSIGN_WORDS = ["Kestrel", "Falcon", "Heron", "Swift", "Osprey", "Raven", "Merlin", "Puffin", "Condor", "Harrier", "Kite", "Tern"];
6875
+ function generateCallsign() {
6876
+ return `${CALLSIGN_WORDS[(0, node_crypto_1.randomInt)(CALLSIGN_WORDS.length)]} ${String((0, node_crypto_1.randomInt)(10, 100))}`;
6877
+ }
6878
+ function normaliseBookingReference(raw) {
6879
+ const cleaned = (raw ?? "").replace(/[\s-]/g, "").toUpperCase();
6880
+ return /^[A-Z0-9]{6}$/.test(cleaned) ? cleaned : void 0;
6881
+ }
6882
+ function callsignProblem(callsign) {
6883
+ const trimmed = callsign.trim();
6884
+ if (trimmed.length === 0)
6885
+ return "A callsign can't be empty.";
6886
+ if (trimmed.length > 40)
6887
+ return "A callsign is 40 characters at most.";
6888
+ if (/[\u0000-\u001f\u007f]/.test(trimmed))
6889
+ return "A callsign can't contain control characters.";
6890
+ return void 0;
6891
+ }
6892
+ var POLL_INTERVAL_MS = 3e3;
6893
+ var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
6894
+ async function runSquadronJoin2(ctx) {
6895
+ const stdin = ctx.stdin ?? process.stdin;
6896
+ const stdout = ctx.stdout ?? process.stdout;
6897
+ const stderr = ctx.stderr ?? process.stderr;
6898
+ const print = (line = "") => stdout.write(`${line}
6899
+ `);
6900
+ if (!stdin.isTTY || !stdout.isTTY) {
6901
+ stderr.write("squadron needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
6902
+ return 0;
6903
+ }
6904
+ const reference = normaliseBookingReference(ctx.bookingReference);
6905
+ if (!reference) {
6906
+ stderr.write("A booking reference is six letters or digits, like FEFBDH.\n");
6907
+ return 1;
6908
+ }
6909
+ let preview;
6910
+ try {
6911
+ preview = await (0, http_1.previewJoinCode)(ctx.apiBaseUrl, reference);
6912
+ } catch (error) {
6913
+ stderr.write(`${describeSquadronError(error)}
6914
+ `);
6915
+ return 1;
6916
+ }
6917
+ const jam = preview.jam;
6918
+ if (preview.labRole !== "Jam" || !jam) {
6919
+ stderr.write(`${reference} isn't a Squadron booking reference. If it's a study code, run join instead.
6920
+ `);
6921
+ return 1;
6922
+ }
6923
+ if (jam.acceptsJoins === false) {
6924
+ 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");
6925
+ return 1;
6926
+ }
6927
+ const aircraftList = jam.aircraft?.length ? jam.aircraft : [...exports.SQUADRON_AIRCRAFT];
6928
+ const colourList = jam.colours?.length ? jam.colours : [...exports.SQUADRON_COLOURS];
6929
+ for (const [flag, value, list] of [["--aircraft", ctx.aircraft, aircraftList], ["--colour", ctx.colour, colourList]]) {
6930
+ if (value !== void 0 && !list.includes(value.trim().toLowerCase())) {
6931
+ stderr.write(`${flag} must be one of: ${list.join(", ")}.
6932
+ `);
6933
+ return 1;
6934
+ }
6935
+ }
6936
+ if (ctx.callsign !== void 0) {
6937
+ const problem = callsignProblem(ctx.callsign);
6938
+ if (problem) {
6939
+ stderr.write(`${problem}
6940
+ `);
6941
+ return 1;
6942
+ }
6943
+ }
6944
+ print();
6945
+ print(`Squadron: ${jam.name ?? preview.labName ?? reference}`);
6946
+ if (jam.mission)
6947
+ print(`Mission: ${jam.mission}`);
6948
+ print(describeGate(jam));
6949
+ print();
6950
+ const prompt = createPrompter(stdin, stdout);
6951
+ try {
6952
+ let callsign = ctx.callsign?.trim();
6953
+ if (callsign === void 0) {
6954
+ const suggested = (ctx.generateCallsign ?? generateCallsign)();
6955
+ for (; ; ) {
6956
+ const answer = await prompt.ask(`Callsign [${suggested}]: `);
6957
+ if (answer === void 0)
6958
+ return notNow(print);
6959
+ const chosen = answer === "" ? suggested : answer;
6960
+ const problem = callsignProblem(chosen);
6961
+ if (!problem) {
6962
+ callsign = chosen.trim();
6963
+ break;
6964
+ }
6965
+ print(problem);
6966
+ }
6967
+ }
6968
+ let aircraft = ctx.aircraft?.trim().toLowerCase();
6969
+ if (aircraft === void 0) {
6970
+ const suggested = aircraftList[(0, node_crypto_1.randomInt)(aircraftList.length)];
6971
+ aircraft = await askFromList(prompt, print, "Aircraft", aircraftList, suggested);
6972
+ if (aircraft === void 0)
6973
+ return notNow(print);
6974
+ }
6975
+ let colour = ctx.colour?.trim().toLowerCase();
6976
+ if (colour === void 0) {
6977
+ const picked = await askFromList(prompt, print, "Colour", colourList, "", "dealt for you");
6978
+ if (picked === void 0)
6979
+ return notNow(print);
6980
+ colour = picked === "" ? void 0 : picked;
6981
+ }
6982
+ print();
6983
+ print(`You'll confirm as ${callsign}, ${aircraft}${colour ? `, ${colour}` : ""}. The confirm page lets you change any of them.`);
6984
+ print();
6985
+ print("Joining shares, with this squadron only:");
6986
+ print(` your activity counts from ${ctx.displayName}: prompts, tool calls, turns and edits, as numbers`);
6987
+ print(" your callsign and aircraft, which the other pilots see");
6988
+ print("Never your prompts, code, file names or project names.");
6989
+ print("Sharing stops on the date the server gives when you join. It's printed then.");
6990
+ print();
6991
+ print(" 1) Join");
6992
+ print(" 2) Not now");
6993
+ print();
6994
+ const choice = await prompt.ask("Choice [Not now]: ");
6995
+ if (choice === void 0 || !/^(1|join|y|yes)$/i.test(choice))
6996
+ return notNow(print);
6997
+ prompt.close();
6998
+ let start;
6999
+ try {
7000
+ start = await (0, http_1.startSquadronJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, { joinCode: reference, handle: callsign, aircraft, colour });
7001
+ } catch (error) {
7002
+ const doorClosed = error instanceof http_1.AscendaApiError && error.status === 404 && !error.errorCode?.startsWith("jam_");
7003
+ 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(error)}
7004
+ `);
7005
+ return 1;
7006
+ }
7007
+ if (start.kind !== void 0 && start.kind !== "jam") {
7008
+ stderr.write(`${reference} opened a study join, not a sortie. Run join instead.
7009
+ `);
7010
+ return 1;
7011
+ }
7012
+ print();
7013
+ const confirmUrl = (0, confirmLinks_1.studyJoinConfirmUrl)(ctx.apiBaseUrl, start.deviceCode);
7014
+ if (confirmUrl) {
7015
+ print(`Open this link to confirm: ${confirmUrl}`);
7016
+ print(`Or confirm in the Ascenda app with code ${start.deviceCode}.`);
7017
+ } else {
7018
+ print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
7019
+ }
7020
+ print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
7021
+ const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
7022
+ const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
7023
+ while (Date.now() < deadline) {
7024
+ await new Promise((resolve3) => setTimeout(resolve3, pollIntervalMs));
7025
+ let poll;
7026
+ try {
7027
+ poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
7028
+ } catch (error) {
7029
+ if (!(error instanceof http_1.AscendaApiError) || error.status >= 500 && error.status <= 599)
7030
+ continue;
7031
+ stderr.write(`${describeSquadronError(error)}
7032
+ `);
7033
+ return 1;
7034
+ }
7035
+ if (poll.status === "pending")
7036
+ continue;
7037
+ if (poll.status === "confirmed") {
7038
+ const until = poll.endUtc ?? poll.jam?.endUtc ?? leaseEnd(poll.jam ?? {});
7039
+ const seat = poll.jam?.handle ? ` as ${poll.jam.handle}` : "";
7040
+ print();
7041
+ print(poll.jam?.alreadyJoined ? `You already have a seat${seat}.` : `Joined${seat}.`);
7042
+ 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.");
7043
+ print(describeStatusAfterJoin(poll.jam));
7044
+ return 0;
7045
+ }
7046
+ if (poll.status === "expired") {
7047
+ print();
7048
+ print("This code expired before it was confirmed. Run squadron again for a fresh code.");
7049
+ return 1;
7050
+ }
7051
+ print();
7052
+ print(describeSquadronRefusal(poll.refusedReason ?? void 0));
7053
+ return 1;
7054
+ }
7055
+ print();
7056
+ print("Timed out waiting for confirmation. Run squadron again for a fresh code.");
7057
+ return 1;
7058
+ } finally {
7059
+ prompt.close();
7060
+ }
7061
+ }
7062
+ function leaseEnd(jam) {
7063
+ const from = Date.parse(jam.startedAt ?? jam.quorumDeadline ?? "");
7064
+ if (Number.isNaN(from) || typeof jam.durationMinutes !== "number")
7065
+ return void 0;
7066
+ return new Date(from + (jam.durationMinutes + 7 * 24 * 60) * 6e4).toISOString();
7067
+ }
7068
+ function notNow(print) {
7069
+ print("Not now.");
7070
+ return 0;
7071
+ }
7072
+ async function askFromList(prompt, print, label, list, suggested, emptyMeans) {
7073
+ print(`${label === "Aircraft" ? "Aircraft" : `${label}s`}: ${list.join(", ")}`);
7074
+ for (; ; ) {
7075
+ const answer = await prompt.ask(`${label} [${emptyMeans ?? suggested}]: `);
7076
+ if (answer === void 0)
7077
+ return void 0;
7078
+ if (answer === "")
7079
+ return suggested;
7080
+ const value = answer.toLowerCase();
7081
+ const byNumber = /^\d+$/.test(value) ? list[Number(value) - 1] : void 0;
7082
+ if (byNumber)
7083
+ return byNumber;
7084
+ if (list.includes(value))
7085
+ return value;
7086
+ print(`Pick one of: ${list.join(", ")}.`);
7087
+ }
7088
+ }
7089
+ function describeGate(jam) {
7090
+ const length = jam.durationMinutes ? `${jam.durationMinutes}-minute flight plan` : "flight plan";
7091
+ if (jam.status === "live")
7092
+ return `In the air now, ${length}.`;
7093
+ const have = jam.activeParticipants ?? 0;
7094
+ const need = jam.minParticipants ?? 0;
7095
+ const deadline = jam.quorumDeadline ? `, gate closes ${formatLocalTime(jam.quorumDeadline)}` : "";
7096
+ 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)}.`;
7097
+ }
7098
+ function describeStatusAfterJoin(jam) {
7099
+ if (!jam)
7100
+ return "Open the Ascenda app to watch the squadron.";
7101
+ if (jam.status === "live" && jam.expiresAt)
7102
+ return `The squadron is in the air until ${formatLocalTime(jam.expiresAt)}. Open the Ascenda app to watch.`;
7103
+ const have = jam.activeParticipants;
7104
+ const need = jam.minParticipants;
7105
+ if (have !== void 0 && need !== void 0 && need > have)
7106
+ return `${have} of ${need} pilots in. The clock starts when the squadron fills.`;
7107
+ return "Open the Ascenda app to watch the squadron.";
7108
+ }
7109
+ function describeSquadronRefusal(code) {
7110
+ switch (code) {
7111
+ case "join_code_not_found":
7112
+ return "No sortie has that booking reference, or it has ended.";
7113
+ case "jam_closed":
7114
+ return "That sortie has ended.";
7115
+ case "jam_locked":
7116
+ return "This sortie's gate is closed. Ask the host to open it.";
7117
+ case "jam_already_left":
7118
+ return "You left this sortie, and leaving is final. Ask the host for a new one.";
7119
+ case "jam_handle_taken":
7120
+ return "Another pilot has that callsign. Run squadron again and pick another.";
7121
+ case "jam_requires_account":
7122
+ return "A sortie needs a signed-in Ascenda account, not a guest one.";
7123
+ case "jam_handle_required":
7124
+ case "jam_handle_too_long":
7125
+ case "jam_handle_invalid":
7126
+ return "The server didn't accept that callsign. Run squadron again and pick another.";
7127
+ case "jam_aircraft_unknown":
7128
+ return "The server didn't recognise that aircraft.";
7129
+ case "jam_colour_unknown":
7130
+ return "The server didn't recognise that colour.";
7131
+ case "unknown_mode":
7132
+ return "This server's join door didn't accept a sortie. It may be older than this command.";
7133
+ case "too_many_open_sessions":
7134
+ return "Too many joins are waiting to be confirmed. Confirm or let one expire, then try again.";
7135
+ case "jam_not_enabled":
7136
+ return "Squadron isn't switched on for this server yet.";
7137
+ default:
7138
+ return code ? `The server refused the join (${code}).` : "The server refused the join.";
7139
+ }
7140
+ }
7141
+ function describeSquadronError(error) {
7142
+ if (error instanceof http_1.AscendaApiError) {
7143
+ if (error.status === 401)
7144
+ return "This collector's pairing isn't accepted any more. Run pair, then try again.";
7145
+ if (error.status === 404 && !error.errorCode?.startsWith("jam_"))
7146
+ return describeSquadronRefusal("join_code_not_found");
7147
+ return describeSquadronRefusal(error.errorCode);
7148
+ }
7149
+ return `Couldn't reach Ascenda: ${error instanceof Error ? error.message : String(error)}`;
7150
+ }
7151
+ function createPrompter(stdin, stdout) {
7152
+ const rl = readline.createInterface({ input: stdin, output: stdout });
7153
+ let closed = false;
7154
+ const lines = [];
7155
+ let waiting;
7156
+ rl.on("line", (line) => {
7157
+ if (waiting) {
7158
+ const resolve3 = waiting;
7159
+ waiting = void 0;
7160
+ resolve3(line.trim());
7161
+ } else {
7162
+ lines.push(line.trim());
7163
+ }
7164
+ });
7165
+ rl.on("close", () => {
7166
+ closed = true;
7167
+ if (waiting) {
7168
+ const resolve3 = waiting;
7169
+ waiting = void 0;
7170
+ resolve3(void 0);
7171
+ }
7172
+ });
7173
+ return {
7174
+ ask(question) {
7175
+ if (lines.length > 0) {
7176
+ stdout.write(question);
7177
+ return Promise.resolve(lines.shift());
7178
+ }
7179
+ if (closed)
7180
+ return Promise.resolve(void 0);
7181
+ stdout.write(question);
7182
+ return new Promise((resolve3) => {
7183
+ waiting = resolve3;
7184
+ });
7185
+ },
7186
+ close() {
7187
+ if (!closed)
7188
+ rl.close();
7189
+ }
7190
+ };
7191
+ }
7192
+ function formatLocalTime(iso) {
7193
+ const date = new Date(iso);
7194
+ if (Number.isNaN(date.getTime()))
7195
+ return iso;
7196
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date);
7197
+ }
7198
+ function formatLocalDate(iso) {
7199
+ const date = new Date(iso);
7200
+ if (Number.isNaN(date.getTime()))
7201
+ return iso;
7202
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", year: "numeric" }).format(date);
7203
+ }
7204
+ }
7205
+ });
7206
+
6717
7207
  // ../packages/tool-kit/out/pluginBundle.js
6718
7208
  var require_pluginBundle = __commonJS({
6719
7209
  "../packages/tool-kit/out/pluginBundle.js"(exports) {
@@ -6954,9 +7444,9 @@ var require_out3 = __commonJS({
6954
7444
  Object.defineProperty(exports, "__esModule", { value: true });
6955
7445
  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;
6956
7446
  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;
6957
- 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;
6958
- 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;
6959
- 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.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;
7447
+ 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 = 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;
7448
+ 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 = 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 = void 0;
7449
+ 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 = 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 = void 0;
6960
7450
  var commandClassifier_1 = require_commandClassifier();
6961
7451
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
6962
7452
  return commandClassifier_1.classifyCommand;
@@ -7400,6 +7890,41 @@ var require_out3 = __commonJS({
7400
7890
  Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
7401
7891
  return forgeKeys_1.repoKeysEnabled;
7402
7892
  } });
7893
+ var squadronJoin_1 = require_squadronJoin();
7894
+ Object.defineProperty(exports, "runSquadronJoin", { enumerable: true, get: function() {
7895
+ return squadronJoin_1.runSquadronJoin;
7896
+ } });
7897
+ Object.defineProperty(exports, "leaseEnd", { enumerable: true, get: function() {
7898
+ return squadronJoin_1.leaseEnd;
7899
+ } });
7900
+ Object.defineProperty(exports, "generateCallsign", { enumerable: true, get: function() {
7901
+ return squadronJoin_1.generateCallsign;
7902
+ } });
7903
+ Object.defineProperty(exports, "normaliseBookingReference", { enumerable: true, get: function() {
7904
+ return squadronJoin_1.normaliseBookingReference;
7905
+ } });
7906
+ Object.defineProperty(exports, "callsignProblem", { enumerable: true, get: function() {
7907
+ return squadronJoin_1.callsignProblem;
7908
+ } });
7909
+ Object.defineProperty(exports, "describeGate", { enumerable: true, get: function() {
7910
+ return squadronJoin_1.describeGate;
7911
+ } });
7912
+ Object.defineProperty(exports, "describeSquadronRefusal", { enumerable: true, get: function() {
7913
+ return squadronJoin_1.describeSquadronRefusal;
7914
+ } });
7915
+ Object.defineProperty(exports, "SQUADRON_AIRCRAFT", { enumerable: true, get: function() {
7916
+ return squadronJoin_1.SQUADRON_AIRCRAFT;
7917
+ } });
7918
+ Object.defineProperty(exports, "SQUADRON_COLOURS", { enumerable: true, get: function() {
7919
+ return squadronJoin_1.SQUADRON_COLOURS;
7920
+ } });
7921
+ var http_1 = require_http();
7922
+ Object.defineProperty(exports, "previewJoinCode", { enumerable: true, get: function() {
7923
+ return http_1.previewJoinCode;
7924
+ } });
7925
+ Object.defineProperty(exports, "startSquadronJoin", { enumerable: true, get: function() {
7926
+ return http_1.startSquadronJoin;
7927
+ } });
7403
7928
  var liveBus_1 = require_liveBus();
7404
7929
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
7405
7930
  return liveBus_1.emitLiveSignal;
@@ -7410,6 +7935,9 @@ var require_out3 = __commonJS({
7410
7935
  Object.defineProperty(exports, "bucketPromptSize", { enumerable: true, get: function() {
7411
7936
  return liveBus_1.bucketPromptSize;
7412
7937
  } });
7938
+ Object.defineProperty(exports, "promptSizeMetadata", { enumerable: true, get: function() {
7939
+ return liveBus_1.promptSizeMetadata;
7940
+ } });
7413
7941
  Object.defineProperty(exports, "liveBusSocketPath", { enumerable: true, get: function() {
7414
7942
  return liveBus_1.liveBusSocketPath;
7415
7943
  } });
@@ -7568,48 +8096,48 @@ var require_out3 = __commonJS({
7568
8096
  Object.defineProperty(exports, "scriptMarkerIn", { enumerable: true, get: function() {
7569
8097
  return agentProcess_1.scriptMarkerIn;
7570
8098
  } });
7571
- var http_1 = require_http();
8099
+ var http_2 = require_http();
7572
8100
  Object.defineProperty(exports, "AscendaApiError", { enumerable: true, get: function() {
7573
- return http_1.AscendaApiError;
8101
+ return http_2.AscendaApiError;
7574
8102
  } });
7575
8103
  Object.defineProperty(exports, "createPairingSession", { enumerable: true, get: function() {
7576
- return http_1.createPairingSession;
8104
+ return http_2.createPairingSession;
7577
8105
  } });
7578
8106
  Object.defineProperty(exports, "getPairingStatus", { enumerable: true, get: function() {
7579
- return http_1.getPairingStatus;
8107
+ return http_2.getPairingStatus;
7580
8108
  } });
7581
8109
  Object.defineProperty(exports, "getStudyJoinStatus", { enumerable: true, get: function() {
7582
- return http_1.getStudyJoinStatus;
8110
+ return http_2.getStudyJoinStatus;
7583
8111
  } });
7584
8112
  Object.defineProperty(exports, "renewToolToken", { enumerable: true, get: function() {
7585
- return http_1.renewToolToken;
8113
+ return http_2.renewToolToken;
7586
8114
  } });
7587
8115
  Object.defineProperty(exports, "postToolEvent", { enumerable: true, get: function() {
7588
- return http_1.postToolEvent;
8116
+ return http_2.postToolEvent;
7589
8117
  } });
7590
8118
  Object.defineProperty(exports, "postToolEventsBatch", { enumerable: true, get: function() {
7591
- return http_1.postToolEventsBatch;
8119
+ return http_2.postToolEventsBatch;
7592
8120
  } });
7593
8121
  Object.defineProperty(exports, "parseIngestResponse", { enumerable: true, get: function() {
7594
- return http_1.parseIngestResponse;
8122
+ return http_2.parseIngestResponse;
7595
8123
  } });
7596
8124
  Object.defineProperty(exports, "isRetryableStatus", { enumerable: true, get: function() {
7597
- return http_1.isRetryableStatus;
8125
+ return http_2.isRetryableStatus;
7598
8126
  } });
7599
8127
  Object.defineProperty(exports, "readInitiatives", { enumerable: true, get: function() {
7600
- return http_1.readInitiatives;
8128
+ return http_2.readInitiatives;
7601
8129
  } });
7602
8130
  Object.defineProperty(exports, "readStudyNotices", { enumerable: true, get: function() {
7603
- return http_1.readStudyNotices;
8131
+ return http_2.readStudyNotices;
7604
8132
  } });
7605
8133
  Object.defineProperty(exports, "markStudyNoticeShown", { enumerable: true, get: function() {
7606
- return http_1.markStudyNoticeShown;
8134
+ return http_2.markStudyNoticeShown;
7607
8135
  } });
7608
8136
  Object.defineProperty(exports, "setStudyObjection", { enumerable: true, get: function() {
7609
- return http_1.setStudyObjection;
8137
+ return http_2.setStudyObjection;
7610
8138
  } });
7611
8139
  Object.defineProperty(exports, "startStudyJoin", { enumerable: true, get: function() {
7612
- return http_1.startStudyJoin;
8140
+ return http_2.startStudyJoin;
7613
8141
  } });
7614
8142
  var initiatives_1 = require_initiatives();
7615
8143
  Object.defineProperty(exports, "INITIATIVE_COPY", { enumerable: true, get: function() {
@@ -7647,10 +8175,16 @@ var require_out3 = __commonJS({
7647
8175
  Object.defineProperty(exports, "formatWindow", { enumerable: true, get: function() {
7648
8176
  return studyJoin_1.formatWindow;
7649
8177
  } });
8178
+ Object.defineProperty(exports, "gitOfferLine", { enumerable: true, get: function() {
8179
+ return studyJoin_1.gitOfferLine;
8180
+ } });
7650
8181
  Object.defineProperty(exports, "runStudyJoin", { enumerable: true, get: function() {
7651
8182
  return studyJoin_1.runStudyJoin;
7652
8183
  } });
7653
8184
  var confirmLinks_1 = require_confirmLinks();
8185
+ Object.defineProperty(exports, "WEEKLY_POSTER_CONNECT_URL", { enumerable: true, get: function() {
8186
+ return confirmLinks_1.WEEKLY_POSTER_CONNECT_URL;
8187
+ } });
7654
8188
  Object.defineProperty(exports, "pairingConfirmLines", { enumerable: true, get: function() {
7655
8189
  return confirmLinks_1.pairingConfirmLines;
7656
8190
  } });
@@ -8009,7 +8543,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
8009
8543
  const next = (label, value) => console.log(` ${ui.bold(label.padEnd(6))} ${value}`);
8010
8544
  console.log("");
8011
8545
  if (chosenLocal) {
8012
- console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
8546
+ console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and Ascenda Flow's live view work now.`);
8013
8547
  console.log(" They run on this machine and need no account or pairing.");
8014
8548
  if (eventLog.path) console.log(` Every event is also written to ${tidyHome(eventLog.path)}, for you or any tool to read.`);
8015
8549
  } else if (unpaired) {
@@ -8024,9 +8558,9 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
8024
8558
  if (unpaired) next(chosenLocal ? "Pair" : "Retry", `${ui.cyan(`${self} pair`)}${chosenLocal ? ui.dim(" (optional)") : ""}`);
8025
8559
  if (chosenLocal) {
8026
8560
  console.log("");
8027
- console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account the"));
8028
- console.log(ui.dim(" Ascenda app is signed in to when you confirm the code, so your sessions appear"));
8029
- console.log(ui.dim(" in the app. Until you pair, nothing leaves this machine."));
8561
+ console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account you"));
8562
+ console.log(ui.dim(" confirm the code with, in Ascenda Flow or at me.ascendaflow.com."));
8563
+ console.log(ui.dim(" Until you pair, nothing leaves this machine."));
8030
8564
  console.log("");
8031
8565
  console.log(ui.dim((0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Claude Code" }).split("\n").map((line) => ` ${line}`).join("\n")));
8032
8566
  }
@@ -8697,7 +9231,7 @@ function mapUserPromptSubmit(input) {
8697
9231
  const prompt = (0, import_tool_kit3.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit3.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
8698
9232
  if (isTaskNotificationPrompt(prompt) || isBashModePrompt(prompt)) return [];
8699
9233
  const autonomy = autonomyModeMetadata(input);
8700
- const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...autonomy } }];
9234
+ const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...(0, import_tool_kit4.promptSizeMetadata)(prompt), ...autonomy } }];
8701
9235
  if ((0, import_tool_kit3.looksLikeCorrection)(prompt)) {
8702
9236
  events.push({ eventType: "ai_correction_prompt", severity: "medium", metadata: { reason: "repeated_reprompting", trigger: "inferred", ...autonomy } });
8703
9237
  }
@@ -9140,11 +9674,7 @@ ${(0, import_tool_kit14.renderSetupDisclosure)({ sends: SENDS2, displayName: isC
9140
9674
  );
9141
9675
  const session = await (0, import_tool_kit14.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
9142
9676
  const code = session.deviceCode ?? session.code;
9143
- const confirm = (0, import_tool_kit14.pairingConfirmLines)(session.qrUrl, code);
9144
- const instructions = confirm.length > 1 ? `${confirm.join("\n")}
9145
- ` : `Pairing code: ${code}
9146
-
9147
- In the Ascenda app: Connections -> Ingest telemetry -> paste the code -> Pair tool.
9677
+ const instructions = `${(0, import_tool_kit14.pairingConfirmLines)(session.qrUrl, code).join("\n")}
9148
9678
  `;
9149
9679
  await writeStdout(`
9150
9680
  ${instructions}Waiting for confirmation (expires ${session.expiresAt})...
@@ -9202,6 +9732,45 @@ async function runJoin(argv) {
9202
9732
  }
9203
9733
  return (0, import_tool_kit14.runStudyJoin)({ apiBaseUrl, eventWriteToken, displayName: "Claude Code", joinCode });
9204
9734
  }
9735
+ async function runSquadron(argv) {
9736
+ const reference = argv[0];
9737
+ if (!reference || reference.startsWith("-")) {
9738
+ process.stderr.write("Usage: ascenda-claude-hook squadron <booking reference> [--callsign <name>] [--aircraft <type>] [--colour <colour>]\n");
9739
+ return 1;
9740
+ }
9741
+ const flag = (name) => {
9742
+ const index = argv.indexOf(name);
9743
+ return index === -1 ? void 0 : argv[index + 1];
9744
+ };
9745
+ let config;
9746
+ try {
9747
+ config = loadConfigFromEnv();
9748
+ } catch {
9749
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
9750
+ process.stderr.write("squadron needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
9751
+ return 0;
9752
+ }
9753
+ await writeStdout("This machine isn't paired yet. A sortie reads its activity from the paired collector, so pair first.\n");
9754
+ await runPair();
9755
+ if (process.exitCode) return Number(process.exitCode);
9756
+ try {
9757
+ config = loadConfigFromEnv();
9758
+ } catch (error) {
9759
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
9760
+ `);
9761
+ return 1;
9762
+ }
9763
+ }
9764
+ return (0, import_tool_kit14.runSquadronJoin)({
9765
+ apiBaseUrl: config.apiBaseUrl,
9766
+ eventWriteToken: config.eventWriteToken,
9767
+ displayName: "Claude Code",
9768
+ bookingReference: reference,
9769
+ callsign: flag("--callsign"),
9770
+ aircraft: flag("--aircraft"),
9771
+ colour: flag("--colour") ?? flag("--color")
9772
+ });
9773
+ }
9205
9774
  async function runObject(argv) {
9206
9775
  let apiBaseUrl;
9207
9776
  let eventWriteToken;
@@ -9225,7 +9794,7 @@ async function main() {
9225
9794
  const command = process.argv[2];
9226
9795
  if (!command) {
9227
9796
  throw new Error(
9228
- "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | join | object | doctor | setup | status | uninstall | plugin-sync"
9797
+ "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | join | squadron | object | doctor | setup | status | uninstall | plugin-sync"
9229
9798
  );
9230
9799
  }
9231
9800
  if (command === "pair") {
@@ -9236,6 +9805,10 @@ async function main() {
9236
9805
  setupExitCode = await runJoin(process.argv.slice(3));
9237
9806
  return;
9238
9807
  }
9808
+ if (command === "squadron") {
9809
+ setupExitCode = await runSquadron(process.argv.slice(3));
9810
+ return;
9811
+ }
9239
9812
  if (command === "object") {
9240
9813
  setupExitCode = await runObject(process.argv.slice(3));
9241
9814
  return;
@@ -9259,7 +9832,7 @@ async function main() {
9259
9832
  }
9260
9833
  if (!isClaudeHookEventName(command)) {
9261
9834
  throw new Error(
9262
- `Unknown command "${command}". Expected a Claude Code hook name, "pair", "join", "object", "doctor", "setup", "status" or "uninstall".`
9835
+ `Unknown command "${command}". Expected a Claude Code hook name, "pair", "join", "squadron", "object", "doctor", "setup", "status" or "uninstall".`
9263
9836
  );
9264
9837
  }
9265
9838
  const hookName = command;
@@ -9302,6 +9875,7 @@ async function main() {
9302
9875
  for (const event of mappedEvents) {
9303
9876
  logUnsent(logFile, event, workContext, (0, import_tool_kit14.getString)(input, ["session_id", "sessionId"]) ?? null);
9304
9877
  }
9878
+ if (!unpaired && !(error instanceof MissingInstallationIdError)) throw error;
9305
9879
  return;
9306
9880
  }
9307
9881
  config.workspaceHash ??= workContext?.workspaceHash ?? null;