@ascenda-one/claude-code-hooks 0.1.34 → 0.1.35

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
@@ -636,9 +636,11 @@ var require_out = __commonJS({
636
636
  "../packages/tool-contract/out/index.js"(exports) {
637
637
  "use strict";
638
638
  Object.defineProperty(exports, "__esModule", { value: true });
639
- exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
639
+ exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.DELIVERY_ENVELOPE_KEYS = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
640
640
  exports.combineDisjointHalves = combineDisjointHalves;
641
641
  exports.requireComparableQuantities = requireComparableQuantities;
642
+ exports.joinEventPayload = joinEventPayload;
643
+ exports.splitEventPayload = splitEventPayload;
642
644
  exports.ASCENDA_TELEMETRY_SOURCES = [
643
645
  "vscode_extension",
644
646
  "cursor_mcp",
@@ -790,6 +792,24 @@ var require_out = __commonJS({
790
792
  "importSchema",
791
793
  "collectorVersion"
792
794
  ];
795
+ exports.DELIVERY_ENVELOPE_KEYS = ["toolInstallationId", "idempotencyKey"];
796
+ function joinEventPayload(envelope, body) {
797
+ const payload = { toolInstallationId: envelope.toolInstallationId };
798
+ for (const [key, value] of Object.entries(body)) {
799
+ payload[key] = value;
800
+ if (key === "occurredAt" && envelope.idempotencyKey !== void 0) {
801
+ payload.idempotencyKey = envelope.idempotencyKey;
802
+ }
803
+ }
804
+ return payload;
805
+ }
806
+ function splitEventPayload(payload) {
807
+ const { toolInstallationId, idempotencyKey, ...body } = payload;
808
+ const envelope = { toolInstallationId };
809
+ if (idempotencyKey !== void 0)
810
+ envelope.idempotencyKey = idempotencyKey;
811
+ return { envelope, body };
812
+ }
793
813
  exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
794
814
  exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
795
815
  exports.EVENT_WORKLOAD_CATEGORY = {
@@ -968,13 +988,387 @@ var require_collectorVersion = __commonJS({
968
988
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
969
989
  exports.describeCollectorVersion = describeCollectorVersion2;
970
990
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
971
- exports.COLLECTOR_VERSION = "0.1.34" ? "0.1.34" : exports.UNRELEASED_COLLECTOR_VERSION;
991
+ exports.COLLECTOR_VERSION = "0.1.35" ? "0.1.35" : exports.UNRELEASED_COLLECTOR_VERSION;
972
992
  function describeCollectorVersion2(version = exports.COLLECTOR_VERSION) {
973
993
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
974
994
  }
975
995
  }
976
996
  });
977
997
 
998
+ // ../packages/agent-events/out/index.js
999
+ var require_out2 = __commonJS({
1000
+ "../packages/agent-events/out/index.js"(exports) {
1001
+ "use strict";
1002
+ Object.defineProperty(exports, "__esModule", { value: true });
1003
+ exports.KNOWN_AGENTS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1004
+ exports.isAgentEventV0 = isAgentEventV0;
1005
+ exports.parseEventLogLine = parseEventLogLine;
1006
+ exports.normaliseKind = normaliseKind;
1007
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1008
+ exports.AGENT_EVENT_KINDS = [
1009
+ "session.started",
1010
+ "session.ended",
1011
+ "prompt.submitted",
1012
+ "tool.started",
1013
+ "tool.completed",
1014
+ "tool.failed",
1015
+ "turn.completed",
1016
+ "agent.waiting",
1017
+ "context.compacted",
1018
+ "subagent.started",
1019
+ "subagent.stopped",
1020
+ "other"
1021
+ ];
1022
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1023
+ function isAgentEventV0(value) {
1024
+ if (!value || typeof value !== "object")
1025
+ return false;
1026
+ const e = value;
1027
+ return e.schema === exports.AGENT_EVENT_SCHEMA && typeof e.id === "string" && e.id.length > 0 && typeof e.time === "string" && !Number.isNaN(Date.parse(e.time)) && typeof e.agent === "string" && e.agent.length > 0 && typeof e.kind === "string";
1028
+ }
1029
+ function parseEventLogLine(line) {
1030
+ if (!line.trim())
1031
+ return void 0;
1032
+ try {
1033
+ const parsed = JSON.parse(line);
1034
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1035
+ } catch {
1036
+ return void 0;
1037
+ }
1038
+ }
1039
+ function normaliseKind(kind) {
1040
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1041
+ }
1042
+ }
1043
+ });
1044
+
1045
+ // ../packages/tool-kit/out/agentEvent.js
1046
+ var require_agentEvent = __commonJS({
1047
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1048
+ "use strict";
1049
+ Object.defineProperty(exports, "__esModule", { value: true });
1050
+ exports.toAgentEvent = toAgentEvent;
1051
+ var agent_events_1 = require_out2();
1052
+ var KIND_BY_TYPE = {
1053
+ create_focus_session: "session.started",
1054
+ recovery_offline_period: "session.ended",
1055
+ ai_prompt_submitted: "prompt.submitted",
1056
+ ai_tool_call_started: "tool.started",
1057
+ ai_tool_call_completed: "tool.completed",
1058
+ ai_file_write: "tool.completed",
1059
+ ai_file_edit: "tool.completed",
1060
+ editor_verification_activity: "tool.completed",
1061
+ ai_tool_call_failed: "tool.failed",
1062
+ compile_error: "tool.failed",
1063
+ tool_failure: "tool.failed",
1064
+ ai_turn_completed: "turn.completed",
1065
+ supervision_interruption: "agent.waiting",
1066
+ context_compression_manual: "context.compacted",
1067
+ context_compression_auto: "context.compacted",
1068
+ subagent_started: "subagent.started",
1069
+ subagent_stopped: "subagent.stopped"
1070
+ };
1071
+ function agentOf(payload) {
1072
+ const host = stringField(payload.metadata?.host);
1073
+ if (host)
1074
+ return host;
1075
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1076
+ }
1077
+ function stringField(value) {
1078
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1079
+ }
1080
+ function toAgentEvent(payload) {
1081
+ const metadata = payload.metadata ?? {};
1082
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1083
+ const tool = kind.startsWith("tool.") ? stringField(metadata.toolName) : void 0;
1084
+ const outcome = stringField(metadata.outcome);
1085
+ return {
1086
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1087
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1088
+ time: payload.occurredAt,
1089
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1090
+ // writes anyway; without it the event in memory and the one on disk differ.
1091
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1092
+ agent: agentOf(payload),
1093
+ kind,
1094
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1095
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1096
+ ...tool ? { tool } : {},
1097
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1098
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1099
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1100
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1101
+ sourceType: payload.eventType
1102
+ };
1103
+ }
1104
+ }
1105
+ });
1106
+
1107
+ // ../packages/tool-kit/out/tokenStore.js
1108
+ var require_tokenStore = __commonJS({
1109
+ "../packages/tool-kit/out/tokenStore.js"(exports) {
1110
+ "use strict";
1111
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1112
+ if (k2 === void 0) k2 = k;
1113
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1114
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1115
+ desc = { enumerable: true, get: function() {
1116
+ return m[k];
1117
+ } };
1118
+ }
1119
+ Object.defineProperty(o, k2, desc);
1120
+ } : function(o, m, k, k2) {
1121
+ if (k2 === void 0) k2 = k;
1122
+ o[k2] = m[k];
1123
+ });
1124
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1125
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1126
+ } : function(o, v) {
1127
+ o["default"] = v;
1128
+ });
1129
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1130
+ var ownKeys = function(o) {
1131
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1132
+ var ar = [];
1133
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1134
+ return ar;
1135
+ };
1136
+ return ownKeys(o);
1137
+ };
1138
+ return function(mod) {
1139
+ if (mod && mod.__esModule) return mod;
1140
+ var result = {};
1141
+ if (mod != null) {
1142
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1143
+ }
1144
+ __setModuleDefault(result, mod);
1145
+ return result;
1146
+ };
1147
+ }();
1148
+ Object.defineProperty(exports, "__esModule", { value: true });
1149
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1150
+ exports.ascendaHome = ascendaHome3;
1151
+ exports.defaultTokenFilePath = defaultTokenFilePath4;
1152
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1153
+ exports.persistEventWriteToken = persistEventWriteToken4;
1154
+ exports.readTokenExpiry = readTokenExpiry;
1155
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
1156
+ exports.readTokenFile = readTokenFile3;
1157
+ exports.sanitizeFilePart = sanitizeFilePart;
1158
+ var fs5 = __importStar(__require("fs"));
1159
+ var os5 = __importStar(__require("os"));
1160
+ var path4 = __importStar(__require("path"));
1161
+ function ascendaHome3(home = os5.homedir()) {
1162
+ return process.env.ASCENDA_HOME ?? path4.join(home, ".ascenda");
1163
+ }
1164
+ function defaultTokenFilePath4(toolInstallationId) {
1165
+ return path4.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1166
+ }
1167
+ function tokenExpiryFilePath(tokenFilePath) {
1168
+ return path4.join(path4.dirname(tokenFilePath), "expiry", path4.basename(tokenFilePath));
1169
+ }
1170
+ function persistEventWriteToken4(tokenFilePath, token, expiresAt) {
1171
+ const dir = path4.dirname(tokenFilePath);
1172
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1173
+ fs5.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1174
+ if (process.platform !== "win32") {
1175
+ fs5.chmodSync(dir, 448);
1176
+ fs5.chmodSync(tokenFilePath, 384);
1177
+ }
1178
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1179
+ try {
1180
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1181
+ fs5.mkdirSync(path4.dirname(expiryFile), { recursive: true, mode: 448 });
1182
+ fs5.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1183
+ } else {
1184
+ fs5.rmSync(expiryFile, { force: true });
1185
+ }
1186
+ } catch {
1187
+ }
1188
+ }
1189
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1190
+ function readTokenExpiry(tokenFilePath) {
1191
+ try {
1192
+ const recorded = Date.parse(fs5.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1193
+ if (Number.isFinite(recorded))
1194
+ return recorded;
1195
+ } catch {
1196
+ }
1197
+ try {
1198
+ return fs5.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1199
+ } catch {
1200
+ return void 0;
1201
+ }
1202
+ }
1203
+ function listPersistedToolInstallationIds2(toolType) {
1204
+ const prefix = `${sanitizeFilePart(toolType)}_`;
1205
+ const dir = path4.join(ascendaHome3(), "tokens");
1206
+ let names;
1207
+ try {
1208
+ names = fs5.readdirSync(dir);
1209
+ } catch {
1210
+ return [];
1211
+ }
1212
+ const ids = [];
1213
+ for (const name of names.sort()) {
1214
+ if (!name.startsWith(prefix) || name.length === prefix.length)
1215
+ continue;
1216
+ const file = path4.join(dir, name);
1217
+ try {
1218
+ if (!fs5.statSync(file).isFile())
1219
+ continue;
1220
+ } catch {
1221
+ continue;
1222
+ }
1223
+ if (readTokenFile3(file) === void 0)
1224
+ continue;
1225
+ ids.push(`${toolType}:${name.slice(prefix.length)}`);
1226
+ }
1227
+ return ids;
1228
+ }
1229
+ function readTokenFile3(tokenFilePath) {
1230
+ try {
1231
+ if (!fs5.existsSync(tokenFilePath))
1232
+ return void 0;
1233
+ const value = fs5.readFileSync(tokenFilePath, "utf8").trim();
1234
+ return value || void 0;
1235
+ } catch {
1236
+ return void 0;
1237
+ }
1238
+ }
1239
+ function sanitizeFilePart(value) {
1240
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1241
+ }
1242
+ }
1243
+ });
1244
+
1245
+ // ../packages/tool-kit/out/credentials.js
1246
+ var require_credentials = __commonJS({
1247
+ "../packages/tool-kit/out/credentials.js"(exports) {
1248
+ "use strict";
1249
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1250
+ if (k2 === void 0) k2 = k;
1251
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1252
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1253
+ desc = { enumerable: true, get: function() {
1254
+ return m[k];
1255
+ } };
1256
+ }
1257
+ Object.defineProperty(o, k2, desc);
1258
+ } : function(o, m, k, k2) {
1259
+ if (k2 === void 0) k2 = k;
1260
+ o[k2] = m[k];
1261
+ });
1262
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1263
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1264
+ } : function(o, v) {
1265
+ o["default"] = v;
1266
+ });
1267
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1268
+ var ownKeys = function(o) {
1269
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1270
+ var ar = [];
1271
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1272
+ return ar;
1273
+ };
1274
+ return ownKeys(o);
1275
+ };
1276
+ return function(mod) {
1277
+ if (mod && mod.__esModule) return mod;
1278
+ var result = {};
1279
+ if (mod != null) {
1280
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1281
+ }
1282
+ __setModuleDefault(result, mod);
1283
+ return result;
1284
+ };
1285
+ }();
1286
+ Object.defineProperty(exports, "__esModule", { value: true });
1287
+ exports.credentialsFilePath = credentialsFilePath2;
1288
+ exports.readMachineCredentials = readMachineCredentials2;
1289
+ exports.writeMachineCredentials = writeMachineCredentials2;
1290
+ exports.writeTopLevelCredentials = writeTopLevelCredentials2;
1291
+ exports.writeEventLogSetting = writeEventLogSetting2;
1292
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
1293
+ exports.readHostCredentials = readHostCredentials;
1294
+ exports.writeHostCredentials = writeHostCredentials;
1295
+ exports.removeHostCredentials = removeHostCredentials;
1296
+ var fs5 = __importStar(__require("fs"));
1297
+ var path4 = __importStar(__require("path"));
1298
+ var tokenStore_1 = require_tokenStore();
1299
+ function credentialsFilePath2() {
1300
+ return path4.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1301
+ }
1302
+ function readMachineCredentials2() {
1303
+ try {
1304
+ const raw = fs5.readFileSync(credentialsFilePath2(), "utf8").trim();
1305
+ if (!raw)
1306
+ return void 0;
1307
+ const parsed = JSON.parse(raw);
1308
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1309
+ return void 0;
1310
+ return parsed;
1311
+ } catch {
1312
+ return void 0;
1313
+ }
1314
+ }
1315
+ function writeMachineCredentials2(credentials) {
1316
+ const file = credentialsFilePath2();
1317
+ fs5.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
1318
+ fs5.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
1319
+ `, { encoding: "utf8", mode: 384 });
1320
+ if (process.platform !== "win32") {
1321
+ fs5.chmodSync(path4.dirname(file), 448);
1322
+ fs5.chmodSync(file, 384);
1323
+ }
1324
+ }
1325
+ function writeTopLevelCredentials2(credentials) {
1326
+ const existing = readMachineCredentials2();
1327
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
1328
+ writeMachineCredentials2({
1329
+ ...credentials,
1330
+ ...eventLogPath ? { eventLogPath } : {},
1331
+ ...existing?.tools ? { tools: existing.tools } : {}
1332
+ });
1333
+ }
1334
+ function writeEventLogSetting2(value) {
1335
+ const existing = readMachineCredentials2() ?? {};
1336
+ writeMachineCredentials2({ ...existing, eventLogPath: value });
1337
+ }
1338
+ function isLocalOnlyHostInstall(host, hasToken) {
1339
+ const credentials = readHostCredentials(host);
1340
+ if (!credentials?.localOnly)
1341
+ return false;
1342
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
1343
+ return false;
1344
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1345
+ }
1346
+ function readHostCredentials(host) {
1347
+ const entry = readMachineCredentials2()?.tools?.[host];
1348
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
1349
+ return void 0;
1350
+ return entry;
1351
+ }
1352
+ function writeHostCredentials(host, credentials) {
1353
+ const existing = readMachineCredentials2() ?? {};
1354
+ writeMachineCredentials2({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1355
+ }
1356
+ function removeHostCredentials(host) {
1357
+ const existing = readMachineCredentials2();
1358
+ if (!existing?.tools || !(host in existing.tools))
1359
+ return;
1360
+ const tools = { ...existing.tools };
1361
+ delete tools[host];
1362
+ const next = { ...existing };
1363
+ if (Object.keys(tools).length)
1364
+ next.tools = tools;
1365
+ else
1366
+ delete next.tools;
1367
+ writeMachineCredentials2(next);
1368
+ }
1369
+ }
1370
+ });
1371
+
978
1372
  // ../packages/tool-kit/out/eventLog.js
979
1373
  var require_eventLog = __commonJS({
980
1374
  "../packages/tool-kit/out/eventLog.js"(exports) {
@@ -1017,14 +1411,22 @@ var require_eventLog = __commonJS({
1017
1411
  };
1018
1412
  }();
1019
1413
  Object.defineProperty(exports, "__esModule", { value: true });
1020
- exports.EVENT_LOG_ENV_VAR = void 0;
1414
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
1021
1415
  exports.expandUserPath = expandUserPath;
1416
+ exports.defaultEventLogPath = defaultEventLogPath;
1417
+ exports.resolveEventLog = resolveEventLog3;
1022
1418
  exports.resolveEventLogPath = resolveEventLogPath2;
1419
+ exports.describeEventLog = describeEventLog3;
1420
+ exports.parseEventLogFlag = parseEventLogFlag2;
1023
1421
  exports.appendEventLog = appendEventLog2;
1024
1422
  var fs5 = __importStar(__require("fs"));
1025
1423
  var os5 = __importStar(__require("os"));
1026
1424
  var path4 = __importStar(__require("path"));
1425
+ var agentEvent_1 = require_agentEvent();
1426
+ var credentials_1 = require_credentials();
1427
+ var tokenStore_1 = require_tokenStore();
1027
1428
  exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1429
+ exports.EVENT_LOG_OFF = "off";
1028
1430
  var MAX_BYTES = 5 * 1024 * 1024;
1029
1431
  function expandUserPath(configured) {
1030
1432
  const value = configured?.trim();
@@ -1036,15 +1438,55 @@ var require_eventLog = __commonJS({
1036
1438
  return path4.join(os5.homedir(), value.slice(2));
1037
1439
  return path4.resolve(value);
1038
1440
  }
1039
- function resolveEventLogPath2() {
1040
- return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
1441
+ function defaultEventLogPath() {
1442
+ return path4.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1443
+ }
1444
+ function resolveEventLog3(options = {}) {
1445
+ for (const [source, raw] of [
1446
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
1447
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
1448
+ ]) {
1449
+ const value = raw?.trim();
1450
+ if (!value)
1451
+ continue;
1452
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
1453
+ return { path: void 0, source: "disabled" };
1454
+ return { path: expandUserPath(value), source };
1455
+ }
1456
+ if (options.localOnly)
1457
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
1458
+ return { path: void 0, source: "off" };
1459
+ }
1460
+ function resolveEventLogPath2(options = {}) {
1461
+ return resolveEventLog3(options).path;
1462
+ }
1463
+ function describeEventLog3(setting, command) {
1464
+ switch (setting.source) {
1465
+ case "env":
1466
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
1467
+ case "credentials":
1468
+ return `${setting.path} (set by ${command} --event-log)`;
1469
+ case "unpaired-default":
1470
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
1471
+ case "disabled":
1472
+ return `off (turned off; ${command} --event-log to turn it on)`;
1473
+ case "off":
1474
+ return `off (${command} --event-log to keep a local copy of every event)`;
1475
+ }
1476
+ }
1477
+ function parseEventLogFlag2(argv, index) {
1478
+ const peek = argv[index + 1];
1479
+ if (peek !== void 0 && !peek.startsWith("-"))
1480
+ return { value: peek, consumed: 1 };
1481
+ return { value: defaultEventLogPath(), consumed: 0 };
1041
1482
  }
1042
1483
  function appendEventLog2(logFilePath, entry) {
1043
1484
  try {
1044
1485
  rotateIfLarge(logFilePath);
1045
1486
  const dir = path4.dirname(logFilePath);
1046
1487
  fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1047
- fs5.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1488
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
1489
+ fs5.appendFileSync(logFilePath, `${JSON.stringify(line)}
1048
1490
  `, { encoding: "utf8", mode: 384 });
1049
1491
  if (process.platform !== "win32")
1050
1492
  fs5.chmodSync(logFilePath, 384);
@@ -1219,235 +1661,97 @@ var require_http = __commonJS({
1219
1661
  method: "POST",
1220
1662
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1221
1663
  signal
1222
- });
1223
- if (response.status === 401)
1224
- return null;
1225
- if (!response.ok)
1226
- throw new AscendaApiError2(response.status, void 0, await response.text());
1227
- return await response.json();
1228
- }
1229
- function isDeliveredStatus(value) {
1230
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1231
- }
1232
- function readSuccessBody(body) {
1233
- let parsed;
1234
- try {
1235
- parsed = JSON.parse(body);
1236
- } catch {
1237
- return { duplicates: 0 };
1238
- }
1239
- if (!parsed || typeof parsed !== "object")
1240
- return { duplicates: 0 };
1241
- const single = parsed.status;
1242
- if (isDeliveredStatus(single))
1243
- return { duplicates: single === "duplicate" ? 1 : 0 };
1244
- const raw = parsed.results;
1245
- if (!Array.isArray(raw))
1246
- return { duplicates: 0 };
1247
- const results = [];
1248
- for (const item of raw) {
1249
- if (!item || typeof item !== "object")
1250
- continue;
1251
- const { index, status, reason } = item;
1252
- if (typeof index !== "number" || typeof status !== "string")
1253
- continue;
1254
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1255
- }
1256
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1257
- }
1258
- function isRetryableStatus(status) {
1259
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1260
- }
1261
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1262
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1263
- }
1264
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1265
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1266
- }
1267
- async function sendIngest(url, eventWriteToken, body, signal) {
1268
- try {
1269
- const response = await fetch(url, {
1270
- method: "POST",
1271
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1272
- body,
1273
- signal
1274
- });
1275
- return parseIngestResponse(response);
1276
- } catch (error) {
1277
- return {
1278
- result: "transport_error",
1279
- detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1280
- };
1281
- }
1282
- }
1283
- async function parseIngestResponse(response) {
1284
- if (response.ok) {
1285
- const outcome = { result: "accepted", httpStatus: response.status };
1286
- let read = { duplicates: 0 };
1287
- try {
1288
- read = readSuccessBody(await response.text());
1289
- } catch {
1290
- read = { duplicates: 0 };
1291
- }
1292
- return {
1293
- ...outcome,
1294
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1295
- ...read.results !== void 0 ? { results: read.results } : {}
1296
- };
1297
- }
1298
- const body = await response.text();
1299
- let errorCode;
1300
- try {
1301
- errorCode = JSON.parse(body).error;
1302
- } catch {
1303
- errorCode = void 0;
1304
- }
1305
- const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1306
- if (response.status === 401)
1307
- return { ...base, result: "auth_failed" };
1308
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1309
- return { ...base, result: "consent_missing" };
1310
- if (response.status === 400 || response.status === 422)
1311
- return { ...base, result: "validation_failed" };
1312
- return { ...base, result: "transport_error" };
1313
- }
1314
- }
1315
- });
1316
-
1317
- // ../packages/tool-kit/out/tokenStore.js
1318
- var require_tokenStore = __commonJS({
1319
- "../packages/tool-kit/out/tokenStore.js"(exports) {
1320
- "use strict";
1321
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1322
- if (k2 === void 0) k2 = k;
1323
- var desc = Object.getOwnPropertyDescriptor(m, k);
1324
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1325
- desc = { enumerable: true, get: function() {
1326
- return m[k];
1327
- } };
1328
- }
1329
- Object.defineProperty(o, k2, desc);
1330
- } : function(o, m, k, k2) {
1331
- if (k2 === void 0) k2 = k;
1332
- o[k2] = m[k];
1333
- });
1334
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1335
- Object.defineProperty(o, "default", { enumerable: true, value: v });
1336
- } : function(o, v) {
1337
- o["default"] = v;
1338
- });
1339
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1340
- var ownKeys = function(o) {
1341
- ownKeys = Object.getOwnPropertyNames || function(o2) {
1342
- var ar = [];
1343
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1344
- return ar;
1345
- };
1346
- return ownKeys(o);
1347
- };
1348
- return function(mod) {
1349
- if (mod && mod.__esModule) return mod;
1350
- var result = {};
1351
- if (mod != null) {
1352
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1353
- }
1354
- __setModuleDefault(result, mod);
1355
- return result;
1356
- };
1357
- }();
1358
- Object.defineProperty(exports, "__esModule", { value: true });
1359
- exports.EVENT_TOKEN_TTL_MS = void 0;
1360
- exports.ascendaHome = ascendaHome3;
1361
- exports.defaultTokenFilePath = defaultTokenFilePath4;
1362
- exports.tokenExpiryFilePath = tokenExpiryFilePath;
1363
- exports.persistEventWriteToken = persistEventWriteToken4;
1364
- exports.readTokenExpiry = readTokenExpiry;
1365
- exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
1366
- exports.readTokenFile = readTokenFile3;
1367
- exports.sanitizeFilePart = sanitizeFilePart;
1368
- var fs5 = __importStar(__require("fs"));
1369
- var os5 = __importStar(__require("os"));
1370
- var path4 = __importStar(__require("path"));
1371
- function ascendaHome3(home = os5.homedir()) {
1372
- return process.env.ASCENDA_HOME ?? path4.join(home, ".ascenda");
1373
- }
1374
- function defaultTokenFilePath4(toolInstallationId) {
1375
- return path4.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1376
- }
1377
- function tokenExpiryFilePath(tokenFilePath) {
1378
- return path4.join(path4.dirname(tokenFilePath), "expiry", path4.basename(tokenFilePath));
1379
- }
1380
- function persistEventWriteToken4(tokenFilePath, token, expiresAt) {
1381
- const dir = path4.dirname(tokenFilePath);
1382
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1383
- fs5.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1384
- if (process.platform !== "win32") {
1385
- fs5.chmodSync(dir, 448);
1386
- fs5.chmodSync(tokenFilePath, 384);
1387
- }
1388
- const expiryFile = tokenExpiryFilePath(tokenFilePath);
1389
- try {
1390
- if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1391
- fs5.mkdirSync(path4.dirname(expiryFile), { recursive: true, mode: 448 });
1392
- fs5.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1393
- } else {
1394
- fs5.rmSync(expiryFile, { force: true });
1395
- }
1396
- } catch {
1397
- }
1664
+ });
1665
+ if (response.status === 401)
1666
+ return null;
1667
+ if (!response.ok)
1668
+ throw new AscendaApiError2(response.status, void 0, await response.text());
1669
+ return await response.json();
1398
1670
  }
1399
- exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1400
- function readTokenExpiry(tokenFilePath) {
1671
+ function isDeliveredStatus(value) {
1672
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1673
+ }
1674
+ function readSuccessBody(body) {
1675
+ let parsed;
1401
1676
  try {
1402
- const recorded = Date.parse(fs5.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1403
- if (Number.isFinite(recorded))
1404
- return recorded;
1677
+ parsed = JSON.parse(body);
1405
1678
  } catch {
1679
+ return { duplicates: 0 };
1406
1680
  }
1407
- try {
1408
- return fs5.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1409
- } catch {
1410
- return void 0;
1681
+ if (!parsed || typeof parsed !== "object")
1682
+ return { duplicates: 0 };
1683
+ const single = parsed.status;
1684
+ if (isDeliveredStatus(single))
1685
+ return { duplicates: single === "duplicate" ? 1 : 0 };
1686
+ const raw = parsed.results;
1687
+ if (!Array.isArray(raw))
1688
+ return { duplicates: 0 };
1689
+ const results = [];
1690
+ for (const item of raw) {
1691
+ if (!item || typeof item !== "object")
1692
+ continue;
1693
+ const { index, status, reason } = item;
1694
+ if (typeof index !== "number" || typeof status !== "string")
1695
+ continue;
1696
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1411
1697
  }
1698
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1412
1699
  }
1413
- function listPersistedToolInstallationIds2(toolType) {
1414
- const prefix = `${sanitizeFilePart(toolType)}_`;
1415
- const dir = path4.join(ascendaHome3(), "tokens");
1416
- let names;
1700
+ function isRetryableStatus(status) {
1701
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1702
+ }
1703
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1704
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1705
+ }
1706
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1707
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1708
+ }
1709
+ async function sendIngest(url, eventWriteToken, body, signal) {
1417
1710
  try {
1418
- names = fs5.readdirSync(dir);
1419
- } catch {
1420
- return [];
1711
+ const response = await fetch(url, {
1712
+ method: "POST",
1713
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1714
+ body,
1715
+ signal
1716
+ });
1717
+ return parseIngestResponse(response);
1718
+ } catch (error) {
1719
+ return {
1720
+ result: "transport_error",
1721
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1722
+ };
1421
1723
  }
1422
- const ids = [];
1423
- for (const name of names.sort()) {
1424
- if (!name.startsWith(prefix) || name.length === prefix.length)
1425
- continue;
1426
- const file = path4.join(dir, name);
1724
+ }
1725
+ async function parseIngestResponse(response) {
1726
+ if (response.ok) {
1727
+ const outcome = { result: "accepted", httpStatus: response.status };
1728
+ let read = { duplicates: 0 };
1427
1729
  try {
1428
- if (!fs5.statSync(file).isFile())
1429
- continue;
1730
+ read = readSuccessBody(await response.text());
1430
1731
  } catch {
1431
- continue;
1732
+ read = { duplicates: 0 };
1432
1733
  }
1433
- if (readTokenFile3(file) === void 0)
1434
- continue;
1435
- ids.push(`${toolType}:${name.slice(prefix.length)}`);
1734
+ return {
1735
+ ...outcome,
1736
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1737
+ ...read.results !== void 0 ? { results: read.results } : {}
1738
+ };
1436
1739
  }
1437
- return ids;
1438
- }
1439
- function readTokenFile3(tokenFilePath) {
1740
+ const body = await response.text();
1741
+ let errorCode;
1440
1742
  try {
1441
- if (!fs5.existsSync(tokenFilePath))
1442
- return void 0;
1443
- const value = fs5.readFileSync(tokenFilePath, "utf8").trim();
1444
- return value || void 0;
1743
+ errorCode = JSON.parse(body).error;
1445
1744
  } catch {
1446
- return void 0;
1745
+ errorCode = void 0;
1447
1746
  }
1448
- }
1449
- function sanitizeFilePart(value) {
1450
- return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1747
+ const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1748
+ if (response.status === 401)
1749
+ return { ...base, result: "auth_failed" };
1750
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
1751
+ return { ...base, result: "consent_missing" };
1752
+ if (response.status === 400 || response.status === 422)
1753
+ return { ...base, result: "validation_failed" };
1754
+ return { ...base, result: "transport_error" };
1451
1755
  }
1452
1756
  }
1453
1757
  });
@@ -1856,6 +2160,7 @@ var require_eventSender = __commonJS({
1856
2160
  "use strict";
1857
2161
  Object.defineProperty(exports, "__esModule", { value: true });
1858
2162
  exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
2163
+ exports.buildEventBody = buildEventBody;
1859
2164
  exports.buildEventPayload = buildEventPayload2;
1860
2165
  var afterHours_1 = require_afterHours();
1861
2166
  var tool_contract_1 = require_out();
@@ -1874,12 +2179,10 @@ var require_eventSender = __commonJS({
1874
2179
  }
1875
2180
  };
1876
2181
  exports.AscendaSemanticEventError = AscendaSemanticEventError;
1877
- function buildEventPayload2(identity, mapped) {
2182
+ function buildEventBody(identity, mapped) {
1878
2183
  return {
1879
- toolInstallationId: identity.toolInstallationId,
1880
2184
  source: identity.source,
1881
2185
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1882
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1883
2186
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1884
2187
  sessionId: identity.sessionId ?? void 0,
1885
2188
  workspaceHash: identity.workspaceHash ?? void 0,
@@ -1891,6 +2194,9 @@ var require_eventSender = __commonJS({
1891
2194
  metadata: withCollectorVersion(mapped.metadata)
1892
2195
  };
1893
2196
  }
2197
+ function buildEventPayload2(identity, mapped) {
2198
+ return (0, tool_contract_1.joinEventPayload)({ toolInstallationId: identity.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() }, buildEventBody(identity, mapped));
2199
+ }
1894
2200
  function withCollectorVersion(metadata) {
1895
2201
  return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION };
1896
2202
  }
@@ -1966,12 +2272,10 @@ var require_eventSender = __commonJS({
1966
2272
  if (!mapped.metadata.skillVersion || !mapped.metadata.skillVersion.trim()) {
1967
2273
  throw new AscendaSemanticEventError(`metadata.skillVersion is required for semantic event "${mapped.eventType}".`);
1968
2274
  }
1969
- const payload = {
1970
- toolInstallationId: this.config.toolInstallationId,
2275
+ const body = {
1971
2276
  source: this.config.source,
1972
2277
  eventType: mapped.eventType,
1973
2278
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1974
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1975
2279
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1976
2280
  severity: "low",
1977
2281
  sessionId: this.config.sessionId ?? void 0,
@@ -1982,7 +2286,7 @@ var require_eventSender = __commonJS({
1982
2286
  privacyMode: "metadata_only",
1983
2287
  metadata: withCollectorVersion(mapped.metadata)
1984
2288
  };
1985
- return this.post(payload);
2289
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
1986
2290
  }
1987
2291
  /**
1988
2292
  * Sends a collaboration event under `workflow_telemetry`.
@@ -1997,12 +2301,10 @@ var require_eventSender = __commonJS({
1997
2301
  if (!tool_contract_1.COLLABORATION_EVENT_TYPES.includes(mapped.eventType)) {
1998
2302
  throw new AscendaSemanticEventError(`"${mapped.eventType}" is not a collaboration event type. Use send() for a deterministic host event.`);
1999
2303
  }
2000
- const payload = {
2001
- toolInstallationId: this.config.toolInstallationId,
2304
+ const body = {
2002
2305
  source: this.config.source,
2003
2306
  eventType: mapped.eventType,
2004
2307
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
2005
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
2006
2308
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
2007
2309
  severity: "low",
2008
2310
  sessionId: this.config.sessionId ?? void 0,
@@ -2013,7 +2315,11 @@ var require_eventSender = __commonJS({
2013
2315
  privacyMode: "metadata_only",
2014
2316
  metadata: withCollectorVersion(mapped.metadata)
2015
2317
  };
2016
- return this.post(payload);
2318
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
2319
+ }
2320
+ /** A fresh envelope per event: the key belongs to the event, so every retry of it reuses this one. */
2321
+ envelope() {
2322
+ return { toolInstallationId: this.config.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() };
2017
2323
  }
2018
2324
  /**
2019
2325
  * The single choke point every event passes through, and therefore the only
@@ -2433,123 +2739,6 @@ var require_contextRegistry = __commonJS({
2433
2739
  }
2434
2740
  });
2435
2741
 
2436
- // ../packages/tool-kit/out/credentials.js
2437
- var require_credentials = __commonJS({
2438
- "../packages/tool-kit/out/credentials.js"(exports) {
2439
- "use strict";
2440
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2441
- if (k2 === void 0) k2 = k;
2442
- var desc = Object.getOwnPropertyDescriptor(m, k);
2443
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2444
- desc = { enumerable: true, get: function() {
2445
- return m[k];
2446
- } };
2447
- }
2448
- Object.defineProperty(o, k2, desc);
2449
- } : function(o, m, k, k2) {
2450
- if (k2 === void 0) k2 = k;
2451
- o[k2] = m[k];
2452
- });
2453
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2454
- Object.defineProperty(o, "default", { enumerable: true, value: v });
2455
- } : function(o, v) {
2456
- o["default"] = v;
2457
- });
2458
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2459
- var ownKeys = function(o) {
2460
- ownKeys = Object.getOwnPropertyNames || function(o2) {
2461
- var ar = [];
2462
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2463
- return ar;
2464
- };
2465
- return ownKeys(o);
2466
- };
2467
- return function(mod) {
2468
- if (mod && mod.__esModule) return mod;
2469
- var result = {};
2470
- if (mod != null) {
2471
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2472
- }
2473
- __setModuleDefault(result, mod);
2474
- return result;
2475
- };
2476
- }();
2477
- Object.defineProperty(exports, "__esModule", { value: true });
2478
- exports.credentialsFilePath = credentialsFilePath2;
2479
- exports.readMachineCredentials = readMachineCredentials2;
2480
- exports.writeMachineCredentials = writeMachineCredentials2;
2481
- exports.writeTopLevelCredentials = writeTopLevelCredentials2;
2482
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2483
- exports.readHostCredentials = readHostCredentials;
2484
- exports.writeHostCredentials = writeHostCredentials;
2485
- exports.removeHostCredentials = removeHostCredentials;
2486
- var fs5 = __importStar(__require("fs"));
2487
- var path4 = __importStar(__require("path"));
2488
- var tokenStore_1 = require_tokenStore();
2489
- function credentialsFilePath2() {
2490
- return path4.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2491
- }
2492
- function readMachineCredentials2() {
2493
- try {
2494
- const raw = fs5.readFileSync(credentialsFilePath2(), "utf8").trim();
2495
- if (!raw)
2496
- return void 0;
2497
- const parsed = JSON.parse(raw);
2498
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2499
- return void 0;
2500
- return parsed;
2501
- } catch {
2502
- return void 0;
2503
- }
2504
- }
2505
- function writeMachineCredentials2(credentials) {
2506
- const file = credentialsFilePath2();
2507
- fs5.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
2508
- fs5.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2509
- `, { encoding: "utf8", mode: 384 });
2510
- if (process.platform !== "win32") {
2511
- fs5.chmodSync(path4.dirname(file), 448);
2512
- fs5.chmodSync(file, 384);
2513
- }
2514
- }
2515
- function writeTopLevelCredentials2(credentials) {
2516
- const existing = readMachineCredentials2();
2517
- writeMachineCredentials2({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2518
- }
2519
- function isLocalOnlyHostInstall(host, hasToken) {
2520
- const credentials = readHostCredentials(host);
2521
- if (!credentials?.localOnly)
2522
- return false;
2523
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2524
- return false;
2525
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2526
- }
2527
- function readHostCredentials(host) {
2528
- const entry = readMachineCredentials2()?.tools?.[host];
2529
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
2530
- return void 0;
2531
- return entry;
2532
- }
2533
- function writeHostCredentials(host, credentials) {
2534
- const existing = readMachineCredentials2() ?? {};
2535
- writeMachineCredentials2({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2536
- }
2537
- function removeHostCredentials(host) {
2538
- const existing = readMachineCredentials2();
2539
- if (!existing?.tools || !(host in existing.tools))
2540
- return;
2541
- const tools = { ...existing.tools };
2542
- delete tools[host];
2543
- const next = { ...existing };
2544
- if (Object.keys(tools).length)
2545
- next.tools = tools;
2546
- else
2547
- delete next.tools;
2548
- writeMachineCredentials2(next);
2549
- }
2550
- }
2551
- });
2552
-
2553
2742
  // ../packages/tool-kit/out/forgeProject.js
2554
2743
  var require_forgeProject = __commonJS({
2555
2744
  "../packages/tool-kit/out/forgeProject.js"(exports) {
@@ -3093,8 +3282,12 @@ var require_hookAdapter = __commonJS({
3093
3282
  return;
3094
3283
  const notice = options.onNotice ?? ((message) => console.error(message));
3095
3284
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3096
- if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken))
3285
+ if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3286
+ const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
3287
+ if (logFile)
3288
+ logUnsent2(logFile, events, options);
3097
3289
  return;
3290
+ }
3098
3291
  let config;
3099
3292
  try {
3100
3293
  config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
@@ -3104,20 +3297,7 @@ var require_hookAdapter = __commonJS({
3104
3297
  const logFile = (0, eventLog_1.resolveEventLogPath)();
3105
3298
  if (!logFile)
3106
3299
  throw error;
3107
- const contextHashes = resolveContextHashes(options.cwd);
3108
- for (const event of events) {
3109
- (0, eventLog_1.appendEventLog)(logFile, {
3110
- loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3111
- delivery: "not_sent",
3112
- payload: (0, eventSender_1.buildEventPayload)({
3113
- toolInstallationId: `${options.toolType}:unpaired`,
3114
- source: options.source,
3115
- sessionId: options.sessionId ?? null,
3116
- workspaceHash: contextHashes.workspaceHash,
3117
- projectHash: contextHashes.projectHash
3118
- }, event)
3119
- });
3120
- }
3300
+ logUnsent2(logFile, events, options);
3121
3301
  return;
3122
3302
  }
3123
3303
  const sender = new eventSender_1.AscendaEventSender({
@@ -3147,6 +3327,22 @@ var require_hookAdapter = __commonJS({
3147
3327
  return;
3148
3328
  }
3149
3329
  }
3330
+ function logUnsent2(logFile, events, options) {
3331
+ const contextHashes = resolveContextHashes(options.cwd);
3332
+ for (const event of events) {
3333
+ (0, eventLog_1.appendEventLog)(logFile, {
3334
+ loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3335
+ delivery: "not_sent",
3336
+ payload: (0, eventSender_1.buildEventPayload)({
3337
+ toolInstallationId: `${options.toolType}:unpaired`,
3338
+ source: options.source,
3339
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || options.sessionId || null,
3340
+ workspaceHash: contextHashes.workspaceHash,
3341
+ projectHash: contextHashes.projectHash
3342
+ }, event)
3343
+ });
3344
+ }
3345
+ }
3150
3346
  function journalSkippedSend2(host, error) {
3151
3347
  const who = host ? `${host}: ` : "";
3152
3348
  (0, stateStore_1.recordSendOutcome)((0, stateStore_1.unresolvedStateFilePath)(error.toolType), (0, stateStore_1.unresolvedToolInstallationId)(error.toolType), "skipped_no_installation_id", {
@@ -4703,6 +4899,7 @@ var require_cliAgentSetup = __commonJS({
4703
4899
  var path4 = __importStar(__require("path"));
4704
4900
  var collectorVersion_1 = require_collectorVersion();
4705
4901
  var credentials_1 = require_credentials();
4902
+ var eventLog_1 = require_eventLog();
4706
4903
  var hookAdapter_1 = require_hookAdapter();
4707
4904
  var http_1 = require_http();
4708
4905
  var hookSet_1 = require_hookSet();
@@ -4741,6 +4938,8 @@ Options
4741
4938
  --tool-installation-id <id> reuse an existing pairing instead of creating one
4742
4939
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
4743
4940
  --no-pair install without pairing: local features on, nothing sent
4941
+ --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
4942
+ On by default when not paired; machine-wide, shared by every agent
4744
4943
  --scope user|project where hooks are registered (default user: every project)
4745
4944
  --project-dir <path> project root for --scope project (default cwd)
4746
4945
  --dry-run print what would change, write nothing
@@ -4795,6 +4994,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4795
4994
  toolInstallationId,
4796
4995
  ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4797
4996
  });
4997
+ if (options.eventLog !== void 0)
4998
+ (0, credentials_1.writeEventLogSetting)(options.eventLog);
4798
4999
  }
4799
5000
  if (isHomeProject2(options)) {
4800
5001
  detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
@@ -4829,6 +5030,11 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4829
5030
  else
4830
5031
  row("warn", "pairing", "not paired: pairing did not finish");
4831
5032
  detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os5.homedir())} (tools.${spec.host})`);
5033
+ const eventLog = (0, eventLog_1.resolveEventLog)({ localOnly: !identity });
5034
+ if (eventLog.path)
5035
+ row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path, os5.homedir())} ${ui.dim("(on this machine only)")}`);
5036
+ else if (options.eventLog !== void 0)
5037
+ row("info", "events", "off");
4832
5038
  if (options.dryRun) {
4833
5039
  console.log("\nDry run. Nothing was written.");
4834
5040
  return 0;
@@ -4839,6 +5045,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4839
5045
  if (chosenLocal) {
4840
5046
  console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
4841
5047
  console.log(" They run on this machine and need no account or pairing.");
5048
+ if (eventLog.path)
5049
+ console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os5.homedir())}, for you or any tool to read.`);
4842
5050
  } else if (!identity) {
4843
5051
  console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
4844
5052
  console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
@@ -4921,6 +5129,12 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4921
5129
  case "--dry-run":
4922
5130
  options.dryRun = true;
4923
5131
  break;
5132
+ case "--event-log": {
5133
+ const { value, consumed } = (0, eventLog_1.parseEventLogFlag)(argv, i);
5134
+ options.eventLog = value;
5135
+ i += consumed;
5136
+ break;
5137
+ }
4924
5138
  case "--no-pair":
4925
5139
  // `--no-pairing` is the spelling this landed under first. Both appeared
4926
5140
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -5143,6 +5357,7 @@ ${serialised}`);
5143
5357
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
5144
5358
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
5145
5359
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
5360
+ console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5146
5361
  console.log(`hook binary ${fs5.existsSync(binary) ? binary : "\u2014 not installed"}`);
5147
5362
  const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5148
5363
  if (node) {
@@ -5226,6 +5441,8 @@ ${serialised}`);
5226
5441
  lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
5227
5442
  }
5228
5443
  lines.push("", ...accountLines(ui, spec));
5444
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
5445
+ lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5229
5446
  console.log(lines.join("\n"));
5230
5447
  return 0;
5231
5448
  }
@@ -5239,9 +5456,9 @@ ${serialised}`);
5239
5456
  ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}`,
5240
5457
  ...id ? [ui.dim(row("info", "Installation id", id))] : [],
5241
5458
  "",
5242
- " Not paired, which is fine: the screen saver and the live view above work",
5243
- " without it. Nothing leaves this machine and nothing is queued. To send your",
5244
- " sessions to Ascenda's servers, so they appear in the app:",
5459
+ " Not paired, which is fine: the screen saver, the live view and the local",
5460
+ " event log work without it. Nothing leaves this machine and nothing is queued.",
5461
+ " To send your sessions to Ascenda's servers, so they appear in the app:",
5245
5462
  ` ${ui.cyan(`${cliAgentSelfCommand(spec)} setup`)}`
5246
5463
  ];
5247
5464
  }
@@ -5522,14 +5739,14 @@ var require_agentProcess = __commonJS({
5522
5739
  });
5523
5740
 
5524
5741
  // ../packages/tool-kit/out/index.js
5525
- var require_out2 = __commonJS({
5742
+ var require_out3 = __commonJS({
5526
5743
  "../packages/tool-kit/out/index.js"(exports) {
5527
5744
  "use strict";
5528
5745
  Object.defineProperty(exports, "__esModule", { value: true });
5529
- 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;
5530
- 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;
5531
- 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;
5532
- 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;
5746
+ exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.resolveEventLog = exports.parseEventLogFlag = exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.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;
5747
+ 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.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = exports.isCliAgentManagementCommand = void 0;
5748
+ 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 = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = void 0;
5749
+ 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 = void 0;
5533
5750
  var commandClassifier_1 = require_commandClassifier();
5534
5751
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5535
5752
  return commandClassifier_1.classifyCommand;
@@ -5630,19 +5847,41 @@ var require_out2 = __commonJS({
5630
5847
  Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
5631
5848
  return eventSender_1.TOKEN_RENEW_LEAD_MS;
5632
5849
  } });
5850
+ Object.defineProperty(exports, "buildEventBody", { enumerable: true, get: function() {
5851
+ return eventSender_1.buildEventBody;
5852
+ } });
5633
5853
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
5634
5854
  return eventSender_1.buildEventPayload;
5635
5855
  } });
5856
+ var agentEvent_1 = require_agentEvent();
5857
+ Object.defineProperty(exports, "toAgentEvent", { enumerable: true, get: function() {
5858
+ return agentEvent_1.toAgentEvent;
5859
+ } });
5636
5860
  var eventLog_1 = require_eventLog();
5637
5861
  Object.defineProperty(exports, "EVENT_LOG_ENV_VAR", { enumerable: true, get: function() {
5638
5862
  return eventLog_1.EVENT_LOG_ENV_VAR;
5639
5863
  } });
5864
+ Object.defineProperty(exports, "EVENT_LOG_OFF", { enumerable: true, get: function() {
5865
+ return eventLog_1.EVENT_LOG_OFF;
5866
+ } });
5640
5867
  Object.defineProperty(exports, "appendEventLog", { enumerable: true, get: function() {
5641
5868
  return eventLog_1.appendEventLog;
5642
5869
  } });
5870
+ Object.defineProperty(exports, "defaultEventLogPath", { enumerable: true, get: function() {
5871
+ return eventLog_1.defaultEventLogPath;
5872
+ } });
5873
+ Object.defineProperty(exports, "describeEventLog", { enumerable: true, get: function() {
5874
+ return eventLog_1.describeEventLog;
5875
+ } });
5643
5876
  Object.defineProperty(exports, "expandUserPath", { enumerable: true, get: function() {
5644
5877
  return eventLog_1.expandUserPath;
5645
5878
  } });
5879
+ Object.defineProperty(exports, "parseEventLogFlag", { enumerable: true, get: function() {
5880
+ return eventLog_1.parseEventLogFlag;
5881
+ } });
5882
+ Object.defineProperty(exports, "resolveEventLog", { enumerable: true, get: function() {
5883
+ return eventLog_1.resolveEventLog;
5884
+ } });
5646
5885
  Object.defineProperty(exports, "resolveEventLogPath", { enumerable: true, get: function() {
5647
5886
  return eventLog_1.resolveEventLogPath;
5648
5887
  } });
@@ -5719,6 +5958,9 @@ var require_out2 = __commonJS({
5719
5958
  Object.defineProperty(exports, "writeHostCredentials", { enumerable: true, get: function() {
5720
5959
  return credentials_1.writeHostCredentials;
5721
5960
  } });
5961
+ Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
5962
+ return credentials_1.writeEventLogSetting;
5963
+ } });
5722
5964
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5723
5965
  return credentials_1.writeMachineCredentials;
5724
5966
  } });
@@ -6173,8 +6415,8 @@ var import_tool_kit5, import_tool_kit6;
6173
6415
  var init_paths = __esm({
6174
6416
  "src/paths.ts"() {
6175
6417
  "use strict";
6176
- import_tool_kit5 = __toESM(require_out2(), 1);
6177
- import_tool_kit6 = __toESM(require_out2(), 1);
6418
+ import_tool_kit5 = __toESM(require_out3(), 1);
6419
+ import_tool_kit6 = __toESM(require_out3(), 1);
6178
6420
  }
6179
6421
  });
6180
6422
 
@@ -6250,7 +6492,7 @@ var import_tool_kit7, DEFAULT_API_BASE_URL, MissingInstallationIdError;
6250
6492
  var init_config = __esm({
6251
6493
  "src/config.ts"() {
6252
6494
  "use strict";
6253
- import_tool_kit7 = __toESM(require_out2(), 1);
6495
+ import_tool_kit7 = __toESM(require_out3(), 1);
6254
6496
  init_paths();
6255
6497
  init_types();
6256
6498
  DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -6282,9 +6524,9 @@ var import_tool_kit8, import_tool_kit9, TOOL;
6282
6524
  var init_hookHealth = __esm({
6283
6525
  "src/hookHealth.ts"() {
6284
6526
  "use strict";
6285
- import_tool_kit8 = __toESM(require_out2(), 1);
6527
+ import_tool_kit8 = __toESM(require_out3(), 1);
6286
6528
  init_paths();
6287
- import_tool_kit9 = __toESM(require_out2(), 1);
6529
+ import_tool_kit9 = __toESM(require_out3(), 1);
6288
6530
  TOOL = "claude_code";
6289
6531
  }
6290
6532
  });
@@ -6294,7 +6536,7 @@ var import_tool_kit10, LAUNCHER_OPTIONS, LAUNCHER_SCRIPT;
6294
6536
  var init_launcher = __esm({
6295
6537
  "src/launcher.ts"() {
6296
6538
  "use strict";
6297
- import_tool_kit10 = __toESM(require_out2(), 1);
6539
+ import_tool_kit10 = __toESM(require_out3(), 1);
6298
6540
  LAUNCHER_OPTIONS = {
6299
6541
  binaryName: "ascenda-claude-hook",
6300
6542
  setupCommand: "npx @ascenda-one/claude-code-hooks setup",
@@ -6360,6 +6602,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6360
6602
  // picks up.
6361
6603
  ...unpaired ? { localOnly: true, installedAt: now } : { pairedAt: now }
6362
6604
  });
6605
+ if (options.eventLog !== void 0) (0, import_tool_kit11.writeEventLogSetting)(options.eventLog);
6363
6606
  }
6364
6607
  if (isHomeProject(options)) {
6365
6608
  detail("scope", "user (a project install in the home folder only loads when Claude Code starts there)");
@@ -6401,6 +6644,9 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6401
6644
  }
6402
6645
  if (unpaired) detail("installation", `${identity.toolInstallationId} (kept, so pairing later attaches to it)`);
6403
6646
  detail("credentials", tidyHome((0, import_tool_kit6.credentialsFilePath)()));
6647
+ const eventLog = (0, import_tool_kit11.resolveEventLog)({ localOnly: unpaired });
6648
+ if (eventLog.path) row("ok", "events", `${tidyHome(eventLog.path)} ${ui.dim("(on this machine only)")}`);
6649
+ else if (options.eventLog !== void 0) row("info", "events", "off");
6404
6650
  if (options.dryRun) {
6405
6651
  console.log("\nDry run. Nothing was written.");
6406
6652
  return 0;
@@ -6411,6 +6657,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6411
6657
  if (chosenLocal) {
6412
6658
  console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
6413
6659
  console.log(" They run on this machine and need no account or pairing.");
6660
+ if (eventLog.path) console.log(` Every event is also written to ${tidyHome(eventLog.path)}, for you or any tool to read.`);
6414
6661
  } else if (unpaired) {
6415
6662
  console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
6416
6663
  console.log(` Your sessions won't reach Ascenda's servers until pairing completes.`);
@@ -6481,6 +6728,12 @@ function parseArgs(argv) {
6481
6728
  case "--project-dir":
6482
6729
  options.projectDir = path3.resolve(next());
6483
6730
  break;
6731
+ case "--event-log": {
6732
+ const { value, consumed } = (0, import_tool_kit11.parseEventLogFlag)(argv, i);
6733
+ options.eventLog = value;
6734
+ i += consumed;
6735
+ break;
6736
+ }
6484
6737
  case "--no-pair":
6485
6738
  // `--no-pairing` is the spelling the CLI agents' setup landed under
6486
6739
  // first, and the one their README still showed for a day. Both parse
@@ -6716,6 +6969,7 @@ async function printStatus(options) {
6716
6969
  console.log(`token ${fileToken ? "present" : token ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : unpaired ? "\u2014 none until this install is paired" : "\u2014 missing"}`);
6717
6970
  console.log(`delivery ${token ? "active" : unpaired ? "inactive \u2014 nothing is sent, and nothing is queued for later" : "\u2014 no token for this pairing, so nothing can be sent"}`);
6718
6971
  console.log("local features active \u2014 the session prompts and the live socket signal need no pairing");
6972
+ console.log(`event log ${(0, import_tool_kit11.describeEventLog)((0, import_tool_kit11.resolveEventLog)({ localOnly: unpaired }), "npx @ascenda-one/claude-code-hooks setup")}`);
6719
6973
  console.log(`hook binary ${fs3.existsSync(binary) ? binary : "\u2014 not installed"}`);
6720
6974
  const node = process.platform === "win32" ? void 0 : resolveHookNode();
6721
6975
  if (node) {
@@ -6788,7 +7042,7 @@ var import_tool_kit11, HOOK_EVENTS, HOOK_SET, HOOK_TIMEOUT_SECONDS, HOOK_MARKER,
6788
7042
  var init_setup = __esm({
6789
7043
  "src/setup.ts"() {
6790
7044
  "use strict";
6791
- import_tool_kit11 = __toESM(require_out2(), 1);
7045
+ import_tool_kit11 = __toESM(require_out3(), 1);
6792
7046
  init_config();
6793
7047
  init_hookHealth();
6794
7048
  init_launcher();
@@ -6819,6 +7073,8 @@ Options
6819
7073
  --tool-installation-id <id> reuse an existing pairing instead of creating one
6820
7074
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
6821
7075
  --no-pair install without pairing: local features on, nothing sent
7076
+ --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
7077
+ On by default when not paired; machine-wide, shared by every agent
6822
7078
  (--no-pairing is accepted too)
6823
7079
  --scope user|project where hooks are registered (default user: every project)
6824
7080
  --project-dir <path> project root for --scope project (default cwd)
@@ -6831,14 +7087,14 @@ Options
6831
7087
  });
6832
7088
 
6833
7089
  // src/cli.ts
6834
- var import_tool_kit14 = __toESM(require_out2(), 1);
6835
- var import_tool_kit15 = __toESM(require_out2(), 1);
7090
+ var import_tool_kit14 = __toESM(require_out3(), 1);
7091
+ var import_tool_kit15 = __toESM(require_out3(), 1);
6836
7092
  import { randomUUID as randomUUID2 } from "node:crypto";
6837
7093
  import * as fs4 from "node:fs";
6838
7094
 
6839
7095
  // src/ascendaClient.ts
6840
- var import_tool_kit = __toESM(require_out2(), 1);
6841
- var import_tool_kit2 = __toESM(require_out2(), 1);
7096
+ var import_tool_kit = __toESM(require_out3(), 1);
7097
+ var import_tool_kit2 = __toESM(require_out3(), 1);
6842
7098
  var AscendaClient = class {
6843
7099
  sender;
6844
7100
  constructor(config) {
@@ -6873,11 +7129,11 @@ var AscendaClient = class {
6873
7129
  };
6874
7130
 
6875
7131
  // src/mapClaudeEvent.ts
6876
- var import_tool_kit4 = __toESM(require_out2(), 1);
7132
+ var import_tool_kit4 = __toESM(require_out3(), 1);
6877
7133
  init_types();
6878
7134
 
6879
7135
  // src/safeExtract.ts
6880
- var import_tool_kit3 = __toESM(require_out2(), 1);
7136
+ var import_tool_kit3 = __toESM(require_out3(), 1);
6881
7137
 
6882
7138
  // src/mapClaudeEvent.ts
6883
7139
  function mapClaudeEvent(hookName, input) {
@@ -7369,9 +7625,9 @@ init_types();
7369
7625
  init_hookHealth();
7370
7626
 
7371
7627
  // src/liveDoctor.ts
7372
- var import_tool_kit12 = __toESM(require_out2(), 1);
7628
+ var import_tool_kit12 = __toESM(require_out3(), 1);
7373
7629
  init_paths();
7374
- var import_tool_kit13 = __toESM(require_out2(), 1);
7630
+ var import_tool_kit13 = __toESM(require_out3(), 1);
7375
7631
  import * as os4 from "os";
7376
7632
  async function localSignalLines(projectDir = process.cwd()) {
7377
7633
  const { registrationSummary: registrationSummary2, REGISTERED_EVENT_COUNT: REGISTERED_EVENT_COUNT2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
@@ -7557,7 +7813,7 @@ async function main() {
7557
7813
  } catch (error) {
7558
7814
  const unpaired = localOnlyInstall();
7559
7815
  if (!unpaired && error instanceof MissingInstallationIdError) journalSkippedSend(error);
7560
- const logFile = (0, import_tool_kit14.resolveEventLogPath)();
7816
+ const logFile = (0, import_tool_kit14.resolveEventLogPath)({ localOnly: unpaired });
7561
7817
  if (!logFile) {
7562
7818
  if (unpaired) return;
7563
7819
  throw error;
@@ -7707,6 +7963,7 @@ async function runDoctor() {
7707
7963
  lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`, "");
7708
7964
  }
7709
7965
  const unpaired = localOnlyInstall();
7966
+ lines.push(` ${ui.bold("Local events")} ${(0, import_tool_kit14.describeEventLog)((0, import_tool_kit14.resolveEventLog)({ localOnly: unpaired }), "npx @ascenda-one/claude-code-hooks setup")}`, "");
7710
7967
  lines.push(unpaired ? ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}` : ` ${ui.bold("Account sync")} ${ui.dim("(Telemetry)")}`);
7711
7968
  const telemetryStart = lines.length;
7712
7969
  const finish = async () => {
@@ -7757,9 +8014,9 @@ async function runDoctor() {
7757
8014
  if (unpaired) {
7758
8015
  lines.push(
7759
8016
  "",
7760
- " Not paired, which is fine: the screen saver and the live view above work",
7761
- " without it. Nothing leaves this machine and nothing is queued. To send your",
7762
- " sessions to Ascenda's servers, so they appear in the app:",
8017
+ " Not paired, which is fine: the screen saver, the live view and the local",
8018
+ " event log work without it. Nothing leaves this machine and nothing is queued.",
8019
+ " To send your sessions to Ascenda's servers, so they appear in the app:",
7763
8020
  ` ${ui.cyan(`${selfCommand()} pair`)}`
7764
8021
  );
7765
8022
  await finish();