@ascenda-one/claude-code-hooks 0.1.28 → 0.1.33

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
@@ -727,6 +727,10 @@ var require_out = __commonJS({
727
727
  // One constant word, from the agent itself. The session sentence names it.
728
728
  sessionEndReason: "session",
729
729
  interruptionKind: "waiting",
730
+ // Claude Code's own opaque id for one subagent, and the class it belongs
731
+ // to. Never the agent's name or anything it was asked.
732
+ subagentId: "subagents",
733
+ subagentClass: "subagents",
730
734
  // Free text by type, and written by no hook mapper — the IDE extension's
731
735
  // test signal is the only producer. The setup disclosure's third refusal
732
736
  // line says as much, and tool-kit's guard test fails if a mapper starts.
@@ -775,6 +779,8 @@ var require_out = __commonJS({
775
779
  "runtime",
776
780
  "sessionEndReason",
777
781
  "interruptionKind",
782
+ "subagentId",
783
+ "subagentClass",
778
784
  "simulated",
779
785
  "relatedEventType",
780
786
  "skillVersion",
@@ -822,6 +828,12 @@ var require_out = __commonJS({
822
828
  // `ai_prompt_submitted` closes. Neutral so a marker sent once per turn
823
829
  // doesn't weigh on any workload leg.
824
830
  ai_turn_completed: "neutral",
831
+ // A subagent began or finished under a session. Boundaries, not work: the
832
+ // subagent's own tool calls and edits arrive as their own events and carry
833
+ // their own categories. A reader pairs these on `subagentId` to count how
834
+ // many agents ran at once; neutral so that count weighs on no workload leg.
835
+ subagent_started: "neutral",
836
+ subagent_stopped: "neutral",
825
837
  // The agent stopped and is waiting on the person: Claude Code's
826
838
  // `Notification`, Codex's `PermissionRequest`. Supervision, beside the other
827
839
  // oversight overhead, because that is what it is — time the person spends
@@ -894,9 +906,9 @@ var require_payload = __commonJS({
894
906
  }
895
907
  return void 0;
896
908
  }
897
- function getNested2(input, path3) {
909
+ function getNested2(input, path4) {
898
910
  let current = input;
899
- for (const segment of path3) {
911
+ for (const segment of path4) {
900
912
  if (!current || typeof current !== "object")
901
913
  return void 0;
902
914
  current = current[segment];
@@ -904,16 +916,16 @@ var require_payload = __commonJS({
904
916
  return current;
905
917
  }
906
918
  function getNestedString3(input, paths) {
907
- for (const path3 of paths) {
908
- const value = getNested2(input, path3);
919
+ for (const path4 of paths) {
920
+ const value = getNested2(input, path4);
909
921
  if (typeof value === "string" && value.trim())
910
922
  return value;
911
923
  }
912
924
  return void 0;
913
925
  }
914
926
  function getNestedNumber2(input, paths) {
915
- for (const path3 of paths) {
916
- const value = getNested2(input, path3);
927
+ for (const path4 of paths) {
928
+ const value = getNested2(input, path4);
917
929
  if (typeof value === "number" && Number.isFinite(value))
918
930
  return value;
919
931
  }
@@ -956,7 +968,7 @@ var require_collectorVersion = __commonJS({
956
968
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
957
969
  exports.describeCollectorVersion = describeCollectorVersion2;
958
970
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
959
- exports.COLLECTOR_VERSION = "0.1.28" ? "0.1.28" : exports.UNRELEASED_COLLECTOR_VERSION;
971
+ exports.COLLECTOR_VERSION = "0.1.33" ? "0.1.33" : exports.UNRELEASED_COLLECTOR_VERSION;
960
972
  function describeCollectorVersion2(version = exports.COLLECTOR_VERSION) {
961
973
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
962
974
  }
@@ -1009,9 +1021,9 @@ var require_eventLog = __commonJS({
1009
1021
  exports.expandUserPath = expandUserPath;
1010
1022
  exports.resolveEventLogPath = resolveEventLogPath2;
1011
1023
  exports.appendEventLog = appendEventLog2;
1012
- var fs4 = __importStar(__require("fs"));
1013
- var os2 = __importStar(__require("os"));
1014
- var path3 = __importStar(__require("path"));
1024
+ var fs5 = __importStar(__require("fs"));
1025
+ var os3 = __importStar(__require("os"));
1026
+ var path4 = __importStar(__require("path"));
1015
1027
  exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1016
1028
  var MAX_BYTES = 5 * 1024 * 1024;
1017
1029
  function expandUserPath(configured) {
@@ -1019,10 +1031,10 @@ var require_eventLog = __commonJS({
1019
1031
  if (!value)
1020
1032
  return void 0;
1021
1033
  if (value === "~")
1022
- return os2.homedir();
1034
+ return os3.homedir();
1023
1035
  if (value.startsWith("~/"))
1024
- return path3.join(os2.homedir(), value.slice(2));
1025
- return path3.resolve(value);
1036
+ return path4.join(os3.homedir(), value.slice(2));
1037
+ return path4.resolve(value);
1026
1038
  }
1027
1039
  function resolveEventLogPath2() {
1028
1040
  return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
@@ -1030,20 +1042,20 @@ var require_eventLog = __commonJS({
1030
1042
  function appendEventLog2(logFilePath, entry) {
1031
1043
  try {
1032
1044
  rotateIfLarge(logFilePath);
1033
- const dir = path3.dirname(logFilePath);
1034
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
1035
- fs4.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1045
+ const dir = path4.dirname(logFilePath);
1046
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1047
+ fs5.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1036
1048
  `, { encoding: "utf8", mode: 384 });
1037
1049
  if (process.platform !== "win32")
1038
- fs4.chmodSync(logFilePath, 384);
1050
+ fs5.chmodSync(logFilePath, 384);
1039
1051
  } catch {
1040
1052
  }
1041
1053
  }
1042
1054
  function rotateIfLarge(logFilePath) {
1043
1055
  try {
1044
- if (fs4.statSync(logFilePath).size < MAX_BYTES)
1056
+ if (fs5.statSync(logFilePath).size < MAX_BYTES)
1045
1057
  return;
1046
- fs4.renameSync(logFilePath, `${logFilePath}.1`);
1058
+ fs5.renameSync(logFilePath, `${logFilePath}.1`);
1047
1059
  } catch {
1048
1060
  }
1049
1061
  }
@@ -1058,6 +1070,12 @@ var require_http = __commonJS({
1058
1070
  exports.AscendaApiError = void 0;
1059
1071
  exports.createPairingSession = createPairingSession3;
1060
1072
  exports.getPairingStatus = getPairingStatus3;
1073
+ exports.startStudyJoin = startStudyJoin;
1074
+ exports.getStudyJoinStatus = getStudyJoinStatus;
1075
+ exports.readInitiatives = readInitiatives;
1076
+ exports.readStudyNotices = readStudyNotices;
1077
+ exports.setStudyObjection = setStudyObjection;
1078
+ exports.markStudyNoticeShown = markStudyNoticeShown;
1061
1079
  exports.renewToolToken = renewToolToken;
1062
1080
  exports.isRetryableStatus = isRetryableStatus;
1063
1081
  exports.postToolEvent = postToolEvent;
@@ -1094,6 +1112,108 @@ var require_http = __commonJS({
1094
1112
  throw new AscendaApiError2(response.status, void 0, await response.text());
1095
1113
  return await response.json();
1096
1114
  }
1115
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1116
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1117
+ method: "POST",
1118
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1119
+ body: JSON.stringify({ joinCode, mode })
1120
+ });
1121
+ if (!response.ok)
1122
+ throw await apiError(response);
1123
+ return await response.json();
1124
+ }
1125
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1126
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1127
+ method: "GET",
1128
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1129
+ });
1130
+ if (!response.ok)
1131
+ throw await apiError(response);
1132
+ return await response.json();
1133
+ }
1134
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1135
+ let response;
1136
+ try {
1137
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1138
+ method: "GET",
1139
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1140
+ signal
1141
+ });
1142
+ } catch (error) {
1143
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1144
+ }
1145
+ if (response.status === 401)
1146
+ return { kind: "rejected", httpStatus: 401 };
1147
+ if (!response.ok)
1148
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1149
+ let body;
1150
+ try {
1151
+ body = await response.json();
1152
+ } catch {
1153
+ return { kind: "failed", reason: "the reply was not readable" };
1154
+ }
1155
+ if (!Array.isArray(body))
1156
+ return { kind: "failed", reason: "the reply was not a list" };
1157
+ return { kind: "ok", initiatives: body };
1158
+ }
1159
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1160
+ let response;
1161
+ try {
1162
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1163
+ method: "GET",
1164
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1165
+ signal
1166
+ });
1167
+ } catch (error) {
1168
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1169
+ }
1170
+ if (response.status === 404)
1171
+ return { kind: "absent" };
1172
+ if (response.status === 401)
1173
+ return { kind: "rejected", httpStatus: 401 };
1174
+ if (!response.ok)
1175
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1176
+ let body;
1177
+ try {
1178
+ body = await response.json();
1179
+ } catch {
1180
+ return { kind: "absent" };
1181
+ }
1182
+ if (!Array.isArray(body))
1183
+ return { kind: "absent" };
1184
+ return { kind: "ok", notices: body };
1185
+ }
1186
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1187
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1188
+ method: objected ? "POST" : "DELETE",
1189
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
1190
+ });
1191
+ if (!response.ok)
1192
+ throw await apiError(response);
1193
+ }
1194
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1195
+ try {
1196
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1197
+ method: "POST",
1198
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
1199
+ signal
1200
+ });
1201
+ return response.ok;
1202
+ } catch {
1203
+ return false;
1204
+ }
1205
+ }
1206
+ async function apiError(response) {
1207
+ const body = await response.text();
1208
+ let errorCode;
1209
+ try {
1210
+ const parsed = JSON.parse(body);
1211
+ errorCode = parsed.code ?? parsed.error;
1212
+ } catch {
1213
+ errorCode = void 0;
1214
+ }
1215
+ return new AscendaApiError2(response.status, errorCode, body);
1216
+ }
1097
1217
  async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1098
1218
  const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1099
1219
  method: "POST",
@@ -1236,36 +1356,66 @@ var require_tokenStore = __commonJS({
1236
1356
  };
1237
1357
  }();
1238
1358
  Object.defineProperty(exports, "__esModule", { value: true });
1359
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1239
1360
  exports.ascendaHome = ascendaHome3;
1240
1361
  exports.defaultTokenFilePath = defaultTokenFilePath4;
1362
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1241
1363
  exports.persistEventWriteToken = persistEventWriteToken4;
1364
+ exports.readTokenExpiry = readTokenExpiry;
1242
1365
  exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
1243
1366
  exports.readTokenFile = readTokenFile3;
1244
1367
  exports.sanitizeFilePart = sanitizeFilePart;
1245
- var fs4 = __importStar(__require("fs"));
1246
- var os2 = __importStar(__require("os"));
1247
- var path3 = __importStar(__require("path"));
1248
- function ascendaHome3(home = os2.homedir()) {
1249
- return process.env.ASCENDA_HOME ?? path3.join(home, ".ascenda");
1368
+ var fs5 = __importStar(__require("fs"));
1369
+ var os3 = __importStar(__require("os"));
1370
+ var path4 = __importStar(__require("path"));
1371
+ function ascendaHome3(home = os3.homedir()) {
1372
+ return process.env.ASCENDA_HOME ?? path4.join(home, ".ascenda");
1250
1373
  }
1251
1374
  function defaultTokenFilePath4(toolInstallationId) {
1252
- return path3.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1375
+ return path4.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1376
+ }
1377
+ function tokenExpiryFilePath(tokenFilePath) {
1378
+ return path4.join(path4.dirname(tokenFilePath), "expiry", path4.basename(tokenFilePath));
1253
1379
  }
1254
- function persistEventWriteToken4(tokenFilePath, token) {
1255
- const dir = path3.dirname(tokenFilePath);
1256
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
1257
- fs4.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1380
+ function persistEventWriteToken4(tokenFilePath, token, expiresAt) {
1381
+ const dir = path4.dirname(tokenFilePath);
1382
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1383
+ fs5.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1258
1384
  if (process.platform !== "win32") {
1259
- fs4.chmodSync(dir, 448);
1260
- fs4.chmodSync(tokenFilePath, 384);
1385
+ fs5.chmodSync(dir, 448);
1386
+ fs5.chmodSync(tokenFilePath, 384);
1387
+ }
1388
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1389
+ try {
1390
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1391
+ fs5.mkdirSync(path4.dirname(expiryFile), { recursive: true, mode: 448 });
1392
+ fs5.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1393
+ } else {
1394
+ fs5.rmSync(expiryFile, { force: true });
1395
+ }
1396
+ } catch {
1397
+ }
1398
+ }
1399
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1400
+ function readTokenExpiry(tokenFilePath) {
1401
+ try {
1402
+ const recorded = Date.parse(fs5.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1403
+ if (Number.isFinite(recorded))
1404
+ return recorded;
1405
+ } catch {
1406
+ }
1407
+ try {
1408
+ return fs5.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1409
+ } catch {
1410
+ return void 0;
1261
1411
  }
1262
1412
  }
1263
1413
  function listPersistedToolInstallationIds2(toolType) {
1264
1414
  const prefix = `${sanitizeFilePart(toolType)}_`;
1265
- const dir = path3.join(ascendaHome3(), "tokens");
1415
+ const dir = path4.join(ascendaHome3(), "tokens");
1266
1416
  let names;
1267
1417
  try {
1268
- names = fs4.readdirSync(dir);
1418
+ names = fs5.readdirSync(dir);
1269
1419
  } catch {
1270
1420
  return [];
1271
1421
  }
@@ -1273,9 +1423,9 @@ var require_tokenStore = __commonJS({
1273
1423
  for (const name of names.sort()) {
1274
1424
  if (!name.startsWith(prefix) || name.length === prefix.length)
1275
1425
  continue;
1276
- const file = path3.join(dir, name);
1426
+ const file = path4.join(dir, name);
1277
1427
  try {
1278
- if (!fs4.statSync(file).isFile())
1428
+ if (!fs5.statSync(file).isFile())
1279
1429
  continue;
1280
1430
  } catch {
1281
1431
  continue;
@@ -1288,9 +1438,9 @@ var require_tokenStore = __commonJS({
1288
1438
  }
1289
1439
  function readTokenFile3(tokenFilePath) {
1290
1440
  try {
1291
- if (!fs4.existsSync(tokenFilePath))
1441
+ if (!fs5.existsSync(tokenFilePath))
1292
1442
  return void 0;
1293
- const value = fs4.readFileSync(tokenFilePath, "utf8").trim();
1443
+ const value = fs5.readFileSync(tokenFilePath, "utf8").trim();
1294
1444
  return value || void 0;
1295
1445
  } catch {
1296
1446
  return void 0;
@@ -1352,13 +1502,13 @@ var require_stateStore = __commonJS({
1352
1502
  exports.recordOutboxDiscard = recordOutboxDiscard;
1353
1503
  exports.shouldAnnounceFailure = shouldAnnounceFailure2;
1354
1504
  exports.markFailureNotified = markFailureNotified2;
1355
- var fs4 = __importStar(__require("fs"));
1356
- var path3 = __importStar(__require("path"));
1505
+ var fs5 = __importStar(__require("fs"));
1506
+ var path4 = __importStar(__require("path"));
1357
1507
  var tokenStore_1 = require_tokenStore();
1358
1508
  function defaultStateFilePath2(toolInstallationId) {
1359
1509
  const dir = process.env.ASCENDA_STATE_DIR?.trim();
1360
- const base = dir ? dir : path3.join((0, tokenStore_1.ascendaHome)(), "state");
1361
- return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1510
+ const base = dir ? dir : path4.join((0, tokenStore_1.ascendaHome)(), "state");
1511
+ return path4.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1362
1512
  }
1363
1513
  function unresolvedToolInstallationId2(toolType) {
1364
1514
  return `${toolType}:unresolved`;
@@ -1368,9 +1518,9 @@ var require_stateStore = __commonJS({
1368
1518
  }
1369
1519
  function readCollectorState2(stateFilePath) {
1370
1520
  try {
1371
- if (!fs4.existsSync(stateFilePath))
1521
+ if (!fs5.existsSync(stateFilePath))
1372
1522
  return void 0;
1373
- const raw = fs4.readFileSync(stateFilePath, "utf8").trim();
1523
+ const raw = fs5.readFileSync(stateFilePath, "utf8").trim();
1374
1524
  if (!raw)
1375
1525
  return void 0;
1376
1526
  const parsed = JSON.parse(raw);
@@ -1437,17 +1587,17 @@ var require_stateStore = __commonJS({
1437
1587
  function writeStateFile(stateFilePath, state) {
1438
1588
  const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1439
1589
  try {
1440
- const dir = path3.dirname(stateFilePath);
1441
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
1442
- fs4.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1590
+ const dir = path4.dirname(stateFilePath);
1591
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1592
+ fs5.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1443
1593
  `, { encoding: "utf8", mode: 384 });
1444
- fs4.renameSync(temporaryPath, stateFilePath);
1594
+ fs5.renameSync(temporaryPath, stateFilePath);
1445
1595
  if (process.platform !== "win32")
1446
- fs4.chmodSync(stateFilePath, 384);
1596
+ fs5.chmodSync(stateFilePath, 384);
1447
1597
  } catch {
1448
1598
  try {
1449
- if (fs4.existsSync(temporaryPath))
1450
- fs4.unlinkSync(temporaryPath);
1599
+ if (fs5.existsSync(temporaryPath))
1600
+ fs5.unlinkSync(temporaryPath);
1451
1601
  } catch {
1452
1602
  }
1453
1603
  }
@@ -1508,8 +1658,8 @@ var require_outbox = __commonJS({
1508
1658
  exports.readOutboxSummary = readOutboxSummary2;
1509
1659
  exports.claimOutbox = claimOutbox;
1510
1660
  exports.enforceOutboxBounds = enforceOutboxBounds;
1511
- var fs4 = __importStar(__require("fs"));
1512
- var path3 = __importStar(__require("path"));
1661
+ var fs5 = __importStar(__require("fs"));
1662
+ var path4 = __importStar(__require("path"));
1513
1663
  var stateStore_1 = require_stateStore();
1514
1664
  var tokenStore_1 = require_tokenStore();
1515
1665
  exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
@@ -1525,25 +1675,25 @@ var require_outbox = __commonJS({
1525
1675
  return !(value === "0" || value === "false" || value === "no" || value === "off");
1526
1676
  }
1527
1677
  function defaultOutboxFilePath2(toolInstallationId) {
1528
- const dir = path3.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1529
- return path3.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1678
+ const dir = path4.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1679
+ return path4.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1530
1680
  }
1531
1681
  function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1532
1682
  try {
1533
- const dir = path3.dirname(outboxFilePath);
1534
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
1683
+ const dir = path4.dirname(outboxFilePath);
1684
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1535
1685
  const entry = { queuedAt: now.toISOString(), payload };
1536
- fs4.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1686
+ fs5.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1537
1687
  `, { encoding: "utf8", mode: 384 });
1538
1688
  if (process.platform !== "win32")
1539
- fs4.chmodSync(outboxFilePath, 384);
1689
+ fs5.chmodSync(outboxFilePath, 384);
1540
1690
  return true;
1541
1691
  } catch {
1542
1692
  return false;
1543
1693
  }
1544
1694
  }
1545
1695
  function readOutboxSummary2(outboxFilePath) {
1546
- const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs4.existsSync(file));
1696
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs5.existsSync(file));
1547
1697
  if (files.length === 0)
1548
1698
  return void 0;
1549
1699
  let depth = 0;
@@ -1564,7 +1714,7 @@ var require_outbox = __commonJS({
1564
1714
  const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1565
1715
  const claimed = [];
1566
1716
  try {
1567
- fs4.renameSync(outboxFilePath, claimPath);
1717
+ fs5.renameSync(outboxFilePath, claimPath);
1568
1718
  claimed.push(claimPath);
1569
1719
  } catch {
1570
1720
  }
@@ -1573,10 +1723,10 @@ var require_outbox = __commonJS({
1573
1723
  if (claimed.includes(orphan))
1574
1724
  continue;
1575
1725
  try {
1576
- if (now - fs4.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1726
+ if (now - fs5.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1577
1727
  continue;
1578
1728
  const mine = `${claimPath}.${orphanIndex++}`;
1579
- fs4.renameSync(orphan, mine);
1729
+ fs5.renameSync(orphan, mine);
1580
1730
  claimed.push(mine);
1581
1731
  } catch {
1582
1732
  }
@@ -1601,18 +1751,18 @@ var require_outbox = __commonJS({
1601
1751
  released = true;
1602
1752
  if (remainder.length > 0) {
1603
1753
  try {
1604
- fs4.mkdirSync(path3.dirname(outboxFilePath), { recursive: true, mode: 448 });
1605
- fs4.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1754
+ fs5.mkdirSync(path4.dirname(outboxFilePath), { recursive: true, mode: 448 });
1755
+ fs5.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1606
1756
  `).join(""), { encoding: "utf8", mode: 384 });
1607
1757
  if (process.platform !== "win32")
1608
- fs4.chmodSync(outboxFilePath, 384);
1758
+ fs5.chmodSync(outboxFilePath, 384);
1609
1759
  } catch {
1610
1760
  return;
1611
1761
  }
1612
1762
  }
1613
1763
  for (const file of claimed) {
1614
1764
  try {
1615
- fs4.unlinkSync(file);
1765
+ fs5.unlinkSync(file);
1616
1766
  } catch {
1617
1767
  }
1618
1768
  }
@@ -1645,10 +1795,10 @@ var require_outbox = __commonJS({
1645
1795
  return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1646
1796
  }
1647
1797
  function listClaimFiles(outboxFilePath) {
1648
- const dir = path3.dirname(outboxFilePath);
1649
- const prefix = `${path3.basename(outboxFilePath)}.`;
1798
+ const dir = path4.dirname(outboxFilePath);
1799
+ const prefix = `${path4.basename(outboxFilePath)}.`;
1650
1800
  try {
1651
- return fs4.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path3.join(dir, name)).sort();
1801
+ return fs5.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path4.join(dir, name)).sort();
1652
1802
  } catch {
1653
1803
  return [];
1654
1804
  }
@@ -1656,7 +1806,7 @@ var require_outbox = __commonJS({
1656
1806
  function readEntries(file) {
1657
1807
  let raw;
1658
1808
  try {
1659
- raw = fs4.readFileSync(file, "utf8");
1809
+ raw = fs5.readFileSync(file, "utf8");
1660
1810
  } catch {
1661
1811
  return { entries: [], unreadable: 0 };
1662
1812
  }
@@ -1705,7 +1855,7 @@ var require_eventSender = __commonJS({
1705
1855
  "../packages/tool-kit/out/eventSender.js"(exports) {
1706
1856
  "use strict";
1707
1857
  Object.defineProperty(exports, "__esModule", { value: true });
1708
- exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1858
+ exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
1709
1859
  exports.buildEventPayload = buildEventPayload2;
1710
1860
  var afterHours_1 = require_afterHours();
1711
1861
  var tool_contract_1 = require_out();
@@ -1746,6 +1896,7 @@ var require_eventSender = __commonJS({
1746
1896
  }
1747
1897
  var DEFAULT_TIMEOUT_MS = 5e3;
1748
1898
  var RETRY_DELAY_MS = 250;
1899
+ exports.TOKEN_RENEW_LEAD_MS = 21 * 24 * 60 * 60 * 1e3;
1749
1900
  var AscendaEventSender2 = class {
1750
1901
  config;
1751
1902
  eventWriteToken;
@@ -1753,6 +1904,8 @@ var require_eventSender = __commonJS({
1753
1904
  lastDrain;
1754
1905
  /** One outbox pass per sender, i.e. per hook process. The hook is on the user's critical path. */
1755
1906
  outboxServiced = false;
1907
+ /** One look at the token's expiry per sender, for the same reason. */
1908
+ expiryChecked = false;
1756
1909
  /** Resolved once, so every clock read in one pass sees the same instant. */
1757
1910
  time;
1758
1911
  constructor(config) {
@@ -1876,6 +2029,7 @@ var require_eventSender = __commonJS({
1876
2029
  * hook during an outage to one bounded round trip instead of three.
1877
2030
  */
1878
2031
  async post(payload) {
2032
+ await this.renewIfExpiring();
1879
2033
  const halted = await this.serviceOutbox();
1880
2034
  let outcome;
1881
2035
  let queued = false;
@@ -2081,21 +2235,49 @@ var require_eventSender = __commonJS({
2081
2235
  return;
2082
2236
  (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload, ...outbox ? { outbox } : {} });
2083
2237
  }
2084
- /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
2238
+ /**
2239
+ * Renews ahead of expiry, at most once per sender. Waiting for the 401
2240
+ * doesn't work: by then the token has expired, and the server won't renew
2241
+ * an expired token.
2242
+ */
2243
+ async renewIfExpiring() {
2244
+ if (this.expiryChecked || this.config.renewToken === false)
2245
+ return;
2246
+ this.expiryChecked = true;
2247
+ const expiresAt = (0, tokenStore_1.readTokenExpiry)(this.config.tokenFilePath);
2248
+ if (expiresAt === void 0 || this.time.now() < expiresAt - exports.TOKEN_RENEW_LEAD_MS)
2249
+ return;
2250
+ await this.renewEventToken();
2251
+ }
2252
+ /**
2253
+ * Never throws: a renewal that errors is a failed renewal, not a failed turn.
2254
+ *
2255
+ * A refused renewal usually means another process got there first. Hooks
2256
+ * and the MCP server share one token file, and renewing revokes the token
2257
+ * it replaces, so the loser holds a revoked token while the winner's
2258
+ * replacement is already on disk. Adopting that counts as a renewal.
2259
+ */
2085
2260
  async renewEventToken() {
2086
2261
  if (this.config.renewToken === false)
2087
2262
  return false;
2088
2263
  try {
2089
2264
  const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
2090
2265
  if (!renewed)
2091
- return false;
2266
+ return this.adoptPersistedToken();
2092
2267
  this.eventWriteToken = renewed.eventWriteToken;
2093
- (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken);
2268
+ (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken, renewed.expiresAt);
2094
2269
  return true;
2095
2270
  } catch {
2096
2271
  return false;
2097
2272
  }
2098
2273
  }
2274
+ adoptPersistedToken() {
2275
+ const persisted = (0, tokenStore_1.readTokenFile)(this.config.tokenFilePath);
2276
+ if (!persisted || persisted === this.eventWriteToken)
2277
+ return false;
2278
+ this.eventWriteToken = persisted;
2279
+ return true;
2280
+ }
2099
2281
  signal() {
2100
2282
  return AbortSignal.timeout(this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS);
2101
2283
  }
@@ -2153,16 +2335,16 @@ var require_contextRegistry = __commonJS({
2153
2335
  exports.readWorkContextRegistry = readWorkContextRegistry;
2154
2336
  exports.recordWorkContext = recordWorkContext2;
2155
2337
  exports.recordWorkContextAlias = recordWorkContextAlias;
2156
- var fs4 = __importStar(__require("fs"));
2157
- var os2 = __importStar(__require("os"));
2158
- var path3 = __importStar(__require("path"));
2338
+ var fs5 = __importStar(__require("fs"));
2339
+ var os3 = __importStar(__require("os"));
2340
+ var path4 = __importStar(__require("path"));
2159
2341
  var MAX_PATHS_PER_ENTRY = 8;
2160
2342
  function workContextRegistryFilePath() {
2161
- return path3.join(os2.homedir(), ".ascenda", "work-contexts.json");
2343
+ return path4.join(os3.homedir(), ".ascenda", "work-contexts.json");
2162
2344
  }
2163
2345
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
2164
2346
  try {
2165
- const parsed = JSON.parse(fs4.readFileSync(registryFilePath, "utf8"));
2347
+ const parsed = JSON.parse(fs5.readFileSync(registryFilePath, "utf8"));
2166
2348
  if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
2167
2349
  return parsed;
2168
2350
  }
@@ -2238,14 +2420,14 @@ var require_contextRegistry = __commonJS({
2238
2420
  return iso.slice(0, 10);
2239
2421
  }
2240
2422
  function writeRegistry(registryFilePath, registry) {
2241
- const dir = path3.dirname(registryFilePath);
2242
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
2423
+ const dir = path4.dirname(registryFilePath);
2424
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
2243
2425
  const tmp = `${registryFilePath}.${process.pid}.tmp`;
2244
- fs4.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2426
+ fs5.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2245
2427
  `, { encoding: "utf8", mode: 384 });
2246
- fs4.renameSync(tmp, registryFilePath);
2428
+ fs5.renameSync(tmp, registryFilePath);
2247
2429
  if (process.platform !== "win32") {
2248
- fs4.chmodSync(registryFilePath, 384);
2430
+ fs5.chmodSync(registryFilePath, 384);
2249
2431
  }
2250
2432
  }
2251
2433
  }
@@ -2301,15 +2483,15 @@ var require_credentials = __commonJS({
2301
2483
  exports.readHostCredentials = readHostCredentials;
2302
2484
  exports.writeHostCredentials = writeHostCredentials;
2303
2485
  exports.removeHostCredentials = removeHostCredentials;
2304
- var fs4 = __importStar(__require("fs"));
2305
- var path3 = __importStar(__require("path"));
2486
+ var fs5 = __importStar(__require("fs"));
2487
+ var path4 = __importStar(__require("path"));
2306
2488
  var tokenStore_1 = require_tokenStore();
2307
2489
  function credentialsFilePath2() {
2308
- return path3.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2490
+ return path4.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2309
2491
  }
2310
2492
  function readMachineCredentials2() {
2311
2493
  try {
2312
- const raw = fs4.readFileSync(credentialsFilePath2(), "utf8").trim();
2494
+ const raw = fs5.readFileSync(credentialsFilePath2(), "utf8").trim();
2313
2495
  if (!raw)
2314
2496
  return void 0;
2315
2497
  const parsed = JSON.parse(raw);
@@ -2322,12 +2504,12 @@ var require_credentials = __commonJS({
2322
2504
  }
2323
2505
  function writeMachineCredentials2(credentials) {
2324
2506
  const file = credentialsFilePath2();
2325
- fs4.mkdirSync(path3.dirname(file), { recursive: true, mode: 448 });
2326
- fs4.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2507
+ fs5.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
2508
+ fs5.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2327
2509
  `, { encoding: "utf8", mode: 384 });
2328
2510
  if (process.platform !== "win32") {
2329
- fs4.chmodSync(path3.dirname(file), 448);
2330
- fs4.chmodSync(file, 384);
2511
+ fs5.chmodSync(path4.dirname(file), 448);
2512
+ fs5.chmodSync(file, 384);
2331
2513
  }
2332
2514
  }
2333
2515
  function writeTopLevelCredentials2(credentials) {
@@ -2415,8 +2597,8 @@ var require_forgeProject = __commonJS({
2415
2597
  exports.readForgeFullName = readForgeFullName;
2416
2598
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
2417
2599
  exports.recordForgeProjectAlias = recordForgeProjectAlias2;
2418
- var fs4 = __importStar(__require("fs"));
2419
- var path3 = __importStar(__require("path"));
2600
+ var fs5 = __importStar(__require("fs"));
2601
+ var path4 = __importStar(__require("path"));
2420
2602
  var contextRegistry_1 = require_contextRegistry();
2421
2603
  function forgeProjectHash(value) {
2422
2604
  let h = 2166136261;
@@ -2462,7 +2644,7 @@ var require_forgeProject = __commonJS({
2462
2644
  return null;
2463
2645
  let config;
2464
2646
  try {
2465
- config = fs4.readFileSync(path3.join(repositoryRoot, ".git", "config"), "utf8");
2647
+ config = fs5.readFileSync(path4.join(repositoryRoot, ".git", "config"), "utf8");
2466
2648
  } catch {
2467
2649
  return null;
2468
2650
  }
@@ -2569,31 +2751,31 @@ var require_salt = __commonJS({
2569
2751
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
2570
2752
  exports.hashWithMachineSalt = hashWithMachineSalt;
2571
2753
  var crypto2 = __importStar(__require("crypto"));
2572
- var fs4 = __importStar(__require("fs"));
2573
- var path3 = __importStar(__require("path"));
2754
+ var fs5 = __importStar(__require("fs"));
2755
+ var path4 = __importStar(__require("path"));
2574
2756
  var tokenStore_1 = require_tokenStore();
2575
2757
  function machineSaltFilePath() {
2576
- return path3.join((0, tokenStore_1.ascendaHome)(), "salt");
2758
+ return path4.join((0, tokenStore_1.ascendaHome)(), "salt");
2577
2759
  }
2578
2760
  var cache = /* @__PURE__ */ new Map();
2579
2761
  function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
2580
2762
  const hit = cache.get(saltFilePath);
2581
2763
  if (hit)
2582
2764
  return hit;
2583
- const dir = path3.dirname(saltFilePath);
2584
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
2765
+ const dir = path4.dirname(saltFilePath);
2766
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
2585
2767
  let salt;
2586
2768
  try {
2587
2769
  salt = crypto2.randomBytes(32).toString("hex");
2588
- fs4.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2770
+ fs5.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2589
2771
  } catch (error) {
2590
2772
  if (error.code !== "EEXIST")
2591
2773
  throw error;
2592
- salt = fs4.readFileSync(saltFilePath, "utf8").trim();
2774
+ salt = fs5.readFileSync(saltFilePath, "utf8").trim();
2593
2775
  }
2594
2776
  if (process.platform !== "win32") {
2595
- fs4.chmodSync(dir, 448);
2596
- fs4.chmodSync(saltFilePath, 384);
2777
+ fs5.chmodSync(dir, 448);
2778
+ fs5.chmodSync(saltFilePath, 384);
2597
2779
  }
2598
2780
  cache.set(saltFilePath, salt);
2599
2781
  return salt;
@@ -2653,8 +2835,8 @@ var require_workContext = __commonJS({
2653
2835
  exports.deriveBranchHash = deriveBranchHash;
2654
2836
  exports.readBranchName = readBranchName;
2655
2837
  exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
2656
- var fs4 = __importStar(__require("fs"));
2657
- var path3 = __importStar(__require("path"));
2838
+ var fs5 = __importStar(__require("fs"));
2839
+ var path4 = __importStar(__require("path"));
2658
2840
  var salt_1 = require_salt();
2659
2841
  var MAX_WALK_DEPTH = 64;
2660
2842
  function deriveWorkContext2(cwd, saltFilePath) {
@@ -2685,14 +2867,14 @@ var require_workContext = __commonJS({
2685
2867
  };
2686
2868
  }
2687
2869
  function resolveRepositoryRoots(startDir) {
2688
- if (!fs4.existsSync(startDir))
2870
+ if (!fs5.existsSync(startDir))
2689
2871
  return null;
2690
2872
  let dir = startDir;
2691
2873
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
2692
- const dotGit = path3.join(dir, ".git");
2874
+ const dotGit = path4.join(dir, ".git");
2693
2875
  let stat = null;
2694
2876
  try {
2695
- stat = fs4.statSync(dotGit);
2877
+ stat = fs5.statSync(dotGit);
2696
2878
  } catch {
2697
2879
  stat = null;
2698
2880
  }
@@ -2703,7 +2885,7 @@ var require_workContext = __commonJS({
2703
2885
  const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
2704
2886
  return { checkoutRoot: dir, canonicalRoot, gitDir };
2705
2887
  }
2706
- const parent = path3.dirname(dir);
2888
+ const parent = path4.dirname(dir);
2707
2889
  if (parent === dir)
2708
2890
  return null;
2709
2891
  dir = parent;
@@ -2712,16 +2894,16 @@ var require_workContext = __commonJS({
2712
2894
  }
2713
2895
  function readGitdirPointer(dotGitFile, containingDir) {
2714
2896
  try {
2715
- const match = /^gitdir:\s*(.+)\s*$/m.exec(fs4.readFileSync(dotGitFile, "utf8"));
2897
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(fs5.readFileSync(dotGitFile, "utf8"));
2716
2898
  if (!match)
2717
2899
  return null;
2718
- return path3.resolve(containingDir, match[1].trim());
2900
+ return path4.resolve(containingDir, match[1].trim());
2719
2901
  } catch {
2720
2902
  return null;
2721
2903
  }
2722
2904
  }
2723
2905
  function worktreeParentRoot(resolvedGitDir) {
2724
- const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
2906
+ const marker = `${path4.sep}.git${path4.sep}worktrees${path4.sep}`;
2725
2907
  const idx = resolvedGitDir.indexOf(marker);
2726
2908
  if (idx === -1)
2727
2909
  return null;
@@ -2731,12 +2913,12 @@ var require_workContext = __commonJS({
2731
2913
  const sep = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
2732
2914
  const leading = /^[\\/]/.test(startPath) ? sep : "";
2733
2915
  const segments = startPath.split(/[\\/]/).filter(Boolean);
2734
- const join3 = (count) => leading + segments.slice(0, count).join(sep);
2916
+ const join4 = (count) => leading + segments.slice(0, count).join(sep);
2735
2917
  for (let i = 0; i + 2 < segments.length; i++) {
2736
2918
  if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
2737
2919
  if (i === 0)
2738
2920
  return null;
2739
- return { checkoutRoot: join3(i + 3), canonicalRoot: join3(i), gitDir: null };
2921
+ return { checkoutRoot: join4(i + 3), canonicalRoot: join4(i), gitDir: null };
2740
2922
  }
2741
2923
  }
2742
2924
  for (let i = 0; i + 1 < segments.length; i++) {
@@ -2746,7 +2928,7 @@ var require_workContext = __commonJS({
2746
2928
  continue;
2747
2929
  const repoName = folder.slice(0, -suffix.length);
2748
2930
  const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep);
2749
- return { checkoutRoot: join3(i + 2), canonicalRoot, gitDir: null };
2931
+ return { checkoutRoot: join4(i + 2), canonicalRoot, gitDir: null };
2750
2932
  }
2751
2933
  return null;
2752
2934
  }
@@ -2794,7 +2976,7 @@ var require_workContext = __commonJS({
2794
2976
  return null;
2795
2977
  let head;
2796
2978
  try {
2797
- head = fs4.readFileSync(path3.join(gitDir, "HEAD"), "utf8").trim();
2979
+ head = fs5.readFileSync(path4.join(gitDir, "HEAD"), "utf8").trim();
2798
2980
  } catch {
2799
2981
  return null;
2800
2982
  }
@@ -2978,54 +3160,65 @@ var require_hookAdapter = __commonJS({
2978
3160
  }
2979
3161
  });
2980
3162
 
2981
- // ../packages/tool-kit/out/setupDisclosure.js
2982
- var require_setupDisclosure = __commonJS({
2983
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3163
+ // ../packages/tool-kit/out/hookSet.js
3164
+ var require_hookSet = __commonJS({
3165
+ "../packages/tool-kit/out/hookSet.js"(exports) {
2984
3166
  "use strict";
2985
3167
  Object.defineProperty(exports, "__esModule", { value: true });
2986
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
2987
- exports.renderSetupDisclosure = renderSetupDisclosure3;
2988
- exports.FAMILY_SENTENCES = {
2989
- 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",
2990
- 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",
2991
- tools: "the name of each tool your agent calls",
2992
- outcome: "whether a call succeeded, failed, or was interrupted",
2993
- clock: "your machine's offset from UTC, so an evening is read as an evening",
2994
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
2995
- model: "which model served the session, by name and by tier",
2996
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
2997
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
2998
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
2999
- context: "how full the context window got",
3000
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3001
- reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
3002
- };
3003
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3004
- exports.REFUSALS = [
3005
- "Never your prompts, your agent's replies, or anything inside a file.",
3006
- "Never a file path, a command line, or a repository or branch name.",
3007
- "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
3008
- ];
3009
- exports.FREE_TEXT_KEYS = ["message"];
3010
- function renderSetupDisclosure3({ sends, displayName }) {
3011
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3012
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3013
- const lines = [
3014
- `What this sends from ${displayName}, once paired:`,
3015
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3016
- "",
3017
- ...exports.REFUSALS.map((line) => ` ${line}`),
3018
- "",
3019
- " Turn it off by revoking this tool in the Ascenda app."
3020
- ];
3021
- return lines.join("\n");
3168
+ exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = void 0;
3169
+ exports.hookSetArgument = hookSetArgument2;
3170
+ exports.readHookSet = readHookSet2;
3171
+ exports.isHookSet = isHookSet;
3172
+ exports.readViaPlugin = readViaPlugin2;
3173
+ exports.hookSetOfCommand = hookSetOfCommand2;
3174
+ exports.hookSetChanges = hookSetChanges2;
3175
+ exports.describeHookSetChanges = describeHookSetChanges2;
3176
+ exports.HOOK_SET_FLAG = "--hook-set";
3177
+ exports.UNVERSIONED_HOOK_SET = 1;
3178
+ function hookSetArgument2(hookSet) {
3179
+ return hookSet === void 0 ? "" : ` ${exports.HOOK_SET_FLAG} ${hookSet}`;
3180
+ }
3181
+ function readHookSet2(argv) {
3182
+ const index = argv.indexOf(exports.HOOK_SET_FLAG);
3183
+ if (index === -1)
3184
+ return void 0;
3185
+ const raw = argv[index + 1];
3186
+ if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
3187
+ return void 0;
3188
+ const value = Number(raw);
3189
+ return isHookSet(value) ? value : void 0;
3190
+ }
3191
+ function isHookSet(value) {
3192
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3193
+ }
3194
+ function readViaPlugin2(env) {
3195
+ return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
3196
+ }
3197
+ function hookSetOfCommand2(command) {
3198
+ const match = command.match(/--hook-set\s+(\d+)/);
3199
+ return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
3200
+ }
3201
+ function hookSetChanges2(before, events) {
3202
+ const added = events.filter((event) => !before.has(event));
3203
+ const sets = [...before.values()];
3204
+ return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
3205
+ }
3206
+ function describeHookSetChanges2(changes, hookSet) {
3207
+ if (changes.previousSet === void 0)
3208
+ return void 0;
3209
+ const parts = [];
3210
+ if (changes.added.length)
3211
+ parts.push(`added ${changes.added.join(", ")}`);
3212
+ if (changes.previousSet < hookSet)
3213
+ parts.push(`hook set ${changes.previousSet} \u2192 ${hookSet}`);
3214
+ return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
3022
3215
  }
3023
3216
  }
3024
3217
  });
3025
3218
 
3026
- // ../packages/tool-kit/out/cliAgentSetup.js
3027
- var require_cliAgentSetup = __commonJS({
3028
- "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
3219
+ // ../packages/tool-kit/out/studyJoin.js
3220
+ var require_studyJoin = __commonJS({
3221
+ "../packages/tool-kit/out/studyJoin.js"(exports) {
3029
3222
  "use strict";
3030
3223
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3031
3224
  if (k2 === void 0) k2 = k;
@@ -3065,119 +3258,801 @@ var require_cliAgentSetup = __commonJS({
3065
3258
  };
3066
3259
  }();
3067
3260
  Object.defineProperty(exports, "__esModule", { value: true });
3068
- exports.isCliAgentManagementCommand = isCliAgentManagementCommand;
3069
- exports.cliAgentHookBinPath = cliAgentHookBinPath;
3070
- exports.runCliAgentSetup = runCliAgentSetup;
3071
- exports.writeHookSettings = writeHookSettings;
3072
- exports.findStaleHookCommands = findStaleHookCommands2;
3073
- var crypto2 = __importStar(__require("crypto"));
3074
- var fs4 = __importStar(__require("fs"));
3075
- var os2 = __importStar(__require("os"));
3076
- var path3 = __importStar(__require("path"));
3077
- var collectorVersion_1 = require_collectorVersion();
3078
- var credentials_1 = require_credentials();
3079
- var hookAdapter_1 = require_hookAdapter();
3261
+ exports.runStudyJoin = runStudyJoin2;
3262
+ exports.formatWindow = formatWindow;
3263
+ var readline = __importStar(__require("node:readline"));
3080
3264
  var http_1 = require_http();
3081
- var setupDisclosure_1 = require_setupDisclosure();
3082
- var tokenStore_1 = require_tokenStore();
3083
- var MANAGEMENT_COMMANDS2 = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
3084
- function isCliAgentManagementCommand(argument) {
3085
- return argument !== void 0 && MANAGEMENT_COMMANDS2.has(argument);
3086
- }
3087
- function cliAgentHookBinPath(binaryName) {
3088
- return path3.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3089
- }
3090
- function usage(spec) {
3091
- return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
3092
-
3093
- npx ${spec.packageName} setup [options]
3094
- npx ${spec.packageName} status
3095
- npx ${spec.packageName} uninstall
3096
-
3097
- Options
3098
- --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
3099
- --local [port] shorthand for the local dev server (default port 4477)
3100
- --tool-installation-id <id> reuse an existing pairing instead of creating one
3101
- --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
3102
- --no-pair install without pairing: local features on, nothing sent
3103
- --scope project|user where hooks are registered (default project)
3104
- --project-dir <path> project root for --scope project (default cwd)
3105
- --dry-run print what would change, write nothing
3106
- -h, --help
3107
- `;
3108
- }
3109
- async function runCliAgentSetup(argv, spec) {
3110
- let options;
3265
+ var STUDY_JOIN_MODE = "report";
3266
+ var POLL_INTERVAL_MS = 3e3;
3267
+ var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
3268
+ async function runStudyJoin2(ctx) {
3269
+ const stdin = ctx.stdin ?? process.stdin;
3270
+ const stdout = ctx.stdout ?? process.stdout;
3271
+ const stderr = ctx.stderr ?? process.stderr;
3272
+ const print = (line) => stdout.write(`${line}
3273
+ `);
3274
+ if (!stdin.isTTY || !stdout.isTTY) {
3275
+ stderr.write("join needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
3276
+ return 0;
3277
+ }
3278
+ if (!ctx.joinCode) {
3279
+ stderr.write("Usage: join <code>\n");
3280
+ return 1;
3281
+ }
3282
+ let start;
3111
3283
  try {
3112
- options = parseArgs2(argv, spec);
3284
+ start = await (0, http_1.startStudyJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, ctx.joinCode, STUDY_JOIN_MODE);
3113
3285
  } catch (error) {
3114
- console.error(error instanceof Error ? error.message : String(error));
3286
+ stderr.write(`${describeStartError(error)}
3287
+ `);
3115
3288
  return 1;
3116
3289
  }
3117
- if (options.action === "help") {
3118
- console.log(usage(spec));
3290
+ print("");
3291
+ print(`${start.organisationName}: ${describeStudyKind(start.studyKind)}`);
3292
+ print(formatWindow(start.windowStartUtc, start.windowEndUtc));
3293
+ print("");
3294
+ print("Report (30 days) grants:");
3295
+ for (const grant of start.grants)
3296
+ print(` ${describeGrant(grant)}`);
3297
+ print("");
3298
+ print("Study mode needs the Ascenda app. Open the app to join that way instead.");
3299
+ print("");
3300
+ print("Join in:");
3301
+ print(" 1) Report (30 days)");
3302
+ print(" 2) Not now");
3303
+ print("");
3304
+ const answer = await askChoice(stdin, stdout);
3305
+ if (!/^(1|report)$/i.test(answer)) {
3306
+ print("Not now.");
3119
3307
  return 0;
3120
3308
  }
3121
- if (options.action === "status")
3122
- return printStatus2(options, spec);
3123
- if (options.action === "uninstall")
3124
- return uninstall2(options, spec);
3125
- const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3126
- console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
3127
- console.log(`
3128
- ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}
3309
+ print("");
3310
+ print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
3311
+ print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
3312
+ const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3313
+ const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3314
+ while (Date.now() < deadline) {
3315
+ await new Promise((resolve2) => setTimeout(resolve2, pollIntervalMs));
3316
+ let poll;
3317
+ try {
3318
+ poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
3319
+ } catch (error) {
3320
+ if (isRetryablePollError(error))
3321
+ continue;
3322
+ stderr.write(`${describeStartError(error)}
3129
3323
  `);
3130
- let identity;
3131
- let unpairedReason;
3132
- if (options.skipPairing) {
3133
- unpairedReason = "asked not to pair (--no-pair)";
3134
- } else {
3135
- identity = await resolveIdentity2(apiBaseUrl, options, spec);
3136
- if (identity) {
3137
- console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
3138
- } else {
3139
- unpairedReason = "pairing did not finish \u2014 installing the local half anyway";
3324
+ return 1;
3140
3325
  }
3141
- }
3142
- if (unpairedReason) {
3143
- console.log(` pairing none: ${unpairedReason}`);
3144
- console.log(" local features on, nothing is sent");
3145
- }
3146
- const binary = installBinary2(spec, options.dryRun);
3147
- console.log(` hook binary ${binary}`);
3148
- if (!options.dryRun) {
3149
- const now = (/* @__PURE__ */ new Date()).toISOString();
3150
- const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
3151
- (0, credentials_1.writeHostCredentials)(spec.host, {
3152
- apiBaseUrl,
3153
- toolInstallationId,
3154
- ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
3155
- });
3156
- }
3157
- console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
3158
- const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3159
- const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
3160
- if (written === null)
3326
+ if (poll.status === "pending")
3327
+ continue;
3328
+ if (poll.status === "confirmed") {
3329
+ const granted = poll.granted ?? [];
3330
+ if (granted.length === 0) {
3331
+ print("");
3332
+ print("Nothing was granted. Run join again, or check with your organisation.");
3333
+ return 1;
3334
+ }
3335
+ print("");
3336
+ print("Joined. Granted:");
3337
+ for (const grant of granted)
3338
+ print(` ${describeGrant(grant)}`);
3339
+ print("");
3340
+ print("Each of these can be turned off separately, in the app's consent settings.");
3341
+ print("The organisation sees group counts, never who joined.");
3342
+ return 0;
3343
+ }
3344
+ if (poll.status === "expired") {
3345
+ print("");
3346
+ print("This code expired before it was confirmed. Run join again for a fresh code.");
3347
+ return 1;
3348
+ }
3349
+ if (poll.refusedReason === "grant_failed") {
3350
+ print("");
3351
+ print("Join failed partway through. Some grants may not have gone through.");
3352
+ const granted = poll.granted ?? [];
3353
+ if (granted.length > 0) {
3354
+ print("");
3355
+ print("Granted before the failure:");
3356
+ for (const grant of granted)
3357
+ print(` ${describeGrant(grant)}`);
3358
+ print("");
3359
+ print("Each of these can be turned off separately, in the app's consent settings.");
3360
+ }
3361
+ print("Run join again, or check with your organisation.");
3362
+ return 1;
3363
+ }
3364
+ print("");
3365
+ print(describeRefusal(poll.refusedReason));
3161
3366
  return 1;
3162
- console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
3163
- if (options.dryRun) {
3164
- console.log("\nDry run \u2014 nothing was written.");
3165
- return 0;
3166
3367
  }
3167
- console.log(`
3168
- Done. ${spec.restartHint}`);
3169
- if (!identity) {
3170
- console.log(`Pair later: npx ${spec.packageName} setup`);
3368
+ print("");
3369
+ print("Timed out waiting for confirmation. Run join again for a fresh code.");
3370
+ return 1;
3371
+ }
3372
+ function isRetryablePollError(error) {
3373
+ if (error instanceof http_1.AscendaApiError)
3374
+ return error.status >= 500 && error.status <= 599;
3375
+ return true;
3376
+ }
3377
+ function askChoice(stdin, stdout) {
3378
+ return new Promise((resolve2) => {
3379
+ const rl = readline.createInterface({ input: stdin, output: stdout });
3380
+ let settled = false;
3381
+ const finish = (value) => {
3382
+ if (settled)
3383
+ return;
3384
+ settled = true;
3385
+ rl.close();
3386
+ resolve2(value.trim());
3387
+ };
3388
+ rl.question("Choice [Not now]: ", finish);
3389
+ rl.once("close", () => finish(""));
3390
+ });
3391
+ }
3392
+ function formatLocalTime(iso) {
3393
+ const date = new Date(iso);
3394
+ if (Number.isNaN(date.getTime()))
3395
+ return iso;
3396
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date);
3397
+ }
3398
+ function formatWindow(startUtc, endUtc) {
3399
+ const start = new Date(startUtc);
3400
+ const end = new Date(endUtc);
3401
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
3402
+ const dayMonth = { day: "numeric", month: "short", timeZone: "UTC" };
3403
+ const withYear = { ...dayMonth, year: "numeric" };
3404
+ const startFmt = new Intl.DateTimeFormat("en-GB", sameYear ? dayMonth : withYear);
3405
+ const endFmt = new Intl.DateTimeFormat("en-GB", withYear);
3406
+ return `${startFmt.format(start)} \u2013 ${endFmt.format(end)}`;
3407
+ }
3408
+ var GRANT_SENTENCES = {
3409
+ 501: "AI assistant data processing consent",
3410
+ 507: "Import of the AI-work history already on your machine"
3411
+ };
3412
+ function describeGrant(grant) {
3413
+ return GRANT_SENTENCES[grant.code] ?? humanise(grant.name);
3414
+ }
3415
+ var STUDY_KIND_SENTENCES = {
3416
+ Report30: "a 30-day report",
3417
+ Study90: "a 90-day study"
3418
+ };
3419
+ function describeStudyKind(studyKind) {
3420
+ return STUDY_KIND_SENTENCES[studyKind] ?? humanise(studyKind);
3421
+ }
3422
+ function humanise(name) {
3423
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim() || name;
3424
+ }
3425
+ var REFUSED_REASON_MESSAGES = {
3426
+ study_no_longer_live: "That study is no longer open to join.",
3427
+ withdrawn: "You're no longer an active participant in that study.",
3428
+ // Handled as its own branch above, with its granted list, before this
3429
+ // table is ever consulted — present so the type stays exhaustive, and as
3430
+ // a plain fallback should something call this function with it directly.
3431
+ grant_failed: "Join failed partway through. Some grants may not have gone through.",
3432
+ declined: "You declined in the app. Nothing was granted.",
3433
+ not_enrolled: "That study couldn't enrol you, so nothing was granted."
3434
+ };
3435
+ function describeRefusal(refusedReason) {
3436
+ if (refusedReason && REFUSED_REASON_MESSAGES[refusedReason])
3437
+ return REFUSED_REASON_MESSAGES[refusedReason];
3438
+ return "The join didn't go through. Nothing new was granted.";
3439
+ }
3440
+ var START_ERROR_MESSAGES = {
3441
+ join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
3442
+ unknown_mode: "This tool only offers Report mode from the command line.",
3443
+ no_live_study: "There's nothing open to join with that code right now.",
3444
+ too_many_open_sessions: "This tool has too many joins waiting to be confirmed. Confirm one, or let one expire, then try again.",
3445
+ unknown_session: "That join can no longer be found. Run join again for a fresh code."
3446
+ };
3447
+ function describeStartError(error) {
3448
+ if (error instanceof http_1.AscendaApiError) {
3449
+ if (error.errorCode && START_ERROR_MESSAGES[error.errorCode])
3450
+ return START_ERROR_MESSAGES[error.errorCode];
3451
+ if (error.status === 401)
3452
+ return "This tool's pairing was rejected. Re-pair it, then try again.";
3453
+ return `Could not reach the join code (HTTP ${error.status}).`;
3171
3454
  }
3172
- console.log(`Check anytime: npx ${spec.packageName} status`);
3173
- return 0;
3455
+ return error instanceof Error ? error.message : String(error);
3174
3456
  }
3175
- function parseArgs2(argv, spec) {
3176
- const options = {
3177
- scope: "project",
3178
- projectDir: process.cwd(),
3179
- dryRun: false,
3180
- skipPairing: false,
3457
+ }
3458
+ });
3459
+
3460
+ // ../packages/tool-kit/out/initiatives.js
3461
+ var require_initiatives = __commonJS({
3462
+ "../packages/tool-kit/out/initiatives.js"(exports) {
3463
+ "use strict";
3464
+ Object.defineProperty(exports, "__esModule", { value: true });
3465
+ exports.INITIATIVE_COPY = void 0;
3466
+ exports.initiativesStatusLines = initiativesStatusLines2;
3467
+ exports.renderInitiatives = renderInitiatives;
3468
+ var http_1 = require_http();
3469
+ var studyJoin_1 = require_studyJoin();
3470
+ var READ_TIMEOUT_MS = 5e3;
3471
+ exports.INITIATIVE_COPY = {
3472
+ outcomes: {
3473
+ moved_as_declared: "Moved the way declared, beyond the cohort's own variation",
3474
+ moved_against_declared: "Moved the other way, beyond the cohort's own variation",
3475
+ moved_no_direction_declared: "Moved beyond the cohort's own variation; no direction was declared",
3476
+ within_own_variation: "No further from the baseline than the cohort's own week-to-week variation",
3477
+ withheld: "Withheld"
3478
+ },
3479
+ withheldReasons: {
3480
+ cohort_below_minimum: "the cohort was too small to report on when the scoring window closed",
3481
+ below_minimum_cohort: "the cohort was too small to report on when the scoring window closed",
3482
+ below_minimum_cohort_size: "the cohort was too small to report on when the scoring window closed",
3483
+ baseline_withheld: "the baseline was withheld"
3484
+ }
3485
+ };
3486
+ var OUTCOME_EMPTY = "Not stated";
3487
+ var OUTCOME_UNKNOWN = "An outcome this app does not recognise";
3488
+ var WITHHELD_UNKNOWN = "Withheld, for a reason this version of the app doesn't name yet.";
3489
+ var DIRECTION_WORDS = {
3490
+ up: "Expected to rise",
3491
+ down: "Expected to fall",
3492
+ none_declared: "No direction declared"
3493
+ };
3494
+ var DIRECTION_UNKNOWN = "A direction this app does not recognise";
3495
+ async function initiativesStatusLines2(ctx) {
3496
+ const heading = "Changes your organisation has published to you";
3497
+ if (!ctx.eventWriteToken) {
3498
+ return [heading, " Not checked: this install holds no token, so nothing was fetched."];
3499
+ }
3500
+ const read = await (0, http_1.readInitiatives)(ctx.apiBaseUrl, ctx.eventWriteToken, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3501
+ if (read.kind === "rejected") {
3502
+ return [
3503
+ heading,
3504
+ ` Couldn't check: the server turned this install's request down. If that keeps happening, pair again with \`${ctx.pairCommand}\`.`
3505
+ ];
3506
+ }
3507
+ if (read.kind === "failed") {
3508
+ return [heading, ` Couldn't check: ${read.reason}. Run status again to retry.`];
3509
+ }
3510
+ return [heading, ...renderInitiatives(read.initiatives)];
3511
+ }
3512
+ function renderInitiatives(entries, copy = exports.INITIATIVE_COPY) {
3513
+ if (entries.length === 0)
3514
+ return [" None published to you."];
3515
+ const lines = [];
3516
+ let unreadable = 0;
3517
+ for (const entry of entries) {
3518
+ const initiative = asInitiative(entry);
3519
+ if (!initiative) {
3520
+ unreadable += 1;
3521
+ continue;
3522
+ }
3523
+ lines.push(...renderOne(initiative, copy));
3524
+ }
3525
+ if (unreadable > 0) {
3526
+ lines.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3527
+ }
3528
+ return lines;
3529
+ }
3530
+ function renderOne(initiative, copy) {
3531
+ const lines = [` ${initiative.organisationName}: ${initiative.title}`];
3532
+ lines.push(` ${describeStatus(initiative)}`);
3533
+ if (initiative.summaryForCohort) {
3534
+ for (const line of initiative.summaryForCohort.split(/\r?\n/))
3535
+ lines.push(` ${line}`);
3536
+ }
3537
+ if (initiative.direction)
3538
+ lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
3539
+ lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
3540
+ if (initiative.result)
3541
+ lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
3542
+ lines.push("");
3543
+ return lines;
3544
+ }
3545
+ function describeStatus(initiative) {
3546
+ switch (initiative.status) {
3547
+ case "published":
3548
+ return "Published, not scored yet.";
3549
+ case "scored":
3550
+ return "Scored.";
3551
+ case "withdrawn":
3552
+ return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
3553
+ default:
3554
+ return "Status not recognised.";
3555
+ }
3556
+ }
3557
+ function renderResult(result, unit, copy) {
3558
+ const lines = [];
3559
+ const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
3560
+ if (result.value === null) {
3561
+ const why = copy.withheldReasons[result.withheldReason ?? ""];
3562
+ lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
3563
+ return lines;
3564
+ }
3565
+ lines.push(` Result: ${show(result.value)}`);
3566
+ lines.push(` ${movementLine(result)}`);
3567
+ lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
3568
+ return lines;
3569
+ }
3570
+ function movementLine(result) {
3571
+ if (result.outcome === "within_own_variation")
3572
+ return "No material change against frozen baseline";
3573
+ if (result.delta === null)
3574
+ return "No reading";
3575
+ if (result.delta > 0)
3576
+ return `Up ${figure(result.delta)} against frozen baseline`;
3577
+ if (result.delta < 0)
3578
+ return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
3579
+ return "No change against frozen baseline";
3580
+ }
3581
+ function figure(n) {
3582
+ return String(Number(n.toPrecision(12)));
3583
+ }
3584
+ function asInitiative(value) {
3585
+ if (!value || typeof value !== "object")
3586
+ return void 0;
3587
+ const o = value;
3588
+ if (typeof o.title !== "string" || typeof o.status !== "string")
3589
+ return void 0;
3590
+ return {
3591
+ id: typeof o.id === "string" ? o.id : "",
3592
+ organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3593
+ title: o.title,
3594
+ summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3595
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3596
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3597
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3598
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3599
+ status: o.status,
3600
+ direction: typeof o.direction === "string" ? o.direction : null,
3601
+ result: asResult(o.result)
3602
+ };
3603
+ }
3604
+ function asResult(value) {
3605
+ if (!value || typeof value !== "object")
3606
+ return null;
3607
+ const r = value;
3608
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
3609
+ return {
3610
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3611
+ value: num(r.value),
3612
+ baselineValue: num(r.baselineValue),
3613
+ delta: num(r.delta),
3614
+ movement: typeof r.movement === "string" ? r.movement : null,
3615
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
3616
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3617
+ basis: typeof r.basis === "string" ? r.basis : null
3618
+ };
3619
+ }
3620
+ function formatWindowOrRaw(startUtc, endUtc) {
3621
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3622
+ return "not given";
3623
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3624
+ }
3625
+ function formatDay(iso) {
3626
+ const date = new Date(iso);
3627
+ if (Number.isNaN(date.getTime()))
3628
+ return iso;
3629
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
3630
+ }
3631
+ }
3632
+ });
3633
+
3634
+ // ../packages/tool-kit/out/setupDisclosure.js
3635
+ var require_setupDisclosure = __commonJS({
3636
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3637
+ "use strict";
3638
+ Object.defineProperty(exports, "__esModule", { value: true });
3639
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3640
+ exports.renderSetupDisclosure = renderSetupDisclosure3;
3641
+ exports.FAMILY_SENTENCES = {
3642
+ 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",
3643
+ 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",
3644
+ tools: "the name of each tool your agent calls",
3645
+ outcome: "whether a call succeeded, failed, or was interrupted",
3646
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
3647
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3648
+ model: "which model served the session, by name and by tier",
3649
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3650
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
3651
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3652
+ context: "how full the context window got",
3653
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3654
+ subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
3655
+ reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
3656
+ };
3657
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3658
+ exports.REFUSALS = [
3659
+ "Never your prompts, your agent's replies, or anything inside a file.",
3660
+ "Never a file path, a command line, or a repository or branch name.",
3661
+ "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
3662
+ ];
3663
+ exports.FREE_TEXT_KEYS = ["message"];
3664
+ function renderSetupDisclosure3({ sends, displayName }) {
3665
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3666
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3667
+ const lines = [
3668
+ `What this sends from ${displayName}, once paired:`,
3669
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3670
+ "",
3671
+ ...exports.REFUSALS.map((line) => ` ${line}`),
3672
+ "",
3673
+ " Turn it off by revoking this tool in the Ascenda app."
3674
+ ];
3675
+ return lines.join("\n");
3676
+ }
3677
+ }
3678
+ });
3679
+
3680
+ // ../packages/tool-kit/out/studyNotices.js
3681
+ var require_studyNotices = __commonJS({
3682
+ "../packages/tool-kit/out/studyNotices.js"(exports) {
3683
+ "use strict";
3684
+ Object.defineProperty(exports, "__esModule", { value: true });
3685
+ exports.NOTICED_PURPOSES = void 0;
3686
+ exports.studyNoticeStatus = studyNoticeStatus2;
3687
+ exports.renderStudyNotices = renderStudyNotices;
3688
+ exports.runStudyObjection = runStudyObjection2;
3689
+ var http_1 = require_http();
3690
+ var READ_TIMEOUT_MS = 5e3;
3691
+ var NOTICE_LABEL = "Counted unless you object";
3692
+ var PROCESSOR = "Ascenda";
3693
+ exports.NOTICED_PURPOSES = [
3694
+ { code: 501, slug: "telemetry", title: "Live tool telemetry" },
3695
+ { code: 507, slug: "import", title: "One-time import of past AI work" },
3696
+ { code: 11, slug: "work-patterns", title: "Work-pattern axes in the group figures" }
3697
+ ];
3698
+ var BASIS_WORDS = {
3699
+ legitimate_interests: "legitimate interests",
3700
+ collective_agreement: "a collective agreement"
3701
+ };
3702
+ async function studyNoticeStatus2(ctx) {
3703
+ const nothing = { lines: [], markShown: async () => {
3704
+ } };
3705
+ const token = ctx.eventWriteToken;
3706
+ if (!token)
3707
+ return nothing;
3708
+ const read = await (0, http_1.readStudyNotices)(ctx.apiBaseUrl, token, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3709
+ if (read.kind !== "ok")
3710
+ return nothing;
3711
+ const lines = renderStudyNotices(read.notices, ctx.commandPrefix, ctx.now);
3712
+ if (lines.length === 0)
3713
+ return nothing;
3714
+ const unshown = shownPurposes(read.notices).filter((n) => !n.noticeFromUtc && n.organisationId);
3715
+ return {
3716
+ lines,
3717
+ markShown: async () => {
3718
+ const signal = AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS);
3719
+ await Promise.all(unshown.map((n) => (0, http_1.markStudyNoticeShown)(ctx.apiBaseUrl, token, n.organisationId, n.code, signal)));
3720
+ }
3721
+ };
3722
+ }
3723
+ function shownPurposes(entries) {
3724
+ return entries.map(asNotice).filter((n) => n !== void 0 && exports.NOTICED_PURPOSES.some((p) => p.code === n.code));
3725
+ }
3726
+ function renderStudyNotices(entries, commandPrefix, now = /* @__PURE__ */ new Date()) {
3727
+ const body = [];
3728
+ let unreadable = 0;
3729
+ for (const entry of entries) {
3730
+ const notice = asNotice(entry);
3731
+ const purpose = notice && exports.NOTICED_PURPOSES.find((p) => p.code === notice.code);
3732
+ if (!notice || !purpose) {
3733
+ unreadable += 1;
3734
+ continue;
3735
+ }
3736
+ body.push(...renderOne(notice, purpose, commandPrefix, now));
3737
+ }
3738
+ if (body.length === 0)
3739
+ return [];
3740
+ if (unreadable > 0) {
3741
+ body.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3742
+ }
3743
+ return ["", "Your organisation's study", ...body];
3744
+ }
3745
+ function renderOne(notice, purpose, commandPrefix, now) {
3746
+ const org = notice.organisationName;
3747
+ const command = `${commandPrefix} object ${purpose.slug}`;
3748
+ const lines = [` ${org}: ${purpose.title}`];
3749
+ lines.push(` ${notice.label || NOTICE_LABEL}`);
3750
+ lines.push(` ${basisLine(notice)}`);
3751
+ if (notice.signatoryName)
3752
+ lines.push(` Recorded by ${notice.signatoryName}.`);
3753
+ lines.push(` ${notice.processor || PROCESSOR} processes this for ${org}.`);
3754
+ if (notice.objected === true) {
3755
+ lines.push(" You objected. You are left out from the next report on.");
3756
+ lines.push(` To undo: ${command} --undo`);
3757
+ } else if (notice.objected === false) {
3758
+ lines.push(" You haven't objected.");
3759
+ if (notice.noticeFromUtc && isDate(notice.noticeFromUtc)) {
3760
+ const starts = notice.countingFromUtc && isDate(notice.countingFromUtc) ? notice.countingFromUtc : new Date(Date.parse(notice.noticeFromUtc) + NOTICE_PERIOD_MS).toISOString();
3761
+ if (Date.parse(starts) > now.getTime()) {
3762
+ lines.push(` Notice given ${formatDay(notice.noticeFromUtc)}. Counting starts ${formatDay(starts)}.`);
3763
+ }
3764
+ }
3765
+ lines.push(` To object: ${command}. No reason is asked. You are left out from the next report on, and earlier reports stay as they were.`);
3766
+ } else {
3767
+ lines.push(" This version of the tool couldn't read whether you've objected. Run status again.");
3768
+ lines.push(` To object: ${command}`);
3769
+ lines.push(` To undo: ${command} --undo`);
3770
+ }
3771
+ lines.push("");
3772
+ return lines;
3773
+ }
3774
+ function basisLine(notice) {
3775
+ const words = notice.basisLabel ?? BASIS_WORDS[notice.basis];
3776
+ const head = words ? `${notice.organisationName}'s basis is ${words}.` : `${notice.organisationName}'s basis is one this version of the tool can't name.`;
3777
+ const dated = notice.documentDate && isDate(notice.documentDate) ? formatDay(notice.documentDate) : null;
3778
+ const ref = notice.documentReference ? `ref ${notice.documentReference}` : null;
3779
+ const title = notice.documentTitle ? dated ? `${notice.documentTitle} (${dated})` : notice.documentTitle : null;
3780
+ const document = [title, ref].filter((part) => Boolean(part)).join(", ");
3781
+ return document ? `${head} Document: ${document}.` : head;
3782
+ }
3783
+ var NOTICE_PERIOD_MS = 14 * 24 * 60 * 60 * 1e3;
3784
+ function asNotice(value) {
3785
+ if (!value || typeof value !== "object")
3786
+ return void 0;
3787
+ const o = value;
3788
+ if (typeof o.code !== "number")
3789
+ return void 0;
3790
+ if (typeof o.mode === "string" && o.mode.trim().toLowerCase() !== "notice")
3791
+ return void 0;
3792
+ const str = (x) => typeof x === "string" && x.trim() ? x : null;
3793
+ return {
3794
+ organisationId: str(o.organisationId),
3795
+ organisationName: str(o.organisationName) ?? "Your organisation",
3796
+ code: o.code,
3797
+ name: str(o.name),
3798
+ label: str(o.label),
3799
+ processor: str(o.processor),
3800
+ basis: typeof o.basis === "string" ? o.basis : "",
3801
+ basisLabel: str(o.basisLabel),
3802
+ documentTitle: str(o.documentTitle),
3803
+ documentDate: str(o.documentDate),
3804
+ documentReference: str(o.documentReference),
3805
+ signatoryName: str(o.signatoryName),
3806
+ objected: typeof o.objected === "boolean" ? o.objected : null,
3807
+ objectedAtUtc: str(o.objectedAtUtc),
3808
+ noticeFromUtc: str(o.noticeFromUtc),
3809
+ countingFromUtc: str(o.countingFromUtc)
3810
+ };
3811
+ }
3812
+ async function runStudyObjection2(ctx) {
3813
+ const stdin = ctx.stdin ?? process.stdin;
3814
+ const stdout = ctx.stdout ?? process.stdout;
3815
+ const stderr = ctx.stderr ?? process.stderr;
3816
+ const print = (line) => stdout.write(`${line}
3817
+ `);
3818
+ if (!stdin.isTTY || !stdout.isTTY) {
3819
+ stderr.write("object needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
3820
+ return 1;
3821
+ }
3822
+ const undo = ctx.argv.includes("--undo");
3823
+ const rest = ctx.argv.filter((a) => a !== "--undo");
3824
+ const purpose = rest.length === 1 ? exports.NOTICED_PURPOSES.find((p) => p.slug === rest[0]) : void 0;
3825
+ if (!purpose) {
3826
+ stderr.write(objectionUsage(ctx.commandPrefix));
3827
+ return 1;
3828
+ }
3829
+ if (!ctx.eventWriteToken) {
3830
+ stderr.write(`This install isn't paired, so there's nothing to object to. Pair with \`${ctx.pairCommand}\`.
3831
+ `);
3832
+ return 1;
3833
+ }
3834
+ const command = `${ctx.commandPrefix} object ${purpose.slug}`;
3835
+ try {
3836
+ await (0, http_1.setStudyObjection)(ctx.apiBaseUrl, ctx.eventWriteToken, purpose.code, !undo);
3837
+ } catch (error) {
3838
+ stderr.write(`${describeObjectionError(error, purpose, undo, ctx.pairCommand)}
3839
+ `);
3840
+ return 1;
3841
+ }
3842
+ if (undo) {
3843
+ print(`Objection withdrawn: ${purpose.title}.`);
3844
+ print("You're counted again from the next report.");
3845
+ print(`To object again: ${command}`);
3846
+ } else {
3847
+ print(`Objected: ${purpose.title}.`);
3848
+ print("You objected. You are left out from the next report on, and earlier reports stay as they were.");
3849
+ print(`To undo: ${command} --undo`);
3850
+ }
3851
+ return 0;
3852
+ }
3853
+ function objectionUsage(commandPrefix) {
3854
+ const lines = [`Usage: ${commandPrefix} object <purpose> [--undo]`, "", "Purposes:"];
3855
+ for (const p of exports.NOTICED_PURPOSES)
3856
+ lines.push(` ${p.slug.padEnd(14)}${p.title}`);
3857
+ lines.push("", "status shows which of these your organisation counts unless you object.");
3858
+ return `${lines.join("\n")}
3859
+ `;
3860
+ }
3861
+ function describeObjectionError(error, purpose, undo, pairCommand) {
3862
+ if (error instanceof http_1.AscendaApiError) {
3863
+ if (error.status === 404 && error.errorCode === "not_noticed") {
3864
+ return undo ? `Your organisation doesn't count you for ${purpose.title} unless you object, so there's no objection to undo.` : `Your organisation doesn't count you for ${purpose.title} unless you object, so there's nothing to object to.`;
3865
+ }
3866
+ if (error.status === 401)
3867
+ return `The server turned this install's request down. If that keeps happening, pair again with \`${pairCommand}\`.`;
3868
+ if (error.status === 404)
3869
+ return "This server doesn't take objections yet. Nothing changed.";
3870
+ return `Couldn't record that (HTTP ${error.status}). Nothing changed. Run it again to retry.`;
3871
+ }
3872
+ return "Couldn't reach the server. Nothing changed. Run it again to retry.";
3873
+ }
3874
+ function isDate(iso) {
3875
+ return !Number.isNaN(Date.parse(iso));
3876
+ }
3877
+ var MONTHS2 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
3878
+ function formatDay(iso) {
3879
+ const date = new Date(iso);
3880
+ return `${date.getUTCDate()} ${MONTHS2[date.getUTCMonth()]} ${date.getUTCFullYear()}`;
3881
+ }
3882
+ }
3883
+ });
3884
+
3885
+ // ../packages/tool-kit/out/cliAgentSetup.js
3886
+ var require_cliAgentSetup = __commonJS({
3887
+ "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
3888
+ "use strict";
3889
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3890
+ if (k2 === void 0) k2 = k;
3891
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3892
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3893
+ desc = { enumerable: true, get: function() {
3894
+ return m[k];
3895
+ } };
3896
+ }
3897
+ Object.defineProperty(o, k2, desc);
3898
+ } : function(o, m, k, k2) {
3899
+ if (k2 === void 0) k2 = k;
3900
+ o[k2] = m[k];
3901
+ });
3902
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3903
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3904
+ } : function(o, v) {
3905
+ o["default"] = v;
3906
+ });
3907
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3908
+ var ownKeys = function(o) {
3909
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3910
+ var ar = [];
3911
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3912
+ return ar;
3913
+ };
3914
+ return ownKeys(o);
3915
+ };
3916
+ return function(mod) {
3917
+ if (mod && mod.__esModule) return mod;
3918
+ var result = {};
3919
+ if (mod != null) {
3920
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3921
+ }
3922
+ __setModuleDefault(result, mod);
3923
+ return result;
3924
+ };
3925
+ }();
3926
+ Object.defineProperty(exports, "__esModule", { value: true });
3927
+ exports.isCliAgentManagementCommand = isCliAgentManagementCommand;
3928
+ exports.cliAgentHookBinPath = cliAgentHookBinPath;
3929
+ exports.runCliAgentSetup = runCliAgentSetup;
3930
+ exports.writeHookSettings = writeHookSettings;
3931
+ exports.registeredHookSets = registeredHookSets;
3932
+ exports.findStaleHookCommands = findStaleHookCommands2;
3933
+ var crypto2 = __importStar(__require("crypto"));
3934
+ var fs5 = __importStar(__require("fs"));
3935
+ var os3 = __importStar(__require("os"));
3936
+ var path4 = __importStar(__require("path"));
3937
+ var collectorVersion_1 = require_collectorVersion();
3938
+ var credentials_1 = require_credentials();
3939
+ var hookAdapter_1 = require_hookAdapter();
3940
+ var http_1 = require_http();
3941
+ var hookSet_1 = require_hookSet();
3942
+ var initiatives_1 = require_initiatives();
3943
+ var setupDisclosure_1 = require_setupDisclosure();
3944
+ var stateStore_1 = require_stateStore();
3945
+ var studyJoin_1 = require_studyJoin();
3946
+ var studyNotices_1 = require_studyNotices();
3947
+ var tokenStore_1 = require_tokenStore();
3948
+ var MANAGEMENT_COMMANDS2 = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "join", "object", "-h", "--help"]);
3949
+ function isCliAgentManagementCommand(argument) {
3950
+ return argument !== void 0 && MANAGEMENT_COMMANDS2.has(argument);
3951
+ }
3952
+ function cliAgentHookBinPath(binaryName) {
3953
+ return path4.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3954
+ }
3955
+ function usage(spec) {
3956
+ return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
3957
+
3958
+ npx ${spec.packageName} setup [options]
3959
+ npx ${spec.packageName} status
3960
+ npx ${spec.packageName} uninstall
3961
+ npx ${spec.packageName} join <code>
3962
+ npx ${spec.packageName} object <purpose> [--undo]
3963
+
3964
+ Options
3965
+ --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
3966
+ --local [port] shorthand for the local dev server (default port 4477)
3967
+ --tool-installation-id <id> reuse an existing pairing instead of creating one
3968
+ --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
3969
+ --no-pair install without pairing: local features on, nothing sent
3970
+ --scope project|user where hooks are registered (default project)
3971
+ --project-dir <path> project root for --scope project (default cwd)
3972
+ --dry-run print what would change, write nothing
3973
+ -h, --help
3974
+ `;
3975
+ }
3976
+ async function runCliAgentSetup(argv, spec) {
3977
+ if (argv[0] === "join")
3978
+ return runCliAgentStudyJoin(argv.slice(1), spec);
3979
+ if (argv[0] === "object")
3980
+ return runCliAgentStudyObjection(argv.slice(1), spec);
3981
+ let options;
3982
+ try {
3983
+ options = parseArgs2(argv, spec);
3984
+ } catch (error) {
3985
+ console.error(error instanceof Error ? error.message : String(error));
3986
+ return 1;
3987
+ }
3988
+ if (options.action === "help") {
3989
+ console.log(usage(spec));
3990
+ return 0;
3991
+ }
3992
+ if (options.action === "status")
3993
+ return await printStatus2(options, spec);
3994
+ if (options.action === "uninstall")
3995
+ return uninstall2(options, spec);
3996
+ const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3997
+ console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
3998
+ console.log(`
3999
+ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}
4000
+ `);
4001
+ let identity;
4002
+ let unpairedReason;
4003
+ if (options.skipPairing) {
4004
+ unpairedReason = "asked not to pair (--no-pair)";
4005
+ } else {
4006
+ identity = await resolveIdentity2(apiBaseUrl, options, spec);
4007
+ if (identity) {
4008
+ console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
4009
+ } else {
4010
+ unpairedReason = "pairing did not finish \u2014 installing the local half anyway";
4011
+ }
4012
+ }
4013
+ if (unpairedReason) {
4014
+ console.log(` pairing none: ${unpairedReason}`);
4015
+ console.log(" local features on, nothing is sent");
4016
+ }
4017
+ const binary = installBinary2(spec, options.dryRun);
4018
+ console.log(` hook binary ${binary}`);
4019
+ if (!options.dryRun) {
4020
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4021
+ const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
4022
+ (0, credentials_1.writeHostCredentials)(spec.host, {
4023
+ apiBaseUrl,
4024
+ toolInstallationId,
4025
+ ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4026
+ });
4027
+ }
4028
+ console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
4029
+ const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4030
+ const before = registeredHookSets(readSettings(settingsFile), spec);
4031
+ const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
4032
+ if (written === null)
4033
+ return 1;
4034
+ console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
4035
+ const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
4036
+ if (changes)
4037
+ console.log(` ${changes}`);
4038
+ if (options.dryRun) {
4039
+ console.log("\nDry run \u2014 nothing was written.");
4040
+ return 0;
4041
+ }
4042
+ console.log(`
4043
+ Done. ${spec.restartHint}`);
4044
+ if (!identity) {
4045
+ console.log(`Pair later: npx ${spec.packageName} setup`);
4046
+ }
4047
+ console.log(`Check anytime: npx ${spec.packageName} status`);
4048
+ return 0;
4049
+ }
4050
+ function parseArgs2(argv, spec) {
4051
+ const options = {
4052
+ scope: "project",
4053
+ projectDir: process.cwd(),
4054
+ dryRun: false,
4055
+ skipPairing: false,
3181
4056
  action: "install"
3182
4057
  };
3183
4058
  for (let i = 0; i < argv.length; i++) {
@@ -3222,7 +4097,7 @@ Done. ${spec.restartHint}`);
3222
4097
  break;
3223
4098
  }
3224
4099
  case "--project-dir":
3225
- options.projectDir = path3.resolve(next());
4100
+ options.projectDir = path4.resolve(next());
3226
4101
  break;
3227
4102
  case "--dry-run":
3228
4103
  options.dryRun = true;
@@ -3247,6 +4122,45 @@ ${usage(spec)}`);
3247
4122
  }
3248
4123
  return options;
3249
4124
  }
4125
+ async function runCliAgentStudyJoin(argv, spec) {
4126
+ const joinCode = argv[0];
4127
+ if (!joinCode || joinCode.startsWith("-")) {
4128
+ console.error(`Usage: npx ${spec.packageName} join <code>`);
4129
+ return 1;
4130
+ }
4131
+ const pairing = resolvePairedToken(spec);
4132
+ if (!pairing)
4133
+ return 1;
4134
+ return (0, studyJoin_1.runStudyJoin)({ ...pairing, displayName: spec.displayName, joinCode });
4135
+ }
4136
+ async function runCliAgentStudyObjection(argv, spec) {
4137
+ const pairing = resolvePairedToken(spec);
4138
+ if (!pairing)
4139
+ return 1;
4140
+ return (0, studyNotices_1.runStudyObjection)({
4141
+ ...pairing,
4142
+ commandPrefix: `npx ${spec.packageName}`,
4143
+ pairCommand: `npx ${spec.packageName} setup`,
4144
+ argv
4145
+ });
4146
+ }
4147
+ function resolvePairedToken(spec) {
4148
+ const setupCommand = `npx ${spec.packageName} setup`;
4149
+ let toolInstallationId;
4150
+ try {
4151
+ ({ toolInstallationId } = (0, hookAdapter_1.resolveCliAgentInstallationId)(spec.toolType, { host: spec.host, setupCommand }));
4152
+ } catch (error) {
4153
+ console.error(error instanceof hookAdapter_1.MissingInstallationIdError ? error.message : error instanceof Error ? error.message : String(error));
4154
+ return void 0;
4155
+ }
4156
+ const eventWriteToken = (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId)) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
4157
+ if (!eventWriteToken) {
4158
+ console.error(`Not paired: no write token for ${toolInstallationId}. Run: ${setupCommand}`);
4159
+ return void 0;
4160
+ }
4161
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4162
+ return { apiBaseUrl, eventWriteToken };
4163
+ }
3250
4164
  async function resolveIdentity2(apiBaseUrl, options, spec) {
3251
4165
  const existingId = options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId;
3252
4166
  if (existingId && options.token) {
@@ -3254,8 +4168,13 @@ ${usage(spec)}`);
3254
4168
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(existingId), options.token);
3255
4169
  return { toolInstallationId: existingId, paired: false };
3256
4170
  }
3257
- if (existingId && (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId))) {
3258
- return { toolInstallationId: existingId, paired: false };
4171
+ const existingToken = existingId ? (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId)) : void 0;
4172
+ if (existingId && existingToken) {
4173
+ const check = await checkSavedToken(apiBaseUrl, existingId, existingToken);
4174
+ if (check === "keep")
4175
+ return { toolInstallationId: existingId, paired: false };
4176
+ console.log(`
4177
+ The saved token for ${existingId} isn't accepted any more. Pairing again.`);
3259
4178
  }
3260
4179
  if (options.dryRun) {
3261
4180
  return { toolInstallationId: existingId ?? `${spec.toolType}:<paired at run time>`, paired: false };
@@ -3263,7 +4182,7 @@ ${usage(spec)}`);
3263
4182
  const toolInstallationId = existingId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
3264
4183
  let session;
3265
4184
  try {
3266
- session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os2.hostname()}`);
4185
+ session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os3.hostname()}`);
3267
4186
  } catch (error) {
3268
4187
  console.error(`
3269
4188
  Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
@@ -3276,6 +4195,18 @@ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message
3276
4195
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(toolInstallationId), token);
3277
4196
  return { toolInstallationId, paired: true };
3278
4197
  }
4198
+ var TOKEN_CHECK_TIMEOUT_MS = 5e3;
4199
+ async function checkSavedToken(apiBaseUrl, toolInstallationId, token) {
4200
+ const read = await (0, http_1.readInitiatives)(apiBaseUrl, token, AbortSignal.timeout(TOKEN_CHECK_TIMEOUT_MS));
4201
+ if (read.kind === "rejected")
4202
+ return "repair";
4203
+ if (read.kind === "failed" && (0, stateStore_1.readCollectorState)((0, stateStore_1.defaultStateFilePath)(toolInstallationId))?.lastOutcome === "auth_failed") {
4204
+ console.log(`
4205
+ Couldn't check the saved token (${read.reason}), and the last send was refused.`);
4206
+ console.log(" Keeping it for now. Run setup again once the server is reachable.");
4207
+ }
4208
+ return "keep";
4209
+ }
3279
4210
  async function pollForToken2(apiBaseUrl, pairingSessionId, code, expiresAt) {
3280
4211
  const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
3281
4212
  let announced = false;
@@ -3304,19 +4235,19 @@ Pairing ${status.status}. Run setup again.`);
3304
4235
  if (dryRun)
3305
4236
  return target;
3306
4237
  const source = process.argv[1];
3307
- fs4.mkdirSync(path3.dirname(target), { recursive: true });
3308
- if (path3.resolve(source) !== path3.resolve(target)) {
3309
- fs4.copyFileSync(source, target);
4238
+ fs5.mkdirSync(path4.dirname(target), { recursive: true });
4239
+ if (path4.resolve(source) !== path4.resolve(target)) {
4240
+ fs5.copyFileSync(source, target);
3310
4241
  }
3311
4242
  if (process.platform !== "win32")
3312
- fs4.chmodSync(target, 493);
4243
+ fs5.chmodSync(target, 493);
3313
4244
  return target;
3314
4245
  }
3315
4246
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
3316
4247
  let settings = { ...spec.settings.scaffold ?? {} };
3317
- const exists = fs4.existsSync(settingsFile);
4248
+ const exists = fs5.existsSync(settingsFile);
3318
4249
  if (exists) {
3319
- const raw = fs4.readFileSync(settingsFile, "utf8").trim();
4250
+ const raw = fs5.readFileSync(settingsFile, "utf8").trim();
3320
4251
  if (raw) {
3321
4252
  try {
3322
4253
  settings = JSON.parse(raw);
@@ -3327,7 +4258,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
3327
4258
  }
3328
4259
  }
3329
4260
  }
3330
- const command = hookCommand2(binary);
4261
+ const command = hookCommand2(binary, spec);
3331
4262
  const hooks = { ...settings.hooks ?? {} };
3332
4263
  for (const event of spec.hookEvents) {
3333
4264
  const kept = (hooks[event] ?? []).filter((entry) => !isOurs2(entry, spec));
@@ -3336,7 +4267,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
3336
4267
  const updated = { ...settings, hooks };
3337
4268
  const serialised = `${JSON.stringify(updated, null, 2)}
3338
4269
  `;
3339
- if (exists && fs4.readFileSync(settingsFile, "utf8") === serialised)
4270
+ if (exists && fs5.readFileSync(settingsFile, "utf8") === serialised)
3340
4271
  return false;
3341
4272
  if (dryRun) {
3342
4273
  console.log(`
@@ -3345,13 +4276,25 @@ ${serialised}`);
3345
4276
  return true;
3346
4277
  }
3347
4278
  if (exists)
3348
- fs4.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3349
- fs4.mkdirSync(path3.dirname(settingsFile), { recursive: true });
3350
- fs4.writeFileSync(settingsFile, serialised, "utf8");
4279
+ fs5.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4280
+ fs5.mkdirSync(path4.dirname(settingsFile), { recursive: true });
4281
+ fs5.writeFileSync(settingsFile, serialised, "utf8");
3351
4282
  return true;
3352
4283
  }
3353
- function hookCommand2(binary) {
3354
- return `"${process.execPath}" "${binary}"`;
4284
+ function hookCommand2(binary, spec) {
4285
+ return `"${process.execPath}" "${binary}"${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
4286
+ }
4287
+ function registeredHookSets(settings, spec) {
4288
+ const sets = /* @__PURE__ */ new Map();
4289
+ for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
4290
+ for (const entry of entries ?? []) {
4291
+ if (!isOurs2(entry, spec))
4292
+ continue;
4293
+ const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
4294
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
4295
+ }
4296
+ }
4297
+ return sets;
3355
4298
  }
3356
4299
  function isOurs2(entry, spec) {
3357
4300
  const command = spec.settings.commandOf(entry);
@@ -3373,12 +4316,12 @@ ${serialised}`);
3373
4316
  }
3374
4317
  function readSettings(settingsFile) {
3375
4318
  try {
3376
- return JSON.parse(fs4.readFileSync(settingsFile, "utf8"));
4319
+ return JSON.parse(fs5.readFileSync(settingsFile, "utf8"));
3377
4320
  } catch {
3378
4321
  return {};
3379
4322
  }
3380
4323
  }
3381
- function printStatus2(options, spec) {
4324
+ async function printStatus2(options, spec) {
3382
4325
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
3383
4326
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3384
4327
  const binary = cliAgentHookBinPath(spec.binaryName);
@@ -3391,23 +4334,41 @@ ${serialised}`);
3391
4334
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
3392
4335
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
3393
4336
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
3394
- console.log(`hook binary ${fs4.existsSync(binary) ? binary : "\u2014 not installed"}`);
4337
+ console.log(`hook binary ${fs5.existsSync(binary) ? binary : "\u2014 not installed"}`);
3395
4338
  console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
4339
+ if (spec.hookSet !== void 0 && registered > 0) {
4340
+ const sets = [...registeredHookSets(settings, spec).values()];
4341
+ const oldest = Math.min(...sets);
4342
+ console.log(oldest < spec.hookSet ? `hook set ${oldest}, this version registers ${spec.hookSet}. Upgrade: npx ${spec.packageName} setup${options.scope === "user" ? " --scope user" : ""}` : `hook set ${spec.hookSet} (current)`);
4343
+ }
3396
4344
  if (stale.length) {
3397
4345
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
3398
4346
  for (const command of stale)
3399
4347
  console.log(` ${command}`);
3400
4348
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
3401
4349
  }
4350
+ const tokenValue = localOnly ? void 0 : (tokenFile ? (0, tokenStore_1.readTokenFile)(tokenFile) : void 0) ?? (process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim() || void 0);
4351
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4352
+ const [initiativeLines, notices] = await Promise.all([
4353
+ (0, initiatives_1.initiativesStatusLines)({ apiBaseUrl, eventWriteToken: tokenValue, pairCommand: `npx ${spec.packageName} setup` }),
4354
+ (0, studyNotices_1.studyNoticeStatus)({ apiBaseUrl, eventWriteToken: tokenValue, commandPrefix: `npx ${spec.packageName}` })
4355
+ ]);
4356
+ console.log("");
4357
+ for (const line of initiativeLines)
4358
+ console.log(line);
4359
+ for (const line of notices.lines)
4360
+ console.log(line);
4361
+ if (process.stdout.isTTY)
4362
+ await notices.markShown();
3402
4363
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
3403
- const healthy = paired && registered === spec.hookEvents.length && fs4.existsSync(binary) && !stale.length;
4364
+ const healthy = paired && registered === spec.hookEvents.length && fs5.existsSync(binary) && !stale.length;
3404
4365
  return healthy ? 0 : 1;
3405
4366
  }
3406
4367
  function uninstall2(options, spec) {
3407
4368
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3408
- if (fs4.existsSync(settingsFile)) {
4369
+ if (fs5.existsSync(settingsFile)) {
3409
4370
  try {
3410
- const settings = JSON.parse(fs4.readFileSync(settingsFile, "utf8"));
4371
+ const settings = JSON.parse(fs5.readFileSync(settingsFile, "utf8"));
3411
4372
  const hooks = { ...settings.hooks ?? {} };
3412
4373
  for (const event of Object.keys(hooks)) {
3413
4374
  const kept = hooks[event].filter((entry) => !isOurs2(entry, spec));
@@ -3419,8 +4380,8 @@ ${serialised}`);
3419
4380
  const updated = { ...settings, hooks };
3420
4381
  if (!Object.keys(hooks).length)
3421
4382
  delete updated.hooks;
3422
- fs4.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3423
- fs4.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4383
+ fs5.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4384
+ fs5.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
3424
4385
  `, "utf8");
3425
4386
  console.log(`hooks removed from ${settingsFile}`);
3426
4387
  } catch {
@@ -3429,15 +4390,15 @@ ${serialised}`);
3429
4390
  }
3430
4391
  }
3431
4392
  const binary = cliAgentHookBinPath(spec.binaryName);
3432
- if (fs4.existsSync(binary)) {
3433
- fs4.rmSync(binary);
4393
+ if (fs5.existsSync(binary)) {
4394
+ fs5.rmSync(binary);
3434
4395
  console.log(`removed ${binary}`);
3435
4396
  }
3436
4397
  if ((0, credentials_1.readHostCredentials)(spec.host)) {
3437
4398
  (0, credentials_1.removeHostCredentials)(spec.host);
3438
4399
  console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
3439
4400
  }
3440
- console.log(`tokens left in ${path3.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
4401
+ console.log(`tokens left in ${path4.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
3441
4402
  return 0;
3442
4403
  }
3443
4404
  }
@@ -3487,12 +4448,12 @@ var require_turnState = __commonJS({
3487
4448
  Object.defineProperty(exports, "__esModule", { value: true });
3488
4449
  exports.recordTurnStart = recordTurnStart;
3489
4450
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
3490
- var fs4 = __importStar(__require("fs"));
3491
- var path3 = __importStar(__require("path"));
4451
+ var fs5 = __importStar(__require("fs"));
4452
+ var path4 = __importStar(__require("path"));
3492
4453
  var tokenStore_1 = require_tokenStore();
3493
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join((0, tokenStore_1.ascendaHome)(), "state");
4454
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path4.join((0, tokenStore_1.ascendaHome)(), "state");
3494
4455
  function turnFile(agent, sessionId) {
3495
- return path3.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
4456
+ return path4.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
3496
4457
  }
3497
4458
  function sanitize(value) {
3498
4459
  return value.replace(/[^a-zA-Z0-9._-]/g, "_");
@@ -3501,8 +4462,8 @@ var require_turnState = __commonJS({
3501
4462
  if (!sessionId)
3502
4463
  return;
3503
4464
  try {
3504
- fs4.mkdirSync(stateDir(), { recursive: true });
3505
- fs4.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
4465
+ fs5.mkdirSync(stateDir(), { recursive: true });
4466
+ fs5.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
3506
4467
  } catch {
3507
4468
  }
3508
4469
  }
@@ -3511,8 +4472,8 @@ var require_turnState = __commonJS({
3511
4472
  return void 0;
3512
4473
  const file = turnFile(agent, sessionId);
3513
4474
  try {
3514
- const started = Number(fs4.readFileSync(file, "utf8").trim());
3515
- fs4.rmSync(file, { force: true });
4475
+ const started = Number(fs5.readFileSync(file, "utf8").trim());
4476
+ fs5.rmSync(file, { force: true });
3516
4477
  if (!Number.isFinite(started) || started <= 0 || started > now)
3517
4478
  return void 0;
3518
4479
  return now - started;
@@ -3565,26 +4526,29 @@ var require_liveBus = __commonJS({
3565
4526
  };
3566
4527
  }();
3567
4528
  Object.defineProperty(exports, "__esModule", { value: true });
4529
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
3568
4530
  exports.liveBusSocketCandidates = liveBusSocketCandidates;
3569
4531
  exports.liveBusSocketPath = liveBusSocketPath;
3570
4532
  exports.bucketPromptSize = bucketPromptSize2;
3571
4533
  exports.emitLiveSignal = emitLiveSignal2;
3572
- var fs4 = __importStar(__require("fs"));
4534
+ var fs5 = __importStar(__require("fs"));
3573
4535
  var net = __importStar(__require("net"));
3574
- var os2 = __importStar(__require("os"));
3575
- var path3 = __importStar(__require("path"));
4536
+ var os3 = __importStar(__require("os"));
4537
+ var path4 = __importStar(__require("path"));
4538
+ var hookSet_1 = require_hookSet();
3576
4539
  var WRITE_TIMEOUT_MS = 50;
4540
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
3577
4541
  var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
3578
4542
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3579
4543
  function liveBusSocketCandidates() {
3580
4544
  const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
3581
4545
  if (override)
3582
4546
  return [override];
3583
- const home = os2.homedir();
4547
+ const home = os3.homedir();
3584
4548
  return [
3585
- path3.join(home, ".ascenda", "live.sock"),
3586
- path3.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
3587
- path3.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4549
+ path4.join(home, ".ascenda", "live.sock"),
4550
+ path4.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4551
+ path4.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
3588
4552
  ];
3589
4553
  }
3590
4554
  function existingSocketCandidates() {
@@ -3593,7 +4557,7 @@ var require_liveBus = __commonJS({
3593
4557
  return candidates;
3594
4558
  return candidates.filter((candidate) => {
3595
4559
  try {
3596
- return fs4.statSync(candidate).isSocket();
4560
+ return fs5.statSync(candidate).isSocket();
3597
4561
  } catch {
3598
4562
  return false;
3599
4563
  }
@@ -3613,6 +4577,14 @@ var require_liveBus = __commonJS({
3613
4577
  return "xl";
3614
4578
  }
3615
4579
  var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4580
+ function onTheWire(signal) {
4581
+ const out = { ...signal };
4582
+ if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4583
+ delete out.hookSet;
4584
+ if ("viaPlugin" in out && out.viaPlugin !== true)
4585
+ delete out.viaPlugin;
4586
+ return out;
4587
+ }
3616
4588
  function emitLiveSignal2(signal) {
3617
4589
  return new Promise((resolve2) => {
3618
4590
  const candidates = existingSocketCandidates();
@@ -3654,34 +4626,173 @@ var require_liveBus = __commonJS({
3654
4626
  tryFrom(index + 1);
3655
4627
  return;
3656
4628
  }
3657
- socket = attempt;
3658
- if (typeof attempt.unref === "function")
3659
- attempt.unref();
3660
- let connected = false;
3661
- attempt.on("error", (error) => {
3662
- if (settled || socket !== attempt)
3663
- return;
3664
- if (!connected && error.code && NOBODY_LISTENING.has(error.code)) {
3665
- drop();
3666
- tryFrom(index + 1);
3667
- return;
3668
- }
3669
- done();
3670
- });
3671
- attempt.on("connect", () => {
3672
- if (settled || socket !== attempt)
3673
- return;
3674
- connected = true;
3675
- try {
3676
- attempt.write(`${JSON.stringify(signal)}
3677
- `, done);
3678
- } catch {
3679
- done();
4629
+ socket = attempt;
4630
+ if (typeof attempt.unref === "function")
4631
+ attempt.unref();
4632
+ let connected = false;
4633
+ attempt.on("error", (error) => {
4634
+ if (settled || socket !== attempt)
4635
+ return;
4636
+ if (!connected && error.code && NOBODY_LISTENING.has(error.code)) {
4637
+ drop();
4638
+ tryFrom(index + 1);
4639
+ return;
4640
+ }
4641
+ done();
4642
+ });
4643
+ attempt.on("connect", () => {
4644
+ if (settled || socket !== attempt)
4645
+ return;
4646
+ connected = true;
4647
+ try {
4648
+ attempt.write(`${JSON.stringify(onTheWire(signal))}
4649
+ `, done);
4650
+ } catch {
4651
+ done();
4652
+ }
4653
+ });
4654
+ };
4655
+ tryFrom(0);
4656
+ });
4657
+ }
4658
+ }
4659
+ });
4660
+
4661
+ // ../packages/tool-kit/out/agentProcess.js
4662
+ var require_agentProcess = __commonJS({
4663
+ "../packages/tool-kit/out/agentProcess.js"(exports) {
4664
+ "use strict";
4665
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4666
+ if (k2 === void 0) k2 = k;
4667
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4668
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4669
+ desc = { enumerable: true, get: function() {
4670
+ return m[k];
4671
+ } };
4672
+ }
4673
+ Object.defineProperty(o, k2, desc);
4674
+ } : function(o, m, k, k2) {
4675
+ if (k2 === void 0) k2 = k;
4676
+ o[k2] = m[k];
4677
+ });
4678
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4679
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4680
+ } : function(o, v) {
4681
+ o["default"] = v;
4682
+ });
4683
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4684
+ var ownKeys = function(o) {
4685
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4686
+ var ar = [];
4687
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4688
+ return ar;
4689
+ };
4690
+ return ownKeys(o);
4691
+ };
4692
+ return function(mod) {
4693
+ if (mod && mod.__esModule) return mod;
4694
+ var result = {};
4695
+ if (mod != null) {
4696
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4697
+ }
4698
+ __setModuleDefault(result, mod);
4699
+ return result;
4700
+ };
4701
+ }();
4702
+ Object.defineProperty(exports, "__esModule", { value: true });
4703
+ exports.psArgsLookup = exports.psLookup = exports.AGENT_PROCESS = void 0;
4704
+ exports.scriptMarkerIn = scriptMarkerIn;
4705
+ exports.findAgentProcess = findAgentProcess2;
4706
+ exports.findAgentPid = findAgentPid;
4707
+ exports.livePidFields = livePidFields2;
4708
+ var child_process_1 = __require("child_process");
4709
+ var path4 = __importStar(__require("path"));
4710
+ exports.AGENT_PROCESS = {
4711
+ claude_code: {
4712
+ executable: (command) => path4.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
4713
+ scriptMarkers: ["@anthropic-ai/claude-code"]
4714
+ },
4715
+ codex: {
4716
+ executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path4.basename(command)),
4717
+ args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
4718
+ },
4719
+ gemini_cli: {
4720
+ executable: () => false,
4721
+ args: (args) => !/\s--(experimental-)?acp(\s|=|$)/.test(args),
4722
+ scriptMarkers: ["@google/gemini-cli"]
4723
+ }
4724
+ };
4725
+ var SCRIPT_RUNTIME = /^(node|bun|deno)$/;
4726
+ function scriptMarkerIn(args, markers) {
4727
+ return markers.find((marker) => args.includes(`/${marker}/`));
4728
+ }
4729
+ var MAX_DEPTH = 6;
4730
+ var PS_TIMEOUT_MS = 100;
4731
+ function ps(columns, pid) {
4732
+ try {
4733
+ const result = (0, child_process_1.spawnSync)("/bin/ps", ["-o", columns, "-p", String(pid)], {
4734
+ encoding: "utf8",
4735
+ timeout: PS_TIMEOUT_MS
4736
+ });
4737
+ if (result.status !== 0 || typeof result.stdout !== "string")
4738
+ return void 0;
4739
+ const line = result.stdout.trim();
4740
+ return line === "" ? void 0 : line;
4741
+ } catch {
4742
+ return void 0;
4743
+ }
4744
+ }
4745
+ var psLookup = (pid) => {
4746
+ const line = ps("ppid=,comm=", pid);
4747
+ const match = line ? /^(\d+)\s+(.+)$/.exec(line) : null;
4748
+ return match ? { ppid: Number(match[1]), command: match[2] } : void 0;
4749
+ };
4750
+ exports.psLookup = psLookup;
4751
+ var psArgsLookup = (pid) => ps("args=", pid);
4752
+ exports.psArgsLookup = psArgsLookup;
4753
+ function findAgentProcess2(rule, options = {}) {
4754
+ if (!rule)
4755
+ return void 0;
4756
+ if ((options.platform ?? process.platform) !== "darwin")
4757
+ return void 0;
4758
+ const lookup = options.lookup ?? exports.psLookup;
4759
+ const argsLookup = options.argsLookup ?? exports.psArgsLookup;
4760
+ const markers = rule.scriptMarkers ?? [];
4761
+ let pid = options.startPid ?? process.ppid;
4762
+ for (let depth = 0; depth < MAX_DEPTH && pid > 1; depth++) {
4763
+ const info = lookup(pid);
4764
+ if (!info)
4765
+ return void 0;
4766
+ if (pid !== process.pid) {
4767
+ if (rule.executable(info.command)) {
4768
+ return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
4769
+ }
4770
+ if (markers.length > 0 && SCRIPT_RUNTIME.test(path4.basename(info.command))) {
4771
+ const args = argsLookup(pid);
4772
+ const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
4773
+ if (marker !== void 0) {
4774
+ return accepts(rule, args) ? { pid, match: "path", marker } : void 0;
3680
4775
  }
3681
- });
3682
- };
3683
- tryFrom(0);
3684
- });
4776
+ }
4777
+ }
4778
+ pid = info.ppid;
4779
+ }
4780
+ return void 0;
4781
+ }
4782
+ function accepts(rule, args) {
4783
+ if (!rule.args)
4784
+ return true;
4785
+ return args !== void 0 && rule.args(args);
4786
+ }
4787
+ function findAgentPid(rule, options = {}) {
4788
+ return findAgentProcess2(rule, options)?.pid;
4789
+ }
4790
+ function livePidFields2(match) {
4791
+ if (!match)
4792
+ return {};
4793
+ if (match.match === "executable")
4794
+ return { pid: match.pid };
4795
+ return { pid: match.pid, pidMatch: "path", pidMarker: match.marker };
3685
4796
  }
3686
4797
  }
3687
4798
  });
@@ -3691,9 +4802,9 @@ var require_out2 = __commonJS({
3691
4802
  "../packages/tool-kit/out/index.js"(exports) {
3692
4803
  "use strict";
3693
4804
  Object.defineProperty(exports, "__esModule", { value: true });
3694
- exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = 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.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
3695
- exports.readForgeFullName = exports.parseForgeFullName = 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 = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = void 0;
3696
- exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = void 0;
4805
+ exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = 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.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
4806
+ 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 = 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.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = void 0;
4807
+ exports.runStudyJoin = 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.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
3697
4808
  var commandClassifier_1 = require_commandClassifier();
3698
4809
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
3699
4810
  return commandClassifier_1.classifyCommand;
@@ -3791,6 +4902,9 @@ var require_out2 = __commonJS({
3791
4902
  Object.defineProperty(exports, "AscendaSemanticEventError", { enumerable: true, get: function() {
3792
4903
  return eventSender_1.AscendaSemanticEventError;
3793
4904
  } });
4905
+ Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
4906
+ return eventSender_1.TOKEN_RENEW_LEAD_MS;
4907
+ } });
3794
4908
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
3795
4909
  return eventSender_1.buildEventPayload;
3796
4910
  } });
@@ -3836,6 +4950,9 @@ var require_out2 = __commonJS({
3836
4950
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
3837
4951
  return cliAgentSetup_1.isCliAgentManagementCommand;
3838
4952
  } });
4953
+ Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
4954
+ return cliAgentSetup_1.registeredHookSets;
4955
+ } });
3839
4956
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
3840
4957
  return cliAgentSetup_1.runCliAgentSetup;
3841
4958
  } });
@@ -3891,6 +5008,9 @@ var require_out2 = __commonJS({
3891
5008
  return turnState_1.recordTurnStart;
3892
5009
  } });
3893
5010
  var tokenStore_1 = require_tokenStore();
5011
+ Object.defineProperty(exports, "EVENT_TOKEN_TTL_MS", { enumerable: true, get: function() {
5012
+ return tokenStore_1.EVENT_TOKEN_TTL_MS;
5013
+ } });
3894
5014
  Object.defineProperty(exports, "ascendaHome", { enumerable: true, get: function() {
3895
5015
  return tokenStore_1.ascendaHome;
3896
5016
  } });
@@ -3903,9 +5023,15 @@ var require_out2 = __commonJS({
3903
5023
  Object.defineProperty(exports, "persistEventWriteToken", { enumerable: true, get: function() {
3904
5024
  return tokenStore_1.persistEventWriteToken;
3905
5025
  } });
5026
+ Object.defineProperty(exports, "readTokenExpiry", { enumerable: true, get: function() {
5027
+ return tokenStore_1.readTokenExpiry;
5028
+ } });
3906
5029
  Object.defineProperty(exports, "readTokenFile", { enumerable: true, get: function() {
3907
5030
  return tokenStore_1.readTokenFile;
3908
5031
  } });
5032
+ Object.defineProperty(exports, "tokenExpiryFilePath", { enumerable: true, get: function() {
5033
+ return tokenStore_1.tokenExpiryFilePath;
5034
+ } });
3909
5035
  var stateStore_1 = require_stateStore();
3910
5036
  Object.defineProperty(exports, "defaultStateFilePath", { enumerable: true, get: function() {
3911
5037
  return stateStore_1.defaultStateFilePath;
@@ -4037,6 +5163,59 @@ var require_out2 = __commonJS({
4037
5163
  Object.defineProperty(exports, "liveBusSocketCandidates", { enumerable: true, get: function() {
4038
5164
  return liveBus_1.liveBusSocketCandidates;
4039
5165
  } });
5166
+ Object.defineProperty(exports, "LIVE_BUS_BACKGROUND_TRUST_MS", { enumerable: true, get: function() {
5167
+ return liveBus_1.LIVE_BUS_BACKGROUND_TRUST_MS;
5168
+ } });
5169
+ var hookSet_1 = require_hookSet();
5170
+ Object.defineProperty(exports, "HOOK_SET_FLAG", { enumerable: true, get: function() {
5171
+ return hookSet_1.HOOK_SET_FLAG;
5172
+ } });
5173
+ Object.defineProperty(exports, "UNVERSIONED_HOOK_SET", { enumerable: true, get: function() {
5174
+ return hookSet_1.UNVERSIONED_HOOK_SET;
5175
+ } });
5176
+ Object.defineProperty(exports, "describeHookSetChanges", { enumerable: true, get: function() {
5177
+ return hookSet_1.describeHookSetChanges;
5178
+ } });
5179
+ Object.defineProperty(exports, "hookSetArgument", { enumerable: true, get: function() {
5180
+ return hookSet_1.hookSetArgument;
5181
+ } });
5182
+ Object.defineProperty(exports, "hookSetChanges", { enumerable: true, get: function() {
5183
+ return hookSet_1.hookSetChanges;
5184
+ } });
5185
+ Object.defineProperty(exports, "hookSetOfCommand", { enumerable: true, get: function() {
5186
+ return hookSet_1.hookSetOfCommand;
5187
+ } });
5188
+ Object.defineProperty(exports, "isHookSet", { enumerable: true, get: function() {
5189
+ return hookSet_1.isHookSet;
5190
+ } });
5191
+ Object.defineProperty(exports, "readHookSet", { enumerable: true, get: function() {
5192
+ return hookSet_1.readHookSet;
5193
+ } });
5194
+ Object.defineProperty(exports, "readViaPlugin", { enumerable: true, get: function() {
5195
+ return hookSet_1.readViaPlugin;
5196
+ } });
5197
+ var agentProcess_1 = require_agentProcess();
5198
+ Object.defineProperty(exports, "AGENT_PROCESS", { enumerable: true, get: function() {
5199
+ return agentProcess_1.AGENT_PROCESS;
5200
+ } });
5201
+ Object.defineProperty(exports, "findAgentPid", { enumerable: true, get: function() {
5202
+ return agentProcess_1.findAgentPid;
5203
+ } });
5204
+ Object.defineProperty(exports, "findAgentProcess", { enumerable: true, get: function() {
5205
+ return agentProcess_1.findAgentProcess;
5206
+ } });
5207
+ Object.defineProperty(exports, "livePidFields", { enumerable: true, get: function() {
5208
+ return agentProcess_1.livePidFields;
5209
+ } });
5210
+ Object.defineProperty(exports, "psArgsLookup", { enumerable: true, get: function() {
5211
+ return agentProcess_1.psArgsLookup;
5212
+ } });
5213
+ Object.defineProperty(exports, "psLookup", { enumerable: true, get: function() {
5214
+ return agentProcess_1.psLookup;
5215
+ } });
5216
+ Object.defineProperty(exports, "scriptMarkerIn", { enumerable: true, get: function() {
5217
+ return agentProcess_1.scriptMarkerIn;
5218
+ } });
4040
5219
  var http_1 = require_http();
4041
5220
  Object.defineProperty(exports, "AscendaApiError", { enumerable: true, get: function() {
4042
5221
  return http_1.AscendaApiError;
@@ -4047,6 +5226,9 @@ var require_out2 = __commonJS({
4047
5226
  Object.defineProperty(exports, "getPairingStatus", { enumerable: true, get: function() {
4048
5227
  return http_1.getPairingStatus;
4049
5228
  } });
5229
+ Object.defineProperty(exports, "getStudyJoinStatus", { enumerable: true, get: function() {
5230
+ return http_1.getStudyJoinStatus;
5231
+ } });
4050
5232
  Object.defineProperty(exports, "renewToolToken", { enumerable: true, get: function() {
4051
5233
  return http_1.renewToolToken;
4052
5234
  } });
@@ -4062,39 +5244,48 @@ var require_out2 = __commonJS({
4062
5244
  Object.defineProperty(exports, "isRetryableStatus", { enumerable: true, get: function() {
4063
5245
  return http_1.isRetryableStatus;
4064
5246
  } });
4065
- }
4066
- });
4067
-
4068
- // src/paths.ts
4069
- import * as fs from "fs";
4070
- import * as path from "path";
4071
- function hookBinPath() {
4072
- return path.join((0, import_tool_kit3.ascendaHome)(), "bin", "ascenda-claude-hook");
4073
- }
4074
- function readCredentials() {
4075
- const credentials = (0, import_tool_kit3.readMachineCredentials)();
4076
- if (!credentials) return void 0;
4077
- const { tools: _tools, ...topLevel } = credentials;
4078
- return topLevel;
4079
- }
4080
- function writeCredentials(credentials) {
4081
- (0, import_tool_kit3.writeTopLevelCredentials)(credentials);
4082
- }
4083
- function removeCredentials() {
4084
- const credentials = (0, import_tool_kit3.readMachineCredentials)();
4085
- if (!credentials) return;
4086
- if (credentials.tools && Object.keys(credentials.tools).length > 0) {
4087
- (0, import_tool_kit3.writeMachineCredentials)({ tools: credentials.tools });
4088
- return;
4089
- }
4090
- fs.rmSync((0, import_tool_kit3.credentialsFilePath)(), { force: true });
4091
- }
4092
- var import_tool_kit3, import_tool_kit4;
4093
- var init_paths = __esm({
4094
- "src/paths.ts"() {
4095
- "use strict";
4096
- import_tool_kit3 = __toESM(require_out2(), 1);
4097
- import_tool_kit4 = __toESM(require_out2(), 1);
5247
+ Object.defineProperty(exports, "readInitiatives", { enumerable: true, get: function() {
5248
+ return http_1.readInitiatives;
5249
+ } });
5250
+ Object.defineProperty(exports, "readStudyNotices", { enumerable: true, get: function() {
5251
+ return http_1.readStudyNotices;
5252
+ } });
5253
+ Object.defineProperty(exports, "markStudyNoticeShown", { enumerable: true, get: function() {
5254
+ return http_1.markStudyNoticeShown;
5255
+ } });
5256
+ Object.defineProperty(exports, "setStudyObjection", { enumerable: true, get: function() {
5257
+ return http_1.setStudyObjection;
5258
+ } });
5259
+ Object.defineProperty(exports, "startStudyJoin", { enumerable: true, get: function() {
5260
+ return http_1.startStudyJoin;
5261
+ } });
5262
+ var initiatives_1 = require_initiatives();
5263
+ Object.defineProperty(exports, "INITIATIVE_COPY", { enumerable: true, get: function() {
5264
+ return initiatives_1.INITIATIVE_COPY;
5265
+ } });
5266
+ Object.defineProperty(exports, "initiativesStatusLines", { enumerable: true, get: function() {
5267
+ return initiatives_1.initiativesStatusLines;
5268
+ } });
5269
+ Object.defineProperty(exports, "renderInitiatives", { enumerable: true, get: function() {
5270
+ return initiatives_1.renderInitiatives;
5271
+ } });
5272
+ var studyNotices_1 = require_studyNotices();
5273
+ Object.defineProperty(exports, "NOTICED_PURPOSES", { enumerable: true, get: function() {
5274
+ return studyNotices_1.NOTICED_PURPOSES;
5275
+ } });
5276
+ Object.defineProperty(exports, "renderStudyNotices", { enumerable: true, get: function() {
5277
+ return studyNotices_1.renderStudyNotices;
5278
+ } });
5279
+ Object.defineProperty(exports, "runStudyObjection", { enumerable: true, get: function() {
5280
+ return studyNotices_1.runStudyObjection;
5281
+ } });
5282
+ Object.defineProperty(exports, "studyNoticeStatus", { enumerable: true, get: function() {
5283
+ return studyNotices_1.studyNoticeStatus;
5284
+ } });
5285
+ var studyJoin_1 = require_studyJoin();
5286
+ Object.defineProperty(exports, "runStudyJoin", { enumerable: true, get: function() {
5287
+ return studyJoin_1.runStudyJoin;
5288
+ } });
4098
5289
  }
4099
5290
  });
4100
5291
 
@@ -4120,33 +5311,69 @@ var init_types = __esm({
4120
5311
  "PreCompact",
4121
5312
  "PostCompact",
4122
5313
  "Stop",
5314
+ "StopFailure",
4123
5315
  "Notification",
4124
- "SessionEnd"
5316
+ "SessionEnd",
5317
+ "SubagentStart",
5318
+ "SubagentStop"
4125
5319
  ];
4126
5320
  ASCENDA_TOOL_TYPE = "claude_code";
4127
5321
  CLAUDE_HOST = "claude_code";
4128
5322
  }
4129
5323
  });
4130
5324
 
5325
+ // src/paths.ts
5326
+ import * as fs2 from "fs";
5327
+ import * as path2 from "path";
5328
+ function hookBinPath() {
5329
+ return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook");
5330
+ }
5331
+ function readCredentials() {
5332
+ const credentials = (0, import_tool_kit5.readMachineCredentials)();
5333
+ if (!credentials) return void 0;
5334
+ const { tools: _tools, ...topLevel } = credentials;
5335
+ return topLevel;
5336
+ }
5337
+ function writeCredentials(credentials) {
5338
+ (0, import_tool_kit5.writeTopLevelCredentials)(credentials);
5339
+ }
5340
+ function removeCredentials() {
5341
+ const credentials = (0, import_tool_kit5.readMachineCredentials)();
5342
+ if (!credentials) return;
5343
+ if (credentials.tools && Object.keys(credentials.tools).length > 0) {
5344
+ (0, import_tool_kit5.writeMachineCredentials)({ tools: credentials.tools });
5345
+ return;
5346
+ }
5347
+ fs2.rmSync((0, import_tool_kit5.credentialsFilePath)(), { force: true });
5348
+ }
5349
+ var import_tool_kit5, import_tool_kit6;
5350
+ var init_paths = __esm({
5351
+ "src/paths.ts"() {
5352
+ "use strict";
5353
+ import_tool_kit5 = __toESM(require_out2(), 1);
5354
+ import_tool_kit6 = __toESM(require_out2(), 1);
5355
+ }
5356
+ });
5357
+
4131
5358
  // src/config.ts
4132
5359
  function resolveOutboxFilePath(toolInstallationId) {
4133
- return process.env.ASCENDA_OUTBOX_FILE ?? (0, import_tool_kit5.defaultOutboxFilePath)(toolInstallationId);
5360
+ return process.env.ASCENDA_OUTBOX_FILE ?? (0, import_tool_kit7.defaultOutboxFilePath)(toolInstallationId);
4134
5361
  }
4135
5362
  function resolveStateFilePath(toolInstallationId) {
4136
- return process.env.ASCENDA_STATE_FILE ?? (toolInstallationId ? (0, import_tool_kit5.defaultStateFilePath)(toolInstallationId) : (0, import_tool_kit5.unresolvedStateFilePath)(ASCENDA_TOOL_TYPE));
5363
+ return process.env.ASCENDA_STATE_FILE ?? (toolInstallationId ? (0, import_tool_kit7.defaultStateFilePath)(toolInstallationId) : (0, import_tool_kit7.unresolvedStateFilePath)(ASCENDA_TOOL_TYPE));
4137
5364
  }
4138
5365
  function localOnlyInstall(credentials = readCredentials()) {
4139
5366
  if (!credentials?.localOnly) return false;
4140
5367
  if (envOverride("ASCENDA_EVENT_WRITE_TOKEN")) return false;
4141
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (credentials.toolInstallationId ? (0, import_tool_kit5.defaultTokenFilePath)(credentials.toolInstallationId) : void 0);
4142
- return !(tokenFilePath && (0, import_tool_kit5.readTokenFile)(tokenFilePath));
5368
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (credentials.toolInstallationId ? (0, import_tool_kit7.defaultTokenFilePath)(credentials.toolInstallationId) : void 0);
5369
+ return !(tokenFilePath && (0, import_tool_kit7.readTokenFile)(tokenFilePath));
4143
5370
  }
4144
5371
  function resolveToolInstallationId(credentials = readCredentials()) {
4145
5372
  const fromEnv = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
4146
5373
  if (fromEnv) return { toolInstallationId: normalizeToolInstallationId(fromEnv), source: "env" };
4147
5374
  const fromCredentials = credentials?.toolInstallationId?.trim();
4148
5375
  if (fromCredentials) return { toolInstallationId: normalizeToolInstallationId(fromCredentials), source: "credentials" };
4149
- const candidates = (0, import_tool_kit5.listPersistedToolInstallationIds)(ASCENDA_TOOL_TYPE);
5376
+ const candidates = (0, import_tool_kit7.listPersistedToolInstallationIds)(ASCENDA_TOOL_TYPE);
4150
5377
  if (candidates.length === 1) return { toolInstallationId: candidates[0], source: "disk" };
4151
5378
  throw new MissingInstallationIdError(candidates);
4152
5379
  }
@@ -4154,11 +5381,11 @@ function loadConfigFromEnv() {
4154
5381
  const credentials = readCredentials();
4155
5382
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
4156
5383
  const { toolInstallationId } = resolveToolInstallationId(credentials);
4157
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit5.defaultTokenFilePath)(toolInstallationId);
4158
- const fileToken = (0, import_tool_kit5.readTokenFile)(tokenFilePath);
5384
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit7.defaultTokenFilePath)(toolInstallationId);
5385
+ const fileToken = (0, import_tool_kit7.readTokenFile)(tokenFilePath);
4159
5386
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
4160
5387
  if (!eventWriteToken) throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
4161
- if (!fileToken) (0, import_tool_kit5.persistEventWriteToken)(tokenFilePath, eventWriteToken);
5388
+ if (!fileToken) (0, import_tool_kit7.persistEventWriteToken)(tokenFilePath, eventWriteToken);
4162
5389
  return {
4163
5390
  apiBaseUrl,
4164
5391
  toolInstallationId,
@@ -4196,11 +5423,11 @@ function normalizeToolInstallationId(value) {
4196
5423
  if (trimmed.startsWith("claude_tool_")) return `${ASCENDA_TOOL_TYPE}:${trimmed.slice("claude_tool_".length)}`;
4197
5424
  return `${ASCENDA_TOOL_TYPE}:${trimmed}`;
4198
5425
  }
4199
- var import_tool_kit5, DEFAULT_API_BASE_URL, MissingInstallationIdError;
5426
+ var import_tool_kit7, DEFAULT_API_BASE_URL, MissingInstallationIdError;
4200
5427
  var init_config = __esm({
4201
5428
  "src/config.ts"() {
4202
5429
  "use strict";
4203
- import_tool_kit5 = __toESM(require_out2(), 1);
5430
+ import_tool_kit7 = __toESM(require_out2(), 1);
4204
5431
  init_paths();
4205
5432
  init_types();
4206
5433
  DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -4221,15 +5448,17 @@ var init_config = __esm({
4221
5448
  // src/setup.ts
4222
5449
  var setup_exports = {};
4223
5450
  __export(setup_exports, {
5451
+ HOOK_SET: () => HOOK_SET,
4224
5452
  SENDS: () => SENDS,
4225
5453
  findStaleHookCommands: () => findStaleHookCommands,
5454
+ ourHookSets: () => ourHookSets,
4226
5455
  runSetup: () => runSetup,
4227
5456
  writeSettings: () => writeSettings
4228
5457
  });
4229
5458
  import * as crypto from "crypto";
4230
- import * as fs2 from "fs";
4231
- import * as os from "os";
4232
- import * as path2 from "path";
5459
+ import * as fs3 from "fs";
5460
+ import * as os2 from "os";
5461
+ import * as path3 from "path";
4233
5462
  async function runSetup(argv) {
4234
5463
  let options;
4235
5464
  try {
@@ -4242,7 +5471,7 @@ async function runSetup(argv) {
4242
5471
  console.log(USAGE);
4243
5472
  return 0;
4244
5473
  }
4245
- if (options.action === "status") return printStatus(options);
5474
+ if (options.action === "status") return await printStatus(options);
4246
5475
  if (options.action === "uninstall") return uninstall(options);
4247
5476
  const apiBaseUrl = (options.apiBaseUrl ?? readCredentials()?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
4248
5477
  console.log(`Ascenda setup \u2014 ${apiBaseUrl}`);
@@ -4267,11 +5496,19 @@ ${(0, import_tool_kit8.renderSetupDisclosure)({ sends: SENDS, displayName: "Clau
4267
5496
  ...unpaired ? { localOnly: true, installedAt: now } : { pairedAt: now }
4268
5497
  });
4269
5498
  }
4270
- console.log(` credentials ${(0, import_tool_kit4.credentialsFilePath)()}`);
5499
+ console.log(` credentials ${(0, import_tool_kit6.credentialsFilePath)()}`);
4271
5500
  const settingsFile = settingsPath(options);
5501
+ const before = ourHookSets(readSettingsFile(settingsFile));
4272
5502
  const written = writeSettings(settingsFile, binary, options.dryRun);
4273
5503
  if (written === null) return 1;
4274
5504
  console.log(` hooks ${settingsFile} (${HOOK_EVENTS.length} events${written ? "" : ", already current"})`);
5505
+ const changes = (0, import_tool_kit8.describeHookSetChanges)((0, import_tool_kit8.hookSetChanges)(before, HOOK_EVENTS), HOOK_SET);
5506
+ if (changes) console.log(` ${changes}`);
5507
+ const otherFile = settingsPath({ ...options, scope: options.scope === "user" ? "project" : "user" });
5508
+ if (otherFile !== settingsFile && ourHookSets(readSettingsFile(otherFile)).size > 0) {
5509
+ console.log(` note ${otherFile} registers these hooks too, so each event runs twice.`);
5510
+ console.log(" Remove the ascenda-claude-hook entries from one of the two files.");
5511
+ }
4275
5512
  if (options.dryRun) {
4276
5513
  console.log("\nDry run \u2014 nothing was written.");
4277
5514
  return 0;
@@ -4337,7 +5574,7 @@ function parseArgs(argv) {
4337
5574
  break;
4338
5575
  }
4339
5576
  case "--project-dir":
4340
- options.projectDir = path2.resolve(next());
5577
+ options.projectDir = path3.resolve(next());
4341
5578
  break;
4342
5579
  case "--no-pair":
4343
5580
  // `--no-pairing` is the spelling the CLI agents' setup landed under
@@ -4380,7 +5617,7 @@ async function resolveIdentity(apiBaseUrl, options) {
4380
5617
  }
4381
5618
  let session;
4382
5619
  try {
4383
- session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os.hostname()}`);
5620
+ session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os2.hostname()}`);
4384
5621
  } catch (error) {
4385
5622
  return {
4386
5623
  toolInstallationId,
@@ -4426,21 +5663,21 @@ function installBinary(dryRun) {
4426
5663
  const target = hookBinPath();
4427
5664
  if (dryRun) return target;
4428
5665
  const source = process.argv[1];
4429
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
4430
- if (path2.resolve(source) !== path2.resolve(target)) {
4431
- fs2.copyFileSync(source, target);
5666
+ fs3.mkdirSync(path3.dirname(target), { recursive: true });
5667
+ if (path3.resolve(source) !== path3.resolve(target)) {
5668
+ fs3.copyFileSync(source, target);
4432
5669
  }
4433
- if (process.platform !== "win32") fs2.chmodSync(target, 493);
5670
+ if (process.platform !== "win32") fs3.chmodSync(target, 493);
4434
5671
  return target;
4435
5672
  }
4436
5673
  function settingsPath(options) {
4437
- return options.scope === "user" ? path2.join(os.homedir(), ".claude", "settings.json") : path2.join(options.projectDir, ".claude", "settings.local.json");
5674
+ return options.scope === "user" ? path3.join(os2.homedir(), ".claude", "settings.json") : path3.join(options.projectDir, ".claude", "settings.local.json");
4438
5675
  }
4439
5676
  function writeSettings(settingsFile, binary, dryRun) {
4440
5677
  let settings = {};
4441
- const exists = fs2.existsSync(settingsFile);
5678
+ const exists = fs3.existsSync(settingsFile);
4442
5679
  if (exists) {
4443
- const raw = fs2.readFileSync(settingsFile, "utf8").trim();
5680
+ const raw = fs3.readFileSync(settingsFile, "utf8").trim();
4444
5681
  if (raw) {
4445
5682
  try {
4446
5683
  settings = JSON.parse(raw);
@@ -4455,21 +5692,21 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
4455
5692
  const hooks = { ...settings.hooks ?? {} };
4456
5693
  for (const event of HOOK_EVENTS) {
4457
5694
  const kept = (hooks[event] ?? []).filter((group) => !isOurs(group));
4458
- hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
5695
+ hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}${(0, import_tool_kit8.hookSetArgument)(HOOK_SET)}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
4459
5696
  }
4460
5697
  const updated = { ...settings, hooks };
4461
5698
  const serialised = `${JSON.stringify(updated, null, 2)}
4462
5699
  `;
4463
- if (exists && fs2.readFileSync(settingsFile, "utf8") === serialised) return false;
5700
+ if (exists && fs3.readFileSync(settingsFile, "utf8") === serialised) return false;
4464
5701
  if (dryRun) {
4465
5702
  console.log(`
4466
5703
  --- ${settingsFile} (dry run) ---
4467
5704
  ${serialised}`);
4468
5705
  return true;
4469
5706
  }
4470
- if (exists) fs2.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4471
- fs2.mkdirSync(path2.dirname(settingsFile), { recursive: true });
4472
- fs2.writeFileSync(settingsFile, serialised, "utf8");
5707
+ if (exists) fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5708
+ fs3.mkdirSync(path3.dirname(settingsFile), { recursive: true });
5709
+ fs3.writeFileSync(settingsFile, serialised, "utf8");
4473
5710
  return true;
4474
5711
  }
4475
5712
  function hookCommand(binary) {
@@ -4492,17 +5729,32 @@ function findStaleHookCommands(settings, binary) {
4492
5729
  }
4493
5730
  return [...stale];
4494
5731
  }
4495
- function countRegistered(settingsFile, binary) {
4496
- const settings = (() => {
4497
- try {
4498
- return JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
4499
- } catch {
4500
- return {};
5732
+ function readSettingsFile(settingsFile) {
5733
+ try {
5734
+ return JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
5735
+ } catch {
5736
+ return {};
5737
+ }
5738
+ }
5739
+ function ourHookSets(settings) {
5740
+ const sets = /* @__PURE__ */ new Map();
5741
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5742
+ for (const group of groups ?? []) {
5743
+ if (!isOurs(group)) continue;
5744
+ for (const entry of group.hooks ?? []) {
5745
+ if (typeof entry?.command !== "string") continue;
5746
+ const set = (0, import_tool_kit8.hookSetOfCommand)(entry.command);
5747
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5748
+ }
4501
5749
  }
4502
- })();
5750
+ }
5751
+ return sets;
5752
+ }
5753
+ function countRegistered(settingsFile, binary) {
5754
+ const settings = readSettingsFile(settingsFile);
4503
5755
  return { settings, registered: HOOK_EVENTS.filter((event) => (settings.hooks?.[event] ?? []).some(isOurs)).length };
4504
5756
  }
4505
- function printStatus(options) {
5757
+ async function printStatus(options) {
4506
5758
  const credentials = readCredentials();
4507
5759
  const settingsFile = settingsPath(options);
4508
5760
  const binary = hookBinPath();
@@ -4523,22 +5775,37 @@ function printStatus(options) {
4523
5775
  console.log(`token ${fileToken ? "present" : token ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : unpaired ? "\u2014 none until this install is paired" : "\u2014 missing"}`);
4524
5776
  console.log(`delivery ${token ? "active" : unpaired ? "inactive \u2014 nothing is sent, and nothing is queued for later" : "\u2014 no token for this pairing, so nothing can be sent"}`);
4525
5777
  console.log("local features active \u2014 the session prompts and the live socket signal need no pairing");
4526
- console.log(`hook binary ${fs2.existsSync(binary) ? binary : "\u2014 not installed"}`);
5778
+ console.log(`hook binary ${fs3.existsSync(binary) ? binary : "\u2014 not installed"}`);
4527
5779
  console.log(`hooks ${registered}/${HOOK_EVENTS.length} registered in ${settingsFile}`);
4528
5780
  if (elsewhere && elsewhere.registered > 0) {
4529
5781
  console.log(` ${elsewhere.registered}/${HOOK_EVENTS.length} found in ${otherFile} (--scope ${otherScope.scope})`);
4530
5782
  }
5783
+ const where = registered > 0 ? { settings, scope: options.scope } : elsewhere && elsewhere.registered > 0 ? { settings: elsewhere.settings, scope: otherScope.scope } : void 0;
5784
+ if (where) {
5785
+ const oldest = Math.min(...ourHookSets(where.settings).values());
5786
+ console.log(oldest < HOOK_SET ? `hook set ${oldest}, this version registers ${HOOK_SET}. Upgrade: npx @ascenda-one/claude-code-hooks setup${where.scope === "user" ? " --scope user" : ""}` : `hook set ${HOOK_SET} (current)`);
5787
+ }
4531
5788
  if (stale.length) {
4532
5789
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
4533
5790
  for (const command of stale) console.log(` ${command}`);
4534
5791
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
4535
5792
  }
5793
+ const tokenValue = unpaired ? void 0 : (tokenFile ? (0, import_tool_kit8.readTokenFile)(tokenFile) : void 0) ?? envOverride("ASCENDA_EVENT_WRITE_TOKEN") ?? void 0;
5794
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
5795
+ const [initiativeLines, notices] = await Promise.all([
5796
+ (0, import_tool_kit8.initiativesStatusLines)({ apiBaseUrl, eventWriteToken: tokenValue, pairCommand: "npx @ascenda-one/claude-code-hooks pair" }),
5797
+ (0, import_tool_kit8.studyNoticeStatus)({ apiBaseUrl, eventWriteToken: tokenValue, commandPrefix: "npx @ascenda-one/claude-code-hooks" })
5798
+ ]);
5799
+ console.log("");
5800
+ for (const line of initiativeLines) console.log(line);
5801
+ for (const line of notices.lines) console.log(line);
5802
+ if (process.stdout.isTTY) await notices.markShown();
4536
5803
  if (unpaired) {
4537
5804
  console.log("\nInstalled, not paired. Pair when you want the telemetry half:");
4538
5805
  console.log(" npx @ascenda-one/claude-code-hooks pair");
4539
5806
  }
4540
5807
  const wired = registered === HOOK_EVENTS.length || options.scope === "project" && elsewhere?.registered === HOOK_EVENTS.length;
4541
- const healthy = credentials?.toolInstallationId && wired && fs2.existsSync(binary) && !stale.length;
5808
+ const healthy = credentials?.toolInstallationId && wired && fs3.existsSync(binary) && !stale.length;
4542
5809
  return healthy ? 0 : 1;
4543
5810
  }
4544
5811
  function describePairing(credentials, unpaired) {
@@ -4550,9 +5817,9 @@ function describePairing(credentials, unpaired) {
4550
5817
  function uninstall(options) {
4551
5818
  const unpaired = localOnlyInstall();
4552
5819
  const settingsFile = settingsPath(options);
4553
- if (fs2.existsSync(settingsFile)) {
5820
+ if (fs3.existsSync(settingsFile)) {
4554
5821
  try {
4555
- const settings = JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
5822
+ const settings = JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
4556
5823
  const hooks = { ...settings.hooks ?? {} };
4557
5824
  for (const event of Object.keys(hooks)) {
4558
5825
  const kept = hooks[event].filter((group) => !isOurs(group));
@@ -4561,8 +5828,8 @@ function uninstall(options) {
4561
5828
  }
4562
5829
  const updated = { ...settings, hooks };
4563
5830
  if (!Object.keys(hooks).length) delete updated.hooks;
4564
- fs2.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4565
- fs2.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5831
+ fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5832
+ fs3.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4566
5833
  `, "utf8");
4567
5834
  console.log(`hooks removed from ${settingsFile}`);
4568
5835
  } catch {
@@ -4571,19 +5838,19 @@ function uninstall(options) {
4571
5838
  }
4572
5839
  }
4573
5840
  const binary = hookBinPath();
4574
- if (fs2.existsSync(binary)) {
4575
- fs2.rmSync(binary);
5841
+ if (fs3.existsSync(binary)) {
5842
+ fs3.rmSync(binary);
4576
5843
  console.log(`removed ${binary}`);
4577
5844
  }
4578
- const credentialsFile2 = (0, import_tool_kit4.credentialsFilePath)();
4579
- if (fs2.existsSync(credentialsFile2)) {
5845
+ const credentialsFile2 = (0, import_tool_kit6.credentialsFilePath)();
5846
+ if (fs3.existsSync(credentialsFile2)) {
4580
5847
  removeCredentials();
4581
- console.log(fs2.existsSync(credentialsFile2) ? `cleared the Claude Code pairing from ${credentialsFile2} (other tools' pairings kept)` : `removed ${credentialsFile2}`);
5848
+ console.log(fs3.existsSync(credentialsFile2) ? `cleared the Claude Code pairing from ${credentialsFile2} (other tools' pairings kept)` : `removed ${credentialsFile2}`);
4582
5849
  }
4583
- console.log(unpaired ? "this install was never paired, so there is no token here and nothing to revoke" : `tokens left in ${path2.join((0, import_tool_kit8.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
5850
+ console.log(unpaired ? "this install was never paired, so there is no token here and nothing to revoke" : `tokens left in ${path3.join((0, import_tool_kit8.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
4584
5851
  return 0;
4585
5852
  }
4586
- var import_tool_kit8, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, SENDS, USAGE, POLL_ERROR_TOLERANCE;
5853
+ var import_tool_kit8, HOOK_EVENTS, HOOK_SET, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, SENDS, USAGE, POLL_ERROR_TOLERANCE;
4587
5854
  var init_setup = __esm({
4588
5855
  "src/setup.ts"() {
4589
5856
  "use strict";
@@ -4591,10 +5858,11 @@ var init_setup = __esm({
4591
5858
  init_config();
4592
5859
  init_paths();
4593
5860
  init_types();
4594
- HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "Notification", "SessionEnd"];
5861
+ HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop"];
5862
+ HOOK_SET = 3;
4595
5863
  HOOK_TIMEOUT_SECONDS = 5;
4596
5864
  HOOK_MARKER = "ascenda-claude-hook";
4597
- SENDS = ["model", "posture", "git", "edits", "waiting"];
5865
+ SENDS = ["model", "posture", "git", "edits", "waiting", "subagents"];
4598
5866
  USAGE = `ascenda-claude-hook setup \u2014 wire Claude Code to Ascenda telemetry
4599
5867
 
4600
5868
  npx @ascenda-one/claude-code-hooks setup [options]
@@ -4602,9 +5870,12 @@ var init_setup = __esm({
4602
5870
  npx @ascenda-one/claude-code-hooks doctor
4603
5871
  npx @ascenda-one/claude-code-hooks pair [--tool-type <type>]
4604
5872
  npx @ascenda-one/claude-code-hooks uninstall
5873
+ npx @ascenda-one/claude-code-hooks object <purpose> [--undo]
4605
5874
 
4606
5875
  doctor prints the send journal, outbox and one live round trip
4607
5876
  pair prints a code to paste into the app, then waits for confirmation
5877
+ object stop being counted for a purpose your organisation counts unless
5878
+ you object, from the next report; --undo reverses it
4608
5879
 
4609
5880
  Options
4610
5881
  --api-base-url <url> ingest host (default ${DEFAULT_API_BASE_URL})
@@ -4625,7 +5896,7 @@ Options
4625
5896
  // src/cli.ts
4626
5897
  var import_tool_kit9 = __toESM(require_out2(), 1);
4627
5898
  import { randomUUID as randomUUID2 } from "node:crypto";
4628
- import * as fs3 from "node:fs";
5899
+ import * as fs4 from "node:fs";
4629
5900
 
4630
5901
  // src/ascendaClient.ts
4631
5902
  var import_tool_kit = __toESM(require_out2(), 1);
@@ -4663,25 +5934,23 @@ var AscendaClient = class {
4663
5934
  }
4664
5935
  };
4665
5936
 
4666
- // src/cli.ts
4667
- init_config();
4668
-
4669
5937
  // src/mapClaudeEvent.ts
4670
- var import_tool_kit7 = __toESM(require_out2(), 1);
5938
+ var import_tool_kit4 = __toESM(require_out2(), 1);
4671
5939
  init_types();
4672
5940
 
4673
5941
  // src/safeExtract.ts
4674
- var import_tool_kit6 = __toESM(require_out2(), 1);
5942
+ var import_tool_kit3 = __toESM(require_out2(), 1);
4675
5943
 
4676
5944
  // src/mapClaudeEvent.ts
4677
5945
  function mapClaudeEvent(hookName, input) {
4678
5946
  const events = mapEvent(hookName, input);
4679
5947
  if (events.length === 0) return events;
4680
- const branchHash = (0, import_tool_kit7.deriveBranchHashForCwd)((0, import_tool_kit6.getString)(input, ["cwd"]) ?? process.cwd());
5948
+ const branchHash = (0, import_tool_kit4.deriveBranchHashForCwd)((0, import_tool_kit3.getString)(input, ["cwd"]) ?? process.cwd());
4681
5949
  const runtime = claudeRuntime();
5950
+ const subagentId = readSubagentId(input);
4682
5951
  return events.map((event) => ({
4683
5952
  ...event,
4684
- metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...event.metadata }
5953
+ metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...subagentId ? { subagentId } : {}, ...event.metadata }
4685
5954
  }));
4686
5955
  }
4687
5956
  function mapEvent(hookName, input) {
@@ -4705,27 +5974,35 @@ function mapEvent(hookName, input) {
4705
5974
  return [{ eventType: "context_pressure_high", severity: "medium", metadata: { trigger: "inferred", reason: "context_limit" } }];
4706
5975
  case "Stop":
4707
5976
  return mapStop(input);
5977
+ // Live signal only (see `emitLive` in cli.ts). The payload carries the
5978
+ // last assistant message, and nothing here reads it.
5979
+ case "StopFailure":
5980
+ return [];
4708
5981
  case "Notification":
4709
5982
  return mapNotification(input);
4710
5983
  case "SessionEnd":
4711
5984
  return mapSessionEnd(input);
5985
+ case "SubagentStart":
5986
+ return mapSubagent("subagent_started", input);
5987
+ case "SubagentStop":
5988
+ return mapSubagent("subagent_stopped", input);
4712
5989
  default:
4713
5990
  return [];
4714
5991
  }
4715
5992
  }
4716
5993
  function isNewSessionStart(input) {
4717
- const source = (0, import_tool_kit6.getString)(input, ["source"]);
5994
+ const source = (0, import_tool_kit3.getString)(input, ["source"]);
4718
5995
  return !source || source === "startup" || source === "resume";
4719
5996
  }
4720
5997
  function milestoneInviting(input) {
4721
- if ((0, import_tool_kit6.outcomeForHook)("PostToolUse", input) !== "success") return false;
4722
- const command = (0, import_tool_kit6.getString)(input, ["command"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
4723
- return (0, import_tool_kit7.invitesDebrief)((0, import_tool_kit7.classifyWorkMilestone)(command));
5998
+ if ((0, import_tool_kit3.outcomeForHook)("PostToolUse", input) !== "success") return false;
5999
+ const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
6000
+ return (0, import_tool_kit4.invitesDebrief)((0, import_tool_kit4.classifyWorkMilestone)(command));
4724
6001
  }
4725
6002
  function mapSessionStart(input) {
4726
6003
  if (!isNewSessionStart(input)) return [];
4727
6004
  const modelId = readModelIdentifier(input)?.trim();
4728
- const modelClass = (0, import_tool_kit7.classifyModelClass)(modelId);
6005
+ const modelClass = (0, import_tool_kit4.classifyModelClass)(modelId);
4729
6006
  return [{
4730
6007
  eventType: "create_focus_session",
4731
6008
  severity: "low",
@@ -4754,11 +6031,39 @@ function classifySessionEndReason(raw) {
4754
6031
  return SESSION_END_REASONS.includes(value) ? value : "unknown";
4755
6032
  }
4756
6033
  var SESSION_END_REASONS = ["clear", "resume", "logout", "prompt_input_exit", "other"];
6034
+ function mapSubagent(eventType, input) {
6035
+ const raw = input["agent_type"];
6036
+ return [{
6037
+ eventType,
6038
+ severity: "low",
6039
+ metadata: raw === void 0 || raw === null ? {} : { subagentClass: classifySubagentType(raw) }
6040
+ }];
6041
+ }
6042
+ function classifySubagentType(raw) {
6043
+ if (typeof raw !== "string") return "unknown";
6044
+ const value = raw.trim().toLowerCase();
6045
+ if (value === "") return "none";
6046
+ if (value.includes(":")) return "plugin";
6047
+ return BUILT_IN_SUBAGENTS[value] ?? "custom";
6048
+ }
6049
+ var BUILT_IN_SUBAGENTS = {
6050
+ "general-purpose": "general_purpose",
6051
+ explore: "explore",
6052
+ plan: "plan",
6053
+ "statusline-setup": "statusline_setup",
6054
+ "claude-code-guide": "claude_code_guide"
6055
+ };
6056
+ function readSubagentId(input) {
6057
+ const raw = input["agent_id"];
6058
+ if (typeof raw !== "string") return void 0;
6059
+ const value = raw.trim();
6060
+ return /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : void 0;
6061
+ }
4757
6062
  function mapUserPromptSubmit(input) {
4758
- const prompt = (0, import_tool_kit6.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
6063
+ const prompt = (0, import_tool_kit3.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit3.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
4759
6064
  const autonomy = autonomyModeMetadata(input);
4760
6065
  const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...autonomy } }];
4761
- if ((0, import_tool_kit6.looksLikeCorrection)(prompt)) {
6066
+ if ((0, import_tool_kit3.looksLikeCorrection)(prompt)) {
4762
6067
  events.push({ eventType: "ai_correction_prompt", severity: "medium", metadata: { reason: "repeated_reprompting", trigger: "inferred", ...autonomy } });
4763
6068
  }
4764
6069
  return events;
@@ -4772,7 +6077,7 @@ function mapNotification(input) {
4772
6077
  // Low, always. Being asked is overhead to be counted, not a failure to be
4773
6078
  // flagged, and a severity that climbed would make this the input to a score.
4774
6079
  severity: "low",
4775
- metadata: { interruptionKind: notificationKind((0, import_tool_kit6.getString)(input, ["message"])) }
6080
+ metadata: { interruptionKind: notificationKind((0, import_tool_kit3.getString)(input, ["message"])) }
4776
6081
  }];
4777
6082
  }
4778
6083
  function notificationKind(message) {
@@ -4784,32 +6089,32 @@ function notificationKind(message) {
4784
6089
  function mapPostToolUse(hookName, input) {
4785
6090
  const toolName = getToolName(input);
4786
6091
  const safeToolName = sanitiseToolName(toolName);
4787
- const outcome = (0, import_tool_kit6.outcomeForHook)(hookName, input);
4788
- const durationMs = (0, import_tool_kit6.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit6.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
4789
- const command = (0, import_tool_kit6.getString)(input, ["command"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
4790
- const commandClass = (0, import_tool_kit7.classifyCommand)(command);
4791
- const gitAction = outcome === "success" ? (0, import_tool_kit7.classifyGitAction)(command) : void 0;
4792
- const milestoneKind = outcome === "success" ? (0, import_tool_kit7.classifyWorkMilestone)(command) : void 0;
6092
+ const outcome = (0, import_tool_kit3.outcomeForHook)(hookName, input);
6093
+ const durationMs = (0, import_tool_kit3.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit3.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
6094
+ const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
6095
+ const commandClass = (0, import_tool_kit4.classifyCommand)(command);
6096
+ const gitAction = outcome === "success" ? (0, import_tool_kit4.classifyGitAction)(command) : void 0;
6097
+ const milestoneKind = outcome === "success" ? (0, import_tool_kit4.classifyWorkMilestone)(command) : void 0;
4793
6098
  const autonomy = autonomyModeMetadata(input);
4794
6099
  if (outcome === "cancelled") {
4795
- return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "manual_interrupt", ...autonomy } }];
6100
+ return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), reason: "manual_interrupt", ...autonomy } }];
4796
6101
  }
4797
6102
  if (outcome === "failure") {
4798
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit7.isVerificationCommand)(commandClass)) {
4799
- return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "test_failure", ...autonomy } }];
6103
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit4.isVerificationCommand)(commandClass)) {
6104
+ return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), reason: "test_failure", ...autonomy } }];
4800
6105
  }
4801
- return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "tool_failure", ...autonomy } }];
6106
+ return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), reason: "tool_failure", ...autonomy } }];
4802
6107
  }
4803
6108
  if (isWriteTool(toolName)) {
4804
6109
  const linesChanged = computeLinesChanged(toolName, input);
4805
- const userModified = (0, import_tool_kit6.getNested)(input, ["tool_response", "userModified"]);
6110
+ const userModified = (0, import_tool_kit3.getNested)(input, ["tool_response", "userModified"]);
4806
6111
  return [{
4807
6112
  eventType: toolName?.toLowerCase() === "write" ? "ai_file_write" : "ai_file_edit",
4808
6113
  severity: "low",
4809
6114
  metadata: {
4810
6115
  toolName: safeToolName,
4811
6116
  outcome,
4812
- durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
6117
+ durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs),
4813
6118
  ...autonomy,
4814
6119
  // `false` is kept, not suppressed: without the negatives there is a
4815
6120
  // numerator and no denominator, and no correction *rate* can be
@@ -4822,12 +6127,12 @@ function mapPostToolUse(hookName, input) {
4822
6127
  // second event type exists for this — the bucket on the existing
4823
6128
  // creation event *is* the boundary, deliberately, since the write
4824
6129
  // already happened; there is nothing else to mark.
4825
- ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit6.bucketLinesChanged)(linesChanged) } : {}
6130
+ ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit3.bucketLinesChanged)(linesChanged) } : {}
4826
6131
  }
4827
6132
  }];
4828
6133
  }
4829
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit7.isVerificationCommand)(commandClass)) {
4830
- return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), activity: "ai_test_or_build_run", ...autonomy } }];
6134
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit4.isVerificationCommand)(commandClass)) {
6135
+ return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), activity: "ai_test_or_build_run", ...autonomy } }];
4831
6136
  }
4832
6137
  return [{
4833
6138
  eventType: "ai_tool_call_completed",
@@ -4836,14 +6141,14 @@ function mapPostToolUse(hookName, input) {
4836
6141
  toolName: safeToolName,
4837
6142
  commandClass,
4838
6143
  outcome,
4839
- durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
6144
+ durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs),
4840
6145
  ...autonomy,
4841
6146
  // The boundary and rework signal both ride this existing event rather
4842
6147
  // than minting a type: the backend already reads `gitAction` off any
4843
6148
  // event, and a commit is not a different *kind* of thing happening, it
4844
6149
  // is a fact about the tool call that just happened.
4845
6150
  ...gitAction !== void 0 ? { gitAction } : {},
4846
- ...(0, import_tool_kit7.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
6151
+ ...(0, import_tool_kit4.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
4847
6152
  // Same reasoning as `gitAction` above, one grain coarser: a milestone is
4848
6153
  // a fact about the tool call that just happened, not a different kind of
4849
6154
  // event. It rides here so the record carries the work's own rhythm —
@@ -4853,13 +6158,13 @@ function mapPostToolUse(hookName, input) {
4853
6158
  }];
4854
6159
  }
4855
6160
  function mapPreCompact(input) {
4856
- const trigger = (0, import_tool_kit6.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
6161
+ const trigger = (0, import_tool_kit3.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit3.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
4857
6162
  const isManual = trigger?.toLowerCase().includes("manual") ?? false;
4858
6163
  return [{ eventType: isManual ? "context_compression_manual" : "context_compression_auto", severity: isManual ? "medium" : "high", metadata: { trigger: isManual ? "manual" : "auto", reason: "context_limit" } }];
4859
6164
  }
4860
6165
  function mapStop(input) {
4861
- const durationMs = (0, import_tool_kit6.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit6.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
4862
- const durationBucket = (0, import_tool_kit6.bucketDurationMs)(durationMs);
6166
+ const durationMs = (0, import_tool_kit3.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit3.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
6167
+ const durationBucket = (0, import_tool_kit3.bucketDurationMs)(durationMs);
4863
6168
  const autonomy = autonomyModeMetadata(input);
4864
6169
  const events = [];
4865
6170
  if (durationBucket === "30-60m" || durationBucket === "60m+") {
@@ -4876,7 +6181,7 @@ function readPermissionMode(input) {
4876
6181
  const candidates = [
4877
6182
  input["permission_mode"],
4878
6183
  input["permissionMode"],
4879
- (0, import_tool_kit6.getNested)(input, ["payload", "permission_mode"])
6184
+ (0, import_tool_kit3.getNested)(input, ["payload", "permission_mode"])
4880
6185
  ];
4881
6186
  for (const value of candidates) {
4882
6187
  if (value !== void 0 && value !== null) return value;
@@ -4896,13 +6201,13 @@ var AUTONOMY_BY_PERMISSION_MODE = {
4896
6201
  bypasspermissions: "bypass_permissions"
4897
6202
  };
4898
6203
  function readModelIdentifier(input) {
4899
- return (0, import_tool_kit6.getString)(input, ["model", "model_id", "modelId"]) ?? (0, import_tool_kit6.getNestedString)(input, [["model", "id"], ["model", "display_name"], ["model", "name"], ["payload", "model"]]);
6204
+ return (0, import_tool_kit3.getString)(input, ["model", "model_id", "modelId"]) ?? (0, import_tool_kit3.getNestedString)(input, [["model", "id"], ["model", "display_name"], ["model", "name"], ["payload", "model"]]);
4900
6205
  }
4901
6206
  function getToolName(input) {
4902
- return (0, import_tool_kit6.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
6207
+ return (0, import_tool_kit3.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
4903
6208
  }
4904
6209
  function computeLinesChanged(toolName, input) {
4905
- const toolInput = (0, import_tool_kit6.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit6.getNested)(input, ["input"]) ?? (0, import_tool_kit6.getNested)(input, ["parameters"]);
6210
+ const toolInput = (0, import_tool_kit3.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit3.getNested)(input, ["input"]) ?? (0, import_tool_kit3.getNested)(input, ["parameters"]);
4906
6211
  if (!toolInput || typeof toolInput !== "object") return void 0;
4907
6212
  const record = toolInput;
4908
6213
  switch (toolName?.toLowerCase()) {
@@ -4947,7 +6252,178 @@ function sanitiseToolName(toolName) {
4947
6252
  return toolName.replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 40) || "unknown";
4948
6253
  }
4949
6254
 
6255
+ // src/liveEvent.ts
6256
+ function liveEventFor(hookName, input) {
6257
+ switch (hookName) {
6258
+ case "UserPromptSubmit":
6259
+ return "prompt_submitted";
6260
+ case "PreToolUse":
6261
+ return getToolName(input) === ASK_USER_QUESTION ? "awaiting" : "tool_call";
6262
+ case "PreCompact":
6263
+ return "compaction";
6264
+ case "PostToolUseFailure":
6265
+ return "tool_failure";
6266
+ case "Stop":
6267
+ return "stop";
6268
+ case "StopFailure":
6269
+ return "halted";
6270
+ case "Notification":
6271
+ return notificationLiveEvent(input);
6272
+ default:
6273
+ return void 0;
6274
+ }
6275
+ }
6276
+ var ASK_USER_QUESTION = "AskUserQuestion";
6277
+ var NOTIFICATION_EVENTS = {
6278
+ permission_prompt: "awaiting",
6279
+ elicitation_dialog: "awaiting",
6280
+ idle_prompt: "halted"
6281
+ };
6282
+ var NOTIFICATION_KIND_EVENTS = {
6283
+ permission_request: "awaiting",
6284
+ idle_prompt: "halted"
6285
+ };
6286
+ function notificationLiveEvent(input) {
6287
+ const kind = (0, import_tool_kit3.getString)(input, ["notification_type", "notificationType"]);
6288
+ if (kind !== void 0) return Object.hasOwn(NOTIFICATION_EVENTS, kind) ? NOTIFICATION_EVENTS[kind] : void 0;
6289
+ const label = notificationKind((0, import_tool_kit3.getString)(input, ["message"]));
6290
+ return Object.hasOwn(NOTIFICATION_KIND_EVENTS, label) ? NOTIFICATION_KIND_EVENTS[label] : void 0;
6291
+ }
6292
+
6293
+ // src/usageLimitReset.ts
6294
+ import * as fs from "node:fs";
6295
+ import * as os from "node:os";
6296
+ import * as path from "node:path";
6297
+ var MAX_RESUME_AHEAD_MS = 6 * 60 * 60 * 1e3;
6298
+ var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
6299
+ var RESET_CLAUSE = new RegExp(
6300
+ "\\bresets?(?:\\s+at)?\\s+(?:([a-z]{3,9})\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s+(?:at\\s+)?)?(\\d{1,2})(?::(\\d{2}))?\\s*(am|pm|a\\.m\\.|p\\.m\\.)?(?:\\s*\\(([^)]+)\\))?",
6301
+ "i"
6302
+ );
6303
+ var PIPE_EPOCH = /usage limit reached\|(\d{10,13})\b/i;
6304
+ function parseUsageLimitReset(text, now, localZone) {
6305
+ const piped = PIPE_EPOCH.exec(text);
6306
+ if (piped) {
6307
+ const raw = Number(piped[1]);
6308
+ return piped[1].length > 10 ? raw : raw * 1e3;
6309
+ }
6310
+ const match = RESET_CLAUSE.exec(text);
6311
+ if (!match) return void 0;
6312
+ const [, monthWord, dayText, hourText, minuteText, meridiem, zoneText] = match;
6313
+ const hour = to24Hour(Number(hourText), meridiem, minuteText !== void 0);
6314
+ if (hour === void 0) return void 0;
6315
+ const minute = minuteText === void 0 ? 0 : Number(minuteText);
6316
+ if (minute > 59) return void 0;
6317
+ const zone = zoneText?.trim() || localZone || Intl.DateTimeFormat().resolvedOptions().timeZone;
6318
+ const today = wallDate(now, zone);
6319
+ if (!today) return void 0;
6320
+ if (monthWord !== void 0) {
6321
+ const month = MONTHS.indexOf(monthWord.slice(0, 3).toLowerCase());
6322
+ if (month < 0 || !matchesMonthName(monthWord, month)) return void 0;
6323
+ const day = Number(dayText);
6324
+ if (day < 1 || day > 31) return void 0;
6325
+ let at = zonedToEpoch({ year: today.year, month: month + 1, day, hour, minute }, zone);
6326
+ if (at !== void 0 && at <= now.getTime()) {
6327
+ at = zonedToEpoch({ year: today.year + 1, month: month + 1, day, hour, minute }, zone);
6328
+ }
6329
+ return at;
6330
+ }
6331
+ const sameDay = zonedToEpoch({ ...today, hour, minute }, zone);
6332
+ if (sameDay === void 0) return void 0;
6333
+ if (sameDay > now.getTime()) return sameDay;
6334
+ return zonedToEpoch({ ...nextDay(today), hour, minute }, zone);
6335
+ }
6336
+ function resumesAtFor(text, now, localZone) {
6337
+ if (!text) return void 0;
6338
+ const at = parseUsageLimitReset(text, now, localZone);
6339
+ if (at === void 0) return void 0;
6340
+ const ahead = at - now.getTime();
6341
+ if (ahead <= 0 || ahead > MAX_RESUME_AHEAD_MS) return void 0;
6342
+ return Math.round(at / 6e4) * 60;
6343
+ }
6344
+ function to24Hour(hour, meridiem, hasMinutes) {
6345
+ if (meridiem === void 0) {
6346
+ if (!hasMinutes || hour > 23) return void 0;
6347
+ return hour;
6348
+ }
6349
+ if (hour < 1 || hour > 12) return void 0;
6350
+ const pm = meridiem.toLowerCase().startsWith("p");
6351
+ if (hour === 12) return pm ? 12 : 0;
6352
+ return pm ? hour + 12 : hour;
6353
+ }
6354
+ function matchesMonthName(word, month) {
6355
+ const full = new Date(Date.UTC(2e3, month, 1)).toLocaleString("en-US", { month: "long", timeZone: "UTC" }).toLowerCase();
6356
+ return full.startsWith(word.toLowerCase());
6357
+ }
6358
+ function wallDate(instant, zone) {
6359
+ const parts = wallParts(instant.getTime(), zone);
6360
+ return parts && { year: parts.year, month: parts.month, day: parts.day };
6361
+ }
6362
+ function nextDay(date) {
6363
+ const next = new Date(Date.UTC(date.year, date.month - 1, date.day + 1));
6364
+ return { year: next.getUTCFullYear(), month: next.getUTCMonth() + 1, day: next.getUTCDate() };
6365
+ }
6366
+ function wallParts(epochMs, zone) {
6367
+ let format;
6368
+ try {
6369
+ format = new Intl.DateTimeFormat("en-US", {
6370
+ timeZone: zone,
6371
+ hourCycle: "h23",
6372
+ year: "numeric",
6373
+ month: "numeric",
6374
+ day: "numeric",
6375
+ hour: "numeric",
6376
+ minute: "numeric"
6377
+ });
6378
+ } catch {
6379
+ return void 0;
6380
+ }
6381
+ const value = (type) => Number(format.formatToParts(epochMs).find((part) => part.type === type)?.value);
6382
+ return { year: value("year"), month: value("month"), day: value("day"), hour: value("hour"), minute: value("minute") };
6383
+ }
6384
+ function zonedToEpoch(time, zone) {
6385
+ const asUtc = Date.UTC(time.year, time.month - 1, time.day, time.hour, time.minute);
6386
+ const check = new Date(asUtc);
6387
+ if (check.getUTCDate() !== time.day) return void 0;
6388
+ let guess = asUtc;
6389
+ for (let pass = 0; pass < 2; pass += 1) {
6390
+ const seen = wallParts(guess, zone);
6391
+ if (!seen) return void 0;
6392
+ const seenUtc = Date.UTC(seen.year, seen.month - 1, seen.day, seen.hour, seen.minute);
6393
+ guess += asUtc - seenUtc;
6394
+ }
6395
+ return guess;
6396
+ }
6397
+ function managedSettingsPath() {
6398
+ if (process.env.ASCENDA_CLAUDE_MANAGED_SETTINGS) return process.env.ASCENDA_CLAUDE_MANAGED_SETTINGS;
6399
+ if (process.platform === "darwin") return "/Library/Application Support/ClaudeCode/managed-settings.json";
6400
+ if (process.platform === "win32") return "C:\\Program Files\\ClaudeCode\\managed-settings.json";
6401
+ return "/etc/claude-code/managed-settings.json";
6402
+ }
6403
+ function autoContinueEnabled(sources = {}) {
6404
+ const home = sources.home ?? os.homedir();
6405
+ const files = [
6406
+ sources.managedPath ?? managedSettingsPath(),
6407
+ ...sources.projectDir ? [path.join(sources.projectDir, ".claude", "settings.local.json"), path.join(sources.projectDir, ".claude", "settings.json")] : [],
6408
+ path.join(home, ".claude", "settings.json")
6409
+ ];
6410
+ for (const file of files) {
6411
+ const value = readSetting(file, "autoContinueAtUsageLimit");
6412
+ if (value !== void 0) return value === true;
6413
+ }
6414
+ return false;
6415
+ }
6416
+ function readSetting(file, key) {
6417
+ try {
6418
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
6419
+ if (parsed && typeof parsed === "object" && key in parsed) return parsed[key];
6420
+ } catch {
6421
+ }
6422
+ return void 0;
6423
+ }
6424
+
4950
6425
  // src/cli.ts
6426
+ init_config();
4951
6427
  init_paths();
4952
6428
  init_types();
4953
6429
  var INTENTION_INVITE = "Ascenda tip: if it's natural, you can ask what would make this session count before diving in \u2014 one line is enough. Not a required step, and skip it entirely if the user is already mid-task.";
@@ -5003,7 +6479,7 @@ Waiting for confirmation (expires ${session.expiresAt})...
5003
6479
  writeCredentials({ apiBaseUrl, toolInstallationId: pairedId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
5004
6480
  await writeStdout(
5005
6481
  `Paired. Write token saved to ${tokenFilePath}
5006
- Pairing saved to ${(0, import_tool_kit4.credentialsFilePath)()}
6482
+ Pairing saved to ${(0, import_tool_kit6.credentialsFilePath)()}
5007
6483
 
5008
6484
  Restart Claude Code and events flow. Nothing to add to your shell profile.
5009
6485
 
@@ -5014,18 +6490,61 @@ Restart Claude Code and events flow. Nothing to add to your shell profile.
5014
6490
  process.stderr.write("Timed out waiting for confirmation. Run the command again for a fresh code.\n");
5015
6491
  process.exitCode = 1;
5016
6492
  }
6493
+ async function runJoin(argv) {
6494
+ const joinCode = argv[0];
6495
+ if (!joinCode || joinCode.startsWith("-")) {
6496
+ process.stderr.write("Usage: ascenda-claude-hook join <code>\n");
6497
+ return 1;
6498
+ }
6499
+ let apiBaseUrl;
6500
+ let eventWriteToken;
6501
+ try {
6502
+ ({ apiBaseUrl, eventWriteToken } = loadConfigFromEnv());
6503
+ } catch (error) {
6504
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
6505
+ `);
6506
+ return 1;
6507
+ }
6508
+ return (0, import_tool_kit9.runStudyJoin)({ apiBaseUrl, eventWriteToken, displayName: "Claude Code", joinCode });
6509
+ }
6510
+ async function runObject(argv) {
6511
+ let apiBaseUrl;
6512
+ let eventWriteToken;
6513
+ try {
6514
+ ({ apiBaseUrl, eventWriteToken } = loadConfigFromEnv());
6515
+ } catch (error) {
6516
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
6517
+ `);
6518
+ return 1;
6519
+ }
6520
+ return (0, import_tool_kit9.runStudyObjection)({
6521
+ apiBaseUrl,
6522
+ eventWriteToken,
6523
+ commandPrefix: "npx @ascenda-one/claude-code-hooks",
6524
+ pairCommand: "npx @ascenda-one/claude-code-hooks pair",
6525
+ argv
6526
+ });
6527
+ }
5017
6528
  var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
5018
6529
  async function main() {
5019
6530
  const command = process.argv[2];
5020
6531
  if (!command) {
5021
6532
  throw new Error(
5022
- "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | doctor | setup | status | uninstall"
6533
+ "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | join | object | doctor | setup | status | uninstall"
5023
6534
  );
5024
6535
  }
5025
6536
  if (command === "pair") {
5026
6537
  await runPair();
5027
6538
  return;
5028
6539
  }
6540
+ if (command === "join") {
6541
+ setupExitCode = await runJoin(process.argv.slice(3));
6542
+ return;
6543
+ }
6544
+ if (command === "object") {
6545
+ setupExitCode = await runObject(process.argv.slice(3));
6546
+ return;
6547
+ }
5029
6548
  if (command === "doctor") {
5030
6549
  await runDoctor();
5031
6550
  return;
@@ -5037,7 +6556,7 @@ async function main() {
5037
6556
  }
5038
6557
  if (!isClaudeHookEventName(command)) {
5039
6558
  throw new Error(
5040
- `Unknown command "${command}". Expected a Claude Code hook name, "pair", "doctor", "setup", "status" or "uninstall".`
6559
+ `Unknown command "${command}". Expected a Claude Code hook name, "pair", "join", "object", "doctor", "setup", "status" or "uninstall".`
5041
6560
  );
5042
6561
  }
5043
6562
  const hookName = command;
@@ -5110,12 +6629,23 @@ function explainRejection(result) {
5110
6629
  return `Ascenda telemetry rejected: ${result}`;
5111
6630
  }
5112
6631
  async function emitLive(hookName, input) {
5113
- const event = hookName === "UserPromptSubmit" ? "prompt_submitted" : hookName === "PreToolUse" ? "tool_call" : hookName === "PreCompact" ? "compaction" : hookName === "PostToolUseFailure" ? "tool_failure" : hookName === "Stop" ? "stop" : void 0;
6632
+ let event;
6633
+ try {
6634
+ event = liveEventFor(hookName, input);
6635
+ } catch {
6636
+ return;
6637
+ }
5114
6638
  if (!event) return;
5115
6639
  try {
5116
6640
  const prompt = event === "prompt_submitted" ? (0, import_tool_kit9.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit9.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]) : void 0;
5117
6641
  const promptSource = event === "prompt_submitted" ? (0, import_tool_kit9.getString)(input, ["promptSource", "prompt_source"]) : void 0;
5118
6642
  const queued = promptSource === void 0 ? void 0 : promptSource === "queued";
6643
+ const backgroundTasks = event === "stop" ? countBackgroundTasks(input) : void 0;
6644
+ const errorKind = hookName === "StopFailure" && event === "halted" ? (0, import_tool_kit9.getString)(input, ["error"]) === "rate_limit" ? "rate_limit" : "error" : void 0;
6645
+ const resumesAt = errorKind === "rate_limit" ? usageLimitResumesAt(input) : void 0;
6646
+ const agent = (0, import_tool_kit9.findAgentProcess)(import_tool_kit9.AGENT_PROCESS.claude_code);
6647
+ const hookSet = (0, import_tool_kit9.readHookSet)(process.argv);
6648
+ const viaPlugin = (0, import_tool_kit9.readViaPlugin)(process.env);
5119
6649
  await (0, import_tool_kit9.emitLiveSignal)({
5120
6650
  tool: process.env.ASCENDA_TOOL_TYPE ?? "claude_code",
5121
6651
  // Concurrent sessions must count as separate streams for the X gauge.
@@ -5123,13 +6653,43 @@ async function emitLive(hookName, input) {
5123
6653
  // this process's parent — still per-session in practice, since Claude
5124
6654
  // Code spawns hooks from the session process.
5125
6655
  session: (0, import_tool_kit9.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
6656
+ ...(0, import_tool_kit9.livePidFields)(agent),
5126
6657
  event,
5127
6658
  ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit9.bucketPromptSize)(prompt) } : {},
5128
- ...queued !== void 0 ? { queued } : {}
6659
+ ...queued !== void 0 ? { queued } : {},
6660
+ ...backgroundTasks !== void 0 ? { backgroundTasks } : {},
6661
+ ...hookSet !== void 0 ? { hookSet } : {},
6662
+ ...viaPlugin === true ? { viaPlugin } : {},
6663
+ ...errorKind !== void 0 ? { errorKind } : {},
6664
+ ...resumesAt !== void 0 ? { resumesAt } : {}
5129
6665
  });
5130
6666
  } catch {
5131
6667
  }
5132
6668
  }
6669
+ function usageLimitResumesAt(input) {
6670
+ const projectDir = process.env.CLAUDE_PROJECT_DIR ?? (0, import_tool_kit9.getString)(input, ["cwd"]);
6671
+ if (!autoContinueEnabled({ projectDir })) return void 0;
6672
+ const now = /* @__PURE__ */ new Date();
6673
+ const texts = [
6674
+ (0, import_tool_kit9.getString)(input, ["error_details"]),
6675
+ (0, import_tool_kit9.getNestedString)(input, [["error_details", "message"]]),
6676
+ (0, import_tool_kit9.getString)(input, ["last_assistant_message"])
6677
+ ];
6678
+ for (const text of texts) {
6679
+ const at = resumesAtFor(text, now);
6680
+ if (at !== void 0) return at;
6681
+ }
6682
+ return void 0;
6683
+ }
6684
+ function countBackgroundTasks(input) {
6685
+ const tasks = input.background_tasks;
6686
+ if (!Array.isArray(tasks)) return void 0;
6687
+ return tasks.filter((task) => {
6688
+ const status = task && typeof task === "object" ? task.status : void 0;
6689
+ return typeof status !== "string" || !ENDED_TASK_STATUSES.has(status);
6690
+ }).length;
6691
+ }
6692
+ var ENDED_TASK_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "killed", "stopped", "cancelled"]);
5133
6693
  function pendingFailureNotice(hookName) {
5134
6694
  if (hookName !== "SessionStart" && hookName !== "PostToolUse") return void 0;
5135
6695
  if (process.env.ASCENDA_DISABLE_FAILURE_NOTICE === "true") return void 0;
@@ -5193,7 +6753,7 @@ async function runDoctor() {
5193
6753
  const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit9.defaultTokenFilePath)(toolInstallationId);
5194
6754
  lines.push(` Token file ${tokenFilePath}`);
5195
6755
  lines.push(` Token ${describeToken(tokenFilePath, unpaired)}`);
5196
- const hasToken = fs3.existsSync(tokenFilePath) || Boolean(process.env.ASCENDA_EVENT_WRITE_TOKEN);
6756
+ const hasToken = fs4.existsSync(tokenFilePath) || Boolean(process.env.ASCENDA_EVENT_WRITE_TOKEN);
5197
6757
  lines.push(` Mode ${unpaired ? "installed, not paired \u2014 local features active, telemetry inactive" : hasToken ? "paired \u2014 local features and telemetry active" : "paired, but no token on this machine \u2014 local features active, nothing can be sent"}`);
5198
6758
  const stateFilePath = resolveStateFilePath(toolInstallationId);
5199
6759
  lines.push(` Journal ${stateFilePath}`);
@@ -5294,11 +6854,11 @@ function describeAge(isoTimestamp) {
5294
6854
  }
5295
6855
  function describeToken(tokenFilePath, unpaired) {
5296
6856
  try {
5297
- if (!fs3.existsSync(tokenFilePath)) {
6857
+ if (!fs4.existsSync(tokenFilePath)) {
5298
6858
  if (process.env.ASCENDA_EVENT_WRITE_TOKEN) return "from ASCENDA_EVENT_WRITE_TOKEN (no file)";
5299
6859
  return unpaired ? "none \u2014 this install has no pairing" : "MISSING \u2014 run `pair`";
5300
6860
  }
5301
- const stat = fs3.statSync(tokenFilePath);
6861
+ const stat = fs4.statSync(tokenFilePath);
5302
6862
  const ageDays = Math.floor((Date.now() - stat.mtimeMs) / 864e5);
5303
6863
  return `present, last written ${stat.mtime.toISOString()} (${ageDays}d ago)`;
5304
6864
  } catch (error) {