@ascenda-one/agent-mcp 0.1.28 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +1242 -18
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -724,6 +724,10 @@ var require_out = __commonJS({
724
724
  // One constant word, from the agent itself. The session sentence names it.
725
725
  sessionEndReason: "session",
726
726
  interruptionKind: "waiting",
727
+ // Claude Code's own opaque id for one subagent, and the class it belongs
728
+ // to. Never the agent's name or anything it was asked.
729
+ subagentId: "subagents",
730
+ subagentClass: "subagents",
727
731
  // Free text by type, and written by no hook mapper — the IDE extension's
728
732
  // test signal is the only producer. The setup disclosure's third refusal
729
733
  // line says as much, and tool-kit's guard test fails if a mapper starts.
@@ -772,6 +776,8 @@ var require_out = __commonJS({
772
776
  "runtime",
773
777
  "sessionEndReason",
774
778
  "interruptionKind",
779
+ "subagentId",
780
+ "subagentClass",
775
781
  "simulated",
776
782
  "relatedEventType",
777
783
  "skillVersion",
@@ -819,6 +825,12 @@ var require_out = __commonJS({
819
825
  // `ai_prompt_submitted` closes. Neutral so a marker sent once per turn
820
826
  // doesn't weigh on any workload leg.
821
827
  ai_turn_completed: "neutral",
828
+ // A subagent began or finished under a session. Boundaries, not work: the
829
+ // subagent's own tool calls and edits arrive as their own events and carry
830
+ // their own categories. A reader pairs these on `subagentId` to count how
831
+ // many agents ran at once; neutral so that count weighs on no workload leg.
832
+ subagent_started: "neutral",
833
+ subagent_stopped: "neutral",
822
834
  // The agent stopped and is waiting on the person: Claude Code's
823
835
  // `Notification`, Codex's `PermissionRequest`. Supervision, beside the other
824
836
  // oversight overhead, because that is what it is — time the person spends
@@ -953,7 +965,7 @@ var require_collectorVersion = __commonJS({
953
965
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
954
966
  exports.describeCollectorVersion = describeCollectorVersion;
955
967
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
956
- exports.COLLECTOR_VERSION = "0.1.28" ? "0.1.28" : exports.UNRELEASED_COLLECTOR_VERSION;
968
+ exports.COLLECTOR_VERSION = "0.1.33" ? "0.1.33" : exports.UNRELEASED_COLLECTOR_VERSION;
957
969
  function describeCollectorVersion(version2 = exports.COLLECTOR_VERSION) {
958
970
  return version2 === exports.UNRELEASED_COLLECTOR_VERSION ? `${version2} (built from a checkout, not a release)` : version2;
959
971
  }
@@ -1055,6 +1067,12 @@ var require_http = __commonJS({
1055
1067
  exports.AscendaApiError = void 0;
1056
1068
  exports.createPairingSession = createPairingSession;
1057
1069
  exports.getPairingStatus = getPairingStatus;
1070
+ exports.startStudyJoin = startStudyJoin;
1071
+ exports.getStudyJoinStatus = getStudyJoinStatus;
1072
+ exports.readInitiatives = readInitiatives;
1073
+ exports.readStudyNotices = readStudyNotices;
1074
+ exports.setStudyObjection = setStudyObjection;
1075
+ exports.markStudyNoticeShown = markStudyNoticeShown;
1058
1076
  exports.renewToolToken = renewToolToken;
1059
1077
  exports.isRetryableStatus = isRetryableStatus;
1060
1078
  exports.postToolEvent = postToolEvent;
@@ -1091,6 +1109,108 @@ var require_http = __commonJS({
1091
1109
  throw new AscendaApiError(response.status, void 0, await response.text());
1092
1110
  return await response.json();
1093
1111
  }
1112
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1113
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1114
+ method: "POST",
1115
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1116
+ body: JSON.stringify({ joinCode, mode })
1117
+ });
1118
+ if (!response.ok)
1119
+ throw await apiError(response);
1120
+ return await response.json();
1121
+ }
1122
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1123
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1124
+ method: "GET",
1125
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1126
+ });
1127
+ if (!response.ok)
1128
+ throw await apiError(response);
1129
+ return await response.json();
1130
+ }
1131
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1132
+ let response;
1133
+ try {
1134
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1135
+ method: "GET",
1136
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1137
+ signal
1138
+ });
1139
+ } catch (error2) {
1140
+ return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1141
+ }
1142
+ if (response.status === 401)
1143
+ return { kind: "rejected", httpStatus: 401 };
1144
+ if (!response.ok)
1145
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1146
+ let body;
1147
+ try {
1148
+ body = await response.json();
1149
+ } catch {
1150
+ return { kind: "failed", reason: "the reply was not readable" };
1151
+ }
1152
+ if (!Array.isArray(body))
1153
+ return { kind: "failed", reason: "the reply was not a list" };
1154
+ return { kind: "ok", initiatives: body };
1155
+ }
1156
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1157
+ let response;
1158
+ try {
1159
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1160
+ method: "GET",
1161
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1162
+ signal
1163
+ });
1164
+ } catch (error2) {
1165
+ return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1166
+ }
1167
+ if (response.status === 404)
1168
+ return { kind: "absent" };
1169
+ if (response.status === 401)
1170
+ return { kind: "rejected", httpStatus: 401 };
1171
+ if (!response.ok)
1172
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1173
+ let body;
1174
+ try {
1175
+ body = await response.json();
1176
+ } catch {
1177
+ return { kind: "absent" };
1178
+ }
1179
+ if (!Array.isArray(body))
1180
+ return { kind: "absent" };
1181
+ return { kind: "ok", notices: body };
1182
+ }
1183
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1184
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1185
+ method: objected ? "POST" : "DELETE",
1186
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
1187
+ });
1188
+ if (!response.ok)
1189
+ throw await apiError(response);
1190
+ }
1191
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1192
+ try {
1193
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1194
+ method: "POST",
1195
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
1196
+ signal
1197
+ });
1198
+ return response.ok;
1199
+ } catch {
1200
+ return false;
1201
+ }
1202
+ }
1203
+ async function apiError(response) {
1204
+ const body = await response.text();
1205
+ let errorCode;
1206
+ try {
1207
+ const parsed = JSON.parse(body);
1208
+ errorCode = parsed.code ?? parsed.error;
1209
+ } catch {
1210
+ errorCode = void 0;
1211
+ }
1212
+ return new AscendaApiError(response.status, errorCode, body);
1213
+ }
1094
1214
  async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1095
1215
  const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1096
1216
  method: "POST",
@@ -1233,9 +1353,12 @@ var require_tokenStore = __commonJS({
1233
1353
  };
1234
1354
  }();
1235
1355
  Object.defineProperty(exports, "__esModule", { value: true });
1356
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1236
1357
  exports.ascendaHome = ascendaHome;
1237
1358
  exports.defaultTokenFilePath = defaultTokenFilePath2;
1359
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1238
1360
  exports.persistEventWriteToken = persistEventWriteToken2;
1361
+ exports.readTokenExpiry = readTokenExpiry;
1239
1362
  exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1240
1363
  exports.readTokenFile = readTokenFile2;
1241
1364
  exports.sanitizeFilePart = sanitizeFilePart;
@@ -1248,7 +1371,10 @@ var require_tokenStore = __commonJS({
1248
1371
  function defaultTokenFilePath2(toolInstallationId) {
1249
1372
  return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1250
1373
  }
1251
- function persistEventWriteToken2(tokenFilePath, token) {
1374
+ function tokenExpiryFilePath(tokenFilePath) {
1375
+ return path.join(path.dirname(tokenFilePath), "expiry", path.basename(tokenFilePath));
1376
+ }
1377
+ function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
1252
1378
  const dir = path.dirname(tokenFilePath);
1253
1379
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1254
1380
  fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
@@ -1256,6 +1382,30 @@ var require_tokenStore = __commonJS({
1256
1382
  fs.chmodSync(dir, 448);
1257
1383
  fs.chmodSync(tokenFilePath, 384);
1258
1384
  }
1385
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1386
+ try {
1387
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1388
+ fs.mkdirSync(path.dirname(expiryFile), { recursive: true, mode: 448 });
1389
+ fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1390
+ } else {
1391
+ fs.rmSync(expiryFile, { force: true });
1392
+ }
1393
+ } catch {
1394
+ }
1395
+ }
1396
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1397
+ function readTokenExpiry(tokenFilePath) {
1398
+ try {
1399
+ const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1400
+ if (Number.isFinite(recorded))
1401
+ return recorded;
1402
+ } catch {
1403
+ }
1404
+ try {
1405
+ return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1406
+ } catch {
1407
+ return void 0;
1408
+ }
1259
1409
  }
1260
1410
  function listPersistedToolInstallationIds(toolType) {
1261
1411
  const prefix = `${sanitizeFilePart(toolType)}_`;
@@ -1702,7 +1852,7 @@ var require_eventSender = __commonJS({
1702
1852
  "../packages/tool-kit/out/eventSender.js"(exports) {
1703
1853
  "use strict";
1704
1854
  Object.defineProperty(exports, "__esModule", { value: true });
1705
- exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1855
+ exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
1706
1856
  exports.buildEventPayload = buildEventPayload;
1707
1857
  var afterHours_1 = require_afterHours();
1708
1858
  var tool_contract_1 = require_out();
@@ -1743,6 +1893,7 @@ var require_eventSender = __commonJS({
1743
1893
  }
1744
1894
  var DEFAULT_TIMEOUT_MS = 5e3;
1745
1895
  var RETRY_DELAY_MS = 250;
1896
+ exports.TOKEN_RENEW_LEAD_MS = 21 * 24 * 60 * 60 * 1e3;
1746
1897
  var AscendaEventSender2 = class {
1747
1898
  config;
1748
1899
  eventWriteToken;
@@ -1750,6 +1901,8 @@ var require_eventSender = __commonJS({
1750
1901
  lastDrain;
1751
1902
  /** One outbox pass per sender, i.e. per hook process. The hook is on the user's critical path. */
1752
1903
  outboxServiced = false;
1904
+ /** One look at the token's expiry per sender, for the same reason. */
1905
+ expiryChecked = false;
1753
1906
  /** Resolved once, so every clock read in one pass sees the same instant. */
1754
1907
  time;
1755
1908
  constructor(config2) {
@@ -1873,6 +2026,7 @@ var require_eventSender = __commonJS({
1873
2026
  * hook during an outage to one bounded round trip instead of three.
1874
2027
  */
1875
2028
  async post(payload) {
2029
+ await this.renewIfExpiring();
1876
2030
  const halted = await this.serviceOutbox();
1877
2031
  let outcome;
1878
2032
  let queued = false;
@@ -2078,21 +2232,49 @@ var require_eventSender = __commonJS({
2078
2232
  return;
2079
2233
  (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload, ...outbox ? { outbox } : {} });
2080
2234
  }
2081
- /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
2235
+ /**
2236
+ * Renews ahead of expiry, at most once per sender. Waiting for the 401
2237
+ * doesn't work: by then the token has expired, and the server won't renew
2238
+ * an expired token.
2239
+ */
2240
+ async renewIfExpiring() {
2241
+ if (this.expiryChecked || this.config.renewToken === false)
2242
+ return;
2243
+ this.expiryChecked = true;
2244
+ const expiresAt = (0, tokenStore_1.readTokenExpiry)(this.config.tokenFilePath);
2245
+ if (expiresAt === void 0 || this.time.now() < expiresAt - exports.TOKEN_RENEW_LEAD_MS)
2246
+ return;
2247
+ await this.renewEventToken();
2248
+ }
2249
+ /**
2250
+ * Never throws: a renewal that errors is a failed renewal, not a failed turn.
2251
+ *
2252
+ * A refused renewal usually means another process got there first. Hooks
2253
+ * and the MCP server share one token file, and renewing revokes the token
2254
+ * it replaces, so the loser holds a revoked token while the winner's
2255
+ * replacement is already on disk. Adopting that counts as a renewal.
2256
+ */
2082
2257
  async renewEventToken() {
2083
2258
  if (this.config.renewToken === false)
2084
2259
  return false;
2085
2260
  try {
2086
2261
  const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
2087
2262
  if (!renewed)
2088
- return false;
2263
+ return this.adoptPersistedToken();
2089
2264
  this.eventWriteToken = renewed.eventWriteToken;
2090
- (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken);
2265
+ (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken, renewed.expiresAt);
2091
2266
  return true;
2092
2267
  } catch {
2093
2268
  return false;
2094
2269
  }
2095
2270
  }
2271
+ adoptPersistedToken() {
2272
+ const persisted = (0, tokenStore_1.readTokenFile)(this.config.tokenFilePath);
2273
+ if (!persisted || persisted === this.eventWriteToken)
2274
+ return false;
2275
+ this.eventWriteToken = persisted;
2276
+ return true;
2277
+ }
2096
2278
  signal() {
2097
2279
  return AbortSignal.timeout(this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS);
2098
2280
  }
@@ -2975,6 +3157,477 @@ var require_hookAdapter = __commonJS({
2975
3157
  }
2976
3158
  });
2977
3159
 
3160
+ // ../packages/tool-kit/out/hookSet.js
3161
+ var require_hookSet = __commonJS({
3162
+ "../packages/tool-kit/out/hookSet.js"(exports) {
3163
+ "use strict";
3164
+ Object.defineProperty(exports, "__esModule", { value: true });
3165
+ exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = void 0;
3166
+ exports.hookSetArgument = hookSetArgument;
3167
+ exports.readHookSet = readHookSet;
3168
+ exports.isHookSet = isHookSet;
3169
+ exports.readViaPlugin = readViaPlugin;
3170
+ exports.hookSetOfCommand = hookSetOfCommand;
3171
+ exports.hookSetChanges = hookSetChanges;
3172
+ exports.describeHookSetChanges = describeHookSetChanges;
3173
+ exports.HOOK_SET_FLAG = "--hook-set";
3174
+ exports.UNVERSIONED_HOOK_SET = 1;
3175
+ function hookSetArgument(hookSet) {
3176
+ return hookSet === void 0 ? "" : ` ${exports.HOOK_SET_FLAG} ${hookSet}`;
3177
+ }
3178
+ function readHookSet(argv) {
3179
+ const index = argv.indexOf(exports.HOOK_SET_FLAG);
3180
+ if (index === -1)
3181
+ return void 0;
3182
+ const raw = argv[index + 1];
3183
+ if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
3184
+ return void 0;
3185
+ const value = Number(raw);
3186
+ return isHookSet(value) ? value : void 0;
3187
+ }
3188
+ function isHookSet(value) {
3189
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3190
+ }
3191
+ function readViaPlugin(env) {
3192
+ return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
3193
+ }
3194
+ function hookSetOfCommand(command) {
3195
+ const match = command.match(/--hook-set\s+(\d+)/);
3196
+ return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
3197
+ }
3198
+ function hookSetChanges(before, events) {
3199
+ const added = events.filter((event) => !before.has(event));
3200
+ const sets = [...before.values()];
3201
+ return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
3202
+ }
3203
+ function describeHookSetChanges(changes, hookSet) {
3204
+ if (changes.previousSet === void 0)
3205
+ return void 0;
3206
+ const parts = [];
3207
+ if (changes.added.length)
3208
+ parts.push(`added ${changes.added.join(", ")}`);
3209
+ if (changes.previousSet < hookSet)
3210
+ parts.push(`hook set ${changes.previousSet} \u2192 ${hookSet}`);
3211
+ return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
3212
+ }
3213
+ }
3214
+ });
3215
+
3216
+ // ../packages/tool-kit/out/studyJoin.js
3217
+ var require_studyJoin = __commonJS({
3218
+ "../packages/tool-kit/out/studyJoin.js"(exports) {
3219
+ "use strict";
3220
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3221
+ if (k2 === void 0) k2 = k;
3222
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3223
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3224
+ desc = { enumerable: true, get: function() {
3225
+ return m[k];
3226
+ } };
3227
+ }
3228
+ Object.defineProperty(o, k2, desc);
3229
+ } : function(o, m, k, k2) {
3230
+ if (k2 === void 0) k2 = k;
3231
+ o[k2] = m[k];
3232
+ });
3233
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3234
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3235
+ } : function(o, v) {
3236
+ o["default"] = v;
3237
+ });
3238
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3239
+ var ownKeys = function(o) {
3240
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3241
+ var ar = [];
3242
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3243
+ return ar;
3244
+ };
3245
+ return ownKeys(o);
3246
+ };
3247
+ return function(mod) {
3248
+ if (mod && mod.__esModule) return mod;
3249
+ var result = {};
3250
+ if (mod != null) {
3251
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3252
+ }
3253
+ __setModuleDefault(result, mod);
3254
+ return result;
3255
+ };
3256
+ }();
3257
+ Object.defineProperty(exports, "__esModule", { value: true });
3258
+ exports.runStudyJoin = runStudyJoin;
3259
+ exports.formatWindow = formatWindow;
3260
+ var readline = __importStar(__require("node:readline"));
3261
+ var http_1 = require_http();
3262
+ var STUDY_JOIN_MODE = "report";
3263
+ var POLL_INTERVAL_MS = 3e3;
3264
+ var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
3265
+ async function runStudyJoin(ctx) {
3266
+ const stdin = ctx.stdin ?? process.stdin;
3267
+ const stdout = ctx.stdout ?? process.stdout;
3268
+ const stderr = ctx.stderr ?? process.stderr;
3269
+ const print = (line) => stdout.write(`${line}
3270
+ `);
3271
+ if (!stdin.isTTY || !stdout.isTTY) {
3272
+ stderr.write("join needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
3273
+ return 0;
3274
+ }
3275
+ if (!ctx.joinCode) {
3276
+ stderr.write("Usage: join <code>\n");
3277
+ return 1;
3278
+ }
3279
+ let start;
3280
+ try {
3281
+ start = await (0, http_1.startStudyJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, ctx.joinCode, STUDY_JOIN_MODE);
3282
+ } catch (error2) {
3283
+ stderr.write(`${describeStartError(error2)}
3284
+ `);
3285
+ return 1;
3286
+ }
3287
+ print("");
3288
+ print(`${start.organisationName}: ${describeStudyKind(start.studyKind)}`);
3289
+ print(formatWindow(start.windowStartUtc, start.windowEndUtc));
3290
+ print("");
3291
+ print("Report (30 days) grants:");
3292
+ for (const grant of start.grants)
3293
+ print(` ${describeGrant(grant)}`);
3294
+ print("");
3295
+ print("Study mode needs the Ascenda app. Open the app to join that way instead.");
3296
+ print("");
3297
+ print("Join in:");
3298
+ print(" 1) Report (30 days)");
3299
+ print(" 2) Not now");
3300
+ print("");
3301
+ const answer = await askChoice(stdin, stdout);
3302
+ if (!/^(1|report)$/i.test(answer)) {
3303
+ print("Not now.");
3304
+ return 0;
3305
+ }
3306
+ print("");
3307
+ print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
3308
+ print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
3309
+ const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3310
+ const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3311
+ while (Date.now() < deadline) {
3312
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
3313
+ let poll;
3314
+ try {
3315
+ poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
3316
+ } catch (error2) {
3317
+ if (isRetryablePollError(error2))
3318
+ continue;
3319
+ stderr.write(`${describeStartError(error2)}
3320
+ `);
3321
+ return 1;
3322
+ }
3323
+ if (poll.status === "pending")
3324
+ continue;
3325
+ if (poll.status === "confirmed") {
3326
+ const granted = poll.granted ?? [];
3327
+ if (granted.length === 0) {
3328
+ print("");
3329
+ print("Nothing was granted. Run join again, or check with your organisation.");
3330
+ return 1;
3331
+ }
3332
+ print("");
3333
+ print("Joined. Granted:");
3334
+ for (const grant of granted)
3335
+ print(` ${describeGrant(grant)}`);
3336
+ print("");
3337
+ print("Each of these can be turned off separately, in the app's consent settings.");
3338
+ print("The organisation sees group counts, never who joined.");
3339
+ return 0;
3340
+ }
3341
+ if (poll.status === "expired") {
3342
+ print("");
3343
+ print("This code expired before it was confirmed. Run join again for a fresh code.");
3344
+ return 1;
3345
+ }
3346
+ if (poll.refusedReason === "grant_failed") {
3347
+ print("");
3348
+ print("Join failed partway through. Some grants may not have gone through.");
3349
+ const granted = poll.granted ?? [];
3350
+ if (granted.length > 0) {
3351
+ print("");
3352
+ print("Granted before the failure:");
3353
+ for (const grant of granted)
3354
+ print(` ${describeGrant(grant)}`);
3355
+ print("");
3356
+ print("Each of these can be turned off separately, in the app's consent settings.");
3357
+ }
3358
+ print("Run join again, or check with your organisation.");
3359
+ return 1;
3360
+ }
3361
+ print("");
3362
+ print(describeRefusal(poll.refusedReason));
3363
+ return 1;
3364
+ }
3365
+ print("");
3366
+ print("Timed out waiting for confirmation. Run join again for a fresh code.");
3367
+ return 1;
3368
+ }
3369
+ function isRetryablePollError(error2) {
3370
+ if (error2 instanceof http_1.AscendaApiError)
3371
+ return error2.status >= 500 && error2.status <= 599;
3372
+ return true;
3373
+ }
3374
+ function askChoice(stdin, stdout) {
3375
+ return new Promise((resolve) => {
3376
+ const rl = readline.createInterface({ input: stdin, output: stdout });
3377
+ let settled = false;
3378
+ const finish = (value) => {
3379
+ if (settled)
3380
+ return;
3381
+ settled = true;
3382
+ rl.close();
3383
+ resolve(value.trim());
3384
+ };
3385
+ rl.question("Choice [Not now]: ", finish);
3386
+ rl.once("close", () => finish(""));
3387
+ });
3388
+ }
3389
+ function formatLocalTime(iso) {
3390
+ const date3 = new Date(iso);
3391
+ if (Number.isNaN(date3.getTime()))
3392
+ return iso;
3393
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date3);
3394
+ }
3395
+ function formatWindow(startUtc, endUtc) {
3396
+ const start = new Date(startUtc);
3397
+ const end = new Date(endUtc);
3398
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
3399
+ const dayMonth = { day: "numeric", month: "short", timeZone: "UTC" };
3400
+ const withYear = { ...dayMonth, year: "numeric" };
3401
+ const startFmt = new Intl.DateTimeFormat("en-GB", sameYear ? dayMonth : withYear);
3402
+ const endFmt = new Intl.DateTimeFormat("en-GB", withYear);
3403
+ return `${startFmt.format(start)} \u2013 ${endFmt.format(end)}`;
3404
+ }
3405
+ var GRANT_SENTENCES = {
3406
+ 501: "AI assistant data processing consent",
3407
+ 507: "Import of the AI-work history already on your machine"
3408
+ };
3409
+ function describeGrant(grant) {
3410
+ return GRANT_SENTENCES[grant.code] ?? humanise(grant.name);
3411
+ }
3412
+ var STUDY_KIND_SENTENCES = {
3413
+ Report30: "a 30-day report",
3414
+ Study90: "a 90-day study"
3415
+ };
3416
+ function describeStudyKind(studyKind) {
3417
+ return STUDY_KIND_SENTENCES[studyKind] ?? humanise(studyKind);
3418
+ }
3419
+ function humanise(name) {
3420
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim() || name;
3421
+ }
3422
+ var REFUSED_REASON_MESSAGES = {
3423
+ study_no_longer_live: "That study is no longer open to join.",
3424
+ withdrawn: "You're no longer an active participant in that study.",
3425
+ // Handled as its own branch above, with its granted list, before this
3426
+ // table is ever consulted — present so the type stays exhaustive, and as
3427
+ // a plain fallback should something call this function with it directly.
3428
+ grant_failed: "Join failed partway through. Some grants may not have gone through.",
3429
+ declined: "You declined in the app. Nothing was granted.",
3430
+ not_enrolled: "That study couldn't enrol you, so nothing was granted."
3431
+ };
3432
+ function describeRefusal(refusedReason) {
3433
+ if (refusedReason && REFUSED_REASON_MESSAGES[refusedReason])
3434
+ return REFUSED_REASON_MESSAGES[refusedReason];
3435
+ return "The join didn't go through. Nothing new was granted.";
3436
+ }
3437
+ var START_ERROR_MESSAGES = {
3438
+ join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
3439
+ unknown_mode: "This tool only offers Report mode from the command line.",
3440
+ no_live_study: "There's nothing open to join with that code right now.",
3441
+ too_many_open_sessions: "This tool has too many joins waiting to be confirmed. Confirm one, or let one expire, then try again.",
3442
+ unknown_session: "That join can no longer be found. Run join again for a fresh code."
3443
+ };
3444
+ function describeStartError(error2) {
3445
+ if (error2 instanceof http_1.AscendaApiError) {
3446
+ if (error2.errorCode && START_ERROR_MESSAGES[error2.errorCode])
3447
+ return START_ERROR_MESSAGES[error2.errorCode];
3448
+ if (error2.status === 401)
3449
+ return "This tool's pairing was rejected. Re-pair it, then try again.";
3450
+ return `Could not reach the join code (HTTP ${error2.status}).`;
3451
+ }
3452
+ return error2 instanceof Error ? error2.message : String(error2);
3453
+ }
3454
+ }
3455
+ });
3456
+
3457
+ // ../packages/tool-kit/out/initiatives.js
3458
+ var require_initiatives = __commonJS({
3459
+ "../packages/tool-kit/out/initiatives.js"(exports) {
3460
+ "use strict";
3461
+ Object.defineProperty(exports, "__esModule", { value: true });
3462
+ exports.INITIATIVE_COPY = void 0;
3463
+ exports.initiativesStatusLines = initiativesStatusLines;
3464
+ exports.renderInitiatives = renderInitiatives;
3465
+ var http_1 = require_http();
3466
+ var studyJoin_1 = require_studyJoin();
3467
+ var READ_TIMEOUT_MS = 5e3;
3468
+ exports.INITIATIVE_COPY = {
3469
+ outcomes: {
3470
+ moved_as_declared: "Moved the way declared, beyond the cohort's own variation",
3471
+ moved_against_declared: "Moved the other way, beyond the cohort's own variation",
3472
+ moved_no_direction_declared: "Moved beyond the cohort's own variation; no direction was declared",
3473
+ within_own_variation: "No further from the baseline than the cohort's own week-to-week variation",
3474
+ withheld: "Withheld"
3475
+ },
3476
+ withheldReasons: {
3477
+ cohort_below_minimum: "the cohort was too small to report on when the scoring window closed",
3478
+ below_minimum_cohort: "the cohort was too small to report on when the scoring window closed",
3479
+ below_minimum_cohort_size: "the cohort was too small to report on when the scoring window closed",
3480
+ baseline_withheld: "the baseline was withheld"
3481
+ }
3482
+ };
3483
+ var OUTCOME_EMPTY = "Not stated";
3484
+ var OUTCOME_UNKNOWN = "An outcome this app does not recognise";
3485
+ var WITHHELD_UNKNOWN = "Withheld, for a reason this version of the app doesn't name yet.";
3486
+ var DIRECTION_WORDS = {
3487
+ up: "Expected to rise",
3488
+ down: "Expected to fall",
3489
+ none_declared: "No direction declared"
3490
+ };
3491
+ var DIRECTION_UNKNOWN = "A direction this app does not recognise";
3492
+ async function initiativesStatusLines(ctx) {
3493
+ const heading = "Changes your organisation has published to you";
3494
+ if (!ctx.eventWriteToken) {
3495
+ return [heading, " Not checked: this install holds no token, so nothing was fetched."];
3496
+ }
3497
+ const read = await (0, http_1.readInitiatives)(ctx.apiBaseUrl, ctx.eventWriteToken, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3498
+ if (read.kind === "rejected") {
3499
+ return [
3500
+ heading,
3501
+ ` Couldn't check: the server turned this install's request down. If that keeps happening, pair again with \`${ctx.pairCommand}\`.`
3502
+ ];
3503
+ }
3504
+ if (read.kind === "failed") {
3505
+ return [heading, ` Couldn't check: ${read.reason}. Run status again to retry.`];
3506
+ }
3507
+ return [heading, ...renderInitiatives(read.initiatives)];
3508
+ }
3509
+ function renderInitiatives(entries, copy = exports.INITIATIVE_COPY) {
3510
+ if (entries.length === 0)
3511
+ return [" None published to you."];
3512
+ const lines = [];
3513
+ let unreadable = 0;
3514
+ for (const entry of entries) {
3515
+ const initiative = asInitiative(entry);
3516
+ if (!initiative) {
3517
+ unreadable += 1;
3518
+ continue;
3519
+ }
3520
+ lines.push(...renderOne(initiative, copy));
3521
+ }
3522
+ if (unreadable > 0) {
3523
+ lines.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3524
+ }
3525
+ return lines;
3526
+ }
3527
+ function renderOne(initiative, copy) {
3528
+ const lines = [` ${initiative.organisationName}: ${initiative.title}`];
3529
+ lines.push(` ${describeStatus(initiative)}`);
3530
+ if (initiative.summaryForCohort) {
3531
+ for (const line of initiative.summaryForCohort.split(/\r?\n/))
3532
+ lines.push(` ${line}`);
3533
+ }
3534
+ if (initiative.direction)
3535
+ lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
3536
+ lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
3537
+ if (initiative.result)
3538
+ lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
3539
+ lines.push("");
3540
+ return lines;
3541
+ }
3542
+ function describeStatus(initiative) {
3543
+ switch (initiative.status) {
3544
+ case "published":
3545
+ return "Published, not scored yet.";
3546
+ case "scored":
3547
+ return "Scored.";
3548
+ case "withdrawn":
3549
+ return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
3550
+ default:
3551
+ return "Status not recognised.";
3552
+ }
3553
+ }
3554
+ function renderResult(result, unit, copy) {
3555
+ const lines = [];
3556
+ const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
3557
+ if (result.value === null) {
3558
+ const why = copy.withheldReasons[result.withheldReason ?? ""];
3559
+ lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
3560
+ return lines;
3561
+ }
3562
+ lines.push(` Result: ${show(result.value)}`);
3563
+ lines.push(` ${movementLine(result)}`);
3564
+ lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
3565
+ return lines;
3566
+ }
3567
+ function movementLine(result) {
3568
+ if (result.outcome === "within_own_variation")
3569
+ return "No material change against frozen baseline";
3570
+ if (result.delta === null)
3571
+ return "No reading";
3572
+ if (result.delta > 0)
3573
+ return `Up ${figure(result.delta)} against frozen baseline`;
3574
+ if (result.delta < 0)
3575
+ return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
3576
+ return "No change against frozen baseline";
3577
+ }
3578
+ function figure(n) {
3579
+ return String(Number(n.toPrecision(12)));
3580
+ }
3581
+ function asInitiative(value) {
3582
+ if (!value || typeof value !== "object")
3583
+ return void 0;
3584
+ const o = value;
3585
+ if (typeof o.title !== "string" || typeof o.status !== "string")
3586
+ return void 0;
3587
+ return {
3588
+ id: typeof o.id === "string" ? o.id : "",
3589
+ organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3590
+ title: o.title,
3591
+ summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3592
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3593
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3594
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3595
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3596
+ status: o.status,
3597
+ direction: typeof o.direction === "string" ? o.direction : null,
3598
+ result: asResult(o.result)
3599
+ };
3600
+ }
3601
+ function asResult(value) {
3602
+ if (!value || typeof value !== "object")
3603
+ return null;
3604
+ const r = value;
3605
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
3606
+ return {
3607
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3608
+ value: num(r.value),
3609
+ baselineValue: num(r.baselineValue),
3610
+ delta: num(r.delta),
3611
+ movement: typeof r.movement === "string" ? r.movement : null,
3612
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
3613
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3614
+ basis: typeof r.basis === "string" ? r.basis : null
3615
+ };
3616
+ }
3617
+ function formatWindowOrRaw(startUtc, endUtc) {
3618
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3619
+ return "not given";
3620
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3621
+ }
3622
+ function formatDay(iso) {
3623
+ const date3 = new Date(iso);
3624
+ if (Number.isNaN(date3.getTime()))
3625
+ return iso;
3626
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date3);
3627
+ }
3628
+ }
3629
+ });
3630
+
2978
3631
  // ../packages/tool-kit/out/setupDisclosure.js
2979
3632
  var require_setupDisclosure = __commonJS({
2980
3633
  "../packages/tool-kit/out/setupDisclosure.js"(exports) {
@@ -2995,6 +3648,7 @@ var require_setupDisclosure = __commonJS({
2995
3648
  edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
2996
3649
  context: "how full the context window got",
2997
3650
  waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3651
+ 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",
2998
3652
  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"
2999
3653
  };
3000
3654
  exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
@@ -3020,6 +3674,211 @@ var require_setupDisclosure = __commonJS({
3020
3674
  }
3021
3675
  });
3022
3676
 
3677
+ // ../packages/tool-kit/out/studyNotices.js
3678
+ var require_studyNotices = __commonJS({
3679
+ "../packages/tool-kit/out/studyNotices.js"(exports) {
3680
+ "use strict";
3681
+ Object.defineProperty(exports, "__esModule", { value: true });
3682
+ exports.NOTICED_PURPOSES = void 0;
3683
+ exports.studyNoticeStatus = studyNoticeStatus;
3684
+ exports.renderStudyNotices = renderStudyNotices;
3685
+ exports.runStudyObjection = runStudyObjection;
3686
+ var http_1 = require_http();
3687
+ var READ_TIMEOUT_MS = 5e3;
3688
+ var NOTICE_LABEL = "Counted unless you object";
3689
+ var PROCESSOR = "Ascenda";
3690
+ exports.NOTICED_PURPOSES = [
3691
+ { code: 501, slug: "telemetry", title: "Live tool telemetry" },
3692
+ { code: 507, slug: "import", title: "One-time import of past AI work" },
3693
+ { code: 11, slug: "work-patterns", title: "Work-pattern axes in the group figures" }
3694
+ ];
3695
+ var BASIS_WORDS = {
3696
+ legitimate_interests: "legitimate interests",
3697
+ collective_agreement: "a collective agreement"
3698
+ };
3699
+ async function studyNoticeStatus(ctx) {
3700
+ const nothing = { lines: [], markShown: async () => {
3701
+ } };
3702
+ const token = ctx.eventWriteToken;
3703
+ if (!token)
3704
+ return nothing;
3705
+ const read = await (0, http_1.readStudyNotices)(ctx.apiBaseUrl, token, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3706
+ if (read.kind !== "ok")
3707
+ return nothing;
3708
+ const lines = renderStudyNotices(read.notices, ctx.commandPrefix, ctx.now);
3709
+ if (lines.length === 0)
3710
+ return nothing;
3711
+ const unshown = shownPurposes(read.notices).filter((n) => !n.noticeFromUtc && n.organisationId);
3712
+ return {
3713
+ lines,
3714
+ markShown: async () => {
3715
+ const signal = AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS);
3716
+ await Promise.all(unshown.map((n) => (0, http_1.markStudyNoticeShown)(ctx.apiBaseUrl, token, n.organisationId, n.code, signal)));
3717
+ }
3718
+ };
3719
+ }
3720
+ function shownPurposes(entries) {
3721
+ return entries.map(asNotice).filter((n) => n !== void 0 && exports.NOTICED_PURPOSES.some((p) => p.code === n.code));
3722
+ }
3723
+ function renderStudyNotices(entries, commandPrefix, now = /* @__PURE__ */ new Date()) {
3724
+ const body = [];
3725
+ let unreadable = 0;
3726
+ for (const entry of entries) {
3727
+ const notice = asNotice(entry);
3728
+ const purpose = notice && exports.NOTICED_PURPOSES.find((p) => p.code === notice.code);
3729
+ if (!notice || !purpose) {
3730
+ unreadable += 1;
3731
+ continue;
3732
+ }
3733
+ body.push(...renderOne(notice, purpose, commandPrefix, now));
3734
+ }
3735
+ if (body.length === 0)
3736
+ return [];
3737
+ if (unreadable > 0) {
3738
+ body.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3739
+ }
3740
+ return ["", "Your organisation's study", ...body];
3741
+ }
3742
+ function renderOne(notice, purpose, commandPrefix, now) {
3743
+ const org = notice.organisationName;
3744
+ const command = `${commandPrefix} object ${purpose.slug}`;
3745
+ const lines = [` ${org}: ${purpose.title}`];
3746
+ lines.push(` ${notice.label || NOTICE_LABEL}`);
3747
+ lines.push(` ${basisLine(notice)}`);
3748
+ if (notice.signatoryName)
3749
+ lines.push(` Recorded by ${notice.signatoryName}.`);
3750
+ lines.push(` ${notice.processor || PROCESSOR} processes this for ${org}.`);
3751
+ if (notice.objected === true) {
3752
+ lines.push(" You objected. You are left out from the next report on.");
3753
+ lines.push(` To undo: ${command} --undo`);
3754
+ } else if (notice.objected === false) {
3755
+ lines.push(" You haven't objected.");
3756
+ if (notice.noticeFromUtc && isDate(notice.noticeFromUtc)) {
3757
+ const starts = notice.countingFromUtc && isDate(notice.countingFromUtc) ? notice.countingFromUtc : new Date(Date.parse(notice.noticeFromUtc) + NOTICE_PERIOD_MS).toISOString();
3758
+ if (Date.parse(starts) > now.getTime()) {
3759
+ lines.push(` Notice given ${formatDay(notice.noticeFromUtc)}. Counting starts ${formatDay(starts)}.`);
3760
+ }
3761
+ }
3762
+ 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.`);
3763
+ } else {
3764
+ lines.push(" This version of the tool couldn't read whether you've objected. Run status again.");
3765
+ lines.push(` To object: ${command}`);
3766
+ lines.push(` To undo: ${command} --undo`);
3767
+ }
3768
+ lines.push("");
3769
+ return lines;
3770
+ }
3771
+ function basisLine(notice) {
3772
+ const words = notice.basisLabel ?? BASIS_WORDS[notice.basis];
3773
+ const head = words ? `${notice.organisationName}'s basis is ${words}.` : `${notice.organisationName}'s basis is one this version of the tool can't name.`;
3774
+ const dated = notice.documentDate && isDate(notice.documentDate) ? formatDay(notice.documentDate) : null;
3775
+ const ref = notice.documentReference ? `ref ${notice.documentReference}` : null;
3776
+ const title = notice.documentTitle ? dated ? `${notice.documentTitle} (${dated})` : notice.documentTitle : null;
3777
+ const document = [title, ref].filter((part) => Boolean(part)).join(", ");
3778
+ return document ? `${head} Document: ${document}.` : head;
3779
+ }
3780
+ var NOTICE_PERIOD_MS = 14 * 24 * 60 * 60 * 1e3;
3781
+ function asNotice(value) {
3782
+ if (!value || typeof value !== "object")
3783
+ return void 0;
3784
+ const o = value;
3785
+ if (typeof o.code !== "number")
3786
+ return void 0;
3787
+ if (typeof o.mode === "string" && o.mode.trim().toLowerCase() !== "notice")
3788
+ return void 0;
3789
+ const str = (x) => typeof x === "string" && x.trim() ? x : null;
3790
+ return {
3791
+ organisationId: str(o.organisationId),
3792
+ organisationName: str(o.organisationName) ?? "Your organisation",
3793
+ code: o.code,
3794
+ name: str(o.name),
3795
+ label: str(o.label),
3796
+ processor: str(o.processor),
3797
+ basis: typeof o.basis === "string" ? o.basis : "",
3798
+ basisLabel: str(o.basisLabel),
3799
+ documentTitle: str(o.documentTitle),
3800
+ documentDate: str(o.documentDate),
3801
+ documentReference: str(o.documentReference),
3802
+ signatoryName: str(o.signatoryName),
3803
+ objected: typeof o.objected === "boolean" ? o.objected : null,
3804
+ objectedAtUtc: str(o.objectedAtUtc),
3805
+ noticeFromUtc: str(o.noticeFromUtc),
3806
+ countingFromUtc: str(o.countingFromUtc)
3807
+ };
3808
+ }
3809
+ async function runStudyObjection(ctx) {
3810
+ const stdin = ctx.stdin ?? process.stdin;
3811
+ const stdout = ctx.stdout ?? process.stdout;
3812
+ const stderr = ctx.stderr ?? process.stderr;
3813
+ const print = (line) => stdout.write(`${line}
3814
+ `);
3815
+ if (!stdin.isTTY || !stdout.isTTY) {
3816
+ stderr.write("object needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
3817
+ return 1;
3818
+ }
3819
+ const undo = ctx.argv.includes("--undo");
3820
+ const rest = ctx.argv.filter((a) => a !== "--undo");
3821
+ const purpose = rest.length === 1 ? exports.NOTICED_PURPOSES.find((p) => p.slug === rest[0]) : void 0;
3822
+ if (!purpose) {
3823
+ stderr.write(objectionUsage(ctx.commandPrefix));
3824
+ return 1;
3825
+ }
3826
+ if (!ctx.eventWriteToken) {
3827
+ stderr.write(`This install isn't paired, so there's nothing to object to. Pair with \`${ctx.pairCommand}\`.
3828
+ `);
3829
+ return 1;
3830
+ }
3831
+ const command = `${ctx.commandPrefix} object ${purpose.slug}`;
3832
+ try {
3833
+ await (0, http_1.setStudyObjection)(ctx.apiBaseUrl, ctx.eventWriteToken, purpose.code, !undo);
3834
+ } catch (error2) {
3835
+ stderr.write(`${describeObjectionError(error2, purpose, undo, ctx.pairCommand)}
3836
+ `);
3837
+ return 1;
3838
+ }
3839
+ if (undo) {
3840
+ print(`Objection withdrawn: ${purpose.title}.`);
3841
+ print("You're counted again from the next report.");
3842
+ print(`To object again: ${command}`);
3843
+ } else {
3844
+ print(`Objected: ${purpose.title}.`);
3845
+ print("You objected. You are left out from the next report on, and earlier reports stay as they were.");
3846
+ print(`To undo: ${command} --undo`);
3847
+ }
3848
+ return 0;
3849
+ }
3850
+ function objectionUsage(commandPrefix) {
3851
+ const lines = [`Usage: ${commandPrefix} object <purpose> [--undo]`, "", "Purposes:"];
3852
+ for (const p of exports.NOTICED_PURPOSES)
3853
+ lines.push(` ${p.slug.padEnd(14)}${p.title}`);
3854
+ lines.push("", "status shows which of these your organisation counts unless you object.");
3855
+ return `${lines.join("\n")}
3856
+ `;
3857
+ }
3858
+ function describeObjectionError(error2, purpose, undo, pairCommand) {
3859
+ if (error2 instanceof http_1.AscendaApiError) {
3860
+ if (error2.status === 404 && error2.errorCode === "not_noticed") {
3861
+ 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.`;
3862
+ }
3863
+ if (error2.status === 401)
3864
+ return `The server turned this install's request down. If that keeps happening, pair again with \`${pairCommand}\`.`;
3865
+ if (error2.status === 404)
3866
+ return "This server doesn't take objections yet. Nothing changed.";
3867
+ return `Couldn't record that (HTTP ${error2.status}). Nothing changed. Run it again to retry.`;
3868
+ }
3869
+ return "Couldn't reach the server. Nothing changed. Run it again to retry.";
3870
+ }
3871
+ function isDate(iso) {
3872
+ return !Number.isNaN(Date.parse(iso));
3873
+ }
3874
+ var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
3875
+ function formatDay(iso) {
3876
+ const date3 = new Date(iso);
3877
+ return `${date3.getUTCDate()} ${MONTHS[date3.getUTCMonth()]} ${date3.getUTCFullYear()}`;
3878
+ }
3879
+ }
3880
+ });
3881
+
3023
3882
  // ../packages/tool-kit/out/cliAgentSetup.js
3024
3883
  var require_cliAgentSetup = __commonJS({
3025
3884
  "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
@@ -3066,6 +3925,7 @@ var require_cliAgentSetup = __commonJS({
3066
3925
  exports.cliAgentHookBinPath = cliAgentHookBinPath;
3067
3926
  exports.runCliAgentSetup = runCliAgentSetup;
3068
3927
  exports.writeHookSettings = writeHookSettings;
3928
+ exports.registeredHookSets = registeredHookSets;
3069
3929
  exports.findStaleHookCommands = findStaleHookCommands;
3070
3930
  var crypto = __importStar(__require("crypto"));
3071
3931
  var fs = __importStar(__require("fs"));
@@ -3075,9 +3935,14 @@ var require_cliAgentSetup = __commonJS({
3075
3935
  var credentials_1 = require_credentials();
3076
3936
  var hookAdapter_1 = require_hookAdapter();
3077
3937
  var http_1 = require_http();
3938
+ var hookSet_1 = require_hookSet();
3939
+ var initiatives_1 = require_initiatives();
3078
3940
  var setupDisclosure_1 = require_setupDisclosure();
3941
+ var stateStore_1 = require_stateStore();
3942
+ var studyJoin_1 = require_studyJoin();
3943
+ var studyNotices_1 = require_studyNotices();
3079
3944
  var tokenStore_1 = require_tokenStore();
3080
- var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
3945
+ var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "join", "object", "-h", "--help"]);
3081
3946
  function isCliAgentManagementCommand(argument) {
3082
3947
  return argument !== void 0 && MANAGEMENT_COMMANDS.has(argument);
3083
3948
  }
@@ -3090,6 +3955,8 @@ var require_cliAgentSetup = __commonJS({
3090
3955
  npx ${spec.packageName} setup [options]
3091
3956
  npx ${spec.packageName} status
3092
3957
  npx ${spec.packageName} uninstall
3958
+ npx ${spec.packageName} join <code>
3959
+ npx ${spec.packageName} object <purpose> [--undo]
3093
3960
 
3094
3961
  Options
3095
3962
  --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
@@ -3104,6 +3971,10 @@ Options
3104
3971
  `;
3105
3972
  }
3106
3973
  async function runCliAgentSetup(argv, spec) {
3974
+ if (argv[0] === "join")
3975
+ return runCliAgentStudyJoin(argv.slice(1), spec);
3976
+ if (argv[0] === "object")
3977
+ return runCliAgentStudyObjection(argv.slice(1), spec);
3107
3978
  let options;
3108
3979
  try {
3109
3980
  options = parseArgs(argv, spec);
@@ -3116,7 +3987,7 @@ Options
3116
3987
  return 0;
3117
3988
  }
3118
3989
  if (options.action === "status")
3119
- return printStatus(options, spec);
3990
+ return await printStatus(options, spec);
3120
3991
  if (options.action === "uninstall")
3121
3992
  return uninstall(options, spec);
3122
3993
  const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
@@ -3153,10 +4024,14 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
3153
4024
  }
3154
4025
  console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
3155
4026
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4027
+ const before = registeredHookSets(readSettings(settingsFile), spec);
3156
4028
  const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
3157
4029
  if (written === null)
3158
4030
  return 1;
3159
4031
  console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
4032
+ const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
4033
+ if (changes)
4034
+ console.log(` ${changes}`);
3160
4035
  if (options.dryRun) {
3161
4036
  console.log("\nDry run \u2014 nothing was written.");
3162
4037
  return 0;
@@ -3244,6 +4119,45 @@ ${usage(spec)}`);
3244
4119
  }
3245
4120
  return options;
3246
4121
  }
4122
+ async function runCliAgentStudyJoin(argv, spec) {
4123
+ const joinCode = argv[0];
4124
+ if (!joinCode || joinCode.startsWith("-")) {
4125
+ console.error(`Usage: npx ${spec.packageName} join <code>`);
4126
+ return 1;
4127
+ }
4128
+ const pairing = resolvePairedToken(spec);
4129
+ if (!pairing)
4130
+ return 1;
4131
+ return (0, studyJoin_1.runStudyJoin)({ ...pairing, displayName: spec.displayName, joinCode });
4132
+ }
4133
+ async function runCliAgentStudyObjection(argv, spec) {
4134
+ const pairing = resolvePairedToken(spec);
4135
+ if (!pairing)
4136
+ return 1;
4137
+ return (0, studyNotices_1.runStudyObjection)({
4138
+ ...pairing,
4139
+ commandPrefix: `npx ${spec.packageName}`,
4140
+ pairCommand: `npx ${spec.packageName} setup`,
4141
+ argv
4142
+ });
4143
+ }
4144
+ function resolvePairedToken(spec) {
4145
+ const setupCommand = `npx ${spec.packageName} setup`;
4146
+ let toolInstallationId;
4147
+ try {
4148
+ ({ toolInstallationId } = (0, hookAdapter_1.resolveCliAgentInstallationId)(spec.toolType, { host: spec.host, setupCommand }));
4149
+ } catch (error2) {
4150
+ console.error(error2 instanceof hookAdapter_1.MissingInstallationIdError ? error2.message : error2 instanceof Error ? error2.message : String(error2));
4151
+ return void 0;
4152
+ }
4153
+ const eventWriteToken = (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId)) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
4154
+ if (!eventWriteToken) {
4155
+ console.error(`Not paired: no write token for ${toolInstallationId}. Run: ${setupCommand}`);
4156
+ return void 0;
4157
+ }
4158
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4159
+ return { apiBaseUrl, eventWriteToken };
4160
+ }
3247
4161
  async function resolveIdentity(apiBaseUrl, options, spec) {
3248
4162
  const existingId = options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId;
3249
4163
  if (existingId && options.token) {
@@ -3251,8 +4165,13 @@ ${usage(spec)}`);
3251
4165
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(existingId), options.token);
3252
4166
  return { toolInstallationId: existingId, paired: false };
3253
4167
  }
3254
- if (existingId && (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId))) {
3255
- return { toolInstallationId: existingId, paired: false };
4168
+ const existingToken = existingId ? (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId)) : void 0;
4169
+ if (existingId && existingToken) {
4170
+ const check2 = await checkSavedToken(apiBaseUrl, existingId, existingToken);
4171
+ if (check2 === "keep")
4172
+ return { toolInstallationId: existingId, paired: false };
4173
+ console.log(`
4174
+ The saved token for ${existingId} isn't accepted any more. Pairing again.`);
3256
4175
  }
3257
4176
  if (options.dryRun) {
3258
4177
  return { toolInstallationId: existingId ?? `${spec.toolType}:<paired at run time>`, paired: false };
@@ -3273,6 +4192,18 @@ Could not reach ${apiBaseUrl} to pair: ${error2 instanceof Error ? error2.messag
3273
4192
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(toolInstallationId), token);
3274
4193
  return { toolInstallationId, paired: true };
3275
4194
  }
4195
+ var TOKEN_CHECK_TIMEOUT_MS = 5e3;
4196
+ async function checkSavedToken(apiBaseUrl, toolInstallationId, token) {
4197
+ const read = await (0, http_1.readInitiatives)(apiBaseUrl, token, AbortSignal.timeout(TOKEN_CHECK_TIMEOUT_MS));
4198
+ if (read.kind === "rejected")
4199
+ return "repair";
4200
+ if (read.kind === "failed" && (0, stateStore_1.readCollectorState)((0, stateStore_1.defaultStateFilePath)(toolInstallationId))?.lastOutcome === "auth_failed") {
4201
+ console.log(`
4202
+ Couldn't check the saved token (${read.reason}), and the last send was refused.`);
4203
+ console.log(" Keeping it for now. Run setup again once the server is reachable.");
4204
+ }
4205
+ return "keep";
4206
+ }
3276
4207
  async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
3277
4208
  const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
3278
4209
  let announced = false;
@@ -3324,7 +4255,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
3324
4255
  }
3325
4256
  }
3326
4257
  }
3327
- const command = hookCommand(binary);
4258
+ const command = hookCommand(binary, spec);
3328
4259
  const hooks = { ...settings.hooks ?? {} };
3329
4260
  for (const event of spec.hookEvents) {
3330
4261
  const kept = (hooks[event] ?? []).filter((entry) => !isOurs(entry, spec));
@@ -3347,8 +4278,20 @@ ${serialised}`);
3347
4278
  fs.writeFileSync(settingsFile, serialised, "utf8");
3348
4279
  return true;
3349
4280
  }
3350
- function hookCommand(binary) {
3351
- return `"${process.execPath}" "${binary}"`;
4281
+ function hookCommand(binary, spec) {
4282
+ return `"${process.execPath}" "${binary}"${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
4283
+ }
4284
+ function registeredHookSets(settings, spec) {
4285
+ const sets = /* @__PURE__ */ new Map();
4286
+ for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
4287
+ for (const entry of entries ?? []) {
4288
+ if (!isOurs(entry, spec))
4289
+ continue;
4290
+ const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
4291
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
4292
+ }
4293
+ }
4294
+ return sets;
3352
4295
  }
3353
4296
  function isOurs(entry, spec) {
3354
4297
  const command = spec.settings.commandOf(entry);
@@ -3375,7 +4318,7 @@ ${serialised}`);
3375
4318
  return {};
3376
4319
  }
3377
4320
  }
3378
- function printStatus(options, spec) {
4321
+ async function printStatus(options, spec) {
3379
4322
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
3380
4323
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3381
4324
  const binary = cliAgentHookBinPath(spec.binaryName);
@@ -3390,12 +4333,30 @@ ${serialised}`);
3390
4333
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
3391
4334
  console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
3392
4335
  console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
4336
+ if (spec.hookSet !== void 0 && registered > 0) {
4337
+ const sets = [...registeredHookSets(settings, spec).values()];
4338
+ const oldest = Math.min(...sets);
4339
+ 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)`);
4340
+ }
3393
4341
  if (stale.length) {
3394
4342
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
3395
4343
  for (const command of stale)
3396
4344
  console.log(` ${command}`);
3397
4345
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
3398
4346
  }
4347
+ const tokenValue = localOnly ? void 0 : (tokenFile ? (0, tokenStore_1.readTokenFile)(tokenFile) : void 0) ?? (process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim() || void 0);
4348
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4349
+ const [initiativeLines, notices] = await Promise.all([
4350
+ (0, initiatives_1.initiativesStatusLines)({ apiBaseUrl, eventWriteToken: tokenValue, pairCommand: `npx ${spec.packageName} setup` }),
4351
+ (0, studyNotices_1.studyNoticeStatus)({ apiBaseUrl, eventWriteToken: tokenValue, commandPrefix: `npx ${spec.packageName}` })
4352
+ ]);
4353
+ console.log("");
4354
+ for (const line of initiativeLines)
4355
+ console.log(line);
4356
+ for (const line of notices.lines)
4357
+ console.log(line);
4358
+ if (process.stdout.isTTY)
4359
+ await notices.markShown();
3399
4360
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
3400
4361
  const healthy = paired && registered === spec.hookEvents.length && fs.existsSync(binary) && !stale.length;
3401
4362
  return healthy ? 0 : 1;
@@ -3562,6 +4523,7 @@ var require_liveBus = __commonJS({
3562
4523
  };
3563
4524
  }();
3564
4525
  Object.defineProperty(exports, "__esModule", { value: true });
4526
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
3565
4527
  exports.liveBusSocketCandidates = liveBusSocketCandidates;
3566
4528
  exports.liveBusSocketPath = liveBusSocketPath;
3567
4529
  exports.bucketPromptSize = bucketPromptSize;
@@ -3570,7 +4532,9 @@ var require_liveBus = __commonJS({
3570
4532
  var net = __importStar(__require("net"));
3571
4533
  var os = __importStar(__require("os"));
3572
4534
  var path = __importStar(__require("path"));
4535
+ var hookSet_1 = require_hookSet();
3573
4536
  var WRITE_TIMEOUT_MS = 50;
4537
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
3574
4538
  var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
3575
4539
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3576
4540
  function liveBusSocketCandidates() {
@@ -3610,6 +4574,14 @@ var require_liveBus = __commonJS({
3610
4574
  return "xl";
3611
4575
  }
3612
4576
  var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4577
+ function onTheWire(signal) {
4578
+ const out = { ...signal };
4579
+ if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4580
+ delete out.hookSet;
4581
+ if ("viaPlugin" in out && out.viaPlugin !== true)
4582
+ delete out.viaPlugin;
4583
+ return out;
4584
+ }
3613
4585
  function emitLiveSignal(signal) {
3614
4586
  return new Promise((resolve) => {
3615
4587
  const candidates = existingSocketCandidates();
@@ -3670,7 +4642,7 @@ var require_liveBus = __commonJS({
3670
4642
  return;
3671
4643
  connected = true;
3672
4644
  try {
3673
- attempt.write(`${JSON.stringify(signal)}
4645
+ attempt.write(`${JSON.stringify(onTheWire(signal))}
3674
4646
  `, done);
3675
4647
  } catch {
3676
4648
  done();
@@ -3683,14 +4655,153 @@ var require_liveBus = __commonJS({
3683
4655
  }
3684
4656
  });
3685
4657
 
4658
+ // ../packages/tool-kit/out/agentProcess.js
4659
+ var require_agentProcess = __commonJS({
4660
+ "../packages/tool-kit/out/agentProcess.js"(exports) {
4661
+ "use strict";
4662
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4663
+ if (k2 === void 0) k2 = k;
4664
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4665
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4666
+ desc = { enumerable: true, get: function() {
4667
+ return m[k];
4668
+ } };
4669
+ }
4670
+ Object.defineProperty(o, k2, desc);
4671
+ } : function(o, m, k, k2) {
4672
+ if (k2 === void 0) k2 = k;
4673
+ o[k2] = m[k];
4674
+ });
4675
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4676
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4677
+ } : function(o, v) {
4678
+ o["default"] = v;
4679
+ });
4680
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4681
+ var ownKeys = function(o) {
4682
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4683
+ var ar = [];
4684
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4685
+ return ar;
4686
+ };
4687
+ return ownKeys(o);
4688
+ };
4689
+ return function(mod) {
4690
+ if (mod && mod.__esModule) return mod;
4691
+ var result = {};
4692
+ if (mod != null) {
4693
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4694
+ }
4695
+ __setModuleDefault(result, mod);
4696
+ return result;
4697
+ };
4698
+ }();
4699
+ Object.defineProperty(exports, "__esModule", { value: true });
4700
+ exports.psArgsLookup = exports.psLookup = exports.AGENT_PROCESS = void 0;
4701
+ exports.scriptMarkerIn = scriptMarkerIn;
4702
+ exports.findAgentProcess = findAgentProcess;
4703
+ exports.findAgentPid = findAgentPid;
4704
+ exports.livePidFields = livePidFields;
4705
+ var child_process_1 = __require("child_process");
4706
+ var path = __importStar(__require("path"));
4707
+ exports.AGENT_PROCESS = {
4708
+ claude_code: {
4709
+ executable: (command) => path.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
4710
+ scriptMarkers: ["@anthropic-ai/claude-code"]
4711
+ },
4712
+ codex: {
4713
+ executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path.basename(command)),
4714
+ args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
4715
+ },
4716
+ gemini_cli: {
4717
+ executable: () => false,
4718
+ args: (args) => !/\s--(experimental-)?acp(\s|=|$)/.test(args),
4719
+ scriptMarkers: ["@google/gemini-cli"]
4720
+ }
4721
+ };
4722
+ var SCRIPT_RUNTIME = /^(node|bun|deno)$/;
4723
+ function scriptMarkerIn(args, markers) {
4724
+ return markers.find((marker) => args.includes(`/${marker}/`));
4725
+ }
4726
+ var MAX_DEPTH = 6;
4727
+ var PS_TIMEOUT_MS = 100;
4728
+ function ps(columns, pid) {
4729
+ try {
4730
+ const result = (0, child_process_1.spawnSync)("/bin/ps", ["-o", columns, "-p", String(pid)], {
4731
+ encoding: "utf8",
4732
+ timeout: PS_TIMEOUT_MS
4733
+ });
4734
+ if (result.status !== 0 || typeof result.stdout !== "string")
4735
+ return void 0;
4736
+ const line = result.stdout.trim();
4737
+ return line === "" ? void 0 : line;
4738
+ } catch {
4739
+ return void 0;
4740
+ }
4741
+ }
4742
+ var psLookup = (pid) => {
4743
+ const line = ps("ppid=,comm=", pid);
4744
+ const match = line ? /^(\d+)\s+(.+)$/.exec(line) : null;
4745
+ return match ? { ppid: Number(match[1]), command: match[2] } : void 0;
4746
+ };
4747
+ exports.psLookup = psLookup;
4748
+ var psArgsLookup = (pid) => ps("args=", pid);
4749
+ exports.psArgsLookup = psArgsLookup;
4750
+ function findAgentProcess(rule, options = {}) {
4751
+ if (!rule)
4752
+ return void 0;
4753
+ if ((options.platform ?? process.platform) !== "darwin")
4754
+ return void 0;
4755
+ const lookup = options.lookup ?? exports.psLookup;
4756
+ const argsLookup = options.argsLookup ?? exports.psArgsLookup;
4757
+ const markers = rule.scriptMarkers ?? [];
4758
+ let pid = options.startPid ?? process.ppid;
4759
+ for (let depth = 0; depth < MAX_DEPTH && pid > 1; depth++) {
4760
+ const info = lookup(pid);
4761
+ if (!info)
4762
+ return void 0;
4763
+ if (pid !== process.pid) {
4764
+ if (rule.executable(info.command)) {
4765
+ return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
4766
+ }
4767
+ if (markers.length > 0 && SCRIPT_RUNTIME.test(path.basename(info.command))) {
4768
+ const args = argsLookup(pid);
4769
+ const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
4770
+ if (marker !== void 0) {
4771
+ return accepts(rule, args) ? { pid, match: "path", marker } : void 0;
4772
+ }
4773
+ }
4774
+ }
4775
+ pid = info.ppid;
4776
+ }
4777
+ return void 0;
4778
+ }
4779
+ function accepts(rule, args) {
4780
+ if (!rule.args)
4781
+ return true;
4782
+ return args !== void 0 && rule.args(args);
4783
+ }
4784
+ function findAgentPid(rule, options = {}) {
4785
+ return findAgentProcess(rule, options)?.pid;
4786
+ }
4787
+ function livePidFields(match) {
4788
+ if (!match)
4789
+ return {};
4790
+ if (match.match === "executable")
4791
+ return { pid: match.pid };
4792
+ return { pid: match.pid, pidMatch: "path", pidMarker: match.marker };
4793
+ }
4794
+ }
4795
+ });
4796
+
3686
4797
  // ../packages/tool-kit/out/index.js
3687
4798
  var require_out2 = __commonJS({
3688
4799
  "../packages/tool-kit/out/index.js"(exports) {
3689
4800
  "use strict";
3690
4801
  Object.defineProperty(exports, "__esModule", { value: true });
3691
- 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;
3692
- 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;
3693
- 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;
4802
+ 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;
4803
+ 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;
4804
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
3694
4805
  var commandClassifier_1 = require_commandClassifier();
3695
4806
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
3696
4807
  return commandClassifier_1.classifyCommand;
@@ -3788,6 +4899,9 @@ var require_out2 = __commonJS({
3788
4899
  Object.defineProperty(exports, "AscendaSemanticEventError", { enumerable: true, get: function() {
3789
4900
  return eventSender_1.AscendaSemanticEventError;
3790
4901
  } });
4902
+ Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
4903
+ return eventSender_1.TOKEN_RENEW_LEAD_MS;
4904
+ } });
3791
4905
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
3792
4906
  return eventSender_1.buildEventPayload;
3793
4907
  } });
@@ -3833,6 +4947,9 @@ var require_out2 = __commonJS({
3833
4947
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
3834
4948
  return cliAgentSetup_1.isCliAgentManagementCommand;
3835
4949
  } });
4950
+ Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
4951
+ return cliAgentSetup_1.registeredHookSets;
4952
+ } });
3836
4953
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
3837
4954
  return cliAgentSetup_1.runCliAgentSetup;
3838
4955
  } });
@@ -3888,6 +5005,9 @@ var require_out2 = __commonJS({
3888
5005
  return turnState_1.recordTurnStart;
3889
5006
  } });
3890
5007
  var tokenStore_1 = require_tokenStore();
5008
+ Object.defineProperty(exports, "EVENT_TOKEN_TTL_MS", { enumerable: true, get: function() {
5009
+ return tokenStore_1.EVENT_TOKEN_TTL_MS;
5010
+ } });
3891
5011
  Object.defineProperty(exports, "ascendaHome", { enumerable: true, get: function() {
3892
5012
  return tokenStore_1.ascendaHome;
3893
5013
  } });
@@ -3900,9 +5020,15 @@ var require_out2 = __commonJS({
3900
5020
  Object.defineProperty(exports, "persistEventWriteToken", { enumerable: true, get: function() {
3901
5021
  return tokenStore_1.persistEventWriteToken;
3902
5022
  } });
5023
+ Object.defineProperty(exports, "readTokenExpiry", { enumerable: true, get: function() {
5024
+ return tokenStore_1.readTokenExpiry;
5025
+ } });
3903
5026
  Object.defineProperty(exports, "readTokenFile", { enumerable: true, get: function() {
3904
5027
  return tokenStore_1.readTokenFile;
3905
5028
  } });
5029
+ Object.defineProperty(exports, "tokenExpiryFilePath", { enumerable: true, get: function() {
5030
+ return tokenStore_1.tokenExpiryFilePath;
5031
+ } });
3906
5032
  var stateStore_1 = require_stateStore();
3907
5033
  Object.defineProperty(exports, "defaultStateFilePath", { enumerable: true, get: function() {
3908
5034
  return stateStore_1.defaultStateFilePath;
@@ -4034,6 +5160,59 @@ var require_out2 = __commonJS({
4034
5160
  Object.defineProperty(exports, "liveBusSocketCandidates", { enumerable: true, get: function() {
4035
5161
  return liveBus_1.liveBusSocketCandidates;
4036
5162
  } });
5163
+ Object.defineProperty(exports, "LIVE_BUS_BACKGROUND_TRUST_MS", { enumerable: true, get: function() {
5164
+ return liveBus_1.LIVE_BUS_BACKGROUND_TRUST_MS;
5165
+ } });
5166
+ var hookSet_1 = require_hookSet();
5167
+ Object.defineProperty(exports, "HOOK_SET_FLAG", { enumerable: true, get: function() {
5168
+ return hookSet_1.HOOK_SET_FLAG;
5169
+ } });
5170
+ Object.defineProperty(exports, "UNVERSIONED_HOOK_SET", { enumerable: true, get: function() {
5171
+ return hookSet_1.UNVERSIONED_HOOK_SET;
5172
+ } });
5173
+ Object.defineProperty(exports, "describeHookSetChanges", { enumerable: true, get: function() {
5174
+ return hookSet_1.describeHookSetChanges;
5175
+ } });
5176
+ Object.defineProperty(exports, "hookSetArgument", { enumerable: true, get: function() {
5177
+ return hookSet_1.hookSetArgument;
5178
+ } });
5179
+ Object.defineProperty(exports, "hookSetChanges", { enumerable: true, get: function() {
5180
+ return hookSet_1.hookSetChanges;
5181
+ } });
5182
+ Object.defineProperty(exports, "hookSetOfCommand", { enumerable: true, get: function() {
5183
+ return hookSet_1.hookSetOfCommand;
5184
+ } });
5185
+ Object.defineProperty(exports, "isHookSet", { enumerable: true, get: function() {
5186
+ return hookSet_1.isHookSet;
5187
+ } });
5188
+ Object.defineProperty(exports, "readHookSet", { enumerable: true, get: function() {
5189
+ return hookSet_1.readHookSet;
5190
+ } });
5191
+ Object.defineProperty(exports, "readViaPlugin", { enumerable: true, get: function() {
5192
+ return hookSet_1.readViaPlugin;
5193
+ } });
5194
+ var agentProcess_1 = require_agentProcess();
5195
+ Object.defineProperty(exports, "AGENT_PROCESS", { enumerable: true, get: function() {
5196
+ return agentProcess_1.AGENT_PROCESS;
5197
+ } });
5198
+ Object.defineProperty(exports, "findAgentPid", { enumerable: true, get: function() {
5199
+ return agentProcess_1.findAgentPid;
5200
+ } });
5201
+ Object.defineProperty(exports, "findAgentProcess", { enumerable: true, get: function() {
5202
+ return agentProcess_1.findAgentProcess;
5203
+ } });
5204
+ Object.defineProperty(exports, "livePidFields", { enumerable: true, get: function() {
5205
+ return agentProcess_1.livePidFields;
5206
+ } });
5207
+ Object.defineProperty(exports, "psArgsLookup", { enumerable: true, get: function() {
5208
+ return agentProcess_1.psArgsLookup;
5209
+ } });
5210
+ Object.defineProperty(exports, "psLookup", { enumerable: true, get: function() {
5211
+ return agentProcess_1.psLookup;
5212
+ } });
5213
+ Object.defineProperty(exports, "scriptMarkerIn", { enumerable: true, get: function() {
5214
+ return agentProcess_1.scriptMarkerIn;
5215
+ } });
4037
5216
  var http_1 = require_http();
4038
5217
  Object.defineProperty(exports, "AscendaApiError", { enumerable: true, get: function() {
4039
5218
  return http_1.AscendaApiError;
@@ -4044,6 +5223,9 @@ var require_out2 = __commonJS({
4044
5223
  Object.defineProperty(exports, "getPairingStatus", { enumerable: true, get: function() {
4045
5224
  return http_1.getPairingStatus;
4046
5225
  } });
5226
+ Object.defineProperty(exports, "getStudyJoinStatus", { enumerable: true, get: function() {
5227
+ return http_1.getStudyJoinStatus;
5228
+ } });
4047
5229
  Object.defineProperty(exports, "renewToolToken", { enumerable: true, get: function() {
4048
5230
  return http_1.renewToolToken;
4049
5231
  } });
@@ -4059,6 +5241,48 @@ var require_out2 = __commonJS({
4059
5241
  Object.defineProperty(exports, "isRetryableStatus", { enumerable: true, get: function() {
4060
5242
  return http_1.isRetryableStatus;
4061
5243
  } });
5244
+ Object.defineProperty(exports, "readInitiatives", { enumerable: true, get: function() {
5245
+ return http_1.readInitiatives;
5246
+ } });
5247
+ Object.defineProperty(exports, "readStudyNotices", { enumerable: true, get: function() {
5248
+ return http_1.readStudyNotices;
5249
+ } });
5250
+ Object.defineProperty(exports, "markStudyNoticeShown", { enumerable: true, get: function() {
5251
+ return http_1.markStudyNoticeShown;
5252
+ } });
5253
+ Object.defineProperty(exports, "setStudyObjection", { enumerable: true, get: function() {
5254
+ return http_1.setStudyObjection;
5255
+ } });
5256
+ Object.defineProperty(exports, "startStudyJoin", { enumerable: true, get: function() {
5257
+ return http_1.startStudyJoin;
5258
+ } });
5259
+ var initiatives_1 = require_initiatives();
5260
+ Object.defineProperty(exports, "INITIATIVE_COPY", { enumerable: true, get: function() {
5261
+ return initiatives_1.INITIATIVE_COPY;
5262
+ } });
5263
+ Object.defineProperty(exports, "initiativesStatusLines", { enumerable: true, get: function() {
5264
+ return initiatives_1.initiativesStatusLines;
5265
+ } });
5266
+ Object.defineProperty(exports, "renderInitiatives", { enumerable: true, get: function() {
5267
+ return initiatives_1.renderInitiatives;
5268
+ } });
5269
+ var studyNotices_1 = require_studyNotices();
5270
+ Object.defineProperty(exports, "NOTICED_PURPOSES", { enumerable: true, get: function() {
5271
+ return studyNotices_1.NOTICED_PURPOSES;
5272
+ } });
5273
+ Object.defineProperty(exports, "renderStudyNotices", { enumerable: true, get: function() {
5274
+ return studyNotices_1.renderStudyNotices;
5275
+ } });
5276
+ Object.defineProperty(exports, "runStudyObjection", { enumerable: true, get: function() {
5277
+ return studyNotices_1.runStudyObjection;
5278
+ } });
5279
+ Object.defineProperty(exports, "studyNoticeStatus", { enumerable: true, get: function() {
5280
+ return studyNotices_1.studyNoticeStatus;
5281
+ } });
5282
+ var studyJoin_1 = require_studyJoin();
5283
+ Object.defineProperty(exports, "runStudyJoin", { enumerable: true, get: function() {
5284
+ return studyJoin_1.runStudyJoin;
5285
+ } });
4062
5286
  }
4063
5287
  });
4064
5288