@ascenda-one/codex-hooks 0.1.28 → 0.1.34

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
@@ -720,6 +720,10 @@ var require_out = __commonJS({
720
720
  // One constant word, from the agent itself. The session sentence names it.
721
721
  sessionEndReason: "session",
722
722
  interruptionKind: "waiting",
723
+ // Claude Code's own opaque id for one subagent, and the class it belongs
724
+ // to. Never the agent's name or anything it was asked.
725
+ subagentId: "subagents",
726
+ subagentClass: "subagents",
723
727
  // Free text by type, and written by no hook mapper — the IDE extension's
724
728
  // test signal is the only producer. The setup disclosure's third refusal
725
729
  // line says as much, and tool-kit's guard test fails if a mapper starts.
@@ -768,6 +772,8 @@ var require_out = __commonJS({
768
772
  "runtime",
769
773
  "sessionEndReason",
770
774
  "interruptionKind",
775
+ "subagentId",
776
+ "subagentClass",
771
777
  "simulated",
772
778
  "relatedEventType",
773
779
  "skillVersion",
@@ -815,6 +821,12 @@ var require_out = __commonJS({
815
821
  // `ai_prompt_submitted` closes. Neutral so a marker sent once per turn
816
822
  // doesn't weigh on any workload leg.
817
823
  ai_turn_completed: "neutral",
824
+ // A subagent began or finished under a session. Boundaries, not work: the
825
+ // subagent's own tool calls and edits arrive as their own events and carry
826
+ // their own categories. A reader pairs these on `subagentId` to count how
827
+ // many agents ran at once; neutral so that count weighs on no workload leg.
828
+ subagent_started: "neutral",
829
+ subagent_stopped: "neutral",
818
830
  // The agent stopped and is waiting on the person: Claude Code's
819
831
  // `Notification`, Codex's `PermissionRequest`. Supervision, beside the other
820
832
  // oversight overhead, because that is what it is — time the person spends
@@ -949,7 +961,7 @@ var require_collectorVersion = __commonJS({
949
961
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
950
962
  exports.describeCollectorVersion = describeCollectorVersion;
951
963
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
952
- exports.COLLECTOR_VERSION = "0.1.28" ? "0.1.28" : exports.UNRELEASED_COLLECTOR_VERSION;
964
+ exports.COLLECTOR_VERSION = "0.1.34" ? "0.1.34" : exports.UNRELEASED_COLLECTOR_VERSION;
953
965
  function describeCollectorVersion(version = exports.COLLECTOR_VERSION) {
954
966
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
955
967
  }
@@ -1051,6 +1063,12 @@ var require_http = __commonJS({
1051
1063
  exports.AscendaApiError = void 0;
1052
1064
  exports.createPairingSession = createPairingSession;
1053
1065
  exports.getPairingStatus = getPairingStatus;
1066
+ exports.startStudyJoin = startStudyJoin;
1067
+ exports.getStudyJoinStatus = getStudyJoinStatus;
1068
+ exports.readInitiatives = readInitiatives;
1069
+ exports.readStudyNotices = readStudyNotices;
1070
+ exports.setStudyObjection = setStudyObjection;
1071
+ exports.markStudyNoticeShown = markStudyNoticeShown;
1054
1072
  exports.renewToolToken = renewToolToken;
1055
1073
  exports.isRetryableStatus = isRetryableStatus;
1056
1074
  exports.postToolEvent = postToolEvent;
@@ -1087,6 +1105,108 @@ var require_http = __commonJS({
1087
1105
  throw new AscendaApiError(response.status, void 0, await response.text());
1088
1106
  return await response.json();
1089
1107
  }
1108
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1109
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1110
+ method: "POST",
1111
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1112
+ body: JSON.stringify({ joinCode, mode })
1113
+ });
1114
+ if (!response.ok)
1115
+ throw await apiError(response);
1116
+ return await response.json();
1117
+ }
1118
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1119
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1120
+ method: "GET",
1121
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1122
+ });
1123
+ if (!response.ok)
1124
+ throw await apiError(response);
1125
+ return await response.json();
1126
+ }
1127
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1128
+ let response;
1129
+ try {
1130
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1131
+ method: "GET",
1132
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1133
+ signal
1134
+ });
1135
+ } catch (error) {
1136
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1137
+ }
1138
+ if (response.status === 401)
1139
+ return { kind: "rejected", httpStatus: 401 };
1140
+ if (!response.ok)
1141
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1142
+ let body;
1143
+ try {
1144
+ body = await response.json();
1145
+ } catch {
1146
+ return { kind: "failed", reason: "the reply was not readable" };
1147
+ }
1148
+ if (!Array.isArray(body))
1149
+ return { kind: "failed", reason: "the reply was not a list" };
1150
+ return { kind: "ok", initiatives: body };
1151
+ }
1152
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1153
+ let response;
1154
+ try {
1155
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1156
+ method: "GET",
1157
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1158
+ signal
1159
+ });
1160
+ } catch (error) {
1161
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1162
+ }
1163
+ if (response.status === 404)
1164
+ return { kind: "absent" };
1165
+ if (response.status === 401)
1166
+ return { kind: "rejected", httpStatus: 401 };
1167
+ if (!response.ok)
1168
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1169
+ let body;
1170
+ try {
1171
+ body = await response.json();
1172
+ } catch {
1173
+ return { kind: "absent" };
1174
+ }
1175
+ if (!Array.isArray(body))
1176
+ return { kind: "absent" };
1177
+ return { kind: "ok", notices: body };
1178
+ }
1179
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1180
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1181
+ method: objected ? "POST" : "DELETE",
1182
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
1183
+ });
1184
+ if (!response.ok)
1185
+ throw await apiError(response);
1186
+ }
1187
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1188
+ try {
1189
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1190
+ method: "POST",
1191
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
1192
+ signal
1193
+ });
1194
+ return response.ok;
1195
+ } catch {
1196
+ return false;
1197
+ }
1198
+ }
1199
+ async function apiError(response) {
1200
+ const body = await response.text();
1201
+ let errorCode;
1202
+ try {
1203
+ const parsed = JSON.parse(body);
1204
+ errorCode = parsed.code ?? parsed.error;
1205
+ } catch {
1206
+ errorCode = void 0;
1207
+ }
1208
+ return new AscendaApiError(response.status, errorCode, body);
1209
+ }
1090
1210
  async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1091
1211
  const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1092
1212
  method: "POST",
@@ -1229,9 +1349,12 @@ var require_tokenStore = __commonJS({
1229
1349
  };
1230
1350
  }();
1231
1351
  Object.defineProperty(exports, "__esModule", { value: true });
1352
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1232
1353
  exports.ascendaHome = ascendaHome;
1233
1354
  exports.defaultTokenFilePath = defaultTokenFilePath;
1355
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1234
1356
  exports.persistEventWriteToken = persistEventWriteToken;
1357
+ exports.readTokenExpiry = readTokenExpiry;
1235
1358
  exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1236
1359
  exports.readTokenFile = readTokenFile;
1237
1360
  exports.sanitizeFilePart = sanitizeFilePart;
@@ -1244,7 +1367,10 @@ var require_tokenStore = __commonJS({
1244
1367
  function defaultTokenFilePath(toolInstallationId) {
1245
1368
  return path2.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1246
1369
  }
1247
- function persistEventWriteToken(tokenFilePath, token) {
1370
+ function tokenExpiryFilePath(tokenFilePath) {
1371
+ return path2.join(path2.dirname(tokenFilePath), "expiry", path2.basename(tokenFilePath));
1372
+ }
1373
+ function persistEventWriteToken(tokenFilePath, token, expiresAt) {
1248
1374
  const dir = path2.dirname(tokenFilePath);
1249
1375
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1250
1376
  fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
@@ -1252,6 +1378,30 @@ var require_tokenStore = __commonJS({
1252
1378
  fs.chmodSync(dir, 448);
1253
1379
  fs.chmodSync(tokenFilePath, 384);
1254
1380
  }
1381
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1382
+ try {
1383
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1384
+ fs.mkdirSync(path2.dirname(expiryFile), { recursive: true, mode: 448 });
1385
+ fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1386
+ } else {
1387
+ fs.rmSync(expiryFile, { force: true });
1388
+ }
1389
+ } catch {
1390
+ }
1391
+ }
1392
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1393
+ function readTokenExpiry(tokenFilePath) {
1394
+ try {
1395
+ const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1396
+ if (Number.isFinite(recorded))
1397
+ return recorded;
1398
+ } catch {
1399
+ }
1400
+ try {
1401
+ return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1402
+ } catch {
1403
+ return void 0;
1404
+ }
1255
1405
  }
1256
1406
  function listPersistedToolInstallationIds(toolType) {
1257
1407
  const prefix = `${sanitizeFilePart(toolType)}_`;
@@ -1698,7 +1848,7 @@ var require_eventSender = __commonJS({
1698
1848
  "../packages/tool-kit/out/eventSender.js"(exports) {
1699
1849
  "use strict";
1700
1850
  Object.defineProperty(exports, "__esModule", { value: true });
1701
- exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1851
+ exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
1702
1852
  exports.buildEventPayload = buildEventPayload;
1703
1853
  var afterHours_1 = require_afterHours();
1704
1854
  var tool_contract_1 = require_out();
@@ -1739,6 +1889,7 @@ var require_eventSender = __commonJS({
1739
1889
  }
1740
1890
  var DEFAULT_TIMEOUT_MS = 5e3;
1741
1891
  var RETRY_DELAY_MS = 250;
1892
+ exports.TOKEN_RENEW_LEAD_MS = 21 * 24 * 60 * 60 * 1e3;
1742
1893
  var AscendaEventSender = class {
1743
1894
  config;
1744
1895
  eventWriteToken;
@@ -1746,6 +1897,8 @@ var require_eventSender = __commonJS({
1746
1897
  lastDrain;
1747
1898
  /** One outbox pass per sender, i.e. per hook process. The hook is on the user's critical path. */
1748
1899
  outboxServiced = false;
1900
+ /** One look at the token's expiry per sender, for the same reason. */
1901
+ expiryChecked = false;
1749
1902
  /** Resolved once, so every clock read in one pass sees the same instant. */
1750
1903
  time;
1751
1904
  constructor(config) {
@@ -1869,6 +2022,7 @@ var require_eventSender = __commonJS({
1869
2022
  * hook during an outage to one bounded round trip instead of three.
1870
2023
  */
1871
2024
  async post(payload) {
2025
+ await this.renewIfExpiring();
1872
2026
  const halted = await this.serviceOutbox();
1873
2027
  let outcome;
1874
2028
  let queued = false;
@@ -2074,21 +2228,49 @@ var require_eventSender = __commonJS({
2074
2228
  return;
2075
2229
  (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload, ...outbox ? { outbox } : {} });
2076
2230
  }
2077
- /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
2231
+ /**
2232
+ * Renews ahead of expiry, at most once per sender. Waiting for the 401
2233
+ * doesn't work: by then the token has expired, and the server won't renew
2234
+ * an expired token.
2235
+ */
2236
+ async renewIfExpiring() {
2237
+ if (this.expiryChecked || this.config.renewToken === false)
2238
+ return;
2239
+ this.expiryChecked = true;
2240
+ const expiresAt = (0, tokenStore_1.readTokenExpiry)(this.config.tokenFilePath);
2241
+ if (expiresAt === void 0 || this.time.now() < expiresAt - exports.TOKEN_RENEW_LEAD_MS)
2242
+ return;
2243
+ await this.renewEventToken();
2244
+ }
2245
+ /**
2246
+ * Never throws: a renewal that errors is a failed renewal, not a failed turn.
2247
+ *
2248
+ * A refused renewal usually means another process got there first. Hooks
2249
+ * and the MCP server share one token file, and renewing revokes the token
2250
+ * it replaces, so the loser holds a revoked token while the winner's
2251
+ * replacement is already on disk. Adopting that counts as a renewal.
2252
+ */
2078
2253
  async renewEventToken() {
2079
2254
  if (this.config.renewToken === false)
2080
2255
  return false;
2081
2256
  try {
2082
2257
  const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
2083
2258
  if (!renewed)
2084
- return false;
2259
+ return this.adoptPersistedToken();
2085
2260
  this.eventWriteToken = renewed.eventWriteToken;
2086
- (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken);
2261
+ (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken, renewed.expiresAt);
2087
2262
  return true;
2088
2263
  } catch {
2089
2264
  return false;
2090
2265
  }
2091
2266
  }
2267
+ adoptPersistedToken() {
2268
+ const persisted = (0, tokenStore_1.readTokenFile)(this.config.tokenFilePath);
2269
+ if (!persisted || persisted === this.eventWriteToken)
2270
+ return false;
2271
+ this.eventWriteToken = persisted;
2272
+ return true;
2273
+ }
2092
2274
  signal() {
2093
2275
  return AbortSignal.timeout(this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS);
2094
2276
  }
@@ -2971,6 +3153,477 @@ var require_hookAdapter = __commonJS({
2971
3153
  }
2972
3154
  });
2973
3155
 
3156
+ // ../packages/tool-kit/out/hookSet.js
3157
+ var require_hookSet = __commonJS({
3158
+ "../packages/tool-kit/out/hookSet.js"(exports) {
3159
+ "use strict";
3160
+ Object.defineProperty(exports, "__esModule", { value: true });
3161
+ exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = void 0;
3162
+ exports.hookSetArgument = hookSetArgument;
3163
+ exports.readHookSet = readHookSet;
3164
+ exports.isHookSet = isHookSet;
3165
+ exports.readViaPlugin = readViaPlugin;
3166
+ exports.hookSetOfCommand = hookSetOfCommand;
3167
+ exports.hookSetChanges = hookSetChanges;
3168
+ exports.describeHookSetChanges = describeHookSetChanges;
3169
+ exports.HOOK_SET_FLAG = "--hook-set";
3170
+ exports.UNVERSIONED_HOOK_SET = 1;
3171
+ function hookSetArgument(hookSet) {
3172
+ return hookSet === void 0 ? "" : ` ${exports.HOOK_SET_FLAG} ${hookSet}`;
3173
+ }
3174
+ function readHookSet(argv) {
3175
+ const index = argv.indexOf(exports.HOOK_SET_FLAG);
3176
+ if (index === -1)
3177
+ return void 0;
3178
+ const raw = argv[index + 1];
3179
+ if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
3180
+ return void 0;
3181
+ const value = Number(raw);
3182
+ return isHookSet(value) ? value : void 0;
3183
+ }
3184
+ function isHookSet(value) {
3185
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3186
+ }
3187
+ function readViaPlugin(env) {
3188
+ return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
3189
+ }
3190
+ function hookSetOfCommand(command) {
3191
+ const match = command.match(/--hook-set\s+(\d+)/);
3192
+ return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
3193
+ }
3194
+ function hookSetChanges(before, events) {
3195
+ const added = events.filter((event) => !before.has(event));
3196
+ const sets = [...before.values()];
3197
+ return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
3198
+ }
3199
+ function describeHookSetChanges(changes, hookSet) {
3200
+ if (changes.previousSet === void 0)
3201
+ return void 0;
3202
+ const parts = [];
3203
+ if (changes.added.length)
3204
+ parts.push(`added ${changes.added.join(", ")}`);
3205
+ if (changes.previousSet < hookSet)
3206
+ parts.push(`hook set ${changes.previousSet} \u2192 ${hookSet}`);
3207
+ return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
3208
+ }
3209
+ }
3210
+ });
3211
+
3212
+ // ../packages/tool-kit/out/studyJoin.js
3213
+ var require_studyJoin = __commonJS({
3214
+ "../packages/tool-kit/out/studyJoin.js"(exports) {
3215
+ "use strict";
3216
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3217
+ if (k2 === void 0) k2 = k;
3218
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3219
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3220
+ desc = { enumerable: true, get: function() {
3221
+ return m[k];
3222
+ } };
3223
+ }
3224
+ Object.defineProperty(o, k2, desc);
3225
+ } : function(o, m, k, k2) {
3226
+ if (k2 === void 0) k2 = k;
3227
+ o[k2] = m[k];
3228
+ });
3229
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3230
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3231
+ } : function(o, v) {
3232
+ o["default"] = v;
3233
+ });
3234
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3235
+ var ownKeys = function(o) {
3236
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3237
+ var ar = [];
3238
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3239
+ return ar;
3240
+ };
3241
+ return ownKeys(o);
3242
+ };
3243
+ return function(mod) {
3244
+ if (mod && mod.__esModule) return mod;
3245
+ var result = {};
3246
+ if (mod != null) {
3247
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3248
+ }
3249
+ __setModuleDefault(result, mod);
3250
+ return result;
3251
+ };
3252
+ }();
3253
+ Object.defineProperty(exports, "__esModule", { value: true });
3254
+ exports.runStudyJoin = runStudyJoin;
3255
+ exports.formatWindow = formatWindow;
3256
+ var readline = __importStar(__require("node:readline"));
3257
+ var http_1 = require_http();
3258
+ var STUDY_JOIN_MODE = "report";
3259
+ var POLL_INTERVAL_MS = 3e3;
3260
+ var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
3261
+ async function runStudyJoin(ctx) {
3262
+ const stdin = ctx.stdin ?? process.stdin;
3263
+ const stdout = ctx.stdout ?? process.stdout;
3264
+ const stderr = ctx.stderr ?? process.stderr;
3265
+ const print = (line) => stdout.write(`${line}
3266
+ `);
3267
+ if (!stdin.isTTY || !stdout.isTTY) {
3268
+ stderr.write("join needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
3269
+ return 0;
3270
+ }
3271
+ if (!ctx.joinCode) {
3272
+ stderr.write("Usage: join <code>\n");
3273
+ return 1;
3274
+ }
3275
+ let start;
3276
+ try {
3277
+ start = await (0, http_1.startStudyJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, ctx.joinCode, STUDY_JOIN_MODE);
3278
+ } catch (error) {
3279
+ stderr.write(`${describeStartError(error)}
3280
+ `);
3281
+ return 1;
3282
+ }
3283
+ print("");
3284
+ print(`${start.organisationName}: ${describeStudyKind(start.studyKind)}`);
3285
+ print(formatWindow(start.windowStartUtc, start.windowEndUtc));
3286
+ print("");
3287
+ print("Report (30 days) grants:");
3288
+ for (const grant of start.grants)
3289
+ print(` ${describeGrant(grant)}`);
3290
+ print("");
3291
+ print("Study mode needs the Ascenda app. Open the app to join that way instead.");
3292
+ print("");
3293
+ print("Join in:");
3294
+ print(" 1) Report (30 days)");
3295
+ print(" 2) Not now");
3296
+ print("");
3297
+ const answer = await askChoice(stdin, stdout);
3298
+ if (!/^(1|report)$/i.test(answer)) {
3299
+ print("Not now.");
3300
+ return 0;
3301
+ }
3302
+ print("");
3303
+ print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
3304
+ print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
3305
+ const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3306
+ const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3307
+ while (Date.now() < deadline) {
3308
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
3309
+ let poll;
3310
+ try {
3311
+ poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
3312
+ } catch (error) {
3313
+ if (isRetryablePollError(error))
3314
+ continue;
3315
+ stderr.write(`${describeStartError(error)}
3316
+ `);
3317
+ return 1;
3318
+ }
3319
+ if (poll.status === "pending")
3320
+ continue;
3321
+ if (poll.status === "confirmed") {
3322
+ const granted = poll.granted ?? [];
3323
+ if (granted.length === 0) {
3324
+ print("");
3325
+ print("Nothing was granted. Run join again, or check with your organisation.");
3326
+ return 1;
3327
+ }
3328
+ print("");
3329
+ print("Joined. Granted:");
3330
+ for (const grant of granted)
3331
+ print(` ${describeGrant(grant)}`);
3332
+ print("");
3333
+ print("Each of these can be turned off separately, in the app's consent settings.");
3334
+ print("The organisation sees group counts, never who joined.");
3335
+ return 0;
3336
+ }
3337
+ if (poll.status === "expired") {
3338
+ print("");
3339
+ print("This code expired before it was confirmed. Run join again for a fresh code.");
3340
+ return 1;
3341
+ }
3342
+ if (poll.refusedReason === "grant_failed") {
3343
+ print("");
3344
+ print("Join failed partway through. Some grants may not have gone through.");
3345
+ const granted = poll.granted ?? [];
3346
+ if (granted.length > 0) {
3347
+ print("");
3348
+ print("Granted before the failure:");
3349
+ for (const grant of granted)
3350
+ print(` ${describeGrant(grant)}`);
3351
+ print("");
3352
+ print("Each of these can be turned off separately, in the app's consent settings.");
3353
+ }
3354
+ print("Run join again, or check with your organisation.");
3355
+ return 1;
3356
+ }
3357
+ print("");
3358
+ print(describeRefusal(poll.refusedReason));
3359
+ return 1;
3360
+ }
3361
+ print("");
3362
+ print("Timed out waiting for confirmation. Run join again for a fresh code.");
3363
+ return 1;
3364
+ }
3365
+ function isRetryablePollError(error) {
3366
+ if (error instanceof http_1.AscendaApiError)
3367
+ return error.status >= 500 && error.status <= 599;
3368
+ return true;
3369
+ }
3370
+ function askChoice(stdin, stdout) {
3371
+ return new Promise((resolve) => {
3372
+ const rl = readline.createInterface({ input: stdin, output: stdout });
3373
+ let settled = false;
3374
+ const finish = (value) => {
3375
+ if (settled)
3376
+ return;
3377
+ settled = true;
3378
+ rl.close();
3379
+ resolve(value.trim());
3380
+ };
3381
+ rl.question("Choice [Not now]: ", finish);
3382
+ rl.once("close", () => finish(""));
3383
+ });
3384
+ }
3385
+ function formatLocalTime(iso) {
3386
+ const date = new Date(iso);
3387
+ if (Number.isNaN(date.getTime()))
3388
+ return iso;
3389
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date);
3390
+ }
3391
+ function formatWindow(startUtc, endUtc) {
3392
+ const start = new Date(startUtc);
3393
+ const end = new Date(endUtc);
3394
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
3395
+ const dayMonth = { day: "numeric", month: "short", timeZone: "UTC" };
3396
+ const withYear = { ...dayMonth, year: "numeric" };
3397
+ const startFmt = new Intl.DateTimeFormat("en-GB", sameYear ? dayMonth : withYear);
3398
+ const endFmt = new Intl.DateTimeFormat("en-GB", withYear);
3399
+ return `${startFmt.format(start)} \u2013 ${endFmt.format(end)}`;
3400
+ }
3401
+ var GRANT_SENTENCES = {
3402
+ 501: "AI assistant data processing consent",
3403
+ 507: "Import of the AI-work history already on your machine"
3404
+ };
3405
+ function describeGrant(grant) {
3406
+ return GRANT_SENTENCES[grant.code] ?? humanise(grant.name);
3407
+ }
3408
+ var STUDY_KIND_SENTENCES = {
3409
+ Report30: "a 30-day report",
3410
+ Study90: "a 90-day study"
3411
+ };
3412
+ function describeStudyKind(studyKind) {
3413
+ return STUDY_KIND_SENTENCES[studyKind] ?? humanise(studyKind);
3414
+ }
3415
+ function humanise(name) {
3416
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim() || name;
3417
+ }
3418
+ var REFUSED_REASON_MESSAGES = {
3419
+ study_no_longer_live: "That study is no longer open to join.",
3420
+ withdrawn: "You're no longer an active participant in that study.",
3421
+ // Handled as its own branch above, with its granted list, before this
3422
+ // table is ever consulted — present so the type stays exhaustive, and as
3423
+ // a plain fallback should something call this function with it directly.
3424
+ grant_failed: "Join failed partway through. Some grants may not have gone through.",
3425
+ declined: "You declined in the app. Nothing was granted.",
3426
+ not_enrolled: "That study couldn't enrol you, so nothing was granted."
3427
+ };
3428
+ function describeRefusal(refusedReason) {
3429
+ if (refusedReason && REFUSED_REASON_MESSAGES[refusedReason])
3430
+ return REFUSED_REASON_MESSAGES[refusedReason];
3431
+ return "The join didn't go through. Nothing new was granted.";
3432
+ }
3433
+ var START_ERROR_MESSAGES = {
3434
+ join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
3435
+ unknown_mode: "This tool only offers Report mode from the command line.",
3436
+ no_live_study: "There's nothing open to join with that code right now.",
3437
+ too_many_open_sessions: "This tool has too many joins waiting to be confirmed. Confirm one, or let one expire, then try again.",
3438
+ unknown_session: "That join can no longer be found. Run join again for a fresh code."
3439
+ };
3440
+ function describeStartError(error) {
3441
+ if (error instanceof http_1.AscendaApiError) {
3442
+ if (error.errorCode && START_ERROR_MESSAGES[error.errorCode])
3443
+ return START_ERROR_MESSAGES[error.errorCode];
3444
+ if (error.status === 401)
3445
+ return "This tool's pairing was rejected. Re-pair it, then try again.";
3446
+ return `Could not reach the join code (HTTP ${error.status}).`;
3447
+ }
3448
+ return error instanceof Error ? error.message : String(error);
3449
+ }
3450
+ }
3451
+ });
3452
+
3453
+ // ../packages/tool-kit/out/initiatives.js
3454
+ var require_initiatives = __commonJS({
3455
+ "../packages/tool-kit/out/initiatives.js"(exports) {
3456
+ "use strict";
3457
+ Object.defineProperty(exports, "__esModule", { value: true });
3458
+ exports.INITIATIVE_COPY = void 0;
3459
+ exports.initiativesStatusLines = initiativesStatusLines;
3460
+ exports.renderInitiatives = renderInitiatives;
3461
+ var http_1 = require_http();
3462
+ var studyJoin_1 = require_studyJoin();
3463
+ var READ_TIMEOUT_MS = 5e3;
3464
+ exports.INITIATIVE_COPY = {
3465
+ outcomes: {
3466
+ moved_as_declared: "Moved the way declared, beyond the cohort's own variation",
3467
+ moved_against_declared: "Moved the other way, beyond the cohort's own variation",
3468
+ moved_no_direction_declared: "Moved beyond the cohort's own variation; no direction was declared",
3469
+ within_own_variation: "No further from the baseline than the cohort's own week-to-week variation",
3470
+ withheld: "Withheld"
3471
+ },
3472
+ withheldReasons: {
3473
+ cohort_below_minimum: "the cohort was too small to report on when the scoring window closed",
3474
+ below_minimum_cohort: "the cohort was too small to report on when the scoring window closed",
3475
+ below_minimum_cohort_size: "the cohort was too small to report on when the scoring window closed",
3476
+ baseline_withheld: "the baseline was withheld"
3477
+ }
3478
+ };
3479
+ var OUTCOME_EMPTY = "Not stated";
3480
+ var OUTCOME_UNKNOWN = "An outcome this app does not recognise";
3481
+ var WITHHELD_UNKNOWN = "Withheld, for a reason this version of the app doesn't name yet.";
3482
+ var DIRECTION_WORDS = {
3483
+ up: "Expected to rise",
3484
+ down: "Expected to fall",
3485
+ none_declared: "No direction declared"
3486
+ };
3487
+ var DIRECTION_UNKNOWN = "A direction this app does not recognise";
3488
+ async function initiativesStatusLines(ctx) {
3489
+ const heading = "Changes your organisation has published to you";
3490
+ if (!ctx.eventWriteToken) {
3491
+ return [heading, " Not checked: this install holds no token, so nothing was fetched."];
3492
+ }
3493
+ const read = await (0, http_1.readInitiatives)(ctx.apiBaseUrl, ctx.eventWriteToken, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3494
+ if (read.kind === "rejected") {
3495
+ return [
3496
+ heading,
3497
+ ` Couldn't check: the server turned this install's request down. If that keeps happening, pair again with \`${ctx.pairCommand}\`.`
3498
+ ];
3499
+ }
3500
+ if (read.kind === "failed") {
3501
+ return [heading, ` Couldn't check: ${read.reason}. Run status again to retry.`];
3502
+ }
3503
+ return [heading, ...renderInitiatives(read.initiatives)];
3504
+ }
3505
+ function renderInitiatives(entries, copy = exports.INITIATIVE_COPY) {
3506
+ if (entries.length === 0)
3507
+ return [" None published to you."];
3508
+ const lines = [];
3509
+ let unreadable = 0;
3510
+ for (const entry of entries) {
3511
+ const initiative = asInitiative(entry);
3512
+ if (!initiative) {
3513
+ unreadable += 1;
3514
+ continue;
3515
+ }
3516
+ lines.push(...renderOne(initiative, copy));
3517
+ }
3518
+ if (unreadable > 0) {
3519
+ lines.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3520
+ }
3521
+ return lines;
3522
+ }
3523
+ function renderOne(initiative, copy) {
3524
+ const lines = [` ${initiative.organisationName}: ${initiative.title}`];
3525
+ lines.push(` ${describeStatus(initiative)}`);
3526
+ if (initiative.summaryForCohort) {
3527
+ for (const line of initiative.summaryForCohort.split(/\r?\n/))
3528
+ lines.push(` ${line}`);
3529
+ }
3530
+ if (initiative.direction)
3531
+ lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
3532
+ lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
3533
+ if (initiative.result)
3534
+ lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
3535
+ lines.push("");
3536
+ return lines;
3537
+ }
3538
+ function describeStatus(initiative) {
3539
+ switch (initiative.status) {
3540
+ case "published":
3541
+ return "Published, not scored yet.";
3542
+ case "scored":
3543
+ return "Scored.";
3544
+ case "withdrawn":
3545
+ return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
3546
+ default:
3547
+ return "Status not recognised.";
3548
+ }
3549
+ }
3550
+ function renderResult(result, unit, copy) {
3551
+ const lines = [];
3552
+ const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
3553
+ if (result.value === null) {
3554
+ const why = copy.withheldReasons[result.withheldReason ?? ""];
3555
+ lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
3556
+ return lines;
3557
+ }
3558
+ lines.push(` Result: ${show(result.value)}`);
3559
+ lines.push(` ${movementLine(result)}`);
3560
+ lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
3561
+ return lines;
3562
+ }
3563
+ function movementLine(result) {
3564
+ if (result.outcome === "within_own_variation")
3565
+ return "No material change against frozen baseline";
3566
+ if (result.delta === null)
3567
+ return "No reading";
3568
+ if (result.delta > 0)
3569
+ return `Up ${figure(result.delta)} against frozen baseline`;
3570
+ if (result.delta < 0)
3571
+ return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
3572
+ return "No change against frozen baseline";
3573
+ }
3574
+ function figure(n) {
3575
+ return String(Number(n.toPrecision(12)));
3576
+ }
3577
+ function asInitiative(value) {
3578
+ if (!value || typeof value !== "object")
3579
+ return void 0;
3580
+ const o = value;
3581
+ if (typeof o.title !== "string" || typeof o.status !== "string")
3582
+ return void 0;
3583
+ return {
3584
+ id: typeof o.id === "string" ? o.id : "",
3585
+ organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3586
+ title: o.title,
3587
+ summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3588
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3589
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3590
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3591
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3592
+ status: o.status,
3593
+ direction: typeof o.direction === "string" ? o.direction : null,
3594
+ result: asResult(o.result)
3595
+ };
3596
+ }
3597
+ function asResult(value) {
3598
+ if (!value || typeof value !== "object")
3599
+ return null;
3600
+ const r = value;
3601
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
3602
+ return {
3603
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3604
+ value: num(r.value),
3605
+ baselineValue: num(r.baselineValue),
3606
+ delta: num(r.delta),
3607
+ movement: typeof r.movement === "string" ? r.movement : null,
3608
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
3609
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3610
+ basis: typeof r.basis === "string" ? r.basis : null
3611
+ };
3612
+ }
3613
+ function formatWindowOrRaw(startUtc, endUtc) {
3614
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3615
+ return "not given";
3616
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3617
+ }
3618
+ function formatDay(iso) {
3619
+ const date = new Date(iso);
3620
+ if (Number.isNaN(date.getTime()))
3621
+ return iso;
3622
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
3623
+ }
3624
+ }
3625
+ });
3626
+
2974
3627
  // ../packages/tool-kit/out/setupDisclosure.js
2975
3628
  var require_setupDisclosure = __commonJS({
2976
3629
  "../packages/tool-kit/out/setupDisclosure.js"(exports) {
@@ -2991,6 +3644,7 @@ var require_setupDisclosure = __commonJS({
2991
3644
  edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
2992
3645
  context: "how full the context window got",
2993
3646
  waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3647
+ 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",
2994
3648
  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"
2995
3649
  };
2996
3650
  exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
@@ -3016,9 +3670,9 @@ var require_setupDisclosure = __commonJS({
3016
3670
  }
3017
3671
  });
3018
3672
 
3019
- // ../packages/tool-kit/out/cliAgentSetup.js
3020
- var require_cliAgentSetup = __commonJS({
3021
- "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
3673
+ // ../packages/tool-kit/out/hookRunner.js
3674
+ var require_hookRunner = __commonJS({
3675
+ "../packages/tool-kit/out/hookRunner.js"(exports) {
3022
3676
  "use strict";
3023
3677
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3024
3678
  if (k2 === void 0) k2 = k;
@@ -3058,48 +3712,1039 @@ var require_cliAgentSetup = __commonJS({
3058
3712
  };
3059
3713
  }();
3060
3714
  Object.defineProperty(exports, "__esModule", { value: true });
3061
- exports.isCliAgentManagementCommand = isCliAgentManagementCommand2;
3062
- exports.cliAgentHookBinPath = cliAgentHookBinPath;
3063
- exports.runCliAgentSetup = runCliAgentSetup2;
3064
- exports.writeHookSettings = writeHookSettings;
3065
- exports.findStaleHookCommands = findStaleHookCommands;
3066
- var crypto = __importStar(__require("crypto"));
3715
+ exports.hookRunnerPaths = hookRunnerPaths;
3716
+ exports.hookLauncherScript = hookLauncherScript;
3717
+ exports.installHookRunner = installHookRunner;
3718
+ exports.removeHookRunner = removeHookRunner;
3719
+ exports.hookRunnerCommand = hookRunnerCommand;
3720
+ exports.lastHookPath = lastHookPath;
3721
+ exports.stampLastHook = stampLastHook2;
3722
+ exports.readLastHook = readLastHook;
3723
+ exports.describeAge = describeAge;
3724
+ exports.resolveHookNode = resolveHookNode;
3725
+ exports.tidyHomePath = tidyHomePath;
3726
+ var child_process_1 = __require("child_process");
3067
3727
  var fs = __importStar(__require("fs"));
3068
- var os2 = __importStar(__require("os"));
3069
3728
  var path2 = __importStar(__require("path"));
3070
- var collectorVersion_1 = require_collectorVersion();
3071
- var credentials_1 = require_credentials();
3072
- var hookAdapter_1 = require_hookAdapter();
3073
- var http_1 = require_http();
3074
- var setupDisclosure_1 = require_setupDisclosure();
3075
3729
  var tokenStore_1 = require_tokenStore();
3076
- var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
3077
- function isCliAgentManagementCommand2(argument) {
3078
- return argument !== void 0 && MANAGEMENT_COMMANDS.has(argument);
3730
+ function hookRunnerPaths(binaryName) {
3731
+ const launcher = path2.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3732
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
3079
3733
  }
3080
- function cliAgentHookBinPath(binaryName) {
3081
- return path2.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3734
+ var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3735
+ function hookLauncherScript(options) {
3736
+ const { binaryName, setupCommand, loudEvent } = options;
3737
+ return [
3738
+ "#!/bin/sh",
3739
+ `# Ascenda hook launcher (${binaryName}). Written by \`setup\`, replaced by the`,
3740
+ "# next one; edits here are lost. Finds a Node to run the hook bundle beside it.",
3741
+ "",
3742
+ 'dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 0',
3743
+ `bundle="$dir/${binaryName}.mjs"`,
3744
+ `record="$dir/${binaryName}.node"`,
3745
+ `missing="$dir/${binaryName}.no-node"`,
3746
+ "",
3747
+ 'runs() { [ -n "$1" ] && [ -f "$1" ] && [ -x "$1" ]; }',
3748
+ "",
3749
+ "# The hook bundle needs Node 20 or newer. Checked only while searching, so",
3750
+ "# the recorded path costs nothing to reuse.",
3751
+ "recent() {",
3752
+ ` runs "$1" && "$1" -e 'process.exit(parseInt(process.versions.node, 10) >= 20 ? 0 : 1)' >/dev/null 2>&1`,
3753
+ "}",
3754
+ "",
3755
+ "newest_nvm() {",
3756
+ ' [ -d "$HOME/.nvm/versions/node" ] || return 0',
3757
+ ` ls "$HOME/.nvm/versions/node" 2>/dev/null | sed 's/^v//' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1 | sed 's/^/v/'`,
3758
+ "}",
3759
+ "",
3760
+ 'node=""',
3761
+ "how=recorded",
3762
+ '[ -r "$record" ] && IFS= read -r node < "$record"',
3763
+ "",
3764
+ 'if ! runs "$node"; then',
3765
+ ' node=""',
3766
+ " how=found",
3767
+ ' nvm_default=""',
3768
+ ' if [ -r "$HOME/.nvm/alias/default" ]; then',
3769
+ ' IFS= read -r wanted < "$HOME/.nvm/alias/default"',
3770
+ " wanted=${wanted#v}",
3771
+ ' for candidate in "$HOME/.nvm/versions/node/v$wanted"*; do',
3772
+ ' [ -x "$candidate/bin/node" ] && nvm_default="$candidate/bin/node"',
3773
+ " done",
3774
+ " fi",
3775
+ " nvm_newest=$(newest_nvm)",
3776
+ " for candidate in \\",
3777
+ ' "$(command -v node 2>/dev/null)" \\',
3778
+ " /opt/homebrew/bin/node \\",
3779
+ " /usr/local/bin/node \\",
3780
+ ' "$HOME/.volta/bin/node" \\',
3781
+ ' "$nvm_default" \\',
3782
+ ' "$HOME/.local/share/fnm/aliases/default/bin/node" \\',
3783
+ ' "$HOME/Library/Application Support/fnm/aliases/default/bin/node" \\',
3784
+ ' "$HOME/.asdf/shims/node" \\',
3785
+ ' "$HOME/.local/share/mise/shims/node" \\',
3786
+ ' "$HOME/.nvm/versions/node/$nvm_newest/bin/node"',
3787
+ " do",
3788
+ ' if recent "$candidate"; then node=$candidate; break; fi',
3789
+ " done",
3790
+ ' if [ -n "$node" ]; then',
3791
+ ` printf '%s\\n' "$node" > "$record.$$" 2>/dev/null && mv -f "$record.$$" "$record" 2>/dev/null`,
3792
+ ' rm -f "$missing" 2>/dev/null',
3793
+ " fi",
3794
+ "fi",
3795
+ "",
3796
+ 'if [ -n "$ASCENDA_HOOK_LAUNCHER_PROBE" ]; then',
3797
+ ' [ -n "$node" ] || { echo "no Node 20 or newer found on PATH or in the usual install locations" >&2; exit 1; }',
3798
+ ` printf '%s\\t%s\\n' "$node" "$how"`,
3799
+ " exit 0",
3800
+ "fi",
3801
+ "",
3802
+ 'if [ -z "$node" ]; then',
3803
+ ' date -u +%Y-%m-%dT%H:%M:%SZ > "$missing" 2>/dev/null',
3804
+ ' case "$1" in',
3805
+ ...loudEvent ? [
3806
+ ` ${loudEvent})`,
3807
+ " cat >/dev/null 2>&1",
3808
+ ` echo "Ascenda hooks cannot find Node 20 or newer, so none of them are running. Install Node, then run: ${setupCommand}" >&2`,
3809
+ " exit 1 ;;"
3810
+ ] : [],
3811
+ ` ${LAUNCHER_MANAGEMENT_COMMANDS.join("|")})`,
3812
+ ` echo "${binaryName}: no Node 20 or newer found on PATH or in the usual install locations." >&2`,
3813
+ " exit 1 ;;",
3814
+ " *)",
3815
+ " # A hook: say nothing per tool call. status and doctor read the",
3816
+ " # file written above.",
3817
+ " cat >/dev/null 2>&1",
3818
+ " exit 0 ;;",
3819
+ " esac",
3820
+ "fi",
3821
+ "",
3822
+ 'exec "$node" "$bundle" "$@"',
3823
+ ""
3824
+ ].join("\n");
3825
+ }
3826
+ function installHookRunner(options) {
3827
+ const paths = hookRunnerPaths(options.binaryName);
3828
+ if (options.dryRun)
3829
+ return paths.launcher;
3830
+ const source = path2.resolve(options.source ?? process.argv[1]);
3831
+ fs.mkdirSync(path2.dirname(paths.launcher), { recursive: true });
3832
+ if (process.platform === "win32") {
3833
+ if (source !== path2.resolve(paths.launcher))
3834
+ fs.copyFileSync(source, paths.launcher);
3835
+ return paths.launcher;
3836
+ }
3837
+ if (source !== path2.resolve(paths.bundle))
3838
+ writeAtomically(paths.bundle, fs.readFileSync(source), 493);
3839
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
3840
+ writeAtomically(paths.record, `${process.execPath}
3841
+ `, 420);
3842
+ fs.rmSync(paths.noNode, { force: true });
3843
+ return paths.launcher;
3844
+ }
3845
+ function removeHookRunner(binaryName) {
3846
+ const removed = [];
3847
+ for (const file of Object.values(hookRunnerPaths(binaryName))) {
3848
+ if (!fs.existsSync(file))
3849
+ continue;
3850
+ fs.rmSync(file, { force: true });
3851
+ removed.push(file);
3852
+ }
3853
+ return removed;
3082
3854
  }
3083
- function usage(spec) {
3084
- return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
3085
-
3086
- npx ${spec.packageName} setup [options]
3087
- npx ${spec.packageName} status
3088
- npx ${spec.packageName} uninstall
3089
-
3090
- Options
3091
- --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
3855
+ function hookRunnerCommand(launcher) {
3856
+ return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
3857
+ }
3858
+ function writeAtomically(target, contents, mode) {
3859
+ const tmp = `${target}.${process.pid}.tmp`;
3860
+ fs.writeFileSync(tmp, contents, { mode });
3861
+ fs.chmodSync(tmp, mode);
3862
+ fs.renameSync(tmp, target);
3863
+ }
3864
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path2.join((0, tokenStore_1.ascendaHome)(), "state");
3865
+ function lastHookPath(tool) {
3866
+ return path2.join(stateDir(), `${tool}-last-hook.json`);
3867
+ }
3868
+ function stampLastHook2(tool, event, now = /* @__PURE__ */ new Date()) {
3869
+ try {
3870
+ fs.mkdirSync(stateDir(), { recursive: true });
3871
+ const file = lastHookPath(tool);
3872
+ const tmp = `${file}.${process.pid}.tmp`;
3873
+ fs.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
3874
+ `, { mode: 384 });
3875
+ fs.renameSync(tmp, file);
3876
+ } catch {
3877
+ }
3878
+ }
3879
+ function readLastHook(tool) {
3880
+ try {
3881
+ const parsed = JSON.parse(fs.readFileSync(lastHookPath(tool), "utf8"));
3882
+ if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
3883
+ return void 0;
3884
+ return { event: parsed.event, at: parsed.at };
3885
+ } catch {
3886
+ return void 0;
3887
+ }
3888
+ }
3889
+ function describeAge(ms) {
3890
+ if (!Number.isFinite(ms) || ms < 0)
3891
+ return "just now";
3892
+ const seconds = Math.round(ms / 1e3);
3893
+ if (seconds < 60)
3894
+ return `${seconds} s ago`;
3895
+ const minutes = Math.round(seconds / 60);
3896
+ if (minutes < 60)
3897
+ return `${minutes} min ago`;
3898
+ const hours = Math.round(minutes / 60);
3899
+ if (hours < 48)
3900
+ return `${hours} h ago`;
3901
+ return `${Math.round(hours / 24)} days ago`;
3902
+ }
3903
+ function resolveHookNode(launcher) {
3904
+ if (!fs.existsSync(launcher))
3905
+ return { problem: "the hook launcher is not installed" };
3906
+ const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
3907
+ encoding: "utf8",
3908
+ timeout: 5e3,
3909
+ env: { HOME: process.env.HOME ?? "", PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ASCENDA_HOOK_LAUNCHER_PROBE: "1" }
3910
+ });
3911
+ const [node, how] = (probe.stdout ?? "").trim().split(" ");
3912
+ if (probe.status !== 0 || !node) {
3913
+ return { problem: (probe.stderr ?? "").trim() || "the launcher found no Node it can run" };
3914
+ }
3915
+ const version = (0, child_process_1.spawnSync)(node, ["--version"], { encoding: "utf8", timeout: 5e3 });
3916
+ if (version.status !== 0)
3917
+ return { node, how, problem: `${node} did not run` };
3918
+ return { node, how, version: version.stdout.trim() };
3919
+ }
3920
+ function tidyHomePath(file, home = process.env.HOME ?? "") {
3921
+ return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
3922
+ }
3923
+ }
3924
+ });
3925
+
3926
+ // ../packages/tool-kit/out/saverHandoff.js
3927
+ var require_saverHandoff = __commonJS({
3928
+ "../packages/tool-kit/out/saverHandoff.js"(exports) {
3929
+ "use strict";
3930
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3931
+ if (k2 === void 0) k2 = k;
3932
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3933
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3934
+ desc = { enumerable: true, get: function() {
3935
+ return m[k];
3936
+ } };
3937
+ }
3938
+ Object.defineProperty(o, k2, desc);
3939
+ } : function(o, m, k, k2) {
3940
+ if (k2 === void 0) k2 = k;
3941
+ o[k2] = m[k];
3942
+ });
3943
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3944
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3945
+ } : function(o, v) {
3946
+ o["default"] = v;
3947
+ });
3948
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3949
+ var ownKeys = function(o) {
3950
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3951
+ var ar = [];
3952
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3953
+ return ar;
3954
+ };
3955
+ return ownKeys(o);
3956
+ };
3957
+ return function(mod) {
3958
+ if (mod && mod.__esModule) return mod;
3959
+ var result = {};
3960
+ if (mod != null) {
3961
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3962
+ }
3963
+ __setModuleDefault(result, mod);
3964
+ return result;
3965
+ };
3966
+ }();
3967
+ Object.defineProperty(exports, "__esModule", { value: true });
3968
+ exports.SAVER_REPLAY_SCHEMA = exports.SAVER_REPLAY_WINDOW_MS = void 0;
3969
+ exports.saverContainerDir = saverContainerDir;
3970
+ exports.saverSupportDir = saverSupportDir;
3971
+ exports.saverReplayPath = saverReplayPath;
3972
+ exports.saverStatusDir = saverStatusDir;
3973
+ exports.holdForSaver = holdForSaver;
3974
+ exports.heldForSaver = heldForSaver;
3975
+ exports.readSaverStatuses = readSaverStatuses;
3976
+ exports.probeSocket = probeSocket;
3977
+ var fs = __importStar(__require("fs"));
3978
+ var net = __importStar(__require("net"));
3979
+ var os2 = __importStar(__require("os"));
3980
+ var path2 = __importStar(__require("path"));
3981
+ var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3982
+ function saverContainerDir() {
3983
+ return process.env.ASCENDA_SAVER_CONTAINER ?? path2.join(os2.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
3984
+ }
3985
+ function saverSupportDir() {
3986
+ return path2.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
3987
+ }
3988
+ function saverReplayPath() {
3989
+ return path2.join(saverContainerDir(), "l.replay.json");
3990
+ }
3991
+ function saverStatusDir() {
3992
+ return path2.join(saverSupportDir(), "status");
3993
+ }
3994
+ exports.SAVER_REPLAY_WINDOW_MS = 30 * 60 * 1e3;
3995
+ var SAVER_REPLAY_MAX = 32;
3996
+ exports.SAVER_REPLAY_SCHEMA = 1;
3997
+ function holdForSaver(signal, now = Date.now()) {
3998
+ try {
3999
+ if (process.env.ASCENDA_LIVE_BUS_SOCKET && !process.env.ASCENDA_SAVER_CONTAINER)
4000
+ return;
4001
+ if (!fs.existsSync(saverSupportDir()))
4002
+ return;
4003
+ const wire = signal;
4004
+ const tool = wire.tool;
4005
+ const session = wire.session;
4006
+ const event = wire.event;
4007
+ if (typeof tool !== "string" || typeof session !== "string" || typeof event !== "string")
4008
+ return;
4009
+ const file = saverReplayPath();
4010
+ const kept = readHeld(file).filter((held) => now - held.at <= exports.SAVER_REPLAY_WINDOW_MS && !(held.tool === tool && held.session === session));
4011
+ kept.push({ ...wire, tool, session, event, at: now });
4012
+ kept.sort((a, b) => a.at - b.at);
4013
+ const body = JSON.stringify({ schema: exports.SAVER_REPLAY_SCHEMA, signals: kept.slice(-SAVER_REPLAY_MAX) });
4014
+ const tmp = `${file}.${process.pid}.tmp`;
4015
+ fs.writeFileSync(tmp, `${body}
4016
+ `, { mode: 384 });
4017
+ fs.renameSync(tmp, file);
4018
+ } catch {
4019
+ }
4020
+ }
4021
+ function readHeld(file) {
4022
+ try {
4023
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
4024
+ if (parsed.schema !== exports.SAVER_REPLAY_SCHEMA || !Array.isArray(parsed.signals))
4025
+ return [];
4026
+ return parsed.signals.filter((held) => typeof held === "object" && held !== null && typeof held.tool === "string" && typeof held.session === "string" && typeof held.event === "string" && typeof held.at === "number");
4027
+ } catch {
4028
+ return [];
4029
+ }
4030
+ }
4031
+ function heldForSaver(now = Date.now()) {
4032
+ const held = readHeld(saverReplayPath()).filter((entry) => now - entry.at <= exports.SAVER_REPLAY_WINDOW_MS);
4033
+ if (held.length === 0)
4034
+ return { count: 0 };
4035
+ return { count: held.length, newestAgeMs: now - Math.max(...held.map((entry) => entry.at)) };
4036
+ }
4037
+ function readSaverStatuses(now = Date.now()) {
4038
+ let names;
4039
+ try {
4040
+ names = fs.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
4041
+ } catch {
4042
+ return [];
4043
+ }
4044
+ const readings = [];
4045
+ for (const name of names) {
4046
+ try {
4047
+ const status = JSON.parse(fs.readFileSync(path2.join(saverStatusDir(), name), "utf8"));
4048
+ if (typeof status.pid !== "number" || typeof status.updatedAt !== "string")
4049
+ continue;
4050
+ readings.push({ ...status, alive: processAlive(status.pid), ageMs: now - Date.parse(status.updatedAt) });
4051
+ } catch {
4052
+ }
4053
+ }
4054
+ return readings.sort((a, b) => a.ageMs - b.ageMs);
4055
+ }
4056
+ function processAlive(pid) {
4057
+ try {
4058
+ process.kill(pid, 0);
4059
+ return true;
4060
+ } catch (error) {
4061
+ return error.code === "EPERM";
4062
+ }
4063
+ }
4064
+ function probeSocket(socketPath, timeoutMs = 300) {
4065
+ return new Promise((resolve) => {
4066
+ try {
4067
+ if (!fs.statSync(socketPath).isSocket()) {
4068
+ resolve("absent");
4069
+ return;
4070
+ }
4071
+ } catch {
4072
+ resolve("absent");
4073
+ return;
4074
+ }
4075
+ let settled = false;
4076
+ const finish = (state) => {
4077
+ if (settled)
4078
+ return;
4079
+ settled = true;
4080
+ clearTimeout(timer);
4081
+ socket.destroy();
4082
+ resolve(state);
4083
+ };
4084
+ const socket = net.createConnection(socketPath);
4085
+ const timer = setTimeout(() => finish("unreachable"), timeoutMs);
4086
+ socket.on("connect", () => finish("listening"));
4087
+ socket.on("error", (error) => finish(error.code === "ECONNREFUSED" || error.code === "ENOENT" ? "stale" : "unreachable"));
4088
+ });
4089
+ }
4090
+ }
4091
+ });
4092
+
4093
+ // ../packages/tool-kit/out/liveBus.js
4094
+ var require_liveBus = __commonJS({
4095
+ "../packages/tool-kit/out/liveBus.js"(exports) {
4096
+ "use strict";
4097
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4098
+ if (k2 === void 0) k2 = k;
4099
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4100
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4101
+ desc = { enumerable: true, get: function() {
4102
+ return m[k];
4103
+ } };
4104
+ }
4105
+ Object.defineProperty(o, k2, desc);
4106
+ } : function(o, m, k, k2) {
4107
+ if (k2 === void 0) k2 = k;
4108
+ o[k2] = m[k];
4109
+ });
4110
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4111
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4112
+ } : function(o, v) {
4113
+ o["default"] = v;
4114
+ });
4115
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4116
+ var ownKeys = function(o) {
4117
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4118
+ var ar = [];
4119
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4120
+ return ar;
4121
+ };
4122
+ return ownKeys(o);
4123
+ };
4124
+ return function(mod) {
4125
+ if (mod && mod.__esModule) return mod;
4126
+ var result = {};
4127
+ if (mod != null) {
4128
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4129
+ }
4130
+ __setModuleDefault(result, mod);
4131
+ return result;
4132
+ };
4133
+ }();
4134
+ Object.defineProperty(exports, "__esModule", { value: true });
4135
+ exports.SAVER_HOST_BUNDLE_ID = exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
4136
+ exports.liveBusSocketCandidates = liveBusSocketCandidates;
4137
+ exports.existingSocketCandidates = existingSocketCandidates;
4138
+ exports.liveBusSocketPath = liveBusSocketPath;
4139
+ exports.bucketPromptSize = bucketPromptSize2;
4140
+ exports.emitLiveSignal = emitLiveSignal2;
4141
+ exports.deliverLine = deliverLine;
4142
+ var fs = __importStar(__require("fs"));
4143
+ var net = __importStar(__require("net"));
4144
+ var os2 = __importStar(__require("os"));
4145
+ var path2 = __importStar(__require("path"));
4146
+ var hookSet_1 = require_hookSet();
4147
+ var saverHandoff_1 = require_saverHandoff();
4148
+ var WRITE_TIMEOUT_MS = 50;
4149
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
4150
+ var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
4151
+ exports.SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
4152
+ function liveBusSocketCandidates() {
4153
+ const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
4154
+ if (override)
4155
+ return [override];
4156
+ const home = os2.homedir();
4157
+ return [
4158
+ path2.join(home, ".ascenda", "live.sock"),
4159
+ path2.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4160
+ path2.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4161
+ ];
4162
+ }
4163
+ function existingSocketCandidates() {
4164
+ const candidates = liveBusSocketCandidates();
4165
+ if (process.env.ASCENDA_LIVE_BUS_SOCKET)
4166
+ return candidates;
4167
+ return candidates.filter((candidate) => {
4168
+ try {
4169
+ return fs.statSync(candidate).isSocket();
4170
+ } catch {
4171
+ return false;
4172
+ }
4173
+ });
4174
+ }
4175
+ function liveBusSocketPath() {
4176
+ return existingSocketCandidates()[0] ?? liveBusSocketCandidates()[0];
4177
+ }
4178
+ function bucketPromptSize2(text) {
4179
+ const length = typeof text === "string" ? text.length : 0;
4180
+ if (length <= 280)
4181
+ return "s";
4182
+ if (length <= 2e3)
4183
+ return "m";
4184
+ if (length <= 8e3)
4185
+ return "l";
4186
+ return "xl";
4187
+ }
4188
+ var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4189
+ function onTheWire(signal) {
4190
+ const out = { ...signal };
4191
+ if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4192
+ delete out.hookSet;
4193
+ if ("viaPlugin" in out && out.viaPlugin !== true)
4194
+ delete out.viaPlugin;
4195
+ return out;
4196
+ }
4197
+ function emitLiveSignal2(signal) {
4198
+ const wire = onTheWire(signal);
4199
+ return deliverLine(`${JSON.stringify(wire)}
4200
+ `).then((delivered) => {
4201
+ if (!delivered)
4202
+ (0, saverHandoff_1.holdForSaver)(wire);
4203
+ });
4204
+ }
4205
+ function deliverLine(line) {
4206
+ return new Promise((resolve) => {
4207
+ const candidates = existingSocketCandidates();
4208
+ if (candidates.length === 0) {
4209
+ resolve(void 0);
4210
+ return;
4211
+ }
4212
+ let settled = false;
4213
+ let accepted;
4214
+ let socket;
4215
+ const drop = () => {
4216
+ try {
4217
+ socket?.destroy();
4218
+ } catch {
4219
+ }
4220
+ socket = void 0;
4221
+ };
4222
+ const done = () => {
4223
+ if (settled)
4224
+ return;
4225
+ settled = true;
4226
+ clearTimeout(timer);
4227
+ drop();
4228
+ resolve(accepted);
4229
+ };
4230
+ const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4231
+ const tryFrom = (index) => {
4232
+ if (settled)
4233
+ return;
4234
+ if (index >= candidates.length) {
4235
+ done();
4236
+ return;
4237
+ }
4238
+ let attempt;
4239
+ try {
4240
+ attempt = net.createConnection(candidates[index]);
4241
+ } catch {
4242
+ tryFrom(index + 1);
4243
+ return;
4244
+ }
4245
+ socket = attempt;
4246
+ if (typeof attempt.unref === "function")
4247
+ attempt.unref();
4248
+ let connected = false;
4249
+ attempt.on("error", (error) => {
4250
+ if (settled || socket !== attempt)
4251
+ return;
4252
+ if (!connected && error.code && NOBODY_LISTENING.has(error.code)) {
4253
+ drop();
4254
+ tryFrom(index + 1);
4255
+ return;
4256
+ }
4257
+ done();
4258
+ });
4259
+ attempt.on("connect", () => {
4260
+ if (settled || socket !== attempt)
4261
+ return;
4262
+ connected = true;
4263
+ accepted = candidates[index];
4264
+ try {
4265
+ attempt.write(line, done);
4266
+ } catch {
4267
+ done();
4268
+ }
4269
+ });
4270
+ };
4271
+ tryFrom(0);
4272
+ });
4273
+ }
4274
+ }
4275
+ });
4276
+
4277
+ // ../packages/tool-kit/out/terminalStyle.js
4278
+ var require_terminalStyle = __commonJS({
4279
+ "../packages/tool-kit/out/terminalStyle.js"(exports) {
4280
+ "use strict";
4281
+ Object.defineProperty(exports, "__esModule", { value: true });
4282
+ exports.colourEnabled = colourEnabled;
4283
+ exports.terminalStyle = terminalStyle;
4284
+ function colourEnabled(stream = process.stdout, env = process.env) {
4285
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "")
4286
+ return false;
4287
+ if (env.FORCE_COLOR !== void 0)
4288
+ return env.FORCE_COLOR !== "0";
4289
+ if (env.TERM === "dumb")
4290
+ return false;
4291
+ return Boolean(stream.isTTY);
4292
+ }
4293
+ function terminalStyle(enabled = colourEnabled()) {
4294
+ const wrap = (open, close) => (text) => enabled ? `\x1B[${open}m${text}\x1B[${close}m` : text;
4295
+ const bold = wrap(1, 22);
4296
+ const dim = wrap(2, 22);
4297
+ const green = wrap(32, 39);
4298
+ const yellow = wrap(33, 39);
4299
+ const red = wrap(31, 39);
4300
+ const cyan = wrap(36, 39);
4301
+ const colour = { ok: green, warn: yellow, bad: red, info: dim };
4302
+ const marks = { ok: "\u2713", warn: "!", bad: "\u2717", info: "\xB7" };
4303
+ return {
4304
+ enabled,
4305
+ bold,
4306
+ dim,
4307
+ green,
4308
+ yellow,
4309
+ red,
4310
+ cyan,
4311
+ mark: (tone) => colour[tone](marks[tone]),
4312
+ tone: (tone, text) => colour[tone](text)
4313
+ };
4314
+ }
4315
+ }
4316
+ });
4317
+
4318
+ // ../packages/tool-kit/out/liveSignalDoctor.js
4319
+ var require_liveSignalDoctor = __commonJS({
4320
+ "../packages/tool-kit/out/liveSignalDoctor.js"(exports) {
4321
+ "use strict";
4322
+ Object.defineProperty(exports, "__esModule", { value: true });
4323
+ exports.DOCTOR_VALUE_COLUMN = void 0;
4324
+ exports.doctorRow = doctorRow;
4325
+ exports.liveSignalDoctorLines = liveSignalDoctorLines;
4326
+ var hookRunner_1 = require_hookRunner();
4327
+ var liveBus_1 = require_liveBus();
4328
+ var saverHandoff_1 = require_saverHandoff();
4329
+ var terminalStyle_1 = require_terminalStyle();
4330
+ exports.DOCTOR_VALUE_COLUMN = 25;
4331
+ function doctorRow(ui, tone, label, value) {
4332
+ return ` ${ui.mark(tone)} ${label.padEnd(exports.DOCTOR_VALUE_COLUMN - 5)} ${value}`;
4333
+ }
4334
+ async function liveSignalDoctorLines(options) {
4335
+ const ui = options.ui ?? (0, terminalStyle_1.terminalStyle)();
4336
+ const lines = [` ${ui.bold("Live signal")} ${ui.dim("(this machine; needs no pairing)")}`];
4337
+ const now = Date.now();
4338
+ let problems = 0;
4339
+ const row = (tone, label, value) => {
4340
+ if (tone === "bad" || tone === "warn")
4341
+ problems += 1;
4342
+ lines.push(doctorRow(ui, tone, label, tone === "bad" ? ui.red(value) : value));
4343
+ };
4344
+ const more = (value) => lines.push(`${" ".repeat(exports.DOCTOR_VALUE_COLUMN)}${value}`);
4345
+ if (options.launcher && process.platform !== "win32") {
4346
+ const node = (0, hookRunner_1.resolveHookNode)(options.launcher);
4347
+ if (node.problem)
4348
+ row("bad", "Node", `${node.problem}. Install Node 20 or newer, then run setup again`);
4349
+ else
4350
+ row("ok", "Node", `${node.node} ${ui.dim(`(${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`)}`);
4351
+ }
4352
+ if (options.registrations.length === 0)
4353
+ row("bad", "Hooks", `not registered. Run: ${options.setupCommand}`);
4354
+ for (const entry of options.registrations) {
4355
+ const where = entry.homeProject ? `loads only when ${options.displayName} starts in the home folder. Run setup again to move it to every project` : entry.scope === "user" ? "every project" : "this project only";
4356
+ const complete = entry.registered === options.eventCount;
4357
+ row(entry.homeProject || !complete ? "warn" : entry.scope === "user" ? "ok" : "info", "Hooks", `${entry.registered}/${options.eventCount} in ${entry.file} ${ui.dim(`(${where})`)}`);
4358
+ }
4359
+ if (options.registrations.length > 1) {
4360
+ problems += 1;
4361
+ more(ui.yellow("Registered in more than one file, so each event runs more than once. Run setup again to fix."));
4362
+ }
4363
+ const last = (0, hookRunner_1.readLastHook)(options.tool);
4364
+ if (last)
4365
+ row("ok", "Last hook", `${last.event}, ${(0, hookRunner_1.describeAge)(now - Date.parse(last.at))}`);
4366
+ else
4367
+ row("info", "Last hook", `none yet. Start ${options.displayName} (restart it if it was open during setup)${options.lookHint ? `, then ${options.lookHint}` : ""}`);
4368
+ const [appSocket, appContainerSocket, saverSocket] = (0, liveBus_1.liveBusSocketCandidates)();
4369
+ const appState = await (0, saverHandoff_1.probeSocket)(appSocket);
4370
+ const legacyState = appContainerSocket ? await (0, saverHandoff_1.probeSocket)(appContainerSocket) : "absent";
4371
+ if (appState === "listening" || legacyState === "listening")
4372
+ row("ok", "Desktop app", "listening. It takes every signal, and the saver mirrors it");
4373
+ else
4374
+ row("info", "Desktop app", "not listening");
4375
+ const saverState = saverSocket ? await (0, saverHandoff_1.probeSocket)(saverSocket) : "absent";
4376
+ const live = (0, saverHandoff_1.readSaverStatuses)(now).filter((status) => status.alive);
4377
+ const holder = live.find((status) => status.ownsBus);
4378
+ const saver = describeSaver(saverState, holder, live);
4379
+ row(saver.tone, "Screen saver", saver.text);
4380
+ for (const status of live)
4381
+ more(ui.dim(describeProcess(status, now)));
4382
+ const held = (0, saverHandoff_1.heldForSaver)(now);
4383
+ if (held.count > 0) {
4384
+ row("info", "Held for the saver", `${held.count} session${held.count === 1 ? "" : "s"}, newest ${(0, hookRunner_1.describeAge)(held.newestAgeMs ?? 0)}. Replayed when the saver starts`);
4385
+ }
4386
+ const trip = await pingRoundTrip(saverSocket, options.selfCommand);
4387
+ row(trip.tone, "Round trip", trip.text);
4388
+ lines.push("");
4389
+ lines.push(problems === 0 ? ` ${ui.mark("ok")} ${ui.bold("Ready.")} The hooks can run, and the screen saver hears them while it's on screen.` : ` ${ui.mark("bad")} ${ui.bold(`${problems} problem${problems === 1 ? "" : "s"} above.`)} Each line says how to fix it.`);
4390
+ return lines;
4391
+ }
4392
+ function describeSaver(state, holder, live) {
4393
+ if (state === "listening") {
4394
+ if (!holder)
4395
+ return { tone: "warn", text: "listening, from a process that isn't reporting. Restart it: killall legacyScreenSaver" };
4396
+ if (holder.saverViews === 0) {
4397
+ return { tone: "bad", text: `pid ${holder.pid} holds the socket but isn't drawing the saver, so signals go nowhere you can see. Fix: killall legacyScreenSaver` };
4398
+ }
4399
+ return { tone: "ok", text: `listening, pid ${holder.pid}, on screen` };
4400
+ }
4401
+ if (state === "stale")
4402
+ return { tone: "info", text: "not running (a socket file was left behind, which is harmless)" };
4403
+ if (live.some((status) => status.previewViews > 0)) {
4404
+ return { tone: "info", text: "not running. The System Settings preview never listens, so it stays still; the water goes live once the saver itself runs" };
4405
+ }
4406
+ return { tone: "info", text: "not running. That's normal: it listens only while it's on screen" };
4407
+ }
4408
+ function describeProcess(status, now) {
4409
+ const what = [
4410
+ status.saverViews > 0 ? `saver on ${status.saverViews} display${status.saverViews === 1 ? "" : "s"}` : void 0,
4411
+ status.previewViews > 0 ? "preview" : void 0
4412
+ ].filter(Boolean).join(" + ") || "not drawing";
4413
+ const heard = status.lastSignalAt ? `last signal ${status.lastSignalEvent ?? ""} ${(0, hookRunner_1.describeAge)(now - Date.parse(status.lastSignalAt))}`.replace(/\s+/g, " ") : "no signal yet";
4414
+ const replay = status.replayed > 0 ? `, replayed ${status.replayed} since this process started` : "";
4415
+ const beat = status.ageMs > 1e4 ? `, heartbeat ${(0, hookRunner_1.describeAge)(status.ageMs)} (not animating)` : "";
4416
+ return `pid ${status.pid} ${status.version ?? ""}: ${what}, ${status.mode ?? "?"}${status.ownsBus ? ", owns the socket" : ""}, ${heard}${replay}${beat}`.replace(/\s+:/, ":");
4417
+ }
4418
+ async function pingRoundTrip(saverSocket, selfCommand) {
4419
+ const session = `doctor-${process.pid}-${Date.now()}`;
4420
+ const accepted = await (0, liveBus_1.deliverLine)(`${JSON.stringify({ tool: "doctor", session, event: "ping" })}
4421
+ `);
4422
+ if (!accepted) {
4423
+ return { tone: "info", text: `nobody is listening right now, so there is nothing to test. To test the saver: open -a ScreenSaverEngine; sleep 5; ${selfCommand} doctor` };
4424
+ }
4425
+ if (accepted !== saverSocket)
4426
+ return { tone: "ok", text: `the desktop app took it (${accepted})` };
4427
+ for (let waited = 0; waited < 2e3; waited += 100) {
4428
+ await new Promise((resolve) => setTimeout(resolve, 100));
4429
+ const answered = (0, saverHandoff_1.readSaverStatuses)().find((status) => status.lastPingSession === session);
4430
+ if (answered)
4431
+ return { tone: "ok", text: `OK. The screen saver (pid ${answered.pid}) received it` };
4432
+ }
4433
+ return { tone: "bad", text: "the saver's socket took the ping but no saver reported it. It may be a version from before 0.8.1, or stuck. Fix: killall legacyScreenSaver" };
4434
+ }
4435
+ }
4436
+ });
4437
+
4438
+ // ../packages/tool-kit/out/studyNotices.js
4439
+ var require_studyNotices = __commonJS({
4440
+ "../packages/tool-kit/out/studyNotices.js"(exports) {
4441
+ "use strict";
4442
+ Object.defineProperty(exports, "__esModule", { value: true });
4443
+ exports.NOTICED_PURPOSES = void 0;
4444
+ exports.studyNoticeStatus = studyNoticeStatus;
4445
+ exports.renderStudyNotices = renderStudyNotices;
4446
+ exports.runStudyObjection = runStudyObjection;
4447
+ var http_1 = require_http();
4448
+ var READ_TIMEOUT_MS = 5e3;
4449
+ var NOTICE_LABEL = "Counted unless you object";
4450
+ var PROCESSOR = "Ascenda";
4451
+ exports.NOTICED_PURPOSES = [
4452
+ { code: 501, slug: "telemetry", title: "Live tool telemetry" },
4453
+ { code: 507, slug: "import", title: "One-time import of past AI work" },
4454
+ { code: 11, slug: "work-patterns", title: "Work-pattern axes in the group figures" }
4455
+ ];
4456
+ var BASIS_WORDS = {
4457
+ legitimate_interests: "legitimate interests",
4458
+ collective_agreement: "a collective agreement"
4459
+ };
4460
+ async function studyNoticeStatus(ctx) {
4461
+ const nothing = { lines: [], markShown: async () => {
4462
+ } };
4463
+ const token = ctx.eventWriteToken;
4464
+ if (!token)
4465
+ return nothing;
4466
+ const read = await (0, http_1.readStudyNotices)(ctx.apiBaseUrl, token, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
4467
+ if (read.kind !== "ok")
4468
+ return nothing;
4469
+ const lines = renderStudyNotices(read.notices, ctx.commandPrefix, ctx.now);
4470
+ if (lines.length === 0)
4471
+ return nothing;
4472
+ const unshown = shownPurposes(read.notices).filter((n) => !n.noticeFromUtc && n.organisationId);
4473
+ return {
4474
+ lines,
4475
+ markShown: async () => {
4476
+ const signal = AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS);
4477
+ await Promise.all(unshown.map((n) => (0, http_1.markStudyNoticeShown)(ctx.apiBaseUrl, token, n.organisationId, n.code, signal)));
4478
+ }
4479
+ };
4480
+ }
4481
+ function shownPurposes(entries) {
4482
+ return entries.map(asNotice).filter((n) => n !== void 0 && exports.NOTICED_PURPOSES.some((p) => p.code === n.code));
4483
+ }
4484
+ function renderStudyNotices(entries, commandPrefix, now = /* @__PURE__ */ new Date()) {
4485
+ const body = [];
4486
+ let unreadable = 0;
4487
+ for (const entry of entries) {
4488
+ const notice = asNotice(entry);
4489
+ const purpose = notice && exports.NOTICED_PURPOSES.find((p) => p.code === notice.code);
4490
+ if (!notice || !purpose) {
4491
+ unreadable += 1;
4492
+ continue;
4493
+ }
4494
+ body.push(...renderOne(notice, purpose, commandPrefix, now));
4495
+ }
4496
+ if (body.length === 0)
4497
+ return [];
4498
+ if (unreadable > 0) {
4499
+ body.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
4500
+ }
4501
+ return ["", "Your organisation's study", ...body];
4502
+ }
4503
+ function renderOne(notice, purpose, commandPrefix, now) {
4504
+ const org = notice.organisationName;
4505
+ const command = `${commandPrefix} object ${purpose.slug}`;
4506
+ const lines = [` ${org}: ${purpose.title}`];
4507
+ lines.push(` ${notice.label || NOTICE_LABEL}`);
4508
+ lines.push(` ${basisLine(notice)}`);
4509
+ if (notice.signatoryName)
4510
+ lines.push(` Recorded by ${notice.signatoryName}.`);
4511
+ lines.push(` ${notice.processor || PROCESSOR} processes this for ${org}.`);
4512
+ if (notice.objected === true) {
4513
+ lines.push(" You objected. You are left out from the next report on.");
4514
+ lines.push(` To undo: ${command} --undo`);
4515
+ } else if (notice.objected === false) {
4516
+ lines.push(" You haven't objected.");
4517
+ if (notice.noticeFromUtc && isDate(notice.noticeFromUtc)) {
4518
+ const starts = notice.countingFromUtc && isDate(notice.countingFromUtc) ? notice.countingFromUtc : new Date(Date.parse(notice.noticeFromUtc) + NOTICE_PERIOD_MS).toISOString();
4519
+ if (Date.parse(starts) > now.getTime()) {
4520
+ lines.push(` Notice given ${formatDay(notice.noticeFromUtc)}. Counting starts ${formatDay(starts)}.`);
4521
+ }
4522
+ }
4523
+ 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.`);
4524
+ } else {
4525
+ lines.push(" This version of the tool couldn't read whether you've objected. Run status again.");
4526
+ lines.push(` To object: ${command}`);
4527
+ lines.push(` To undo: ${command} --undo`);
4528
+ }
4529
+ lines.push("");
4530
+ return lines;
4531
+ }
4532
+ function basisLine(notice) {
4533
+ const words = notice.basisLabel ?? BASIS_WORDS[notice.basis];
4534
+ const head = words ? `${notice.organisationName}'s basis is ${words}.` : `${notice.organisationName}'s basis is one this version of the tool can't name.`;
4535
+ const dated = notice.documentDate && isDate(notice.documentDate) ? formatDay(notice.documentDate) : null;
4536
+ const ref = notice.documentReference ? `ref ${notice.documentReference}` : null;
4537
+ const title = notice.documentTitle ? dated ? `${notice.documentTitle} (${dated})` : notice.documentTitle : null;
4538
+ const document = [title, ref].filter((part) => Boolean(part)).join(", ");
4539
+ return document ? `${head} Document: ${document}.` : head;
4540
+ }
4541
+ var NOTICE_PERIOD_MS = 14 * 24 * 60 * 60 * 1e3;
4542
+ function asNotice(value) {
4543
+ if (!value || typeof value !== "object")
4544
+ return void 0;
4545
+ const o = value;
4546
+ if (typeof o.code !== "number")
4547
+ return void 0;
4548
+ if (typeof o.mode === "string" && o.mode.trim().toLowerCase() !== "notice")
4549
+ return void 0;
4550
+ const str = (x) => typeof x === "string" && x.trim() ? x : null;
4551
+ return {
4552
+ organisationId: str(o.organisationId),
4553
+ organisationName: str(o.organisationName) ?? "Your organisation",
4554
+ code: o.code,
4555
+ name: str(o.name),
4556
+ label: str(o.label),
4557
+ processor: str(o.processor),
4558
+ basis: typeof o.basis === "string" ? o.basis : "",
4559
+ basisLabel: str(o.basisLabel),
4560
+ documentTitle: str(o.documentTitle),
4561
+ documentDate: str(o.documentDate),
4562
+ documentReference: str(o.documentReference),
4563
+ signatoryName: str(o.signatoryName),
4564
+ objected: typeof o.objected === "boolean" ? o.objected : null,
4565
+ objectedAtUtc: str(o.objectedAtUtc),
4566
+ noticeFromUtc: str(o.noticeFromUtc),
4567
+ countingFromUtc: str(o.countingFromUtc)
4568
+ };
4569
+ }
4570
+ async function runStudyObjection(ctx) {
4571
+ const stdin = ctx.stdin ?? process.stdin;
4572
+ const stdout = ctx.stdout ?? process.stdout;
4573
+ const stderr = ctx.stderr ?? process.stderr;
4574
+ const print = (line) => stdout.write(`${line}
4575
+ `);
4576
+ if (!stdin.isTTY || !stdout.isTTY) {
4577
+ stderr.write("object needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
4578
+ return 1;
4579
+ }
4580
+ const undo = ctx.argv.includes("--undo");
4581
+ const rest = ctx.argv.filter((a) => a !== "--undo");
4582
+ const purpose = rest.length === 1 ? exports.NOTICED_PURPOSES.find((p) => p.slug === rest[0]) : void 0;
4583
+ if (!purpose) {
4584
+ stderr.write(objectionUsage(ctx.commandPrefix));
4585
+ return 1;
4586
+ }
4587
+ if (!ctx.eventWriteToken) {
4588
+ stderr.write(`This install isn't paired, so there's nothing to object to. Pair with \`${ctx.pairCommand}\`.
4589
+ `);
4590
+ return 1;
4591
+ }
4592
+ const command = `${ctx.commandPrefix} object ${purpose.slug}`;
4593
+ try {
4594
+ await (0, http_1.setStudyObjection)(ctx.apiBaseUrl, ctx.eventWriteToken, purpose.code, !undo);
4595
+ } catch (error) {
4596
+ stderr.write(`${describeObjectionError(error, purpose, undo, ctx.pairCommand)}
4597
+ `);
4598
+ return 1;
4599
+ }
4600
+ if (undo) {
4601
+ print(`Objection withdrawn: ${purpose.title}.`);
4602
+ print("You're counted again from the next report.");
4603
+ print(`To object again: ${command}`);
4604
+ } else {
4605
+ print(`Objected: ${purpose.title}.`);
4606
+ print("You objected. You are left out from the next report on, and earlier reports stay as they were.");
4607
+ print(`To undo: ${command} --undo`);
4608
+ }
4609
+ return 0;
4610
+ }
4611
+ function objectionUsage(commandPrefix) {
4612
+ const lines = [`Usage: ${commandPrefix} object <purpose> [--undo]`, "", "Purposes:"];
4613
+ for (const p of exports.NOTICED_PURPOSES)
4614
+ lines.push(` ${p.slug.padEnd(14)}${p.title}`);
4615
+ lines.push("", "status shows which of these your organisation counts unless you object.");
4616
+ return `${lines.join("\n")}
4617
+ `;
4618
+ }
4619
+ function describeObjectionError(error, purpose, undo, pairCommand) {
4620
+ if (error instanceof http_1.AscendaApiError) {
4621
+ if (error.status === 404 && error.errorCode === "not_noticed") {
4622
+ 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.`;
4623
+ }
4624
+ if (error.status === 401)
4625
+ return `The server turned this install's request down. If that keeps happening, pair again with \`${pairCommand}\`.`;
4626
+ if (error.status === 404)
4627
+ return "This server doesn't take objections yet. Nothing changed.";
4628
+ return `Couldn't record that (HTTP ${error.status}). Nothing changed. Run it again to retry.`;
4629
+ }
4630
+ return "Couldn't reach the server. Nothing changed. Run it again to retry.";
4631
+ }
4632
+ function isDate(iso) {
4633
+ return !Number.isNaN(Date.parse(iso));
4634
+ }
4635
+ var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
4636
+ function formatDay(iso) {
4637
+ const date = new Date(iso);
4638
+ return `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]} ${date.getUTCFullYear()}`;
4639
+ }
4640
+ }
4641
+ });
4642
+
4643
+ // ../packages/tool-kit/out/cliAgentSetup.js
4644
+ var require_cliAgentSetup = __commonJS({
4645
+ "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
4646
+ "use strict";
4647
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4648
+ if (k2 === void 0) k2 = k;
4649
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4650
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4651
+ desc = { enumerable: true, get: function() {
4652
+ return m[k];
4653
+ } };
4654
+ }
4655
+ Object.defineProperty(o, k2, desc);
4656
+ } : function(o, m, k, k2) {
4657
+ if (k2 === void 0) k2 = k;
4658
+ o[k2] = m[k];
4659
+ });
4660
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4661
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4662
+ } : function(o, v) {
4663
+ o["default"] = v;
4664
+ });
4665
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4666
+ var ownKeys = function(o) {
4667
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4668
+ var ar = [];
4669
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4670
+ return ar;
4671
+ };
4672
+ return ownKeys(o);
4673
+ };
4674
+ return function(mod) {
4675
+ if (mod && mod.__esModule) return mod;
4676
+ var result = {};
4677
+ if (mod != null) {
4678
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4679
+ }
4680
+ __setModuleDefault(result, mod);
4681
+ return result;
4682
+ };
4683
+ }();
4684
+ Object.defineProperty(exports, "__esModule", { value: true });
4685
+ exports.isCliAgentManagementCommand = isCliAgentManagementCommand2;
4686
+ exports.cliAgentHookBinPath = cliAgentHookBinPath;
4687
+ exports.cliAgentSelfCommand = cliAgentSelfCommand;
4688
+ exports.runCliAgentSetup = runCliAgentSetup2;
4689
+ exports.writeHookSettings = writeHookSettings;
4690
+ exports.registeredHookSets = registeredHookSets;
4691
+ exports.findStaleHookCommands = findStaleHookCommands;
4692
+ exports.cliAgentRegistrations = cliAgentRegistrations;
4693
+ var crypto = __importStar(__require("crypto"));
4694
+ var fs = __importStar(__require("fs"));
4695
+ var os2 = __importStar(__require("os"));
4696
+ var path2 = __importStar(__require("path"));
4697
+ var collectorVersion_1 = require_collectorVersion();
4698
+ var credentials_1 = require_credentials();
4699
+ var hookAdapter_1 = require_hookAdapter();
4700
+ var http_1 = require_http();
4701
+ var hookSet_1 = require_hookSet();
4702
+ var initiatives_1 = require_initiatives();
4703
+ var setupDisclosure_1 = require_setupDisclosure();
4704
+ var hookRunner_1 = require_hookRunner();
4705
+ var liveSignalDoctor_1 = require_liveSignalDoctor();
4706
+ var stateStore_1 = require_stateStore();
4707
+ var studyJoin_1 = require_studyJoin();
4708
+ var studyNotices_1 = require_studyNotices();
4709
+ var terminalStyle_1 = require_terminalStyle();
4710
+ var tokenStore_1 = require_tokenStore();
4711
+ var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "doctor", "join", "object", "-h", "--help"]);
4712
+ function isCliAgentManagementCommand2(argument) {
4713
+ return argument !== void 0 && MANAGEMENT_COMMANDS.has(argument);
4714
+ }
4715
+ function cliAgentHookBinPath(binaryName) {
4716
+ return (0, hookRunner_1.hookRunnerPaths)(binaryName).launcher;
4717
+ }
4718
+ function cliAgentSelfCommand(spec) {
4719
+ return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName), os2.homedir());
4720
+ }
4721
+ function usage(spec) {
4722
+ return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
4723
+
4724
+ npx ${spec.packageName} setup [options]
4725
+ npx ${spec.packageName} status
4726
+ npx ${spec.packageName} doctor
4727
+ npx ${spec.packageName} uninstall
4728
+ npx ${spec.packageName} join <code>
4729
+ npx ${spec.packageName} object <purpose> [--undo]
4730
+
4731
+ Options
4732
+ --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
3092
4733
  --local [port] shorthand for the local dev server (default port 4477)
3093
4734
  --tool-installation-id <id> reuse an existing pairing instead of creating one
3094
4735
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
3095
4736
  --no-pair install without pairing: local features on, nothing sent
3096
- --scope project|user where hooks are registered (default project)
4737
+ --scope user|project where hooks are registered (default user: every project)
3097
4738
  --project-dir <path> project root for --scope project (default cwd)
3098
4739
  --dry-run print what would change, write nothing
3099
4740
  -h, --help
3100
4741
  `;
3101
4742
  }
3102
4743
  async function runCliAgentSetup2(argv, spec) {
4744
+ if (argv[0] === "join")
4745
+ return runCliAgentStudyJoin(argv.slice(1), spec);
4746
+ if (argv[0] === "object")
4747
+ return runCliAgentStudyObjection(argv.slice(1), spec);
3103
4748
  let options;
3104
4749
  try {
3105
4750
  options = parseArgs(argv, spec);
@@ -3112,32 +4757,29 @@ Options
3112
4757
  return 0;
3113
4758
  }
3114
4759
  if (options.action === "status")
3115
- return printStatus(options, spec);
4760
+ return await printStatus(options, spec);
3116
4761
  if (options.action === "uninstall")
3117
4762
  return uninstall(options, spec);
4763
+ if (options.action === "doctor")
4764
+ return await runDoctor(options, spec);
3118
4765
  const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3119
- console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
3120
- console.log(`
3121
- ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}
3122
- `);
4766
+ const ui = (0, terminalStyle_1.terminalStyle)();
4767
+ const row = (tone, label, value) => console.log(` ${ui.mark(tone)} ${label.padEnd(12)} ${value}`);
4768
+ const detail = (label, value) => console.log(ui.dim(` ${label.padEnd(12)} ${value}`));
4769
+ console.log(`${ui.bold("Ascenda setup")} ${ui.dim(`\xB7 ${spec.displayName} \xB7 ${apiBaseUrl}`)}`);
4770
+ if (!options.skipPairing)
4771
+ console.log(`
4772
+ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}`);
4773
+ console.log("");
3123
4774
  let identity;
3124
- let unpairedReason;
3125
- if (options.skipPairing) {
3126
- unpairedReason = "asked not to pair (--no-pair)";
3127
- } else {
4775
+ if (!options.skipPairing)
3128
4776
  identity = await resolveIdentity(apiBaseUrl, options, spec);
3129
- if (identity) {
3130
- console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
3131
- } else {
3132
- unpairedReason = "pairing did not finish \u2014 installing the local half anyway";
3133
- }
3134
- }
3135
- if (unpairedReason) {
3136
- console.log(` pairing none: ${unpairedReason}`);
3137
- console.log(" local features on, nothing is sent");
3138
- }
3139
4777
  const binary = installBinary(spec, options.dryRun);
3140
- console.log(` hook binary ${binary}`);
4778
+ const node = options.dryRun || process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
4779
+ if (node?.problem)
4780
+ row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os2.homedir())}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
4781
+ else
4782
+ row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os2.homedir())}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
3141
4783
  if (!options.dryRun) {
3142
4784
  const now = (/* @__PURE__ */ new Date()).toISOString();
3143
4785
  const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto.randomUUID()}`;
@@ -3147,27 +4789,76 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
3147
4789
  ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
3148
4790
  });
3149
4791
  }
3150
- console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
4792
+ if (isHomeProject(options)) {
4793
+ detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
4794
+ options.scope = "user";
4795
+ }
3151
4796
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4797
+ const before = registeredHookSets(readSettings(settingsFile), spec);
3152
4798
  const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
3153
4799
  if (written === null)
3154
4800
  return 1;
3155
- console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
4801
+ const reach = options.scope === "user" ? "every project" : "this project only";
4802
+ row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile, os2.homedir())} ${ui.dim(`(${spec.hookEvents.length} events, ${reach}${written ? "" : ", already current"})`)}`);
4803
+ const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
4804
+ if (changes)
4805
+ detail("", changes);
4806
+ const otherFile = spec.settings.settingsPath(options.scope === "user" ? "project" : "user", options.projectDir);
4807
+ if (otherFile !== settingsFile && registeredHookSets(readSettings(otherFile), spec).size > 0) {
4808
+ if (options.dryRun) {
4809
+ row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os2.homedir())}, so each event runs once`);
4810
+ } else if (removeOurHookEntries(otherFile, spec)) {
4811
+ row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os2.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
4812
+ } else {
4813
+ row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os2.homedir())} registers these hooks too, so each event runs twice.`);
4814
+ detail("", `Remove the ${spec.binaryName} entries from one of the two files.`);
4815
+ }
4816
+ }
4817
+ const chosenLocal = options.skipPairing;
4818
+ if (identity)
4819
+ row("ok", "pairing", `${identity.toolInstallationId}${ui.dim(identity.paired ? " (new)" : " (existing)")}`);
4820
+ else if (chosenLocal)
4821
+ row("info", "pairing", `none, as asked ${ui.dim("(--no-pair)")}`);
4822
+ else
4823
+ row("warn", "pairing", "not paired: pairing did not finish");
4824
+ detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os2.homedir())} (tools.${spec.host})`);
3156
4825
  if (options.dryRun) {
3157
- console.log("\nDry run \u2014 nothing was written.");
4826
+ console.log("\nDry run. Nothing was written.");
3158
4827
  return 0;
3159
4828
  }
3160
- console.log(`
3161
- Done. ${spec.restartHint}`);
3162
- if (!identity) {
3163
- console.log(`Pair later: npx ${spec.packageName} setup`);
4829
+ const self = cliAgentSelfCommand(spec);
4830
+ const next = (label, value) => console.log(` ${ui.bold(label.padEnd(6))} ${value}`);
4831
+ console.log("");
4832
+ if (chosenLocal) {
4833
+ console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
4834
+ console.log(" They run on this machine and need no account or pairing.");
4835
+ } else if (!identity) {
4836
+ console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
4837
+ console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
4838
+ } else {
4839
+ console.log(`${ui.mark("ok")} ${ui.bold("Done.")} Paired, and the hooks are installed.`);
4840
+ }
4841
+ console.log("");
4842
+ next("Next", spec.restartHint);
4843
+ next("Check", ui.cyan(`${self} doctor`));
4844
+ if (!identity)
4845
+ next(chosenLocal ? "Pair" : "Retry", `${ui.cyan(`${self} setup`)}${chosenLocal ? ui.dim(" (optional)") : ""}`);
4846
+ if (chosenLocal) {
4847
+ console.log("");
4848
+ console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account the"));
4849
+ console.log(ui.dim(" Ascenda app is signed in to when you confirm the code, so your sessions appear"));
4850
+ console.log(ui.dim(" in the app. Until you pair, nothing leaves this machine."));
4851
+ console.log("");
4852
+ console.log(ui.dim((0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName }).split("\n").map((line) => ` ${line}`).join("\n")));
3164
4853
  }
3165
- console.log(`Check anytime: npx ${spec.packageName} status`);
3166
4854
  return 0;
3167
4855
  }
4856
+ function isHomeProject(options) {
4857
+ return options.scope === "project" && path2.resolve(options.projectDir) === path2.resolve(os2.homedir());
4858
+ }
3168
4859
  function parseArgs(argv, spec) {
3169
4860
  const options = {
3170
- scope: "project",
4861
+ scope: "user",
3171
4862
  projectDir: process.cwd(),
3172
4863
  dryRun: false,
3173
4864
  skipPairing: false,
@@ -3192,6 +4883,9 @@ Done. ${spec.restartHint}`);
3192
4883
  case "uninstall":
3193
4884
  options.action = "uninstall";
3194
4885
  break;
4886
+ case "doctor":
4887
+ options.action = "doctor";
4888
+ break;
3195
4889
  case "--api-base-url":
3196
4890
  options.apiBaseUrl = next();
3197
4891
  break;
@@ -3240,6 +4934,45 @@ ${usage(spec)}`);
3240
4934
  }
3241
4935
  return options;
3242
4936
  }
4937
+ async function runCliAgentStudyJoin(argv, spec) {
4938
+ const joinCode = argv[0];
4939
+ if (!joinCode || joinCode.startsWith("-")) {
4940
+ console.error(`Usage: npx ${spec.packageName} join <code>`);
4941
+ return 1;
4942
+ }
4943
+ const pairing = resolvePairedToken(spec);
4944
+ if (!pairing)
4945
+ return 1;
4946
+ return (0, studyJoin_1.runStudyJoin)({ ...pairing, displayName: spec.displayName, joinCode });
4947
+ }
4948
+ async function runCliAgentStudyObjection(argv, spec) {
4949
+ const pairing = resolvePairedToken(spec);
4950
+ if (!pairing)
4951
+ return 1;
4952
+ return (0, studyNotices_1.runStudyObjection)({
4953
+ ...pairing,
4954
+ commandPrefix: `npx ${spec.packageName}`,
4955
+ pairCommand: `npx ${spec.packageName} setup`,
4956
+ argv
4957
+ });
4958
+ }
4959
+ function resolvePairedToken(spec) {
4960
+ const setupCommand = `npx ${spec.packageName} setup`;
4961
+ let toolInstallationId;
4962
+ try {
4963
+ ({ toolInstallationId } = (0, hookAdapter_1.resolveCliAgentInstallationId)(spec.toolType, { host: spec.host, setupCommand }));
4964
+ } catch (error) {
4965
+ console.error(error instanceof hookAdapter_1.MissingInstallationIdError ? error.message : error instanceof Error ? error.message : String(error));
4966
+ return void 0;
4967
+ }
4968
+ const eventWriteToken = (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId)) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
4969
+ if (!eventWriteToken) {
4970
+ console.error(`Not paired: no write token for ${toolInstallationId}. Run: ${setupCommand}`);
4971
+ return void 0;
4972
+ }
4973
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4974
+ return { apiBaseUrl, eventWriteToken };
4975
+ }
3243
4976
  async function resolveIdentity(apiBaseUrl, options, spec) {
3244
4977
  const existingId = options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId;
3245
4978
  if (existingId && options.token) {
@@ -3247,8 +4980,13 @@ ${usage(spec)}`);
3247
4980
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(existingId), options.token);
3248
4981
  return { toolInstallationId: existingId, paired: false };
3249
4982
  }
3250
- if (existingId && (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId))) {
3251
- return { toolInstallationId: existingId, paired: false };
4983
+ const existingToken = existingId ? (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId)) : void 0;
4984
+ if (existingId && existingToken) {
4985
+ const check = await checkSavedToken(apiBaseUrl, existingId, existingToken);
4986
+ if (check === "keep")
4987
+ return { toolInstallationId: existingId, paired: false };
4988
+ console.log(`
4989
+ The saved token for ${existingId} isn't accepted any more. Pairing again.`);
3252
4990
  }
3253
4991
  if (options.dryRun) {
3254
4992
  return { toolInstallationId: existingId ?? `${spec.toolType}:<paired at run time>`, paired: false };
@@ -3269,6 +5007,18 @@ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message
3269
5007
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(toolInstallationId), token);
3270
5008
  return { toolInstallationId, paired: true };
3271
5009
  }
5010
+ var TOKEN_CHECK_TIMEOUT_MS = 5e3;
5011
+ async function checkSavedToken(apiBaseUrl, toolInstallationId, token) {
5012
+ const read = await (0, http_1.readInitiatives)(apiBaseUrl, token, AbortSignal.timeout(TOKEN_CHECK_TIMEOUT_MS));
5013
+ if (read.kind === "rejected")
5014
+ return "repair";
5015
+ if (read.kind === "failed" && (0, stateStore_1.readCollectorState)((0, stateStore_1.defaultStateFilePath)(toolInstallationId))?.lastOutcome === "auth_failed") {
5016
+ console.log(`
5017
+ Couldn't check the saved token (${read.reason}), and the last send was refused.`);
5018
+ console.log(" Keeping it for now. Run setup again once the server is reachable.");
5019
+ }
5020
+ return "keep";
5021
+ }
3272
5022
  async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
3273
5023
  const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
3274
5024
  let announced = false;
@@ -3293,17 +5043,7 @@ Pairing ${status.status}. Run setup again.`);
3293
5043
  return void 0;
3294
5044
  }
3295
5045
  function installBinary(spec, dryRun) {
3296
- const target = cliAgentHookBinPath(spec.binaryName);
3297
- if (dryRun)
3298
- return target;
3299
- const source = process.argv[1];
3300
- fs.mkdirSync(path2.dirname(target), { recursive: true });
3301
- if (path2.resolve(source) !== path2.resolve(target)) {
3302
- fs.copyFileSync(source, target);
3303
- }
3304
- if (process.platform !== "win32")
3305
- fs.chmodSync(target, 493);
3306
- return target;
5046
+ return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
3307
5047
  }
3308
5048
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
3309
5049
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -3320,7 +5060,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
3320
5060
  }
3321
5061
  }
3322
5062
  }
3323
- const command = hookCommand(binary);
5063
+ const command = hookCommand(binary, spec);
3324
5064
  const hooks = { ...settings.hooks ?? {} };
3325
5065
  for (const event of spec.hookEvents) {
3326
5066
  const kept = (hooks[event] ?? []).filter((entry) => !isOurs(entry, spec));
@@ -3343,8 +5083,20 @@ ${serialised}`);
3343
5083
  fs.writeFileSync(settingsFile, serialised, "utf8");
3344
5084
  return true;
3345
5085
  }
3346
- function hookCommand(binary) {
3347
- return `"${process.execPath}" "${binary}"`;
5086
+ function hookCommand(binary, spec) {
5087
+ return `${(0, hookRunner_1.hookRunnerCommand)(binary)}${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
5088
+ }
5089
+ function registeredHookSets(settings, spec) {
5090
+ const sets = /* @__PURE__ */ new Map();
5091
+ for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
5092
+ for (const entry of entries ?? []) {
5093
+ if (!isOurs(entry, spec))
5094
+ continue;
5095
+ const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
5096
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5097
+ }
5098
+ }
5099
+ return sets;
3348
5100
  }
3349
5101
  function isOurs(entry, spec) {
3350
5102
  const command = spec.settings.commandOf(entry);
@@ -3371,7 +5123,7 @@ ${serialised}`);
3371
5123
  return {};
3372
5124
  }
3373
5125
  }
3374
- function printStatus(options, spec) {
5126
+ async function printStatus(options, spec) {
3375
5127
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
3376
5128
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3377
5129
  const binary = cliAgentHookBinPath(spec.binaryName);
@@ -3385,46 +5137,153 @@ ${serialised}`);
3385
5137
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
3386
5138
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
3387
5139
  console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
5140
+ const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5141
+ if (node) {
5142
+ console.log(node.problem ? `node \u2014 ${node.problem}. Install Node 20 or newer, then run setup again` : `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
5143
+ }
5144
+ const last = (0, hookRunner_1.readLastHook)(spec.host);
5145
+ console.log(last ? `last hook ${last.event}, ${(0, hookRunner_1.describeAge)(Date.now() - Date.parse(last.at))}` : `last hook \u2014 none has run yet. Start ${spec.displayName} (restart it if it was open during setup)`);
3388
5146
  console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
5147
+ const otherScope = options.scope === "user" ? "project" : "user";
5148
+ const otherFile = spec.settings.settingsPath(otherScope, options.projectDir);
5149
+ const elsewhere = registered === 0 && otherFile !== settingsFile ? countRegistered(readSettings(otherFile), spec) : 0;
5150
+ if (elsewhere > 0)
5151
+ console.log(` ${elsewhere}/${spec.hookEvents.length} found in ${otherFile} (--scope ${otherScope})`);
5152
+ if (spec.hookSet !== void 0 && registered > 0) {
5153
+ const sets = [...registeredHookSets(settings, spec).values()];
5154
+ const oldest = Math.min(...sets);
5155
+ 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)`);
5156
+ }
3389
5157
  if (stale.length) {
3390
5158
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
3391
5159
  for (const command of stale)
3392
5160
  console.log(` ${command}`);
3393
5161
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
3394
5162
  }
5163
+ const tokenValue = localOnly ? void 0 : (tokenFile ? (0, tokenStore_1.readTokenFile)(tokenFile) : void 0) ?? (process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim() || void 0);
5164
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
5165
+ const [initiativeLines, notices] = await Promise.all([
5166
+ (0, initiatives_1.initiativesStatusLines)({ apiBaseUrl, eventWriteToken: tokenValue, pairCommand: `npx ${spec.packageName} setup` }),
5167
+ (0, studyNotices_1.studyNoticeStatus)({ apiBaseUrl, eventWriteToken: tokenValue, commandPrefix: `npx ${spec.packageName}` })
5168
+ ]);
5169
+ console.log("");
5170
+ for (const line of initiativeLines)
5171
+ console.log(line);
5172
+ for (const line of notices.lines)
5173
+ console.log(line);
5174
+ if (process.stdout.isTTY)
5175
+ await notices.markShown();
3395
5176
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
3396
- const healthy = paired && registered === spec.hookEvents.length && fs.existsSync(binary) && !stale.length;
5177
+ const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5178
+ const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
3397
5179
  return healthy ? 0 : 1;
3398
5180
  }
5181
+ function countRegistered(settings, spec) {
5182
+ return spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs(entry, spec))).length;
5183
+ }
5184
+ function cliAgentRegistrations(spec, projectDir = process.cwd()) {
5185
+ const home = os2.homedir();
5186
+ const userFile = spec.settings.settingsPath("user", projectDir);
5187
+ const projectFile = spec.settings.settingsPath("project", projectDir);
5188
+ const found = [];
5189
+ for (const [scope, file] of [["user", userFile], ["project", projectFile]]) {
5190
+ if (scope === "project" && file === userFile)
5191
+ continue;
5192
+ const registered = countRegistered(readSettings(file), spec);
5193
+ if (registered === 0)
5194
+ continue;
5195
+ found.push({
5196
+ file: (0, hookRunner_1.tidyHomePath)(file, home),
5197
+ registered,
5198
+ scope,
5199
+ homeProject: scope === "project" && path2.resolve(projectDir) === path2.resolve(home)
5200
+ });
5201
+ }
5202
+ return found;
5203
+ }
5204
+ async function runDoctor(options, spec) {
5205
+ const ui = (0, terminalStyle_1.terminalStyle)();
5206
+ const lines = [`${ui.bold("Ascenda doctor")} ${ui.dim(`\xB7 ${spec.displayName}`)}`, ""];
5207
+ try {
5208
+ lines.push(...await (0, liveSignalDoctor_1.liveSignalDoctorLines)({
5209
+ displayName: spec.displayName,
5210
+ tool: spec.host,
5211
+ launcher: process.platform === "win32" ? void 0 : cliAgentHookBinPath(spec.binaryName),
5212
+ registrations: cliAgentRegistrations(spec, options.projectDir),
5213
+ eventCount: spec.hookEvents.length,
5214
+ selfCommand: cliAgentSelfCommand(spec),
5215
+ setupCommand: `npx ${spec.packageName} setup`,
5216
+ ui
5217
+ }));
5218
+ } catch (error) {
5219
+ lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
5220
+ }
5221
+ lines.push("", ...accountLines(ui, spec));
5222
+ console.log(lines.join("\n"));
5223
+ return 0;
5224
+ }
5225
+ function accountLines(ui, spec) {
5226
+ const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5227
+ const id = credentials?.toolInstallationId;
5228
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (installationId) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(installationId)) !== void 0);
5229
+ const row = (tone, label, value) => ` ${ui.mark(tone)} ${label.padEnd(20)} ${value}`;
5230
+ if (!id || localOnly) {
5231
+ return [
5232
+ ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}`,
5233
+ ...id ? [ui.dim(row("info", "Installation id", id))] : [],
5234
+ "",
5235
+ " Not paired, which is fine: the screen saver and the live view above work",
5236
+ " without it. Nothing leaves this machine and nothing is queued. To send your",
5237
+ " sessions to Ascenda's servers, so they appear in the app:",
5238
+ ` ${ui.cyan(`${cliAgentSelfCommand(spec)} setup`)}`
5239
+ ];
5240
+ }
5241
+ const token = (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim();
5242
+ const state = (0, stateStore_1.readCollectorState)((0, stateStore_1.defaultStateFilePath)(id));
5243
+ const outcome = state?.lastOutcome;
5244
+ return [
5245
+ ` ${ui.bold("Account sync")}`,
5246
+ row("info", "Installation id", id),
5247
+ token ? row("ok", "Token", "present") : row("bad", "Token", ui.red(`missing, so nothing can be sent. Run: npx ${spec.packageName} setup`)),
5248
+ outcome ? row(outcome === "accepted" ? "ok" : "warn", "Last send", `${outcome}${state?.lastAttemptAt ? ui.dim(` (${state.lastAttemptAt})`) : ""}`) : row("info", "Last send", "none yet")
5249
+ ];
5250
+ }
5251
+ function removeOurHookEntries(settingsFile, spec) {
5252
+ if (!fs.existsSync(settingsFile))
5253
+ return true;
5254
+ try {
5255
+ const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
5256
+ const hooks = { ...settings.hooks ?? {} };
5257
+ for (const event of Object.keys(hooks)) {
5258
+ const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
5259
+ if (kept.length)
5260
+ hooks[event] = kept;
5261
+ else
5262
+ delete hooks[event];
5263
+ }
5264
+ const updated = { ...settings, hooks };
5265
+ if (!Object.keys(hooks).length)
5266
+ delete updated.hooks;
5267
+ fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5268
+ fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5269
+ `, "utf8");
5270
+ return true;
5271
+ } catch {
5272
+ return false;
5273
+ }
5274
+ }
3399
5275
  function uninstall(options, spec) {
3400
5276
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3401
5277
  if (fs.existsSync(settingsFile)) {
3402
- try {
3403
- const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
3404
- const hooks = { ...settings.hooks ?? {} };
3405
- for (const event of Object.keys(hooks)) {
3406
- const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
3407
- if (kept.length)
3408
- hooks[event] = kept;
3409
- else
3410
- delete hooks[event];
3411
- }
3412
- const updated = { ...settings, hooks };
3413
- if (!Object.keys(hooks).length)
3414
- delete updated.hooks;
3415
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3416
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
3417
- `, "utf8");
3418
- console.log(`hooks removed from ${settingsFile}`);
3419
- } catch {
5278
+ if (!removeOurHookEntries(settingsFile, spec)) {
3420
5279
  console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
3421
5280
  return 1;
3422
5281
  }
5282
+ console.log(`hooks removed from ${settingsFile}`);
3423
5283
  }
3424
- const binary = cliAgentHookBinPath(spec.binaryName);
3425
- if (fs.existsSync(binary)) {
3426
- fs.rmSync(binary);
3427
- console.log(`removed ${binary}`);
5284
+ for (const file of (0, hookRunner_1.removeHookRunner)(spec.binaryName)) {
5285
+ if (!file.endsWith(".node") && !file.endsWith(".no-node"))
5286
+ console.log(`removed ${file}`);
3428
5287
  }
3429
5288
  if ((0, credentials_1.readHostCredentials)(spec.host)) {
3430
5289
  (0, credentials_1.removeHostCredentials)(spec.host);
@@ -3516,9 +5375,9 @@ var require_turnState = __commonJS({
3516
5375
  }
3517
5376
  });
3518
5377
 
3519
- // ../packages/tool-kit/out/liveBus.js
3520
- var require_liveBus = __commonJS({
3521
- "../packages/tool-kit/out/liveBus.js"(exports) {
5378
+ // ../packages/tool-kit/out/agentProcess.js
5379
+ var require_agentProcess = __commonJS({
5380
+ "../packages/tool-kit/out/agentProcess.js"(exports) {
3522
5381
  "use strict";
3523
5382
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3524
5383
  if (k2 === void 0) k2 = k;
@@ -3558,123 +5417,99 @@ var require_liveBus = __commonJS({
3558
5417
  };
3559
5418
  }();
3560
5419
  Object.defineProperty(exports, "__esModule", { value: true });
3561
- exports.liveBusSocketCandidates = liveBusSocketCandidates;
3562
- exports.liveBusSocketPath = liveBusSocketPath;
3563
- exports.bucketPromptSize = bucketPromptSize2;
3564
- exports.emitLiveSignal = emitLiveSignal2;
3565
- var fs = __importStar(__require("fs"));
3566
- var net = __importStar(__require("net"));
3567
- var os2 = __importStar(__require("os"));
5420
+ exports.psArgsLookup = exports.psLookup = exports.AGENT_PROCESS = void 0;
5421
+ exports.scriptMarkerIn = scriptMarkerIn;
5422
+ exports.findAgentProcess = findAgentProcess;
5423
+ exports.findAgentPid = findAgentPid2;
5424
+ exports.livePidFields = livePidFields;
5425
+ var child_process_1 = __require("child_process");
3568
5426
  var path2 = __importStar(__require("path"));
3569
- var WRITE_TIMEOUT_MS = 50;
3570
- var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
3571
- var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3572
- function liveBusSocketCandidates() {
3573
- const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
3574
- if (override)
3575
- return [override];
3576
- const home = os2.homedir();
3577
- return [
3578
- path2.join(home, ".ascenda", "live.sock"),
3579
- path2.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
3580
- path2.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
3581
- ];
5427
+ exports.AGENT_PROCESS = {
5428
+ claude_code: {
5429
+ executable: (command) => path2.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
5430
+ scriptMarkers: ["@anthropic-ai/claude-code"]
5431
+ },
5432
+ codex: {
5433
+ executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path2.basename(command)),
5434
+ args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
5435
+ },
5436
+ gemini_cli: {
5437
+ executable: () => false,
5438
+ args: (args) => !/\s--(experimental-)?acp(\s|=|$)/.test(args),
5439
+ scriptMarkers: ["@google/gemini-cli"]
5440
+ }
5441
+ };
5442
+ var SCRIPT_RUNTIME = /^(node|bun|deno)$/;
5443
+ function scriptMarkerIn(args, markers) {
5444
+ return markers.find((marker) => args.includes(`/${marker}/`));
3582
5445
  }
3583
- function existingSocketCandidates() {
3584
- const candidates = liveBusSocketCandidates();
3585
- if (process.env.ASCENDA_LIVE_BUS_SOCKET)
3586
- return candidates;
3587
- return candidates.filter((candidate) => {
3588
- try {
3589
- return fs.statSync(candidate).isSocket();
3590
- } catch {
3591
- return false;
5446
+ var MAX_DEPTH = 6;
5447
+ var PS_TIMEOUT_MS = 100;
5448
+ function ps(columns, pid) {
5449
+ try {
5450
+ const result = (0, child_process_1.spawnSync)("/bin/ps", ["-o", columns, "-p", String(pid)], {
5451
+ encoding: "utf8",
5452
+ timeout: PS_TIMEOUT_MS
5453
+ });
5454
+ if (result.status !== 0 || typeof result.stdout !== "string")
5455
+ return void 0;
5456
+ const line = result.stdout.trim();
5457
+ return line === "" ? void 0 : line;
5458
+ } catch {
5459
+ return void 0;
5460
+ }
5461
+ }
5462
+ var psLookup = (pid) => {
5463
+ const line = ps("ppid=,comm=", pid);
5464
+ const match = line ? /^(\d+)\s+(.+)$/.exec(line) : null;
5465
+ return match ? { ppid: Number(match[1]), command: match[2] } : void 0;
5466
+ };
5467
+ exports.psLookup = psLookup;
5468
+ var psArgsLookup = (pid) => ps("args=", pid);
5469
+ exports.psArgsLookup = psArgsLookup;
5470
+ function findAgentProcess(rule, options = {}) {
5471
+ if (!rule)
5472
+ return void 0;
5473
+ if ((options.platform ?? process.platform) !== "darwin")
5474
+ return void 0;
5475
+ const lookup = options.lookup ?? exports.psLookup;
5476
+ const argsLookup = options.argsLookup ?? exports.psArgsLookup;
5477
+ const markers = rule.scriptMarkers ?? [];
5478
+ let pid = options.startPid ?? process.ppid;
5479
+ for (let depth = 0; depth < MAX_DEPTH && pid > 1; depth++) {
5480
+ const info = lookup(pid);
5481
+ if (!info)
5482
+ return void 0;
5483
+ if (pid !== process.pid) {
5484
+ if (rule.executable(info.command)) {
5485
+ return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
5486
+ }
5487
+ if (markers.length > 0 && SCRIPT_RUNTIME.test(path2.basename(info.command))) {
5488
+ const args = argsLookup(pid);
5489
+ const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
5490
+ if (marker !== void 0) {
5491
+ return accepts(rule, args) ? { pid, match: "path", marker } : void 0;
5492
+ }
5493
+ }
3592
5494
  }
3593
- });
5495
+ pid = info.ppid;
5496
+ }
5497
+ return void 0;
3594
5498
  }
3595
- function liveBusSocketPath() {
3596
- return existingSocketCandidates()[0] ?? liveBusSocketCandidates()[0];
5499
+ function accepts(rule, args) {
5500
+ if (!rule.args)
5501
+ return true;
5502
+ return args !== void 0 && rule.args(args);
3597
5503
  }
3598
- function bucketPromptSize2(text) {
3599
- const length = typeof text === "string" ? text.length : 0;
3600
- if (length <= 280)
3601
- return "s";
3602
- if (length <= 2e3)
3603
- return "m";
3604
- if (length <= 8e3)
3605
- return "l";
3606
- return "xl";
5504
+ function findAgentPid2(rule, options = {}) {
5505
+ return findAgentProcess(rule, options)?.pid;
3607
5506
  }
3608
- var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
3609
- function emitLiveSignal2(signal) {
3610
- return new Promise((resolve) => {
3611
- const candidates = existingSocketCandidates();
3612
- if (candidates.length === 0) {
3613
- resolve();
3614
- return;
3615
- }
3616
- let settled = false;
3617
- let socket;
3618
- const drop = () => {
3619
- try {
3620
- socket?.destroy();
3621
- } catch {
3622
- }
3623
- socket = void 0;
3624
- };
3625
- const done = () => {
3626
- if (settled)
3627
- return;
3628
- settled = true;
3629
- clearTimeout(timer);
3630
- drop();
3631
- resolve();
3632
- };
3633
- const timer = setTimeout(done, WRITE_TIMEOUT_MS);
3634
- if (typeof timer.unref === "function")
3635
- timer.unref();
3636
- const tryFrom = (index) => {
3637
- if (settled)
3638
- return;
3639
- if (index >= candidates.length) {
3640
- done();
3641
- return;
3642
- }
3643
- let attempt;
3644
- try {
3645
- attempt = net.createConnection(candidates[index]);
3646
- } catch {
3647
- tryFrom(index + 1);
3648
- return;
3649
- }
3650
- socket = attempt;
3651
- if (typeof attempt.unref === "function")
3652
- attempt.unref();
3653
- let connected = false;
3654
- attempt.on("error", (error) => {
3655
- if (settled || socket !== attempt)
3656
- return;
3657
- if (!connected && error.code && NOBODY_LISTENING.has(error.code)) {
3658
- drop();
3659
- tryFrom(index + 1);
3660
- return;
3661
- }
3662
- done();
3663
- });
3664
- attempt.on("connect", () => {
3665
- if (settled || socket !== attempt)
3666
- return;
3667
- connected = true;
3668
- try {
3669
- attempt.write(`${JSON.stringify(signal)}
3670
- `, done);
3671
- } catch {
3672
- done();
3673
- }
3674
- });
3675
- };
3676
- tryFrom(0);
3677
- });
5507
+ function livePidFields(match) {
5508
+ if (!match)
5509
+ return {};
5510
+ if (match.match === "executable")
5511
+ return { pid: match.pid };
5512
+ return { pid: match.pid, pidMatch: "path", pidMarker: match.marker };
3678
5513
  }
3679
5514
  }
3680
5515
  });
@@ -3684,9 +5519,10 @@ var require_out2 = __commonJS({
3684
5519
  "../packages/tool-kit/out/index.js"(exports) {
3685
5520
  "use strict";
3686
5521
  Object.defineProperty(exports, "__esModule", { value: true });
3687
- 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;
3688
- 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;
3689
- 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;
5522
+ 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;
5523
+ 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;
5524
+ exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
5525
+ 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 = void 0;
3690
5526
  var commandClassifier_1 = require_commandClassifier();
3691
5527
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
3692
5528
  return commandClassifier_1.classifyCommand;
@@ -3784,6 +5620,9 @@ var require_out2 = __commonJS({
3784
5620
  Object.defineProperty(exports, "AscendaSemanticEventError", { enumerable: true, get: function() {
3785
5621
  return eventSender_1.AscendaSemanticEventError;
3786
5622
  } });
5623
+ Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
5624
+ return eventSender_1.TOKEN_RENEW_LEAD_MS;
5625
+ } });
3787
5626
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
3788
5627
  return eventSender_1.buildEventPayload;
3789
5628
  } });
@@ -3829,6 +5668,9 @@ var require_out2 = __commonJS({
3829
5668
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
3830
5669
  return cliAgentSetup_1.isCliAgentManagementCommand;
3831
5670
  } });
5671
+ Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5672
+ return cliAgentSetup_1.registeredHookSets;
5673
+ } });
3832
5674
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
3833
5675
  return cliAgentSetup_1.runCliAgentSetup;
3834
5676
  } });
@@ -3884,6 +5726,9 @@ var require_out2 = __commonJS({
3884
5726
  return turnState_1.recordTurnStart;
3885
5727
  } });
3886
5728
  var tokenStore_1 = require_tokenStore();
5729
+ Object.defineProperty(exports, "EVENT_TOKEN_TTL_MS", { enumerable: true, get: function() {
5730
+ return tokenStore_1.EVENT_TOKEN_TTL_MS;
5731
+ } });
3887
5732
  Object.defineProperty(exports, "ascendaHome", { enumerable: true, get: function() {
3888
5733
  return tokenStore_1.ascendaHome;
3889
5734
  } });
@@ -3896,9 +5741,15 @@ var require_out2 = __commonJS({
3896
5741
  Object.defineProperty(exports, "persistEventWriteToken", { enumerable: true, get: function() {
3897
5742
  return tokenStore_1.persistEventWriteToken;
3898
5743
  } });
5744
+ Object.defineProperty(exports, "readTokenExpiry", { enumerable: true, get: function() {
5745
+ return tokenStore_1.readTokenExpiry;
5746
+ } });
3899
5747
  Object.defineProperty(exports, "readTokenFile", { enumerable: true, get: function() {
3900
5748
  return tokenStore_1.readTokenFile;
3901
5749
  } });
5750
+ Object.defineProperty(exports, "tokenExpiryFilePath", { enumerable: true, get: function() {
5751
+ return tokenStore_1.tokenExpiryFilePath;
5752
+ } });
3902
5753
  var stateStore_1 = require_stateStore();
3903
5754
  Object.defineProperty(exports, "defaultStateFilePath", { enumerable: true, get: function() {
3904
5755
  return stateStore_1.defaultStateFilePath;
@@ -4021,6 +5872,9 @@ var require_out2 = __commonJS({
4021
5872
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
4022
5873
  return liveBus_1.emitLiveSignal;
4023
5874
  } });
5875
+ Object.defineProperty(exports, "deliverLine", { enumerable: true, get: function() {
5876
+ return liveBus_1.deliverLine;
5877
+ } });
4024
5878
  Object.defineProperty(exports, "bucketPromptSize", { enumerable: true, get: function() {
4025
5879
  return liveBus_1.bucketPromptSize;
4026
5880
  } });
@@ -4030,6 +5884,138 @@ var require_out2 = __commonJS({
4030
5884
  Object.defineProperty(exports, "liveBusSocketCandidates", { enumerable: true, get: function() {
4031
5885
  return liveBus_1.liveBusSocketCandidates;
4032
5886
  } });
5887
+ Object.defineProperty(exports, "LIVE_BUS_BACKGROUND_TRUST_MS", { enumerable: true, get: function() {
5888
+ return liveBus_1.LIVE_BUS_BACKGROUND_TRUST_MS;
5889
+ } });
5890
+ var saverHandoff_1 = require_saverHandoff();
5891
+ Object.defineProperty(exports, "holdForSaver", { enumerable: true, get: function() {
5892
+ return saverHandoff_1.holdForSaver;
5893
+ } });
5894
+ Object.defineProperty(exports, "heldForSaver", { enumerable: true, get: function() {
5895
+ return saverHandoff_1.heldForSaver;
5896
+ } });
5897
+ Object.defineProperty(exports, "probeSocket", { enumerable: true, get: function() {
5898
+ return saverHandoff_1.probeSocket;
5899
+ } });
5900
+ Object.defineProperty(exports, "readSaverStatuses", { enumerable: true, get: function() {
5901
+ return saverHandoff_1.readSaverStatuses;
5902
+ } });
5903
+ Object.defineProperty(exports, "saverContainerDir", { enumerable: true, get: function() {
5904
+ return saverHandoff_1.saverContainerDir;
5905
+ } });
5906
+ Object.defineProperty(exports, "saverReplayPath", { enumerable: true, get: function() {
5907
+ return saverHandoff_1.saverReplayPath;
5908
+ } });
5909
+ Object.defineProperty(exports, "saverStatusDir", { enumerable: true, get: function() {
5910
+ return saverHandoff_1.saverStatusDir;
5911
+ } });
5912
+ Object.defineProperty(exports, "saverSupportDir", { enumerable: true, get: function() {
5913
+ return saverHandoff_1.saverSupportDir;
5914
+ } });
5915
+ Object.defineProperty(exports, "SAVER_REPLAY_WINDOW_MS", { enumerable: true, get: function() {
5916
+ return saverHandoff_1.SAVER_REPLAY_WINDOW_MS;
5917
+ } });
5918
+ var terminalStyle_1 = require_terminalStyle();
5919
+ Object.defineProperty(exports, "colourEnabled", { enumerable: true, get: function() {
5920
+ return terminalStyle_1.colourEnabled;
5921
+ } });
5922
+ Object.defineProperty(exports, "terminalStyle", { enumerable: true, get: function() {
5923
+ return terminalStyle_1.terminalStyle;
5924
+ } });
5925
+ var hookRunner_1 = require_hookRunner();
5926
+ Object.defineProperty(exports, "describeAge", { enumerable: true, get: function() {
5927
+ return hookRunner_1.describeAge;
5928
+ } });
5929
+ Object.defineProperty(exports, "hookLauncherScript", { enumerable: true, get: function() {
5930
+ return hookRunner_1.hookLauncherScript;
5931
+ } });
5932
+ Object.defineProperty(exports, "hookRunnerCommand", { enumerable: true, get: function() {
5933
+ return hookRunner_1.hookRunnerCommand;
5934
+ } });
5935
+ Object.defineProperty(exports, "hookRunnerPaths", { enumerable: true, get: function() {
5936
+ return hookRunner_1.hookRunnerPaths;
5937
+ } });
5938
+ Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
5939
+ return hookRunner_1.installHookRunner;
5940
+ } });
5941
+ Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
5942
+ return hookRunner_1.lastHookPath;
5943
+ } });
5944
+ Object.defineProperty(exports, "readLastHook", { enumerable: true, get: function() {
5945
+ return hookRunner_1.readLastHook;
5946
+ } });
5947
+ Object.defineProperty(exports, "removeHookRunner", { enumerable: true, get: function() {
5948
+ return hookRunner_1.removeHookRunner;
5949
+ } });
5950
+ Object.defineProperty(exports, "resolveHookNode", { enumerable: true, get: function() {
5951
+ return hookRunner_1.resolveHookNode;
5952
+ } });
5953
+ Object.defineProperty(exports, "stampLastHook", { enumerable: true, get: function() {
5954
+ return hookRunner_1.stampLastHook;
5955
+ } });
5956
+ Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
5957
+ return hookRunner_1.tidyHomePath;
5958
+ } });
5959
+ var liveSignalDoctor_1 = require_liveSignalDoctor();
5960
+ Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
5961
+ return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
5962
+ } });
5963
+ Object.defineProperty(exports, "doctorRow", { enumerable: true, get: function() {
5964
+ return liveSignalDoctor_1.doctorRow;
5965
+ } });
5966
+ Object.defineProperty(exports, "liveSignalDoctorLines", { enumerable: true, get: function() {
5967
+ return liveSignalDoctor_1.liveSignalDoctorLines;
5968
+ } });
5969
+ var hookSet_1 = require_hookSet();
5970
+ Object.defineProperty(exports, "HOOK_SET_FLAG", { enumerable: true, get: function() {
5971
+ return hookSet_1.HOOK_SET_FLAG;
5972
+ } });
5973
+ Object.defineProperty(exports, "UNVERSIONED_HOOK_SET", { enumerable: true, get: function() {
5974
+ return hookSet_1.UNVERSIONED_HOOK_SET;
5975
+ } });
5976
+ Object.defineProperty(exports, "describeHookSetChanges", { enumerable: true, get: function() {
5977
+ return hookSet_1.describeHookSetChanges;
5978
+ } });
5979
+ Object.defineProperty(exports, "hookSetArgument", { enumerable: true, get: function() {
5980
+ return hookSet_1.hookSetArgument;
5981
+ } });
5982
+ Object.defineProperty(exports, "hookSetChanges", { enumerable: true, get: function() {
5983
+ return hookSet_1.hookSetChanges;
5984
+ } });
5985
+ Object.defineProperty(exports, "hookSetOfCommand", { enumerable: true, get: function() {
5986
+ return hookSet_1.hookSetOfCommand;
5987
+ } });
5988
+ Object.defineProperty(exports, "isHookSet", { enumerable: true, get: function() {
5989
+ return hookSet_1.isHookSet;
5990
+ } });
5991
+ Object.defineProperty(exports, "readHookSet", { enumerable: true, get: function() {
5992
+ return hookSet_1.readHookSet;
5993
+ } });
5994
+ Object.defineProperty(exports, "readViaPlugin", { enumerable: true, get: function() {
5995
+ return hookSet_1.readViaPlugin;
5996
+ } });
5997
+ var agentProcess_1 = require_agentProcess();
5998
+ Object.defineProperty(exports, "AGENT_PROCESS", { enumerable: true, get: function() {
5999
+ return agentProcess_1.AGENT_PROCESS;
6000
+ } });
6001
+ Object.defineProperty(exports, "findAgentPid", { enumerable: true, get: function() {
6002
+ return agentProcess_1.findAgentPid;
6003
+ } });
6004
+ Object.defineProperty(exports, "findAgentProcess", { enumerable: true, get: function() {
6005
+ return agentProcess_1.findAgentProcess;
6006
+ } });
6007
+ Object.defineProperty(exports, "livePidFields", { enumerable: true, get: function() {
6008
+ return agentProcess_1.livePidFields;
6009
+ } });
6010
+ Object.defineProperty(exports, "psArgsLookup", { enumerable: true, get: function() {
6011
+ return agentProcess_1.psArgsLookup;
6012
+ } });
6013
+ Object.defineProperty(exports, "psLookup", { enumerable: true, get: function() {
6014
+ return agentProcess_1.psLookup;
6015
+ } });
6016
+ Object.defineProperty(exports, "scriptMarkerIn", { enumerable: true, get: function() {
6017
+ return agentProcess_1.scriptMarkerIn;
6018
+ } });
4033
6019
  var http_1 = require_http();
4034
6020
  Object.defineProperty(exports, "AscendaApiError", { enumerable: true, get: function() {
4035
6021
  return http_1.AscendaApiError;
@@ -4040,6 +6026,9 @@ var require_out2 = __commonJS({
4040
6026
  Object.defineProperty(exports, "getPairingStatus", { enumerable: true, get: function() {
4041
6027
  return http_1.getPairingStatus;
4042
6028
  } });
6029
+ Object.defineProperty(exports, "getStudyJoinStatus", { enumerable: true, get: function() {
6030
+ return http_1.getStudyJoinStatus;
6031
+ } });
4043
6032
  Object.defineProperty(exports, "renewToolToken", { enumerable: true, get: function() {
4044
6033
  return http_1.renewToolToken;
4045
6034
  } });
@@ -4055,6 +6044,48 @@ var require_out2 = __commonJS({
4055
6044
  Object.defineProperty(exports, "isRetryableStatus", { enumerable: true, get: function() {
4056
6045
  return http_1.isRetryableStatus;
4057
6046
  } });
6047
+ Object.defineProperty(exports, "readInitiatives", { enumerable: true, get: function() {
6048
+ return http_1.readInitiatives;
6049
+ } });
6050
+ Object.defineProperty(exports, "readStudyNotices", { enumerable: true, get: function() {
6051
+ return http_1.readStudyNotices;
6052
+ } });
6053
+ Object.defineProperty(exports, "markStudyNoticeShown", { enumerable: true, get: function() {
6054
+ return http_1.markStudyNoticeShown;
6055
+ } });
6056
+ Object.defineProperty(exports, "setStudyObjection", { enumerable: true, get: function() {
6057
+ return http_1.setStudyObjection;
6058
+ } });
6059
+ Object.defineProperty(exports, "startStudyJoin", { enumerable: true, get: function() {
6060
+ return http_1.startStudyJoin;
6061
+ } });
6062
+ var initiatives_1 = require_initiatives();
6063
+ Object.defineProperty(exports, "INITIATIVE_COPY", { enumerable: true, get: function() {
6064
+ return initiatives_1.INITIATIVE_COPY;
6065
+ } });
6066
+ Object.defineProperty(exports, "initiativesStatusLines", { enumerable: true, get: function() {
6067
+ return initiatives_1.initiativesStatusLines;
6068
+ } });
6069
+ Object.defineProperty(exports, "renderInitiatives", { enumerable: true, get: function() {
6070
+ return initiatives_1.renderInitiatives;
6071
+ } });
6072
+ var studyNotices_1 = require_studyNotices();
6073
+ Object.defineProperty(exports, "NOTICED_PURPOSES", { enumerable: true, get: function() {
6074
+ return studyNotices_1.NOTICED_PURPOSES;
6075
+ } });
6076
+ Object.defineProperty(exports, "renderStudyNotices", { enumerable: true, get: function() {
6077
+ return studyNotices_1.renderStudyNotices;
6078
+ } });
6079
+ Object.defineProperty(exports, "runStudyObjection", { enumerable: true, get: function() {
6080
+ return studyNotices_1.runStudyObjection;
6081
+ } });
6082
+ Object.defineProperty(exports, "studyNoticeStatus", { enumerable: true, get: function() {
6083
+ return studyNotices_1.studyNoticeStatus;
6084
+ } });
6085
+ var studyJoin_1 = require_studyJoin();
6086
+ Object.defineProperty(exports, "runStudyJoin", { enumerable: true, get: function() {
6087
+ return studyJoin_1.runStudyJoin;
6088
+ } });
4058
6089
  }
4059
6090
  });
4060
6091
 
@@ -4222,6 +6253,8 @@ function liveSignalFor(hookName, input) {
4222
6253
  return { event: "compaction" };
4223
6254
  case "Stop":
4224
6255
  return { event: "stop" };
6256
+ case "PermissionRequest":
6257
+ return { event: "awaiting" };
4225
6258
  default:
4226
6259
  return void 0;
4227
6260
  }
@@ -4248,7 +6281,7 @@ var SETUP = {
4248
6281
  packageName: "@ascenda-one/codex-hooks",
4249
6282
  binaryName: "ascenda-codex-hook",
4250
6283
  hookEvents: HOOK_EVENTS,
4251
- restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not enable execution. After a session, verify the cli_agent send journal and metadata.host: codex in the event log.",
6284
+ restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not run them.",
4252
6285
  // Codex reports the posture it was working under and its approval gate; it
4253
6286
  // sends no model, no git action and no per-file change size.
4254
6287
  sends: ["posture", "waiting"],
@@ -4281,6 +6314,7 @@ async function main() {
4281
6314
  const input = await readJsonFromStdin();
4282
6315
  const sessionId = typeof input.session_id === "string" ? input.session_id : void 0;
4283
6316
  let turnDurationMs;
6317
+ (0, import_tool_kit3.stampLastHook)(CODEX_HOST, hookName);
4284
6318
  if (hookName === "UserPromptSubmit") (0, import_tool_kit3.recordTurnStart)(CODEX_HOST, sessionId);
4285
6319
  if (hookName === "Stop") turnDurationMs = (0, import_tool_kit3.consumeTurnDurationMs)(CODEX_HOST, sessionId);
4286
6320
  await emitLive(hookName, input, sessionId);
@@ -4297,6 +6331,7 @@ async function emitLive(hookName, input, sessionId) {
4297
6331
  const body = liveSignalFor(hookName, input);
4298
6332
  if (!body) return;
4299
6333
  try {
6334
+ const pid = (0, import_tool_kit3.findAgentPid)(import_tool_kit3.AGENT_PROCESS.codex);
4300
6335
  await (0, import_tool_kit3.emitLiveSignal)({
4301
6336
  // This host's own name, not the shared `cli_agent` tool type the cloud
4302
6337
  // path files these events under. The app keys one decaying envelope per
@@ -4311,6 +6346,7 @@ async function emitLive(hookName, input, sessionId) {
4311
6346
  // this process's parent — still per-session in practice, since the hook
4312
6347
  // is spawned from the session process.
4313
6348
  session: sessionId ?? `ppid-${process.ppid}`,
6349
+ ...pid !== void 0 ? { pid } : {},
4314
6350
  ...body
4315
6351
  });
4316
6352
  } catch {