@ascenda-one/codex-hooks 0.1.33 → 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
@@ -629,9 +629,11 @@ var require_out = __commonJS({
629
629
  "../packages/tool-contract/out/index.js"(exports) {
630
630
  "use strict";
631
631
  Object.defineProperty(exports, "__esModule", { value: true });
632
- 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;
632
+ 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;
633
633
  exports.combineDisjointHalves = combineDisjointHalves;
634
634
  exports.requireComparableQuantities = requireComparableQuantities;
635
+ exports.joinEventPayload = joinEventPayload;
636
+ exports.splitEventPayload = splitEventPayload;
635
637
  exports.ASCENDA_TELEMETRY_SOURCES = [
636
638
  "vscode_extension",
637
639
  "cursor_mcp",
@@ -783,6 +785,24 @@ var require_out = __commonJS({
783
785
  "importSchema",
784
786
  "collectorVersion"
785
787
  ];
788
+ exports.DELIVERY_ENVELOPE_KEYS = ["toolInstallationId", "idempotencyKey"];
789
+ function joinEventPayload(envelope, body) {
790
+ const payload = { toolInstallationId: envelope.toolInstallationId };
791
+ for (const [key, value] of Object.entries(body)) {
792
+ payload[key] = value;
793
+ if (key === "occurredAt" && envelope.idempotencyKey !== void 0) {
794
+ payload.idempotencyKey = envelope.idempotencyKey;
795
+ }
796
+ }
797
+ return payload;
798
+ }
799
+ function splitEventPayload(payload) {
800
+ const { toolInstallationId, idempotencyKey, ...body } = payload;
801
+ const envelope = { toolInstallationId };
802
+ if (idempotencyKey !== void 0)
803
+ envelope.idempotencyKey = idempotencyKey;
804
+ return { envelope, body };
805
+ }
786
806
  exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
787
807
  exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
788
808
  exports.EVENT_WORKLOAD_CATEGORY = {
@@ -961,16 +981,125 @@ var require_collectorVersion = __commonJS({
961
981
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
962
982
  exports.describeCollectorVersion = describeCollectorVersion;
963
983
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
964
- exports.COLLECTOR_VERSION = "0.1.33" ? "0.1.33" : exports.UNRELEASED_COLLECTOR_VERSION;
984
+ exports.COLLECTOR_VERSION = "0.1.35" ? "0.1.35" : exports.UNRELEASED_COLLECTOR_VERSION;
965
985
  function describeCollectorVersion(version = exports.COLLECTOR_VERSION) {
966
986
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
967
987
  }
968
988
  }
969
989
  });
970
990
 
971
- // ../packages/tool-kit/out/eventLog.js
972
- var require_eventLog = __commonJS({
973
- "../packages/tool-kit/out/eventLog.js"(exports) {
991
+ // ../packages/agent-events/out/index.js
992
+ var require_out2 = __commonJS({
993
+ "../packages/agent-events/out/index.js"(exports) {
994
+ "use strict";
995
+ Object.defineProperty(exports, "__esModule", { value: true });
996
+ exports.KNOWN_AGENTS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
997
+ exports.isAgentEventV0 = isAgentEventV0;
998
+ exports.parseEventLogLine = parseEventLogLine;
999
+ exports.normaliseKind = normaliseKind;
1000
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1001
+ exports.AGENT_EVENT_KINDS = [
1002
+ "session.started",
1003
+ "session.ended",
1004
+ "prompt.submitted",
1005
+ "tool.started",
1006
+ "tool.completed",
1007
+ "tool.failed",
1008
+ "turn.completed",
1009
+ "agent.waiting",
1010
+ "context.compacted",
1011
+ "subagent.started",
1012
+ "subagent.stopped",
1013
+ "other"
1014
+ ];
1015
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1016
+ function isAgentEventV0(value) {
1017
+ if (!value || typeof value !== "object")
1018
+ return false;
1019
+ const e = value;
1020
+ 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";
1021
+ }
1022
+ function parseEventLogLine(line) {
1023
+ if (!line.trim())
1024
+ return void 0;
1025
+ try {
1026
+ const parsed = JSON.parse(line);
1027
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1028
+ } catch {
1029
+ return void 0;
1030
+ }
1031
+ }
1032
+ function normaliseKind(kind) {
1033
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1034
+ }
1035
+ }
1036
+ });
1037
+
1038
+ // ../packages/tool-kit/out/agentEvent.js
1039
+ var require_agentEvent = __commonJS({
1040
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1041
+ "use strict";
1042
+ Object.defineProperty(exports, "__esModule", { value: true });
1043
+ exports.toAgentEvent = toAgentEvent;
1044
+ var agent_events_1 = require_out2();
1045
+ var KIND_BY_TYPE = {
1046
+ create_focus_session: "session.started",
1047
+ recovery_offline_period: "session.ended",
1048
+ ai_prompt_submitted: "prompt.submitted",
1049
+ ai_tool_call_started: "tool.started",
1050
+ ai_tool_call_completed: "tool.completed",
1051
+ ai_file_write: "tool.completed",
1052
+ ai_file_edit: "tool.completed",
1053
+ editor_verification_activity: "tool.completed",
1054
+ ai_tool_call_failed: "tool.failed",
1055
+ compile_error: "tool.failed",
1056
+ tool_failure: "tool.failed",
1057
+ ai_turn_completed: "turn.completed",
1058
+ supervision_interruption: "agent.waiting",
1059
+ context_compression_manual: "context.compacted",
1060
+ context_compression_auto: "context.compacted",
1061
+ subagent_started: "subagent.started",
1062
+ subagent_stopped: "subagent.stopped"
1063
+ };
1064
+ function agentOf(payload) {
1065
+ const host = stringField(payload.metadata?.host);
1066
+ if (host)
1067
+ return host;
1068
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1069
+ }
1070
+ function stringField(value) {
1071
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1072
+ }
1073
+ function toAgentEvent(payload) {
1074
+ const metadata = payload.metadata ?? {};
1075
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1076
+ const tool = kind.startsWith("tool.") ? stringField(metadata.toolName) : void 0;
1077
+ const outcome = stringField(metadata.outcome);
1078
+ return {
1079
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1080
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1081
+ time: payload.occurredAt,
1082
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1083
+ // writes anyway; without it the event in memory and the one on disk differ.
1084
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1085
+ agent: agentOf(payload),
1086
+ kind,
1087
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1088
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1089
+ ...tool ? { tool } : {},
1090
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1091
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1092
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1093
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1094
+ sourceType: payload.eventType
1095
+ };
1096
+ }
1097
+ }
1098
+ });
1099
+
1100
+ // ../packages/tool-kit/out/tokenStore.js
1101
+ var require_tokenStore = __commonJS({
1102
+ "../packages/tool-kit/out/tokenStore.js"(exports) {
974
1103
  "use strict";
975
1104
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
976
1105
  if (k2 === void 0) k2 = k;
@@ -1010,306 +1139,232 @@ var require_eventLog = __commonJS({
1010
1139
  };
1011
1140
  }();
1012
1141
  Object.defineProperty(exports, "__esModule", { value: true });
1013
- exports.EVENT_LOG_ENV_VAR = void 0;
1014
- exports.expandUserPath = expandUserPath;
1015
- exports.resolveEventLogPath = resolveEventLogPath;
1016
- exports.appendEventLog = appendEventLog;
1142
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1143
+ exports.ascendaHome = ascendaHome;
1144
+ exports.defaultTokenFilePath = defaultTokenFilePath;
1145
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1146
+ exports.persistEventWriteToken = persistEventWriteToken;
1147
+ exports.readTokenExpiry = readTokenExpiry;
1148
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1149
+ exports.readTokenFile = readTokenFile;
1150
+ exports.sanitizeFilePart = sanitizeFilePart;
1017
1151
  var fs = __importStar(__require("fs"));
1018
1152
  var os2 = __importStar(__require("os"));
1019
1153
  var path2 = __importStar(__require("path"));
1020
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1021
- var MAX_BYTES = 5 * 1024 * 1024;
1022
- function expandUserPath(configured) {
1023
- const value = configured?.trim();
1024
- if (!value)
1025
- return void 0;
1026
- if (value === "~")
1027
- return os2.homedir();
1028
- if (value.startsWith("~/"))
1029
- return path2.join(os2.homedir(), value.slice(2));
1030
- return path2.resolve(value);
1154
+ function ascendaHome(home = os2.homedir()) {
1155
+ return process.env.ASCENDA_HOME ?? path2.join(home, ".ascenda");
1156
+ }
1157
+ function defaultTokenFilePath(toolInstallationId) {
1158
+ return path2.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1031
1159
  }
1032
- function resolveEventLogPath() {
1033
- return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
1160
+ function tokenExpiryFilePath(tokenFilePath) {
1161
+ return path2.join(path2.dirname(tokenFilePath), "expiry", path2.basename(tokenFilePath));
1034
1162
  }
1035
- function appendEventLog(logFilePath, entry) {
1036
- try {
1037
- rotateIfLarge(logFilePath);
1038
- const dir = path2.dirname(logFilePath);
1039
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1040
- fs.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1041
- `, { encoding: "utf8", mode: 384 });
1042
- if (process.platform !== "win32")
1043
- fs.chmodSync(logFilePath, 384);
1044
- } catch {
1163
+ function persistEventWriteToken(tokenFilePath, token, expiresAt) {
1164
+ const dir = path2.dirname(tokenFilePath);
1165
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
1166
+ fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1167
+ if (process.platform !== "win32") {
1168
+ fs.chmodSync(dir, 448);
1169
+ fs.chmodSync(tokenFilePath, 384);
1045
1170
  }
1046
- }
1047
- function rotateIfLarge(logFilePath) {
1171
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1048
1172
  try {
1049
- if (fs.statSync(logFilePath).size < MAX_BYTES)
1050
- return;
1051
- fs.renameSync(logFilePath, `${logFilePath}.1`);
1173
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1174
+ fs.mkdirSync(path2.dirname(expiryFile), { recursive: true, mode: 448 });
1175
+ fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1176
+ } else {
1177
+ fs.rmSync(expiryFile, { force: true });
1178
+ }
1052
1179
  } catch {
1053
1180
  }
1054
1181
  }
1055
- }
1056
- });
1057
-
1058
- // ../packages/tool-kit/out/http.js
1059
- var require_http = __commonJS({
1060
- "../packages/tool-kit/out/http.js"(exports) {
1061
- "use strict";
1062
- Object.defineProperty(exports, "__esModule", { value: true });
1063
- exports.AscendaApiError = void 0;
1064
- exports.createPairingSession = createPairingSession;
1065
- exports.getPairingStatus = getPairingStatus;
1066
- exports.startStudyJoin = startStudyJoin;
1067
- exports.getStudyJoinStatus = getStudyJoinStatus;
1068
- exports.readInitiatives = readInitiatives;
1069
- exports.readStudyNotices = readStudyNotices;
1070
- exports.setStudyObjection = setStudyObjection;
1071
- exports.markStudyNoticeShown = markStudyNoticeShown;
1072
- exports.renewToolToken = renewToolToken;
1073
- exports.isRetryableStatus = isRetryableStatus;
1074
- exports.postToolEvent = postToolEvent;
1075
- exports.postToolEventsBatch = postToolEventsBatch;
1076
- exports.parseIngestResponse = parseIngestResponse;
1077
- var tool_contract_1 = require_out();
1078
- var AscendaApiError = class extends Error {
1079
- status;
1080
- errorCode;
1081
- constructor(status, errorCode, body) {
1082
- super(body ?? `Ascenda API error ${status}`);
1083
- this.status = status;
1084
- this.errorCode = errorCode;
1085
- this.name = "AscendaApiError";
1086
- }
1087
- };
1088
- exports.AscendaApiError = AscendaApiError;
1089
- async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
1090
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1091
- method: "POST",
1092
- headers: { "Content-Type": "application/json" },
1093
- body: JSON.stringify({ toolInstallationId, toolType, displayName })
1094
- });
1095
- if (!response.ok)
1096
- throw new AscendaApiError(response.status, void 0, await response.text());
1097
- return await response.json();
1098
- }
1099
- async function getPairingStatus(apiBaseUrl, pairingSessionId) {
1100
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1101
- method: "GET",
1102
- headers: { Accept: "application/json" }
1103
- });
1104
- if (!response.ok)
1105
- throw new AscendaApiError(response.status, void 0, await response.text());
1106
- return await response.json();
1107
- }
1108
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1109
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1110
- method: "POST",
1111
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1112
- body: JSON.stringify({ joinCode, mode })
1113
- });
1114
- if (!response.ok)
1115
- throw await apiError(response);
1116
- return await response.json();
1117
- }
1118
- async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1119
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1120
- method: "GET",
1121
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1122
- });
1123
- if (!response.ok)
1124
- throw await apiError(response);
1125
- return await response.json();
1126
- }
1127
- async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1128
- let response;
1182
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1183
+ function readTokenExpiry(tokenFilePath) {
1129
1184
  try {
1130
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1131
- method: "GET",
1132
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1133
- signal
1134
- });
1135
- } catch (error) {
1136
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1185
+ const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1186
+ if (Number.isFinite(recorded))
1187
+ return recorded;
1188
+ } catch {
1137
1189
  }
1138
- if (response.status === 401)
1139
- return { kind: "rejected", httpStatus: 401 };
1140
- if (!response.ok)
1141
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1142
- let body;
1143
1190
  try {
1144
- body = await response.json();
1191
+ return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1145
1192
  } catch {
1146
- return { kind: "failed", reason: "the reply was not readable" };
1193
+ return void 0;
1147
1194
  }
1148
- if (!Array.isArray(body))
1149
- return { kind: "failed", reason: "the reply was not a list" };
1150
- return { kind: "ok", initiatives: body };
1151
1195
  }
1152
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1153
- let response;
1196
+ function listPersistedToolInstallationIds(toolType) {
1197
+ const prefix = `${sanitizeFilePart(toolType)}_`;
1198
+ const dir = path2.join(ascendaHome(), "tokens");
1199
+ let names;
1154
1200
  try {
1155
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1156
- method: "GET",
1157
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1158
- signal
1159
- });
1160
- } catch (error) {
1161
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1201
+ names = fs.readdirSync(dir);
1202
+ } catch {
1203
+ return [];
1162
1204
  }
1163
- if (response.status === 404)
1164
- return { kind: "absent" };
1165
- if (response.status === 401)
1166
- return { kind: "rejected", httpStatus: 401 };
1167
- if (!response.ok)
1168
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1169
- let body;
1205
+ const ids = [];
1206
+ for (const name of names.sort()) {
1207
+ if (!name.startsWith(prefix) || name.length === prefix.length)
1208
+ continue;
1209
+ const file = path2.join(dir, name);
1210
+ try {
1211
+ if (!fs.statSync(file).isFile())
1212
+ continue;
1213
+ } catch {
1214
+ continue;
1215
+ }
1216
+ if (readTokenFile(file) === void 0)
1217
+ continue;
1218
+ ids.push(`${toolType}:${name.slice(prefix.length)}`);
1219
+ }
1220
+ return ids;
1221
+ }
1222
+ function readTokenFile(tokenFilePath) {
1170
1223
  try {
1171
- body = await response.json();
1224
+ if (!fs.existsSync(tokenFilePath))
1225
+ return void 0;
1226
+ const value = fs.readFileSync(tokenFilePath, "utf8").trim();
1227
+ return value || void 0;
1172
1228
  } catch {
1173
- return { kind: "absent" };
1229
+ return void 0;
1174
1230
  }
1175
- if (!Array.isArray(body))
1176
- return { kind: "absent" };
1177
- return { kind: "ok", notices: body };
1178
1231
  }
1179
- async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1180
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1181
- method: objected ? "POST" : "DELETE",
1182
- headers: { Authorization: `Bearer ${eventWriteToken}` }
1183
- });
1184
- if (!response.ok)
1185
- throw await apiError(response);
1232
+ function sanitizeFilePart(value) {
1233
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1186
1234
  }
1187
- async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1188
- try {
1189
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1190
- method: "POST",
1191
- headers: { Authorization: `Bearer ${eventWriteToken}` },
1192
- signal
1193
- });
1194
- return response.ok;
1195
- } catch {
1196
- return false;
1235
+ }
1236
+ });
1237
+
1238
+ // ../packages/tool-kit/out/credentials.js
1239
+ var require_credentials = __commonJS({
1240
+ "../packages/tool-kit/out/credentials.js"(exports) {
1241
+ "use strict";
1242
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1243
+ if (k2 === void 0) k2 = k;
1244
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1245
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1246
+ desc = { enumerable: true, get: function() {
1247
+ return m[k];
1248
+ } };
1197
1249
  }
1250
+ Object.defineProperty(o, k2, desc);
1251
+ } : function(o, m, k, k2) {
1252
+ if (k2 === void 0) k2 = k;
1253
+ o[k2] = m[k];
1254
+ });
1255
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1256
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1257
+ } : function(o, v) {
1258
+ o["default"] = v;
1259
+ });
1260
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1261
+ var ownKeys = function(o) {
1262
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1263
+ var ar = [];
1264
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1265
+ return ar;
1266
+ };
1267
+ return ownKeys(o);
1268
+ };
1269
+ return function(mod) {
1270
+ if (mod && mod.__esModule) return mod;
1271
+ var result = {};
1272
+ if (mod != null) {
1273
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1274
+ }
1275
+ __setModuleDefault(result, mod);
1276
+ return result;
1277
+ };
1278
+ }();
1279
+ Object.defineProperty(exports, "__esModule", { value: true });
1280
+ exports.credentialsFilePath = credentialsFilePath;
1281
+ exports.readMachineCredentials = readMachineCredentials;
1282
+ exports.writeMachineCredentials = writeMachineCredentials;
1283
+ exports.writeTopLevelCredentials = writeTopLevelCredentials;
1284
+ exports.writeEventLogSetting = writeEventLogSetting;
1285
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
1286
+ exports.readHostCredentials = readHostCredentials;
1287
+ exports.writeHostCredentials = writeHostCredentials;
1288
+ exports.removeHostCredentials = removeHostCredentials;
1289
+ var fs = __importStar(__require("fs"));
1290
+ var path2 = __importStar(__require("path"));
1291
+ var tokenStore_1 = require_tokenStore();
1292
+ function credentialsFilePath() {
1293
+ return path2.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1198
1294
  }
1199
- async function apiError(response) {
1200
- const body = await response.text();
1201
- let errorCode;
1295
+ function readMachineCredentials() {
1202
1296
  try {
1203
- const parsed = JSON.parse(body);
1204
- errorCode = parsed.code ?? parsed.error;
1297
+ const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
1298
+ if (!raw)
1299
+ return void 0;
1300
+ const parsed = JSON.parse(raw);
1301
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1302
+ return void 0;
1303
+ return parsed;
1205
1304
  } catch {
1206
- errorCode = void 0;
1305
+ return void 0;
1207
1306
  }
1208
- return new AscendaApiError(response.status, errorCode, body);
1209
- }
1210
- async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1211
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1212
- method: "POST",
1213
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1214
- signal
1215
- });
1216
- if (response.status === 401)
1217
- return null;
1218
- if (!response.ok)
1219
- throw new AscendaApiError(response.status, void 0, await response.text());
1220
- return await response.json();
1221
- }
1222
- function isDeliveredStatus(value) {
1223
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1224
1307
  }
1225
- function readSuccessBody(body) {
1226
- let parsed;
1227
- try {
1228
- parsed = JSON.parse(body);
1229
- } catch {
1230
- return { duplicates: 0 };
1231
- }
1232
- if (!parsed || typeof parsed !== "object")
1233
- return { duplicates: 0 };
1234
- const single = parsed.status;
1235
- if (isDeliveredStatus(single))
1236
- return { duplicates: single === "duplicate" ? 1 : 0 };
1237
- const raw = parsed.results;
1238
- if (!Array.isArray(raw))
1239
- return { duplicates: 0 };
1240
- const results = [];
1241
- for (const item of raw) {
1242
- if (!item || typeof item !== "object")
1243
- continue;
1244
- const { index, status, reason } = item;
1245
- if (typeof index !== "number" || typeof status !== "string")
1246
- continue;
1247
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1308
+ function writeMachineCredentials(credentials) {
1309
+ const file = credentialsFilePath();
1310
+ fs.mkdirSync(path2.dirname(file), { recursive: true, mode: 448 });
1311
+ fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
1312
+ `, { encoding: "utf8", mode: 384 });
1313
+ if (process.platform !== "win32") {
1314
+ fs.chmodSync(path2.dirname(file), 448);
1315
+ fs.chmodSync(file, 384);
1248
1316
  }
1249
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1250
1317
  }
1251
- function isRetryableStatus(status) {
1252
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1318
+ function writeTopLevelCredentials(credentials) {
1319
+ const existing = readMachineCredentials();
1320
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
1321
+ writeMachineCredentials({
1322
+ ...credentials,
1323
+ ...eventLogPath ? { eventLogPath } : {},
1324
+ ...existing?.tools ? { tools: existing.tools } : {}
1325
+ });
1253
1326
  }
1254
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1255
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1327
+ function writeEventLogSetting(value) {
1328
+ const existing = readMachineCredentials() ?? {};
1329
+ writeMachineCredentials({ ...existing, eventLogPath: value });
1256
1330
  }
1257
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1258
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1331
+ function isLocalOnlyHostInstall(host, hasToken) {
1332
+ const credentials = readHostCredentials(host);
1333
+ if (!credentials?.localOnly)
1334
+ return false;
1335
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
1336
+ return false;
1337
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1259
1338
  }
1260
- async function sendIngest(url, eventWriteToken, body, signal) {
1261
- try {
1262
- const response = await fetch(url, {
1263
- method: "POST",
1264
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1265
- body,
1266
- signal
1267
- });
1268
- return parseIngestResponse(response);
1269
- } catch (error) {
1270
- return {
1271
- result: "transport_error",
1272
- detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1273
- };
1274
- }
1339
+ function readHostCredentials(host) {
1340
+ const entry = readMachineCredentials()?.tools?.[host];
1341
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
1342
+ return void 0;
1343
+ return entry;
1275
1344
  }
1276
- async function parseIngestResponse(response) {
1277
- if (response.ok) {
1278
- const outcome = { result: "accepted", httpStatus: response.status };
1279
- let read = { duplicates: 0 };
1280
- try {
1281
- read = readSuccessBody(await response.text());
1282
- } catch {
1283
- read = { duplicates: 0 };
1284
- }
1285
- return {
1286
- ...outcome,
1287
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1288
- ...read.results !== void 0 ? { results: read.results } : {}
1289
- };
1290
- }
1291
- const body = await response.text();
1292
- let errorCode;
1293
- try {
1294
- errorCode = JSON.parse(body).error;
1295
- } catch {
1296
- errorCode = void 0;
1297
- }
1298
- const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1299
- if (response.status === 401)
1300
- return { ...base, result: "auth_failed" };
1301
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1302
- return { ...base, result: "consent_missing" };
1303
- if (response.status === 400 || response.status === 422)
1304
- return { ...base, result: "validation_failed" };
1305
- return { ...base, result: "transport_error" };
1345
+ function writeHostCredentials(host, credentials) {
1346
+ const existing = readMachineCredentials() ?? {};
1347
+ writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1348
+ }
1349
+ function removeHostCredentials(host) {
1350
+ const existing = readMachineCredentials();
1351
+ if (!existing?.tools || !(host in existing.tools))
1352
+ return;
1353
+ const tools = { ...existing.tools };
1354
+ delete tools[host];
1355
+ const next = { ...existing };
1356
+ if (Object.keys(tools).length)
1357
+ next.tools = tools;
1358
+ else
1359
+ delete next.tools;
1360
+ writeMachineCredentials(next);
1306
1361
  }
1307
1362
  }
1308
1363
  });
1309
1364
 
1310
- // ../packages/tool-kit/out/tokenStore.js
1311
- var require_tokenStore = __commonJS({
1312
- "../packages/tool-kit/out/tokenStore.js"(exports) {
1365
+ // ../packages/tool-kit/out/eventLog.js
1366
+ var require_eventLog = __commonJS({
1367
+ "../packages/tool-kit/out/eventLog.js"(exports) {
1313
1368
  "use strict";
1314
1369
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1315
1370
  if (k2 === void 0) k2 = k;
@@ -1349,138 +1404,387 @@ var require_tokenStore = __commonJS({
1349
1404
  };
1350
1405
  }();
1351
1406
  Object.defineProperty(exports, "__esModule", { value: true });
1352
- exports.EVENT_TOKEN_TTL_MS = void 0;
1353
- exports.ascendaHome = ascendaHome;
1354
- exports.defaultTokenFilePath = defaultTokenFilePath;
1355
- exports.tokenExpiryFilePath = tokenExpiryFilePath;
1356
- exports.persistEventWriteToken = persistEventWriteToken;
1357
- exports.readTokenExpiry = readTokenExpiry;
1358
- exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1359
- exports.readTokenFile = readTokenFile;
1360
- exports.sanitizeFilePart = sanitizeFilePart;
1407
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
1408
+ exports.expandUserPath = expandUserPath;
1409
+ exports.defaultEventLogPath = defaultEventLogPath;
1410
+ exports.resolveEventLog = resolveEventLog;
1411
+ exports.resolveEventLogPath = resolveEventLogPath;
1412
+ exports.describeEventLog = describeEventLog;
1413
+ exports.parseEventLogFlag = parseEventLogFlag;
1414
+ exports.appendEventLog = appendEventLog;
1361
1415
  var fs = __importStar(__require("fs"));
1362
1416
  var os2 = __importStar(__require("os"));
1363
1417
  var path2 = __importStar(__require("path"));
1364
- function ascendaHome(home = os2.homedir()) {
1365
- return process.env.ASCENDA_HOME ?? path2.join(home, ".ascenda");
1418
+ var agentEvent_1 = require_agentEvent();
1419
+ var credentials_1 = require_credentials();
1420
+ var tokenStore_1 = require_tokenStore();
1421
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1422
+ exports.EVENT_LOG_OFF = "off";
1423
+ var MAX_BYTES = 5 * 1024 * 1024;
1424
+ function expandUserPath(configured) {
1425
+ const value = configured?.trim();
1426
+ if (!value)
1427
+ return void 0;
1428
+ if (value === "~")
1429
+ return os2.homedir();
1430
+ if (value.startsWith("~/"))
1431
+ return path2.join(os2.homedir(), value.slice(2));
1432
+ return path2.resolve(value);
1366
1433
  }
1367
- function defaultTokenFilePath(toolInstallationId) {
1368
- return path2.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1434
+ function defaultEventLogPath() {
1435
+ return path2.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1369
1436
  }
1370
- function tokenExpiryFilePath(tokenFilePath) {
1371
- return path2.join(path2.dirname(tokenFilePath), "expiry", path2.basename(tokenFilePath));
1437
+ function resolveEventLog(options = {}) {
1438
+ for (const [source, raw] of [
1439
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
1440
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
1441
+ ]) {
1442
+ const value = raw?.trim();
1443
+ if (!value)
1444
+ continue;
1445
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
1446
+ return { path: void 0, source: "disabled" };
1447
+ return { path: expandUserPath(value), source };
1448
+ }
1449
+ if (options.localOnly)
1450
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
1451
+ return { path: void 0, source: "off" };
1452
+ }
1453
+ function resolveEventLogPath(options = {}) {
1454
+ return resolveEventLog(options).path;
1455
+ }
1456
+ function describeEventLog(setting, command) {
1457
+ switch (setting.source) {
1458
+ case "env":
1459
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
1460
+ case "credentials":
1461
+ return `${setting.path} (set by ${command} --event-log)`;
1462
+ case "unpaired-default":
1463
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
1464
+ case "disabled":
1465
+ return `off (turned off; ${command} --event-log to turn it on)`;
1466
+ case "off":
1467
+ return `off (${command} --event-log to keep a local copy of every event)`;
1468
+ }
1469
+ }
1470
+ function parseEventLogFlag(argv, index) {
1471
+ const peek = argv[index + 1];
1472
+ if (peek !== void 0 && !peek.startsWith("-"))
1473
+ return { value: peek, consumed: 1 };
1474
+ return { value: defaultEventLogPath(), consumed: 0 };
1372
1475
  }
1373
- function persistEventWriteToken(tokenFilePath, token, expiresAt) {
1374
- const dir = path2.dirname(tokenFilePath);
1375
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1376
- fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1377
- if (process.platform !== "win32") {
1378
- fs.chmodSync(dir, 448);
1379
- fs.chmodSync(tokenFilePath, 384);
1380
- }
1381
- const expiryFile = tokenExpiryFilePath(tokenFilePath);
1476
+ function appendEventLog(logFilePath, entry) {
1382
1477
  try {
1383
- if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1384
- fs.mkdirSync(path2.dirname(expiryFile), { recursive: true, mode: 448 });
1385
- fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1386
- } else {
1387
- fs.rmSync(expiryFile, { force: true });
1388
- }
1478
+ rotateIfLarge(logFilePath);
1479
+ const dir = path2.dirname(logFilePath);
1480
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
1481
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
1482
+ fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
1483
+ `, { encoding: "utf8", mode: 384 });
1484
+ if (process.platform !== "win32")
1485
+ fs.chmodSync(logFilePath, 384);
1389
1486
  } catch {
1390
1487
  }
1391
1488
  }
1392
- exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1393
- function readTokenExpiry(tokenFilePath) {
1489
+ function rotateIfLarge(logFilePath) {
1394
1490
  try {
1395
- const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1396
- if (Number.isFinite(recorded))
1397
- return recorded;
1491
+ if (fs.statSync(logFilePath).size < MAX_BYTES)
1492
+ return;
1493
+ fs.renameSync(logFilePath, `${logFilePath}.1`);
1398
1494
  } catch {
1399
1495
  }
1496
+ }
1497
+ }
1498
+ });
1499
+
1500
+ // ../packages/tool-kit/out/http.js
1501
+ var require_http = __commonJS({
1502
+ "../packages/tool-kit/out/http.js"(exports) {
1503
+ "use strict";
1504
+ Object.defineProperty(exports, "__esModule", { value: true });
1505
+ exports.AscendaApiError = void 0;
1506
+ exports.createPairingSession = createPairingSession;
1507
+ exports.getPairingStatus = getPairingStatus;
1508
+ exports.startStudyJoin = startStudyJoin;
1509
+ exports.getStudyJoinStatus = getStudyJoinStatus;
1510
+ exports.readInitiatives = readInitiatives;
1511
+ exports.readStudyNotices = readStudyNotices;
1512
+ exports.setStudyObjection = setStudyObjection;
1513
+ exports.markStudyNoticeShown = markStudyNoticeShown;
1514
+ exports.renewToolToken = renewToolToken;
1515
+ exports.isRetryableStatus = isRetryableStatus;
1516
+ exports.postToolEvent = postToolEvent;
1517
+ exports.postToolEventsBatch = postToolEventsBatch;
1518
+ exports.parseIngestResponse = parseIngestResponse;
1519
+ var tool_contract_1 = require_out();
1520
+ var AscendaApiError = class extends Error {
1521
+ status;
1522
+ errorCode;
1523
+ constructor(status, errorCode, body) {
1524
+ super(body ?? `Ascenda API error ${status}`);
1525
+ this.status = status;
1526
+ this.errorCode = errorCode;
1527
+ this.name = "AscendaApiError";
1528
+ }
1529
+ };
1530
+ exports.AscendaApiError = AscendaApiError;
1531
+ async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
1532
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1533
+ method: "POST",
1534
+ headers: { "Content-Type": "application/json" },
1535
+ body: JSON.stringify({ toolInstallationId, toolType, displayName })
1536
+ });
1537
+ if (!response.ok)
1538
+ throw new AscendaApiError(response.status, void 0, await response.text());
1539
+ return await response.json();
1540
+ }
1541
+ async function getPairingStatus(apiBaseUrl, pairingSessionId) {
1542
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1543
+ method: "GET",
1544
+ headers: { Accept: "application/json" }
1545
+ });
1546
+ if (!response.ok)
1547
+ throw new AscendaApiError(response.status, void 0, await response.text());
1548
+ return await response.json();
1549
+ }
1550
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1551
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1552
+ method: "POST",
1553
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1554
+ body: JSON.stringify({ joinCode, mode })
1555
+ });
1556
+ if (!response.ok)
1557
+ throw await apiError(response);
1558
+ return await response.json();
1559
+ }
1560
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1561
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1562
+ method: "GET",
1563
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1564
+ });
1565
+ if (!response.ok)
1566
+ throw await apiError(response);
1567
+ return await response.json();
1568
+ }
1569
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1570
+ let response;
1571
+ try {
1572
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1573
+ method: "GET",
1574
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1575
+ signal
1576
+ });
1577
+ } catch (error) {
1578
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1579
+ }
1580
+ if (response.status === 401)
1581
+ return { kind: "rejected", httpStatus: 401 };
1582
+ if (!response.ok)
1583
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1584
+ let body;
1400
1585
  try {
1401
- return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1586
+ body = await response.json();
1402
1587
  } catch {
1403
- return void 0;
1588
+ return { kind: "failed", reason: "the reply was not readable" };
1404
1589
  }
1590
+ if (!Array.isArray(body))
1591
+ return { kind: "failed", reason: "the reply was not a list" };
1592
+ return { kind: "ok", initiatives: body };
1405
1593
  }
1406
- function listPersistedToolInstallationIds(toolType) {
1407
- const prefix = `${sanitizeFilePart(toolType)}_`;
1408
- const dir = path2.join(ascendaHome(), "tokens");
1409
- let names;
1594
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1595
+ let response;
1410
1596
  try {
1411
- names = fs.readdirSync(dir);
1597
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1598
+ method: "GET",
1599
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1600
+ signal
1601
+ });
1602
+ } catch (error) {
1603
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1604
+ }
1605
+ if (response.status === 404)
1606
+ return { kind: "absent" };
1607
+ if (response.status === 401)
1608
+ return { kind: "rejected", httpStatus: 401 };
1609
+ if (!response.ok)
1610
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1611
+ let body;
1612
+ try {
1613
+ body = await response.json();
1412
1614
  } catch {
1413
- return [];
1615
+ return { kind: "absent" };
1414
1616
  }
1415
- const ids = [];
1416
- for (const name of names.sort()) {
1417
- if (!name.startsWith(prefix) || name.length === prefix.length)
1418
- continue;
1419
- const file = path2.join(dir, name);
1420
- try {
1421
- if (!fs.statSync(file).isFile())
1422
- continue;
1423
- } catch {
1424
- continue;
1425
- }
1426
- if (readTokenFile(file) === void 0)
1427
- continue;
1428
- ids.push(`${toolType}:${name.slice(prefix.length)}`);
1617
+ if (!Array.isArray(body))
1618
+ return { kind: "absent" };
1619
+ return { kind: "ok", notices: body };
1620
+ }
1621
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1622
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1623
+ method: objected ? "POST" : "DELETE",
1624
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
1625
+ });
1626
+ if (!response.ok)
1627
+ throw await apiError(response);
1628
+ }
1629
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1630
+ try {
1631
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1632
+ method: "POST",
1633
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
1634
+ signal
1635
+ });
1636
+ return response.ok;
1637
+ } catch {
1638
+ return false;
1429
1639
  }
1430
- return ids;
1431
1640
  }
1432
- function readTokenFile(tokenFilePath) {
1641
+ async function apiError(response) {
1642
+ const body = await response.text();
1643
+ let errorCode;
1433
1644
  try {
1434
- if (!fs.existsSync(tokenFilePath))
1435
- return void 0;
1436
- const value = fs.readFileSync(tokenFilePath, "utf8").trim();
1437
- return value || void 0;
1645
+ const parsed = JSON.parse(body);
1646
+ errorCode = parsed.code ?? parsed.error;
1438
1647
  } catch {
1439
- return void 0;
1648
+ errorCode = void 0;
1440
1649
  }
1650
+ return new AscendaApiError(response.status, errorCode, body);
1441
1651
  }
1442
- function sanitizeFilePart(value) {
1443
- return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1652
+ async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1653
+ const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1654
+ method: "POST",
1655
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1656
+ signal
1657
+ });
1658
+ if (response.status === 401)
1659
+ return null;
1660
+ if (!response.ok)
1661
+ throw new AscendaApiError(response.status, void 0, await response.text());
1662
+ return await response.json();
1444
1663
  }
1445
- }
1446
- });
1447
-
1448
- // ../packages/tool-kit/out/stateStore.js
1449
- var require_stateStore = __commonJS({
1450
- "../packages/tool-kit/out/stateStore.js"(exports) {
1451
- "use strict";
1452
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1453
- if (k2 === void 0) k2 = k;
1454
- var desc = Object.getOwnPropertyDescriptor(m, k);
1455
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1456
- desc = { enumerable: true, get: function() {
1457
- return m[k];
1458
- } };
1664
+ function isDeliveredStatus(value) {
1665
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1666
+ }
1667
+ function readSuccessBody(body) {
1668
+ let parsed;
1669
+ try {
1670
+ parsed = JSON.parse(body);
1671
+ } catch {
1672
+ return { duplicates: 0 };
1459
1673
  }
1460
- Object.defineProperty(o, k2, desc);
1461
- } : function(o, m, k, k2) {
1462
- if (k2 === void 0) k2 = k;
1463
- o[k2] = m[k];
1464
- });
1465
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1466
- Object.defineProperty(o, "default", { enumerable: true, value: v });
1467
- } : function(o, v) {
1468
- o["default"] = v;
1469
- });
1470
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1471
- var ownKeys = function(o) {
1472
- ownKeys = Object.getOwnPropertyNames || function(o2) {
1473
- var ar = [];
1474
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1475
- return ar;
1476
- };
1477
- return ownKeys(o);
1478
- };
1479
- return function(mod) {
1480
- if (mod && mod.__esModule) return mod;
1481
- var result = {};
1482
- if (mod != null) {
1483
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1674
+ if (!parsed || typeof parsed !== "object")
1675
+ return { duplicates: 0 };
1676
+ const single = parsed.status;
1677
+ if (isDeliveredStatus(single))
1678
+ return { duplicates: single === "duplicate" ? 1 : 0 };
1679
+ const raw = parsed.results;
1680
+ if (!Array.isArray(raw))
1681
+ return { duplicates: 0 };
1682
+ const results = [];
1683
+ for (const item of raw) {
1684
+ if (!item || typeof item !== "object")
1685
+ continue;
1686
+ const { index, status, reason } = item;
1687
+ if (typeof index !== "number" || typeof status !== "string")
1688
+ continue;
1689
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1690
+ }
1691
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1692
+ }
1693
+ function isRetryableStatus(status) {
1694
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1695
+ }
1696
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1697
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1698
+ }
1699
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1700
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1701
+ }
1702
+ async function sendIngest(url, eventWriteToken, body, signal) {
1703
+ try {
1704
+ const response = await fetch(url, {
1705
+ method: "POST",
1706
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1707
+ body,
1708
+ signal
1709
+ });
1710
+ return parseIngestResponse(response);
1711
+ } catch (error) {
1712
+ return {
1713
+ result: "transport_error",
1714
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1715
+ };
1716
+ }
1717
+ }
1718
+ async function parseIngestResponse(response) {
1719
+ if (response.ok) {
1720
+ const outcome = { result: "accepted", httpStatus: response.status };
1721
+ let read = { duplicates: 0 };
1722
+ try {
1723
+ read = readSuccessBody(await response.text());
1724
+ } catch {
1725
+ read = { duplicates: 0 };
1726
+ }
1727
+ return {
1728
+ ...outcome,
1729
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1730
+ ...read.results !== void 0 ? { results: read.results } : {}
1731
+ };
1732
+ }
1733
+ const body = await response.text();
1734
+ let errorCode;
1735
+ try {
1736
+ errorCode = JSON.parse(body).error;
1737
+ } catch {
1738
+ errorCode = void 0;
1739
+ }
1740
+ const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1741
+ if (response.status === 401)
1742
+ return { ...base, result: "auth_failed" };
1743
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
1744
+ return { ...base, result: "consent_missing" };
1745
+ if (response.status === 400 || response.status === 422)
1746
+ return { ...base, result: "validation_failed" };
1747
+ return { ...base, result: "transport_error" };
1748
+ }
1749
+ }
1750
+ });
1751
+
1752
+ // ../packages/tool-kit/out/stateStore.js
1753
+ var require_stateStore = __commonJS({
1754
+ "../packages/tool-kit/out/stateStore.js"(exports) {
1755
+ "use strict";
1756
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1757
+ if (k2 === void 0) k2 = k;
1758
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1759
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1760
+ desc = { enumerable: true, get: function() {
1761
+ return m[k];
1762
+ } };
1763
+ }
1764
+ Object.defineProperty(o, k2, desc);
1765
+ } : function(o, m, k, k2) {
1766
+ if (k2 === void 0) k2 = k;
1767
+ o[k2] = m[k];
1768
+ });
1769
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1770
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1771
+ } : function(o, v) {
1772
+ o["default"] = v;
1773
+ });
1774
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1775
+ var ownKeys = function(o) {
1776
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1777
+ var ar = [];
1778
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1779
+ return ar;
1780
+ };
1781
+ return ownKeys(o);
1782
+ };
1783
+ return function(mod) {
1784
+ if (mod && mod.__esModule) return mod;
1785
+ var result = {};
1786
+ if (mod != null) {
1787
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1484
1788
  }
1485
1789
  __setModuleDefault(result, mod);
1486
1790
  return result;
@@ -1849,6 +2153,7 @@ var require_eventSender = __commonJS({
1849
2153
  "use strict";
1850
2154
  Object.defineProperty(exports, "__esModule", { value: true });
1851
2155
  exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
2156
+ exports.buildEventBody = buildEventBody;
1852
2157
  exports.buildEventPayload = buildEventPayload;
1853
2158
  var afterHours_1 = require_afterHours();
1854
2159
  var tool_contract_1 = require_out();
@@ -1867,12 +2172,10 @@ var require_eventSender = __commonJS({
1867
2172
  }
1868
2173
  };
1869
2174
  exports.AscendaSemanticEventError = AscendaSemanticEventError;
1870
- function buildEventPayload(identity, mapped) {
2175
+ function buildEventBody(identity, mapped) {
1871
2176
  return {
1872
- toolInstallationId: identity.toolInstallationId,
1873
2177
  source: identity.source,
1874
2178
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1875
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1876
2179
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1877
2180
  sessionId: identity.sessionId ?? void 0,
1878
2181
  workspaceHash: identity.workspaceHash ?? void 0,
@@ -1884,6 +2187,9 @@ var require_eventSender = __commonJS({
1884
2187
  metadata: withCollectorVersion(mapped.metadata)
1885
2188
  };
1886
2189
  }
2190
+ function buildEventPayload(identity, mapped) {
2191
+ return (0, tool_contract_1.joinEventPayload)({ toolInstallationId: identity.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() }, buildEventBody(identity, mapped));
2192
+ }
1887
2193
  function withCollectorVersion(metadata) {
1888
2194
  return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION };
1889
2195
  }
@@ -1959,12 +2265,10 @@ var require_eventSender = __commonJS({
1959
2265
  if (!mapped.metadata.skillVersion || !mapped.metadata.skillVersion.trim()) {
1960
2266
  throw new AscendaSemanticEventError(`metadata.skillVersion is required for semantic event "${mapped.eventType}".`);
1961
2267
  }
1962
- const payload = {
1963
- toolInstallationId: this.config.toolInstallationId,
2268
+ const body = {
1964
2269
  source: this.config.source,
1965
2270
  eventType: mapped.eventType,
1966
2271
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1967
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1968
2272
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1969
2273
  severity: "low",
1970
2274
  sessionId: this.config.sessionId ?? void 0,
@@ -1975,7 +2279,7 @@ var require_eventSender = __commonJS({
1975
2279
  privacyMode: "metadata_only",
1976
2280
  metadata: withCollectorVersion(mapped.metadata)
1977
2281
  };
1978
- return this.post(payload);
2282
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
1979
2283
  }
1980
2284
  /**
1981
2285
  * Sends a collaboration event under `workflow_telemetry`.
@@ -1990,12 +2294,10 @@ var require_eventSender = __commonJS({
1990
2294
  if (!tool_contract_1.COLLABORATION_EVENT_TYPES.includes(mapped.eventType)) {
1991
2295
  throw new AscendaSemanticEventError(`"${mapped.eventType}" is not a collaboration event type. Use send() for a deterministic host event.`);
1992
2296
  }
1993
- const payload = {
1994
- toolInstallationId: this.config.toolInstallationId,
2297
+ const body = {
1995
2298
  source: this.config.source,
1996
2299
  eventType: mapped.eventType,
1997
2300
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1998
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1999
2301
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
2000
2302
  severity: "low",
2001
2303
  sessionId: this.config.sessionId ?? void 0,
@@ -2006,7 +2308,11 @@ var require_eventSender = __commonJS({
2006
2308
  privacyMode: "metadata_only",
2007
2309
  metadata: withCollectorVersion(mapped.metadata)
2008
2310
  };
2009
- return this.post(payload);
2311
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
2312
+ }
2313
+ /** A fresh envelope per event: the key belongs to the event, so every retry of it reuses this one. */
2314
+ envelope() {
2315
+ return { toolInstallationId: this.config.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() };
2010
2316
  }
2011
2317
  /**
2012
2318
  * The single choke point every event passes through, and therefore the only
@@ -2426,123 +2732,6 @@ var require_contextRegistry = __commonJS({
2426
2732
  }
2427
2733
  });
2428
2734
 
2429
- // ../packages/tool-kit/out/credentials.js
2430
- var require_credentials = __commonJS({
2431
- "../packages/tool-kit/out/credentials.js"(exports) {
2432
- "use strict";
2433
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2434
- if (k2 === void 0) k2 = k;
2435
- var desc = Object.getOwnPropertyDescriptor(m, k);
2436
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2437
- desc = { enumerable: true, get: function() {
2438
- return m[k];
2439
- } };
2440
- }
2441
- Object.defineProperty(o, k2, desc);
2442
- } : function(o, m, k, k2) {
2443
- if (k2 === void 0) k2 = k;
2444
- o[k2] = m[k];
2445
- });
2446
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2447
- Object.defineProperty(o, "default", { enumerable: true, value: v });
2448
- } : function(o, v) {
2449
- o["default"] = v;
2450
- });
2451
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2452
- var ownKeys = function(o) {
2453
- ownKeys = Object.getOwnPropertyNames || function(o2) {
2454
- var ar = [];
2455
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2456
- return ar;
2457
- };
2458
- return ownKeys(o);
2459
- };
2460
- return function(mod) {
2461
- if (mod && mod.__esModule) return mod;
2462
- var result = {};
2463
- if (mod != null) {
2464
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2465
- }
2466
- __setModuleDefault(result, mod);
2467
- return result;
2468
- };
2469
- }();
2470
- Object.defineProperty(exports, "__esModule", { value: true });
2471
- exports.credentialsFilePath = credentialsFilePath;
2472
- exports.readMachineCredentials = readMachineCredentials;
2473
- exports.writeMachineCredentials = writeMachineCredentials;
2474
- exports.writeTopLevelCredentials = writeTopLevelCredentials;
2475
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2476
- exports.readHostCredentials = readHostCredentials;
2477
- exports.writeHostCredentials = writeHostCredentials;
2478
- exports.removeHostCredentials = removeHostCredentials;
2479
- var fs = __importStar(__require("fs"));
2480
- var path2 = __importStar(__require("path"));
2481
- var tokenStore_1 = require_tokenStore();
2482
- function credentialsFilePath() {
2483
- return path2.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2484
- }
2485
- function readMachineCredentials() {
2486
- try {
2487
- const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
2488
- if (!raw)
2489
- return void 0;
2490
- const parsed = JSON.parse(raw);
2491
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2492
- return void 0;
2493
- return parsed;
2494
- } catch {
2495
- return void 0;
2496
- }
2497
- }
2498
- function writeMachineCredentials(credentials) {
2499
- const file = credentialsFilePath();
2500
- fs.mkdirSync(path2.dirname(file), { recursive: true, mode: 448 });
2501
- fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2502
- `, { encoding: "utf8", mode: 384 });
2503
- if (process.platform !== "win32") {
2504
- fs.chmodSync(path2.dirname(file), 448);
2505
- fs.chmodSync(file, 384);
2506
- }
2507
- }
2508
- function writeTopLevelCredentials(credentials) {
2509
- const existing = readMachineCredentials();
2510
- writeMachineCredentials({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2511
- }
2512
- function isLocalOnlyHostInstall(host, hasToken) {
2513
- const credentials = readHostCredentials(host);
2514
- if (!credentials?.localOnly)
2515
- return false;
2516
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2517
- return false;
2518
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2519
- }
2520
- function readHostCredentials(host) {
2521
- const entry = readMachineCredentials()?.tools?.[host];
2522
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
2523
- return void 0;
2524
- return entry;
2525
- }
2526
- function writeHostCredentials(host, credentials) {
2527
- const existing = readMachineCredentials() ?? {};
2528
- writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2529
- }
2530
- function removeHostCredentials(host) {
2531
- const existing = readMachineCredentials();
2532
- if (!existing?.tools || !(host in existing.tools))
2533
- return;
2534
- const tools = { ...existing.tools };
2535
- delete tools[host];
2536
- const next = { ...existing };
2537
- if (Object.keys(tools).length)
2538
- next.tools = tools;
2539
- else
2540
- delete next.tools;
2541
- writeMachineCredentials(next);
2542
- }
2543
- }
2544
- });
2545
-
2546
2735
  // ../packages/tool-kit/out/forgeProject.js
2547
2736
  var require_forgeProject = __commonJS({
2548
2737
  "../packages/tool-kit/out/forgeProject.js"(exports) {
@@ -3086,8 +3275,12 @@ var require_hookAdapter = __commonJS({
3086
3275
  return;
3087
3276
  const notice = options.onNotice ?? ((message) => console.error(message));
3088
3277
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3089
- if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken))
3278
+ if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3279
+ const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
3280
+ if (logFile)
3281
+ logUnsent(logFile, events, options);
3090
3282
  return;
3283
+ }
3091
3284
  let config;
3092
3285
  try {
3093
3286
  config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
@@ -3097,20 +3290,7 @@ var require_hookAdapter = __commonJS({
3097
3290
  const logFile = (0, eventLog_1.resolveEventLogPath)();
3098
3291
  if (!logFile)
3099
3292
  throw error;
3100
- const contextHashes = resolveContextHashes(options.cwd);
3101
- for (const event of events) {
3102
- (0, eventLog_1.appendEventLog)(logFile, {
3103
- loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3104
- delivery: "not_sent",
3105
- payload: (0, eventSender_1.buildEventPayload)({
3106
- toolInstallationId: `${options.toolType}:unpaired`,
3107
- source: options.source,
3108
- sessionId: options.sessionId ?? null,
3109
- workspaceHash: contextHashes.workspaceHash,
3110
- projectHash: contextHashes.projectHash
3111
- }, event)
3112
- });
3113
- }
3293
+ logUnsent(logFile, events, options);
3114
3294
  return;
3115
3295
  }
3116
3296
  const sender = new eventSender_1.AscendaEventSender({
@@ -3140,6 +3320,22 @@ var require_hookAdapter = __commonJS({
3140
3320
  return;
3141
3321
  }
3142
3322
  }
3323
+ function logUnsent(logFile, events, options) {
3324
+ const contextHashes = resolveContextHashes(options.cwd);
3325
+ for (const event of events) {
3326
+ (0, eventLog_1.appendEventLog)(logFile, {
3327
+ loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3328
+ delivery: "not_sent",
3329
+ payload: (0, eventSender_1.buildEventPayload)({
3330
+ toolInstallationId: `${options.toolType}:unpaired`,
3331
+ source: options.source,
3332
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || options.sessionId || null,
3333
+ workspaceHash: contextHashes.workspaceHash,
3334
+ projectHash: contextHashes.projectHash
3335
+ }, event)
3336
+ });
3337
+ }
3338
+ }
3143
3339
  function journalSkippedSend(host, error) {
3144
3340
  const who = host ? `${host}: ` : "";
3145
3341
  (0, stateStore_1.recordSendOutcome)((0, stateStore_1.unresolvedStateFilePath)(error.toolType), (0, stateStore_1.unresolvedToolInstallationId)(error.toolType), "skipped_no_installation_id", {
@@ -3520,152 +3716,917 @@ var require_initiatives = __commonJS({
3520
3716
  }
3521
3717
  return lines;
3522
3718
  }
3523
- function renderOne(initiative, copy) {
3524
- const lines = [` ${initiative.organisationName}: ${initiative.title}`];
3525
- lines.push(` ${describeStatus(initiative)}`);
3526
- if (initiative.summaryForCohort) {
3527
- for (const line of initiative.summaryForCohort.split(/\r?\n/))
3528
- lines.push(` ${line}`);
3529
- }
3530
- if (initiative.direction)
3531
- lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
3532
- lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
3533
- if (initiative.result)
3534
- lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
3535
- lines.push("");
3536
- return lines;
3719
+ function renderOne(initiative, copy) {
3720
+ const lines = [` ${initiative.organisationName}: ${initiative.title}`];
3721
+ lines.push(` ${describeStatus(initiative)}`);
3722
+ if (initiative.summaryForCohort) {
3723
+ for (const line of initiative.summaryForCohort.split(/\r?\n/))
3724
+ lines.push(` ${line}`);
3725
+ }
3726
+ if (initiative.direction)
3727
+ lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
3728
+ lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
3729
+ if (initiative.result)
3730
+ lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
3731
+ lines.push("");
3732
+ return lines;
3733
+ }
3734
+ function describeStatus(initiative) {
3735
+ switch (initiative.status) {
3736
+ case "published":
3737
+ return "Published, not scored yet.";
3738
+ case "scored":
3739
+ return "Scored.";
3740
+ case "withdrawn":
3741
+ return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
3742
+ default:
3743
+ return "Status not recognised.";
3744
+ }
3745
+ }
3746
+ function renderResult(result, unit, copy) {
3747
+ const lines = [];
3748
+ const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
3749
+ if (result.value === null) {
3750
+ const why = copy.withheldReasons[result.withheldReason ?? ""];
3751
+ lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
3752
+ return lines;
3753
+ }
3754
+ lines.push(` Result: ${show(result.value)}`);
3755
+ lines.push(` ${movementLine(result)}`);
3756
+ lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
3757
+ return lines;
3758
+ }
3759
+ function movementLine(result) {
3760
+ if (result.outcome === "within_own_variation")
3761
+ return "No material change against frozen baseline";
3762
+ if (result.delta === null)
3763
+ return "No reading";
3764
+ if (result.delta > 0)
3765
+ return `Up ${figure(result.delta)} against frozen baseline`;
3766
+ if (result.delta < 0)
3767
+ return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
3768
+ return "No change against frozen baseline";
3769
+ }
3770
+ function figure(n) {
3771
+ return String(Number(n.toPrecision(12)));
3772
+ }
3773
+ function asInitiative(value) {
3774
+ if (!value || typeof value !== "object")
3775
+ return void 0;
3776
+ const o = value;
3777
+ if (typeof o.title !== "string" || typeof o.status !== "string")
3778
+ return void 0;
3779
+ return {
3780
+ id: typeof o.id === "string" ? o.id : "",
3781
+ organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3782
+ title: o.title,
3783
+ summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3784
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3785
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3786
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3787
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3788
+ status: o.status,
3789
+ direction: typeof o.direction === "string" ? o.direction : null,
3790
+ result: asResult(o.result)
3791
+ };
3792
+ }
3793
+ function asResult(value) {
3794
+ if (!value || typeof value !== "object")
3795
+ return null;
3796
+ const r = value;
3797
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
3798
+ return {
3799
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3800
+ value: num(r.value),
3801
+ baselineValue: num(r.baselineValue),
3802
+ delta: num(r.delta),
3803
+ movement: typeof r.movement === "string" ? r.movement : null,
3804
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
3805
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3806
+ basis: typeof r.basis === "string" ? r.basis : null
3807
+ };
3808
+ }
3809
+ function formatWindowOrRaw(startUtc, endUtc) {
3810
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3811
+ return "not given";
3812
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3813
+ }
3814
+ function formatDay(iso) {
3815
+ const date = new Date(iso);
3816
+ if (Number.isNaN(date.getTime()))
3817
+ return iso;
3818
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
3819
+ }
3820
+ }
3821
+ });
3822
+
3823
+ // ../packages/tool-kit/out/setupDisclosure.js
3824
+ var require_setupDisclosure = __commonJS({
3825
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3826
+ "use strict";
3827
+ Object.defineProperty(exports, "__esModule", { value: true });
3828
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3829
+ exports.renderSetupDisclosure = renderSetupDisclosure;
3830
+ exports.FAMILY_SENTENCES = {
3831
+ session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
3832
+ counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
3833
+ tools: "the name of each tool your agent calls",
3834
+ outcome: "whether a call succeeded, failed, or was interrupted",
3835
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
3836
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3837
+ model: "which model served the session, by name and by tier",
3838
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3839
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
3840
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3841
+ context: "how full the context window got",
3842
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3843
+ 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",
3844
+ 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"
3845
+ };
3846
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3847
+ exports.REFUSALS = [
3848
+ "Never your prompts, your agent's replies, or anything inside a file.",
3849
+ "Never a file path, a command line, or a repository or branch name.",
3850
+ "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
3851
+ ];
3852
+ exports.FREE_TEXT_KEYS = ["message"];
3853
+ function renderSetupDisclosure({ sends, displayName }) {
3854
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3855
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3856
+ const lines = [
3857
+ `What this sends from ${displayName}, once paired:`,
3858
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3859
+ "",
3860
+ ...exports.REFUSALS.map((line) => ` ${line}`),
3861
+ "",
3862
+ " Turn it off by revoking this tool in the Ascenda app."
3863
+ ];
3864
+ return lines.join("\n");
3865
+ }
3866
+ }
3867
+ });
3868
+
3869
+ // ../packages/tool-kit/out/hookRunner.js
3870
+ var require_hookRunner = __commonJS({
3871
+ "../packages/tool-kit/out/hookRunner.js"(exports) {
3872
+ "use strict";
3873
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3874
+ if (k2 === void 0) k2 = k;
3875
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3876
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3877
+ desc = { enumerable: true, get: function() {
3878
+ return m[k];
3879
+ } };
3880
+ }
3881
+ Object.defineProperty(o, k2, desc);
3882
+ } : function(o, m, k, k2) {
3883
+ if (k2 === void 0) k2 = k;
3884
+ o[k2] = m[k];
3885
+ });
3886
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3887
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3888
+ } : function(o, v) {
3889
+ o["default"] = v;
3890
+ });
3891
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3892
+ var ownKeys = function(o) {
3893
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3894
+ var ar = [];
3895
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3896
+ return ar;
3897
+ };
3898
+ return ownKeys(o);
3899
+ };
3900
+ return function(mod) {
3901
+ if (mod && mod.__esModule) return mod;
3902
+ var result = {};
3903
+ if (mod != null) {
3904
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3905
+ }
3906
+ __setModuleDefault(result, mod);
3907
+ return result;
3908
+ };
3909
+ }();
3910
+ Object.defineProperty(exports, "__esModule", { value: true });
3911
+ exports.hookRunnerPaths = hookRunnerPaths;
3912
+ exports.hookLauncherScript = hookLauncherScript;
3913
+ exports.installHookRunner = installHookRunner;
3914
+ exports.removeHookRunner = removeHookRunner;
3915
+ exports.hookRunnerCommand = hookRunnerCommand;
3916
+ exports.lastHookPath = lastHookPath;
3917
+ exports.stampLastHook = stampLastHook2;
3918
+ exports.readLastHook = readLastHook;
3919
+ exports.describeAge = describeAge;
3920
+ exports.resolveHookNode = resolveHookNode;
3921
+ exports.tidyHomePath = tidyHomePath;
3922
+ var child_process_1 = __require("child_process");
3923
+ var fs = __importStar(__require("fs"));
3924
+ var path2 = __importStar(__require("path"));
3925
+ var tokenStore_1 = require_tokenStore();
3926
+ function hookRunnerPaths(binaryName) {
3927
+ const launcher = path2.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3928
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
3929
+ }
3930
+ var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3931
+ function hookLauncherScript(options) {
3932
+ const { binaryName, setupCommand, loudEvent } = options;
3933
+ return [
3934
+ "#!/bin/sh",
3935
+ `# Ascenda hook launcher (${binaryName}). Written by \`setup\`, replaced by the`,
3936
+ "# next one; edits here are lost. Finds a Node to run the hook bundle beside it.",
3937
+ "",
3938
+ 'dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 0',
3939
+ `bundle="$dir/${binaryName}.mjs"`,
3940
+ `record="$dir/${binaryName}.node"`,
3941
+ `missing="$dir/${binaryName}.no-node"`,
3942
+ "",
3943
+ 'runs() { [ -n "$1" ] && [ -f "$1" ] && [ -x "$1" ]; }',
3944
+ "",
3945
+ "# The hook bundle needs Node 20 or newer. Checked only while searching, so",
3946
+ "# the recorded path costs nothing to reuse.",
3947
+ "recent() {",
3948
+ ` runs "$1" && "$1" -e 'process.exit(parseInt(process.versions.node, 10) >= 20 ? 0 : 1)' >/dev/null 2>&1`,
3949
+ "}",
3950
+ "",
3951
+ "newest_nvm() {",
3952
+ ' [ -d "$HOME/.nvm/versions/node" ] || return 0',
3953
+ ` ls "$HOME/.nvm/versions/node" 2>/dev/null | sed 's/^v//' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1 | sed 's/^/v/'`,
3954
+ "}",
3955
+ "",
3956
+ 'node=""',
3957
+ "how=recorded",
3958
+ '[ -r "$record" ] && IFS= read -r node < "$record"',
3959
+ "",
3960
+ 'if ! runs "$node"; then',
3961
+ ' node=""',
3962
+ " how=found",
3963
+ ' nvm_default=""',
3964
+ ' if [ -r "$HOME/.nvm/alias/default" ]; then',
3965
+ ' IFS= read -r wanted < "$HOME/.nvm/alias/default"',
3966
+ " wanted=${wanted#v}",
3967
+ ' for candidate in "$HOME/.nvm/versions/node/v$wanted"*; do',
3968
+ ' [ -x "$candidate/bin/node" ] && nvm_default="$candidate/bin/node"',
3969
+ " done",
3970
+ " fi",
3971
+ " nvm_newest=$(newest_nvm)",
3972
+ " for candidate in \\",
3973
+ ' "$(command -v node 2>/dev/null)" \\',
3974
+ " /opt/homebrew/bin/node \\",
3975
+ " /usr/local/bin/node \\",
3976
+ ' "$HOME/.volta/bin/node" \\',
3977
+ ' "$nvm_default" \\',
3978
+ ' "$HOME/.local/share/fnm/aliases/default/bin/node" \\',
3979
+ ' "$HOME/Library/Application Support/fnm/aliases/default/bin/node" \\',
3980
+ ' "$HOME/.asdf/shims/node" \\',
3981
+ ' "$HOME/.local/share/mise/shims/node" \\',
3982
+ ' "$HOME/.nvm/versions/node/$nvm_newest/bin/node"',
3983
+ " do",
3984
+ ' if recent "$candidate"; then node=$candidate; break; fi',
3985
+ " done",
3986
+ ' if [ -n "$node" ]; then',
3987
+ ` printf '%s\\n' "$node" > "$record.$$" 2>/dev/null && mv -f "$record.$$" "$record" 2>/dev/null`,
3988
+ ' rm -f "$missing" 2>/dev/null',
3989
+ " fi",
3990
+ "fi",
3991
+ "",
3992
+ 'if [ -n "$ASCENDA_HOOK_LAUNCHER_PROBE" ]; then',
3993
+ ' [ -n "$node" ] || { echo "no Node 20 or newer found on PATH or in the usual install locations" >&2; exit 1; }',
3994
+ ` printf '%s\\t%s\\n' "$node" "$how"`,
3995
+ " exit 0",
3996
+ "fi",
3997
+ "",
3998
+ 'if [ -z "$node" ]; then',
3999
+ ' date -u +%Y-%m-%dT%H:%M:%SZ > "$missing" 2>/dev/null',
4000
+ ' case "$1" in',
4001
+ ...loudEvent ? [
4002
+ ` ${loudEvent})`,
4003
+ " cat >/dev/null 2>&1",
4004
+ ` echo "Ascenda hooks cannot find Node 20 or newer, so none of them are running. Install Node, then run: ${setupCommand}" >&2`,
4005
+ " exit 1 ;;"
4006
+ ] : [],
4007
+ ` ${LAUNCHER_MANAGEMENT_COMMANDS.join("|")})`,
4008
+ ` echo "${binaryName}: no Node 20 or newer found on PATH or in the usual install locations." >&2`,
4009
+ " exit 1 ;;",
4010
+ " *)",
4011
+ " # A hook: say nothing per tool call. status and doctor read the",
4012
+ " # file written above.",
4013
+ " cat >/dev/null 2>&1",
4014
+ " exit 0 ;;",
4015
+ " esac",
4016
+ "fi",
4017
+ "",
4018
+ 'exec "$node" "$bundle" "$@"',
4019
+ ""
4020
+ ].join("\n");
4021
+ }
4022
+ function installHookRunner(options) {
4023
+ const paths = hookRunnerPaths(options.binaryName);
4024
+ if (options.dryRun)
4025
+ return paths.launcher;
4026
+ const source = path2.resolve(options.source ?? process.argv[1]);
4027
+ fs.mkdirSync(path2.dirname(paths.launcher), { recursive: true });
4028
+ if (process.platform === "win32") {
4029
+ if (source !== path2.resolve(paths.launcher))
4030
+ fs.copyFileSync(source, paths.launcher);
4031
+ return paths.launcher;
4032
+ }
4033
+ if (source !== path2.resolve(paths.bundle))
4034
+ writeAtomically(paths.bundle, fs.readFileSync(source), 493);
4035
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4036
+ writeAtomically(paths.record, `${process.execPath}
4037
+ `, 420);
4038
+ fs.rmSync(paths.noNode, { force: true });
4039
+ return paths.launcher;
4040
+ }
4041
+ function removeHookRunner(binaryName) {
4042
+ const removed = [];
4043
+ for (const file of Object.values(hookRunnerPaths(binaryName))) {
4044
+ if (!fs.existsSync(file))
4045
+ continue;
4046
+ fs.rmSync(file, { force: true });
4047
+ removed.push(file);
4048
+ }
4049
+ return removed;
4050
+ }
4051
+ function hookRunnerCommand(launcher) {
4052
+ return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4053
+ }
4054
+ function writeAtomically(target, contents, mode) {
4055
+ const tmp = `${target}.${process.pid}.tmp`;
4056
+ fs.writeFileSync(tmp, contents, { mode });
4057
+ fs.chmodSync(tmp, mode);
4058
+ fs.renameSync(tmp, target);
4059
+ }
4060
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path2.join((0, tokenStore_1.ascendaHome)(), "state");
4061
+ function lastHookPath(tool) {
4062
+ return path2.join(stateDir(), `${tool}-last-hook.json`);
4063
+ }
4064
+ function stampLastHook2(tool, event, now = /* @__PURE__ */ new Date()) {
4065
+ try {
4066
+ fs.mkdirSync(stateDir(), { recursive: true });
4067
+ const file = lastHookPath(tool);
4068
+ const tmp = `${file}.${process.pid}.tmp`;
4069
+ fs.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
4070
+ `, { mode: 384 });
4071
+ fs.renameSync(tmp, file);
4072
+ } catch {
4073
+ }
4074
+ }
4075
+ function readLastHook(tool) {
4076
+ try {
4077
+ const parsed = JSON.parse(fs.readFileSync(lastHookPath(tool), "utf8"));
4078
+ if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
4079
+ return void 0;
4080
+ return { event: parsed.event, at: parsed.at };
4081
+ } catch {
4082
+ return void 0;
4083
+ }
4084
+ }
4085
+ function describeAge(ms) {
4086
+ if (!Number.isFinite(ms) || ms < 0)
4087
+ return "just now";
4088
+ const seconds = Math.round(ms / 1e3);
4089
+ if (seconds < 60)
4090
+ return `${seconds} s ago`;
4091
+ const minutes = Math.round(seconds / 60);
4092
+ if (minutes < 60)
4093
+ return `${minutes} min ago`;
4094
+ const hours = Math.round(minutes / 60);
4095
+ if (hours < 48)
4096
+ return `${hours} h ago`;
4097
+ return `${Math.round(hours / 24)} days ago`;
4098
+ }
4099
+ function resolveHookNode(launcher) {
4100
+ if (!fs.existsSync(launcher))
4101
+ return { problem: "the hook launcher is not installed" };
4102
+ const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
4103
+ encoding: "utf8",
4104
+ timeout: 5e3,
4105
+ env: { HOME: process.env.HOME ?? "", PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ASCENDA_HOOK_LAUNCHER_PROBE: "1" }
4106
+ });
4107
+ const [node, how] = (probe.stdout ?? "").trim().split(" ");
4108
+ if (probe.status !== 0 || !node) {
4109
+ return { problem: (probe.stderr ?? "").trim() || "the launcher found no Node it can run" };
4110
+ }
4111
+ const version = (0, child_process_1.spawnSync)(node, ["--version"], { encoding: "utf8", timeout: 5e3 });
4112
+ if (version.status !== 0)
4113
+ return { node, how, problem: `${node} did not run` };
4114
+ return { node, how, version: version.stdout.trim() };
4115
+ }
4116
+ function tidyHomePath(file, home = process.env.HOME ?? "") {
4117
+ return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
4118
+ }
4119
+ }
4120
+ });
4121
+
4122
+ // ../packages/tool-kit/out/saverHandoff.js
4123
+ var require_saverHandoff = __commonJS({
4124
+ "../packages/tool-kit/out/saverHandoff.js"(exports) {
4125
+ "use strict";
4126
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4127
+ if (k2 === void 0) k2 = k;
4128
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4129
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4130
+ desc = { enumerable: true, get: function() {
4131
+ return m[k];
4132
+ } };
4133
+ }
4134
+ Object.defineProperty(o, k2, desc);
4135
+ } : function(o, m, k, k2) {
4136
+ if (k2 === void 0) k2 = k;
4137
+ o[k2] = m[k];
4138
+ });
4139
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4140
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4141
+ } : function(o, v) {
4142
+ o["default"] = v;
4143
+ });
4144
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4145
+ var ownKeys = function(o) {
4146
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4147
+ var ar = [];
4148
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4149
+ return ar;
4150
+ };
4151
+ return ownKeys(o);
4152
+ };
4153
+ return function(mod) {
4154
+ if (mod && mod.__esModule) return mod;
4155
+ var result = {};
4156
+ if (mod != null) {
4157
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4158
+ }
4159
+ __setModuleDefault(result, mod);
4160
+ return result;
4161
+ };
4162
+ }();
4163
+ Object.defineProperty(exports, "__esModule", { value: true });
4164
+ exports.SAVER_REPLAY_SCHEMA = exports.SAVER_REPLAY_WINDOW_MS = void 0;
4165
+ exports.saverContainerDir = saverContainerDir;
4166
+ exports.saverSupportDir = saverSupportDir;
4167
+ exports.saverReplayPath = saverReplayPath;
4168
+ exports.saverStatusDir = saverStatusDir;
4169
+ exports.holdForSaver = holdForSaver;
4170
+ exports.heldForSaver = heldForSaver;
4171
+ exports.readSaverStatuses = readSaverStatuses;
4172
+ exports.probeSocket = probeSocket;
4173
+ var fs = __importStar(__require("fs"));
4174
+ var net = __importStar(__require("net"));
4175
+ var os2 = __importStar(__require("os"));
4176
+ var path2 = __importStar(__require("path"));
4177
+ var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
4178
+ function saverContainerDir() {
4179
+ return process.env.ASCENDA_SAVER_CONTAINER ?? path2.join(os2.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
4180
+ }
4181
+ function saverSupportDir() {
4182
+ return path2.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
4183
+ }
4184
+ function saverReplayPath() {
4185
+ return path2.join(saverContainerDir(), "l.replay.json");
4186
+ }
4187
+ function saverStatusDir() {
4188
+ return path2.join(saverSupportDir(), "status");
4189
+ }
4190
+ exports.SAVER_REPLAY_WINDOW_MS = 30 * 60 * 1e3;
4191
+ var SAVER_REPLAY_MAX = 32;
4192
+ exports.SAVER_REPLAY_SCHEMA = 1;
4193
+ function holdForSaver(signal, now = Date.now()) {
4194
+ try {
4195
+ if (process.env.ASCENDA_LIVE_BUS_SOCKET && !process.env.ASCENDA_SAVER_CONTAINER)
4196
+ return;
4197
+ if (!fs.existsSync(saverSupportDir()))
4198
+ return;
4199
+ const wire = signal;
4200
+ const tool = wire.tool;
4201
+ const session = wire.session;
4202
+ const event = wire.event;
4203
+ if (typeof tool !== "string" || typeof session !== "string" || typeof event !== "string")
4204
+ return;
4205
+ const file = saverReplayPath();
4206
+ const kept = readHeld(file).filter((held) => now - held.at <= exports.SAVER_REPLAY_WINDOW_MS && !(held.tool === tool && held.session === session));
4207
+ kept.push({ ...wire, tool, session, event, at: now });
4208
+ kept.sort((a, b) => a.at - b.at);
4209
+ const body = JSON.stringify({ schema: exports.SAVER_REPLAY_SCHEMA, signals: kept.slice(-SAVER_REPLAY_MAX) });
4210
+ const tmp = `${file}.${process.pid}.tmp`;
4211
+ fs.writeFileSync(tmp, `${body}
4212
+ `, { mode: 384 });
4213
+ fs.renameSync(tmp, file);
4214
+ } catch {
4215
+ }
4216
+ }
4217
+ function readHeld(file) {
4218
+ try {
4219
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
4220
+ if (parsed.schema !== exports.SAVER_REPLAY_SCHEMA || !Array.isArray(parsed.signals))
4221
+ return [];
4222
+ return parsed.signals.filter((held) => typeof held === "object" && held !== null && typeof held.tool === "string" && typeof held.session === "string" && typeof held.event === "string" && typeof held.at === "number");
4223
+ } catch {
4224
+ return [];
4225
+ }
4226
+ }
4227
+ function heldForSaver(now = Date.now()) {
4228
+ const held = readHeld(saverReplayPath()).filter((entry) => now - entry.at <= exports.SAVER_REPLAY_WINDOW_MS);
4229
+ if (held.length === 0)
4230
+ return { count: 0 };
4231
+ return { count: held.length, newestAgeMs: now - Math.max(...held.map((entry) => entry.at)) };
4232
+ }
4233
+ function readSaverStatuses(now = Date.now()) {
4234
+ let names;
4235
+ try {
4236
+ names = fs.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
4237
+ } catch {
4238
+ return [];
4239
+ }
4240
+ const readings = [];
4241
+ for (const name of names) {
4242
+ try {
4243
+ const status = JSON.parse(fs.readFileSync(path2.join(saverStatusDir(), name), "utf8"));
4244
+ if (typeof status.pid !== "number" || typeof status.updatedAt !== "string")
4245
+ continue;
4246
+ readings.push({ ...status, alive: processAlive(status.pid), ageMs: now - Date.parse(status.updatedAt) });
4247
+ } catch {
4248
+ }
4249
+ }
4250
+ return readings.sort((a, b) => a.ageMs - b.ageMs);
4251
+ }
4252
+ function processAlive(pid) {
4253
+ try {
4254
+ process.kill(pid, 0);
4255
+ return true;
4256
+ } catch (error) {
4257
+ return error.code === "EPERM";
4258
+ }
4259
+ }
4260
+ function probeSocket(socketPath, timeoutMs = 300) {
4261
+ return new Promise((resolve) => {
4262
+ try {
4263
+ if (!fs.statSync(socketPath).isSocket()) {
4264
+ resolve("absent");
4265
+ return;
4266
+ }
4267
+ } catch {
4268
+ resolve("absent");
4269
+ return;
4270
+ }
4271
+ let settled = false;
4272
+ const finish = (state) => {
4273
+ if (settled)
4274
+ return;
4275
+ settled = true;
4276
+ clearTimeout(timer);
4277
+ socket.destroy();
4278
+ resolve(state);
4279
+ };
4280
+ const socket = net.createConnection(socketPath);
4281
+ const timer = setTimeout(() => finish("unreachable"), timeoutMs);
4282
+ socket.on("connect", () => finish("listening"));
4283
+ socket.on("error", (error) => finish(error.code === "ECONNREFUSED" || error.code === "ENOENT" ? "stale" : "unreachable"));
4284
+ });
4285
+ }
4286
+ }
4287
+ });
4288
+
4289
+ // ../packages/tool-kit/out/liveBus.js
4290
+ var require_liveBus = __commonJS({
4291
+ "../packages/tool-kit/out/liveBus.js"(exports) {
4292
+ "use strict";
4293
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4294
+ if (k2 === void 0) k2 = k;
4295
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4296
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4297
+ desc = { enumerable: true, get: function() {
4298
+ return m[k];
4299
+ } };
4300
+ }
4301
+ Object.defineProperty(o, k2, desc);
4302
+ } : function(o, m, k, k2) {
4303
+ if (k2 === void 0) k2 = k;
4304
+ o[k2] = m[k];
4305
+ });
4306
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4307
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4308
+ } : function(o, v) {
4309
+ o["default"] = v;
4310
+ });
4311
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4312
+ var ownKeys = function(o) {
4313
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4314
+ var ar = [];
4315
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4316
+ return ar;
4317
+ };
4318
+ return ownKeys(o);
4319
+ };
4320
+ return function(mod) {
4321
+ if (mod && mod.__esModule) return mod;
4322
+ var result = {};
4323
+ if (mod != null) {
4324
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4325
+ }
4326
+ __setModuleDefault(result, mod);
4327
+ return result;
4328
+ };
4329
+ }();
4330
+ Object.defineProperty(exports, "__esModule", { value: true });
4331
+ exports.SAVER_HOST_BUNDLE_ID = exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
4332
+ exports.liveBusSocketCandidates = liveBusSocketCandidates;
4333
+ exports.existingSocketCandidates = existingSocketCandidates;
4334
+ exports.liveBusSocketPath = liveBusSocketPath;
4335
+ exports.bucketPromptSize = bucketPromptSize2;
4336
+ exports.emitLiveSignal = emitLiveSignal2;
4337
+ exports.deliverLine = deliverLine;
4338
+ var fs = __importStar(__require("fs"));
4339
+ var net = __importStar(__require("net"));
4340
+ var os2 = __importStar(__require("os"));
4341
+ var path2 = __importStar(__require("path"));
4342
+ var hookSet_1 = require_hookSet();
4343
+ var saverHandoff_1 = require_saverHandoff();
4344
+ var WRITE_TIMEOUT_MS = 50;
4345
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
4346
+ var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
4347
+ exports.SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
4348
+ function liveBusSocketCandidates() {
4349
+ const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
4350
+ if (override)
4351
+ return [override];
4352
+ const home = os2.homedir();
4353
+ return [
4354
+ path2.join(home, ".ascenda", "live.sock"),
4355
+ path2.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4356
+ path2.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4357
+ ];
4358
+ }
4359
+ function existingSocketCandidates() {
4360
+ const candidates = liveBusSocketCandidates();
4361
+ if (process.env.ASCENDA_LIVE_BUS_SOCKET)
4362
+ return candidates;
4363
+ return candidates.filter((candidate) => {
4364
+ try {
4365
+ return fs.statSync(candidate).isSocket();
4366
+ } catch {
4367
+ return false;
4368
+ }
4369
+ });
3537
4370
  }
3538
- function describeStatus(initiative) {
3539
- switch (initiative.status) {
3540
- case "published":
3541
- return "Published, not scored yet.";
3542
- case "scored":
3543
- return "Scored.";
3544
- case "withdrawn":
3545
- return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
3546
- default:
3547
- return "Status not recognised.";
3548
- }
4371
+ function liveBusSocketPath() {
4372
+ return existingSocketCandidates()[0] ?? liveBusSocketCandidates()[0];
3549
4373
  }
3550
- function renderResult(result, unit, copy) {
3551
- const lines = [];
3552
- const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
3553
- if (result.value === null) {
3554
- const why = copy.withheldReasons[result.withheldReason ?? ""];
3555
- lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
3556
- return lines;
3557
- }
3558
- lines.push(` Result: ${show(result.value)}`);
3559
- lines.push(` ${movementLine(result)}`);
3560
- lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
3561
- return lines;
4374
+ function bucketPromptSize2(text) {
4375
+ const length = typeof text === "string" ? text.length : 0;
4376
+ if (length <= 280)
4377
+ return "s";
4378
+ if (length <= 2e3)
4379
+ return "m";
4380
+ if (length <= 8e3)
4381
+ return "l";
4382
+ return "xl";
3562
4383
  }
3563
- function movementLine(result) {
3564
- if (result.outcome === "within_own_variation")
3565
- return "No material change against frozen baseline";
3566
- if (result.delta === null)
3567
- return "No reading";
3568
- if (result.delta > 0)
3569
- return `Up ${figure(result.delta)} against frozen baseline`;
3570
- if (result.delta < 0)
3571
- return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
3572
- return "No change against frozen baseline";
4384
+ var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4385
+ function onTheWire(signal) {
4386
+ const out = { ...signal };
4387
+ if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4388
+ delete out.hookSet;
4389
+ if ("viaPlugin" in out && out.viaPlugin !== true)
4390
+ delete out.viaPlugin;
4391
+ return out;
3573
4392
  }
3574
- function figure(n) {
3575
- return String(Number(n.toPrecision(12)));
4393
+ function emitLiveSignal2(signal) {
4394
+ const wire = onTheWire(signal);
4395
+ return deliverLine(`${JSON.stringify(wire)}
4396
+ `).then((delivered) => {
4397
+ if (!delivered)
4398
+ (0, saverHandoff_1.holdForSaver)(wire);
4399
+ });
3576
4400
  }
3577
- function asInitiative(value) {
3578
- if (!value || typeof value !== "object")
3579
- return void 0;
3580
- const o = value;
3581
- if (typeof o.title !== "string" || typeof o.status !== "string")
3582
- return void 0;
3583
- return {
3584
- id: typeof o.id === "string" ? o.id : "",
3585
- organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3586
- title: o.title,
3587
- summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3588
- measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3589
- scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3590
- scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3591
- withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3592
- status: o.status,
3593
- direction: typeof o.direction === "string" ? o.direction : null,
3594
- result: asResult(o.result)
3595
- };
4401
+ function deliverLine(line) {
4402
+ return new Promise((resolve) => {
4403
+ const candidates = existingSocketCandidates();
4404
+ if (candidates.length === 0) {
4405
+ resolve(void 0);
4406
+ return;
4407
+ }
4408
+ let settled = false;
4409
+ let accepted;
4410
+ let socket;
4411
+ const drop = () => {
4412
+ try {
4413
+ socket?.destroy();
4414
+ } catch {
4415
+ }
4416
+ socket = void 0;
4417
+ };
4418
+ const done = () => {
4419
+ if (settled)
4420
+ return;
4421
+ settled = true;
4422
+ clearTimeout(timer);
4423
+ drop();
4424
+ resolve(accepted);
4425
+ };
4426
+ const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4427
+ const tryFrom = (index) => {
4428
+ if (settled)
4429
+ return;
4430
+ if (index >= candidates.length) {
4431
+ done();
4432
+ return;
4433
+ }
4434
+ let attempt;
4435
+ try {
4436
+ attempt = net.createConnection(candidates[index]);
4437
+ } catch {
4438
+ tryFrom(index + 1);
4439
+ return;
4440
+ }
4441
+ socket = attempt;
4442
+ if (typeof attempt.unref === "function")
4443
+ attempt.unref();
4444
+ let connected = false;
4445
+ attempt.on("error", (error) => {
4446
+ if (settled || socket !== attempt)
4447
+ return;
4448
+ if (!connected && error.code && NOBODY_LISTENING.has(error.code)) {
4449
+ drop();
4450
+ tryFrom(index + 1);
4451
+ return;
4452
+ }
4453
+ done();
4454
+ });
4455
+ attempt.on("connect", () => {
4456
+ if (settled || socket !== attempt)
4457
+ return;
4458
+ connected = true;
4459
+ accepted = candidates[index];
4460
+ try {
4461
+ attempt.write(line, done);
4462
+ } catch {
4463
+ done();
4464
+ }
4465
+ });
4466
+ };
4467
+ tryFrom(0);
4468
+ });
3596
4469
  }
3597
- function asResult(value) {
3598
- if (!value || typeof value !== "object")
3599
- return null;
3600
- const r = value;
3601
- const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
4470
+ }
4471
+ });
4472
+
4473
+ // ../packages/tool-kit/out/terminalStyle.js
4474
+ var require_terminalStyle = __commonJS({
4475
+ "../packages/tool-kit/out/terminalStyle.js"(exports) {
4476
+ "use strict";
4477
+ Object.defineProperty(exports, "__esModule", { value: true });
4478
+ exports.colourEnabled = colourEnabled;
4479
+ exports.terminalStyle = terminalStyle;
4480
+ function colourEnabled(stream = process.stdout, env = process.env) {
4481
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "")
4482
+ return false;
4483
+ if (env.FORCE_COLOR !== void 0)
4484
+ return env.FORCE_COLOR !== "0";
4485
+ if (env.TERM === "dumb")
4486
+ return false;
4487
+ return Boolean(stream.isTTY);
4488
+ }
4489
+ function terminalStyle(enabled = colourEnabled()) {
4490
+ const wrap = (open, close) => (text) => enabled ? `\x1B[${open}m${text}\x1B[${close}m` : text;
4491
+ const bold = wrap(1, 22);
4492
+ const dim = wrap(2, 22);
4493
+ const green = wrap(32, 39);
4494
+ const yellow = wrap(33, 39);
4495
+ const red = wrap(31, 39);
4496
+ const cyan = wrap(36, 39);
4497
+ const colour = { ok: green, warn: yellow, bad: red, info: dim };
4498
+ const marks = { ok: "\u2713", warn: "!", bad: "\u2717", info: "\xB7" };
3602
4499
  return {
3603
- scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3604
- value: num(r.value),
3605
- baselineValue: num(r.baselineValue),
3606
- delta: num(r.delta),
3607
- movement: typeof r.movement === "string" ? r.movement : null,
3608
- outcome: typeof r.outcome === "string" ? r.outcome : "",
3609
- withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3610
- basis: typeof r.basis === "string" ? r.basis : null
4500
+ enabled,
4501
+ bold,
4502
+ dim,
4503
+ green,
4504
+ yellow,
4505
+ red,
4506
+ cyan,
4507
+ mark: (tone) => colour[tone](marks[tone]),
4508
+ tone: (tone, text) => colour[tone](text)
3611
4509
  };
3612
4510
  }
3613
- function formatWindowOrRaw(startUtc, endUtc) {
3614
- if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3615
- return "not given";
3616
- return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3617
- }
3618
- function formatDay(iso) {
3619
- const date = new Date(iso);
3620
- if (Number.isNaN(date.getTime()))
3621
- return iso;
3622
- return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
3623
- }
3624
4511
  }
3625
4512
  });
3626
4513
 
3627
- // ../packages/tool-kit/out/setupDisclosure.js
3628
- var require_setupDisclosure = __commonJS({
3629
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
4514
+ // ../packages/tool-kit/out/liveSignalDoctor.js
4515
+ var require_liveSignalDoctor = __commonJS({
4516
+ "../packages/tool-kit/out/liveSignalDoctor.js"(exports) {
3630
4517
  "use strict";
3631
4518
  Object.defineProperty(exports, "__esModule", { value: true });
3632
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3633
- exports.renderSetupDisclosure = renderSetupDisclosure;
3634
- exports.FAMILY_SENTENCES = {
3635
- session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
3636
- counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
3637
- tools: "the name of each tool your agent calls",
3638
- outcome: "whether a call succeeded, failed, or was interrupted",
3639
- clock: "your machine's offset from UTC, so an evening is read as an evening",
3640
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3641
- model: "which model served the session, by name and by tier",
3642
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3643
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
3644
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3645
- context: "how full the context window got",
3646
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3647
- subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
3648
- reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
3649
- };
3650
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3651
- exports.REFUSALS = [
3652
- "Never your prompts, your agent's replies, or anything inside a file.",
3653
- "Never a file path, a command line, or a repository or branch name.",
3654
- "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
3655
- ];
3656
- exports.FREE_TEXT_KEYS = ["message"];
3657
- function renderSetupDisclosure({ sends, displayName }) {
3658
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3659
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3660
- const lines = [
3661
- `What this sends from ${displayName}, once paired:`,
3662
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3663
- "",
3664
- ...exports.REFUSALS.map((line) => ` ${line}`),
3665
- "",
3666
- " Turn it off by revoking this tool in the Ascenda app."
3667
- ];
3668
- return lines.join("\n");
4519
+ exports.DOCTOR_VALUE_COLUMN = void 0;
4520
+ exports.doctorRow = doctorRow;
4521
+ exports.liveSignalDoctorLines = liveSignalDoctorLines;
4522
+ var hookRunner_1 = require_hookRunner();
4523
+ var liveBus_1 = require_liveBus();
4524
+ var saverHandoff_1 = require_saverHandoff();
4525
+ var terminalStyle_1 = require_terminalStyle();
4526
+ exports.DOCTOR_VALUE_COLUMN = 25;
4527
+ function doctorRow(ui, tone, label, value) {
4528
+ return ` ${ui.mark(tone)} ${label.padEnd(exports.DOCTOR_VALUE_COLUMN - 5)} ${value}`;
4529
+ }
4530
+ async function liveSignalDoctorLines(options) {
4531
+ const ui = options.ui ?? (0, terminalStyle_1.terminalStyle)();
4532
+ const lines = [` ${ui.bold("Live signal")} ${ui.dim("(this machine; needs no pairing)")}`];
4533
+ const now = Date.now();
4534
+ let problems = 0;
4535
+ const row = (tone, label, value) => {
4536
+ if (tone === "bad" || tone === "warn")
4537
+ problems += 1;
4538
+ lines.push(doctorRow(ui, tone, label, tone === "bad" ? ui.red(value) : value));
4539
+ };
4540
+ const more = (value) => lines.push(`${" ".repeat(exports.DOCTOR_VALUE_COLUMN)}${value}`);
4541
+ if (options.launcher && process.platform !== "win32") {
4542
+ const node = (0, hookRunner_1.resolveHookNode)(options.launcher);
4543
+ if (node.problem)
4544
+ row("bad", "Node", `${node.problem}. Install Node 20 or newer, then run setup again`);
4545
+ else
4546
+ row("ok", "Node", `${node.node} ${ui.dim(`(${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`)}`);
4547
+ }
4548
+ if (options.registrations.length === 0)
4549
+ row("bad", "Hooks", `not registered. Run: ${options.setupCommand}`);
4550
+ for (const entry of options.registrations) {
4551
+ const where = entry.homeProject ? `loads only when ${options.displayName} starts in the home folder. Run setup again to move it to every project` : entry.scope === "user" ? "every project" : "this project only";
4552
+ const complete = entry.registered === options.eventCount;
4553
+ row(entry.homeProject || !complete ? "warn" : entry.scope === "user" ? "ok" : "info", "Hooks", `${entry.registered}/${options.eventCount} in ${entry.file} ${ui.dim(`(${where})`)}`);
4554
+ }
4555
+ if (options.registrations.length > 1) {
4556
+ problems += 1;
4557
+ more(ui.yellow("Registered in more than one file, so each event runs more than once. Run setup again to fix."));
4558
+ }
4559
+ const last = (0, hookRunner_1.readLastHook)(options.tool);
4560
+ if (last)
4561
+ row("ok", "Last hook", `${last.event}, ${(0, hookRunner_1.describeAge)(now - Date.parse(last.at))}`);
4562
+ else
4563
+ row("info", "Last hook", `none yet. Start ${options.displayName} (restart it if it was open during setup)${options.lookHint ? `, then ${options.lookHint}` : ""}`);
4564
+ const [appSocket, appContainerSocket, saverSocket] = (0, liveBus_1.liveBusSocketCandidates)();
4565
+ const appState = await (0, saverHandoff_1.probeSocket)(appSocket);
4566
+ const legacyState = appContainerSocket ? await (0, saverHandoff_1.probeSocket)(appContainerSocket) : "absent";
4567
+ if (appState === "listening" || legacyState === "listening")
4568
+ row("ok", "Desktop app", "listening. It takes every signal, and the saver mirrors it");
4569
+ else
4570
+ row("info", "Desktop app", "not listening");
4571
+ const saverState = saverSocket ? await (0, saverHandoff_1.probeSocket)(saverSocket) : "absent";
4572
+ const live = (0, saverHandoff_1.readSaverStatuses)(now).filter((status) => status.alive);
4573
+ const holder = live.find((status) => status.ownsBus);
4574
+ const saver = describeSaver(saverState, holder, live);
4575
+ row(saver.tone, "Screen saver", saver.text);
4576
+ for (const status of live)
4577
+ more(ui.dim(describeProcess(status, now)));
4578
+ const held = (0, saverHandoff_1.heldForSaver)(now);
4579
+ if (held.count > 0) {
4580
+ row("info", "Held for the saver", `${held.count} session${held.count === 1 ? "" : "s"}, newest ${(0, hookRunner_1.describeAge)(held.newestAgeMs ?? 0)}. Replayed when the saver starts`);
4581
+ }
4582
+ const trip = await pingRoundTrip(saverSocket, options.selfCommand);
4583
+ row(trip.tone, "Round trip", trip.text);
4584
+ lines.push("");
4585
+ lines.push(problems === 0 ? ` ${ui.mark("ok")} ${ui.bold("Ready.")} The hooks can run, and the screen saver hears them while it's on screen.` : ` ${ui.mark("bad")} ${ui.bold(`${problems} problem${problems === 1 ? "" : "s"} above.`)} Each line says how to fix it.`);
4586
+ return lines;
4587
+ }
4588
+ function describeSaver(state, holder, live) {
4589
+ if (state === "listening") {
4590
+ if (!holder)
4591
+ return { tone: "warn", text: "listening, from a process that isn't reporting. Restart it: killall legacyScreenSaver" };
4592
+ if (holder.saverViews === 0) {
4593
+ return { tone: "bad", text: `pid ${holder.pid} holds the socket but isn't drawing the saver, so signals go nowhere you can see. Fix: killall legacyScreenSaver` };
4594
+ }
4595
+ return { tone: "ok", text: `listening, pid ${holder.pid}, on screen` };
4596
+ }
4597
+ if (state === "stale")
4598
+ return { tone: "info", text: "not running (a socket file was left behind, which is harmless)" };
4599
+ if (live.some((status) => status.previewViews > 0)) {
4600
+ return { tone: "info", text: "not running. The System Settings preview never listens, so it stays still; the water goes live once the saver itself runs" };
4601
+ }
4602
+ return { tone: "info", text: "not running. That's normal: it listens only while it's on screen" };
4603
+ }
4604
+ function describeProcess(status, now) {
4605
+ const what = [
4606
+ status.saverViews > 0 ? `saver on ${status.saverViews} display${status.saverViews === 1 ? "" : "s"}` : void 0,
4607
+ status.previewViews > 0 ? "preview" : void 0
4608
+ ].filter(Boolean).join(" + ") || "not drawing";
4609
+ const heard = status.lastSignalAt ? `last signal ${status.lastSignalEvent ?? ""} ${(0, hookRunner_1.describeAge)(now - Date.parse(status.lastSignalAt))}`.replace(/\s+/g, " ") : "no signal yet";
4610
+ const replay = status.replayed > 0 ? `, replayed ${status.replayed} since this process started` : "";
4611
+ const beat = status.ageMs > 1e4 ? `, heartbeat ${(0, hookRunner_1.describeAge)(status.ageMs)} (not animating)` : "";
4612
+ return `pid ${status.pid} ${status.version ?? ""}: ${what}, ${status.mode ?? "?"}${status.ownsBus ? ", owns the socket" : ""}, ${heard}${replay}${beat}`.replace(/\s+:/, ":");
4613
+ }
4614
+ async function pingRoundTrip(saverSocket, selfCommand) {
4615
+ const session = `doctor-${process.pid}-${Date.now()}`;
4616
+ const accepted = await (0, liveBus_1.deliverLine)(`${JSON.stringify({ tool: "doctor", session, event: "ping" })}
4617
+ `);
4618
+ if (!accepted) {
4619
+ return { tone: "info", text: `nobody is listening right now, so there is nothing to test. To test the saver: open -a ScreenSaverEngine; sleep 5; ${selfCommand} doctor` };
4620
+ }
4621
+ if (accepted !== saverSocket)
4622
+ return { tone: "ok", text: `the desktop app took it (${accepted})` };
4623
+ for (let waited = 0; waited < 2e3; waited += 100) {
4624
+ await new Promise((resolve) => setTimeout(resolve, 100));
4625
+ const answered = (0, saverHandoff_1.readSaverStatuses)().find((status) => status.lastPingSession === session);
4626
+ if (answered)
4627
+ return { tone: "ok", text: `OK. The screen saver (pid ${answered.pid}) received it` };
4628
+ }
4629
+ return { tone: "bad", text: "the saver's socket took the ping but no saver reported it. It may be a version from before 0.8.1, or stuck. Fix: killall legacyScreenSaver" };
3669
4630
  }
3670
4631
  }
3671
4632
  });
@@ -3919,37 +4880,47 @@ var require_cliAgentSetup = __commonJS({
3919
4880
  Object.defineProperty(exports, "__esModule", { value: true });
3920
4881
  exports.isCliAgentManagementCommand = isCliAgentManagementCommand2;
3921
4882
  exports.cliAgentHookBinPath = cliAgentHookBinPath;
4883
+ exports.cliAgentSelfCommand = cliAgentSelfCommand;
3922
4884
  exports.runCliAgentSetup = runCliAgentSetup2;
3923
4885
  exports.writeHookSettings = writeHookSettings;
3924
4886
  exports.registeredHookSets = registeredHookSets;
3925
4887
  exports.findStaleHookCommands = findStaleHookCommands;
4888
+ exports.cliAgentRegistrations = cliAgentRegistrations;
3926
4889
  var crypto = __importStar(__require("crypto"));
3927
4890
  var fs = __importStar(__require("fs"));
3928
4891
  var os2 = __importStar(__require("os"));
3929
4892
  var path2 = __importStar(__require("path"));
3930
4893
  var collectorVersion_1 = require_collectorVersion();
3931
4894
  var credentials_1 = require_credentials();
4895
+ var eventLog_1 = require_eventLog();
3932
4896
  var hookAdapter_1 = require_hookAdapter();
3933
4897
  var http_1 = require_http();
3934
4898
  var hookSet_1 = require_hookSet();
3935
4899
  var initiatives_1 = require_initiatives();
3936
4900
  var setupDisclosure_1 = require_setupDisclosure();
4901
+ var hookRunner_1 = require_hookRunner();
4902
+ var liveSignalDoctor_1 = require_liveSignalDoctor();
3937
4903
  var stateStore_1 = require_stateStore();
3938
4904
  var studyJoin_1 = require_studyJoin();
3939
4905
  var studyNotices_1 = require_studyNotices();
4906
+ var terminalStyle_1 = require_terminalStyle();
3940
4907
  var tokenStore_1 = require_tokenStore();
3941
- var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "join", "object", "-h", "--help"]);
4908
+ var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "doctor", "join", "object", "-h", "--help"]);
3942
4909
  function isCliAgentManagementCommand2(argument) {
3943
4910
  return argument !== void 0 && MANAGEMENT_COMMANDS.has(argument);
3944
4911
  }
3945
4912
  function cliAgentHookBinPath(binaryName) {
3946
- return path2.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
4913
+ return (0, hookRunner_1.hookRunnerPaths)(binaryName).launcher;
4914
+ }
4915
+ function cliAgentSelfCommand(spec) {
4916
+ return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName), os2.homedir());
3947
4917
  }
3948
4918
  function usage(spec) {
3949
4919
  return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
3950
4920
 
3951
4921
  npx ${spec.packageName} setup [options]
3952
4922
  npx ${spec.packageName} status
4923
+ npx ${spec.packageName} doctor
3953
4924
  npx ${spec.packageName} uninstall
3954
4925
  npx ${spec.packageName} join <code>
3955
4926
  npx ${spec.packageName} object <purpose> [--undo]
@@ -3960,7 +4931,9 @@ Options
3960
4931
  --tool-installation-id <id> reuse an existing pairing instead of creating one
3961
4932
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
3962
4933
  --no-pair install without pairing: local features on, nothing sent
3963
- --scope project|user where hooks are registered (default project)
4934
+ --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
4935
+ On by default when not paired; machine-wide, shared by every agent
4936
+ --scope user|project where hooks are registered (default user: every project)
3964
4937
  --project-dir <path> project root for --scope project (default cwd)
3965
4938
  --dry-run print what would change, write nothing
3966
4939
  -h, --help
@@ -3986,29 +4959,26 @@ Options
3986
4959
  return await printStatus(options, spec);
3987
4960
  if (options.action === "uninstall")
3988
4961
  return uninstall(options, spec);
4962
+ if (options.action === "doctor")
4963
+ return await runDoctor(options, spec);
3989
4964
  const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3990
- console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
3991
- console.log(`
3992
- ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}
3993
- `);
4965
+ const ui = (0, terminalStyle_1.terminalStyle)();
4966
+ const row = (tone, label, value) => console.log(` ${ui.mark(tone)} ${label.padEnd(12)} ${value}`);
4967
+ const detail = (label, value) => console.log(ui.dim(` ${label.padEnd(12)} ${value}`));
4968
+ console.log(`${ui.bold("Ascenda setup")} ${ui.dim(`\xB7 ${spec.displayName} \xB7 ${apiBaseUrl}`)}`);
4969
+ if (!options.skipPairing)
4970
+ console.log(`
4971
+ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}`);
4972
+ console.log("");
3994
4973
  let identity;
3995
- let unpairedReason;
3996
- if (options.skipPairing) {
3997
- unpairedReason = "asked not to pair (--no-pair)";
3998
- } else {
4974
+ if (!options.skipPairing)
3999
4975
  identity = await resolveIdentity(apiBaseUrl, options, spec);
4000
- if (identity) {
4001
- console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
4002
- } else {
4003
- unpairedReason = "pairing did not finish \u2014 installing the local half anyway";
4004
- }
4005
- }
4006
- if (unpairedReason) {
4007
- console.log(` pairing none: ${unpairedReason}`);
4008
- console.log(" local features on, nothing is sent");
4009
- }
4010
4976
  const binary = installBinary(spec, options.dryRun);
4011
- console.log(` hook binary ${binary}`);
4977
+ const node = options.dryRun || process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
4978
+ if (node?.problem)
4979
+ row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os2.homedir())}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
4980
+ else
4981
+ row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os2.homedir())}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
4012
4982
  if (!options.dryRun) {
4013
4983
  const now = (/* @__PURE__ */ new Date()).toISOString();
4014
4984
  const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto.randomUUID()}`;
@@ -4017,32 +4987,86 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4017
4987
  toolInstallationId,
4018
4988
  ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4019
4989
  });
4990
+ if (options.eventLog !== void 0)
4991
+ (0, credentials_1.writeEventLogSetting)(options.eventLog);
4992
+ }
4993
+ if (isHomeProject(options)) {
4994
+ detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
4995
+ options.scope = "user";
4020
4996
  }
4021
- console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
4022
4997
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4023
4998
  const before = registeredHookSets(readSettings(settingsFile), spec);
4024
4999
  const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
4025
5000
  if (written === null)
4026
5001
  return 1;
4027
- console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
5002
+ const reach = options.scope === "user" ? "every project" : "this project only";
5003
+ row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile, os2.homedir())} ${ui.dim(`(${spec.hookEvents.length} events, ${reach}${written ? "" : ", already current"})`)}`);
4028
5004
  const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
4029
5005
  if (changes)
4030
- console.log(` ${changes}`);
5006
+ detail("", changes);
5007
+ const otherFile = spec.settings.settingsPath(options.scope === "user" ? "project" : "user", options.projectDir);
5008
+ if (otherFile !== settingsFile && registeredHookSets(readSettings(otherFile), spec).size > 0) {
5009
+ if (options.dryRun) {
5010
+ row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os2.homedir())}, so each event runs once`);
5011
+ } else if (removeOurHookEntries(otherFile, spec)) {
5012
+ row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os2.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
5013
+ } else {
5014
+ row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os2.homedir())} registers these hooks too, so each event runs twice.`);
5015
+ detail("", `Remove the ${spec.binaryName} entries from one of the two files.`);
5016
+ }
5017
+ }
5018
+ const chosenLocal = options.skipPairing;
5019
+ if (identity)
5020
+ row("ok", "pairing", `${identity.toolInstallationId}${ui.dim(identity.paired ? " (new)" : " (existing)")}`);
5021
+ else if (chosenLocal)
5022
+ row("info", "pairing", `none, as asked ${ui.dim("(--no-pair)")}`);
5023
+ else
5024
+ row("warn", "pairing", "not paired: pairing did not finish");
5025
+ detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os2.homedir())} (tools.${spec.host})`);
5026
+ const eventLog = (0, eventLog_1.resolveEventLog)({ localOnly: !identity });
5027
+ if (eventLog.path)
5028
+ row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path, os2.homedir())} ${ui.dim("(on this machine only)")}`);
5029
+ else if (options.eventLog !== void 0)
5030
+ row("info", "events", "off");
4031
5031
  if (options.dryRun) {
4032
- console.log("\nDry run \u2014 nothing was written.");
5032
+ console.log("\nDry run. Nothing was written.");
4033
5033
  return 0;
4034
5034
  }
4035
- console.log(`
4036
- Done. ${spec.restartHint}`);
4037
- if (!identity) {
4038
- console.log(`Pair later: npx ${spec.packageName} setup`);
5035
+ const self = cliAgentSelfCommand(spec);
5036
+ const next = (label, value) => console.log(` ${ui.bold(label.padEnd(6))} ${value}`);
5037
+ console.log("");
5038
+ if (chosenLocal) {
5039
+ console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
5040
+ console.log(" They run on this machine and need no account or pairing.");
5041
+ if (eventLog.path)
5042
+ console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os2.homedir())}, for you or any tool to read.`);
5043
+ } else if (!identity) {
5044
+ console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
5045
+ console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
5046
+ } else {
5047
+ console.log(`${ui.mark("ok")} ${ui.bold("Done.")} Paired, and the hooks are installed.`);
5048
+ }
5049
+ console.log("");
5050
+ next("Next", spec.restartHint);
5051
+ next("Check", ui.cyan(`${self} doctor`));
5052
+ if (!identity)
5053
+ next(chosenLocal ? "Pair" : "Retry", `${ui.cyan(`${self} setup`)}${chosenLocal ? ui.dim(" (optional)") : ""}`);
5054
+ if (chosenLocal) {
5055
+ console.log("");
5056
+ console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account the"));
5057
+ console.log(ui.dim(" Ascenda app is signed in to when you confirm the code, so your sessions appear"));
5058
+ console.log(ui.dim(" in the app. Until you pair, nothing leaves this machine."));
5059
+ console.log("");
5060
+ console.log(ui.dim((0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName }).split("\n").map((line) => ` ${line}`).join("\n")));
4039
5061
  }
4040
- console.log(`Check anytime: npx ${spec.packageName} status`);
4041
5062
  return 0;
4042
5063
  }
5064
+ function isHomeProject(options) {
5065
+ return options.scope === "project" && path2.resolve(options.projectDir) === path2.resolve(os2.homedir());
5066
+ }
4043
5067
  function parseArgs(argv, spec) {
4044
5068
  const options = {
4045
- scope: "project",
5069
+ scope: "user",
4046
5070
  projectDir: process.cwd(),
4047
5071
  dryRun: false,
4048
5072
  skipPairing: false,
@@ -4067,6 +5091,9 @@ Done. ${spec.restartHint}`);
4067
5091
  case "uninstall":
4068
5092
  options.action = "uninstall";
4069
5093
  break;
5094
+ case "doctor":
5095
+ options.action = "doctor";
5096
+ break;
4070
5097
  case "--api-base-url":
4071
5098
  options.apiBaseUrl = next();
4072
5099
  break;
@@ -4095,6 +5122,12 @@ Done. ${spec.restartHint}`);
4095
5122
  case "--dry-run":
4096
5123
  options.dryRun = true;
4097
5124
  break;
5125
+ case "--event-log": {
5126
+ const { value, consumed } = (0, eventLog_1.parseEventLogFlag)(argv, i);
5127
+ options.eventLog = value;
5128
+ i += consumed;
5129
+ break;
5130
+ }
4098
5131
  case "--no-pair":
4099
5132
  // `--no-pairing` is the spelling this landed under first. Both appeared
4100
5133
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -4224,17 +5257,7 @@ Pairing ${status.status}. Run setup again.`);
4224
5257
  return void 0;
4225
5258
  }
4226
5259
  function installBinary(spec, dryRun) {
4227
- const target = cliAgentHookBinPath(spec.binaryName);
4228
- if (dryRun)
4229
- return target;
4230
- const source = process.argv[1];
4231
- fs.mkdirSync(path2.dirname(target), { recursive: true });
4232
- if (path2.resolve(source) !== path2.resolve(target)) {
4233
- fs.copyFileSync(source, target);
4234
- }
4235
- if (process.platform !== "win32")
4236
- fs.chmodSync(target, 493);
4237
- return target;
5260
+ return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
4238
5261
  }
4239
5262
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
4240
5263
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -4275,7 +5298,7 @@ ${serialised}`);
4275
5298
  return true;
4276
5299
  }
4277
5300
  function hookCommand(binary, spec) {
4278
- return `"${process.execPath}" "${binary}"${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
5301
+ return `${(0, hookRunner_1.hookRunnerCommand)(binary)}${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
4279
5302
  }
4280
5303
  function registeredHookSets(settings, spec) {
4281
5304
  const sets = /* @__PURE__ */ new Map();
@@ -4327,8 +5350,20 @@ ${serialised}`);
4327
5350
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
4328
5351
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
4329
5352
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
5353
+ console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
4330
5354
  console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
5355
+ const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5356
+ if (node) {
5357
+ console.log(node.problem ? `node \u2014 ${node.problem}. Install Node 20 or newer, then run setup again` : `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
5358
+ }
5359
+ const last = (0, hookRunner_1.readLastHook)(spec.host);
5360
+ console.log(last ? `last hook ${last.event}, ${(0, hookRunner_1.describeAge)(Date.now() - Date.parse(last.at))}` : `last hook \u2014 none has run yet. Start ${spec.displayName} (restart it if it was open during setup)`);
4331
5361
  console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
5362
+ const otherScope = options.scope === "user" ? "project" : "user";
5363
+ const otherFile = spec.settings.settingsPath(otherScope, options.projectDir);
5364
+ const elsewhere = registered === 0 && otherFile !== settingsFile ? countRegistered(readSettings(otherFile), spec) : 0;
5365
+ if (elsewhere > 0)
5366
+ console.log(` ${elsewhere}/${spec.hookEvents.length} found in ${otherFile} (--scope ${otherScope})`);
4332
5367
  if (spec.hookSet !== void 0 && registered > 0) {
4333
5368
  const sets = [...registeredHookSets(settings, spec).values()];
4334
5369
  const oldest = Math.min(...sets);
@@ -4354,38 +5389,118 @@ ${serialised}`);
4354
5389
  if (process.stdout.isTTY)
4355
5390
  await notices.markShown();
4356
5391
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
4357
- const healthy = paired && registered === spec.hookEvents.length && fs.existsSync(binary) && !stale.length;
5392
+ const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5393
+ const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
4358
5394
  return healthy ? 0 : 1;
4359
5395
  }
5396
+ function countRegistered(settings, spec) {
5397
+ return spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs(entry, spec))).length;
5398
+ }
5399
+ function cliAgentRegistrations(spec, projectDir = process.cwd()) {
5400
+ const home = os2.homedir();
5401
+ const userFile = spec.settings.settingsPath("user", projectDir);
5402
+ const projectFile = spec.settings.settingsPath("project", projectDir);
5403
+ const found = [];
5404
+ for (const [scope, file] of [["user", userFile], ["project", projectFile]]) {
5405
+ if (scope === "project" && file === userFile)
5406
+ continue;
5407
+ const registered = countRegistered(readSettings(file), spec);
5408
+ if (registered === 0)
5409
+ continue;
5410
+ found.push({
5411
+ file: (0, hookRunner_1.tidyHomePath)(file, home),
5412
+ registered,
5413
+ scope,
5414
+ homeProject: scope === "project" && path2.resolve(projectDir) === path2.resolve(home)
5415
+ });
5416
+ }
5417
+ return found;
5418
+ }
5419
+ async function runDoctor(options, spec) {
5420
+ const ui = (0, terminalStyle_1.terminalStyle)();
5421
+ const lines = [`${ui.bold("Ascenda doctor")} ${ui.dim(`\xB7 ${spec.displayName}`)}`, ""];
5422
+ try {
5423
+ lines.push(...await (0, liveSignalDoctor_1.liveSignalDoctorLines)({
5424
+ displayName: spec.displayName,
5425
+ tool: spec.host,
5426
+ launcher: process.platform === "win32" ? void 0 : cliAgentHookBinPath(spec.binaryName),
5427
+ registrations: cliAgentRegistrations(spec, options.projectDir),
5428
+ eventCount: spec.hookEvents.length,
5429
+ selfCommand: cliAgentSelfCommand(spec),
5430
+ setupCommand: `npx ${spec.packageName} setup`,
5431
+ ui
5432
+ }));
5433
+ } catch (error) {
5434
+ lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
5435
+ }
5436
+ lines.push("", ...accountLines(ui, spec));
5437
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
5438
+ lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5439
+ console.log(lines.join("\n"));
5440
+ return 0;
5441
+ }
5442
+ function accountLines(ui, spec) {
5443
+ const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5444
+ const id = credentials?.toolInstallationId;
5445
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (installationId) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(installationId)) !== void 0);
5446
+ const row = (tone, label, value) => ` ${ui.mark(tone)} ${label.padEnd(20)} ${value}`;
5447
+ if (!id || localOnly) {
5448
+ return [
5449
+ ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}`,
5450
+ ...id ? [ui.dim(row("info", "Installation id", id))] : [],
5451
+ "",
5452
+ " Not paired, which is fine: the screen saver, the live view and the local",
5453
+ " event log work without it. Nothing leaves this machine and nothing is queued.",
5454
+ " To send your sessions to Ascenda's servers, so they appear in the app:",
5455
+ ` ${ui.cyan(`${cliAgentSelfCommand(spec)} setup`)}`
5456
+ ];
5457
+ }
5458
+ const token = (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim();
5459
+ const state = (0, stateStore_1.readCollectorState)((0, stateStore_1.defaultStateFilePath)(id));
5460
+ const outcome = state?.lastOutcome;
5461
+ return [
5462
+ ` ${ui.bold("Account sync")}`,
5463
+ row("info", "Installation id", id),
5464
+ token ? row("ok", "Token", "present") : row("bad", "Token", ui.red(`missing, so nothing can be sent. Run: npx ${spec.packageName} setup`)),
5465
+ outcome ? row(outcome === "accepted" ? "ok" : "warn", "Last send", `${outcome}${state?.lastAttemptAt ? ui.dim(` (${state.lastAttemptAt})`) : ""}`) : row("info", "Last send", "none yet")
5466
+ ];
5467
+ }
5468
+ function removeOurHookEntries(settingsFile, spec) {
5469
+ if (!fs.existsSync(settingsFile))
5470
+ return true;
5471
+ try {
5472
+ const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
5473
+ const hooks = { ...settings.hooks ?? {} };
5474
+ for (const event of Object.keys(hooks)) {
5475
+ const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
5476
+ if (kept.length)
5477
+ hooks[event] = kept;
5478
+ else
5479
+ delete hooks[event];
5480
+ }
5481
+ const updated = { ...settings, hooks };
5482
+ if (!Object.keys(hooks).length)
5483
+ delete updated.hooks;
5484
+ fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5485
+ fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5486
+ `, "utf8");
5487
+ return true;
5488
+ } catch {
5489
+ return false;
5490
+ }
5491
+ }
4360
5492
  function uninstall(options, spec) {
4361
5493
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4362
5494
  if (fs.existsSync(settingsFile)) {
4363
- try {
4364
- const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
4365
- const hooks = { ...settings.hooks ?? {} };
4366
- for (const event of Object.keys(hooks)) {
4367
- const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
4368
- if (kept.length)
4369
- hooks[event] = kept;
4370
- else
4371
- delete hooks[event];
4372
- }
4373
- const updated = { ...settings, hooks };
4374
- if (!Object.keys(hooks).length)
4375
- delete updated.hooks;
4376
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4377
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4378
- `, "utf8");
4379
- console.log(`hooks removed from ${settingsFile}`);
4380
- } catch {
5495
+ if (!removeOurHookEntries(settingsFile, spec)) {
4381
5496
  console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
4382
5497
  return 1;
4383
5498
  }
5499
+ console.log(`hooks removed from ${settingsFile}`);
4384
5500
  }
4385
- const binary = cliAgentHookBinPath(spec.binaryName);
4386
- if (fs.existsSync(binary)) {
4387
- fs.rmSync(binary);
4388
- console.log(`removed ${binary}`);
5501
+ for (const file of (0, hookRunner_1.removeHookRunner)(spec.binaryName)) {
5502
+ if (!file.endsWith(".node") && !file.endsWith(".no-node"))
5503
+ console.log(`removed ${file}`);
4389
5504
  }
4390
5505
  if ((0, credentials_1.readHostCredentials)(spec.host)) {
4391
5506
  (0, credentials_1.removeHostCredentials)(spec.host);
@@ -4477,180 +5592,6 @@ var require_turnState = __commonJS({
4477
5592
  }
4478
5593
  });
4479
5594
 
4480
- // ../packages/tool-kit/out/liveBus.js
4481
- var require_liveBus = __commonJS({
4482
- "../packages/tool-kit/out/liveBus.js"(exports) {
4483
- "use strict";
4484
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4485
- if (k2 === void 0) k2 = k;
4486
- var desc = Object.getOwnPropertyDescriptor(m, k);
4487
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4488
- desc = { enumerable: true, get: function() {
4489
- return m[k];
4490
- } };
4491
- }
4492
- Object.defineProperty(o, k2, desc);
4493
- } : function(o, m, k, k2) {
4494
- if (k2 === void 0) k2 = k;
4495
- o[k2] = m[k];
4496
- });
4497
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4498
- Object.defineProperty(o, "default", { enumerable: true, value: v });
4499
- } : function(o, v) {
4500
- o["default"] = v;
4501
- });
4502
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4503
- var ownKeys = function(o) {
4504
- ownKeys = Object.getOwnPropertyNames || function(o2) {
4505
- var ar = [];
4506
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4507
- return ar;
4508
- };
4509
- return ownKeys(o);
4510
- };
4511
- return function(mod) {
4512
- if (mod && mod.__esModule) return mod;
4513
- var result = {};
4514
- if (mod != null) {
4515
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4516
- }
4517
- __setModuleDefault(result, mod);
4518
- return result;
4519
- };
4520
- }();
4521
- Object.defineProperty(exports, "__esModule", { value: true });
4522
- exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
4523
- exports.liveBusSocketCandidates = liveBusSocketCandidates;
4524
- exports.liveBusSocketPath = liveBusSocketPath;
4525
- exports.bucketPromptSize = bucketPromptSize2;
4526
- exports.emitLiveSignal = emitLiveSignal2;
4527
- var fs = __importStar(__require("fs"));
4528
- var net = __importStar(__require("net"));
4529
- var os2 = __importStar(__require("os"));
4530
- var path2 = __importStar(__require("path"));
4531
- var hookSet_1 = require_hookSet();
4532
- var WRITE_TIMEOUT_MS = 50;
4533
- exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
4534
- var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
4535
- var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
4536
- function liveBusSocketCandidates() {
4537
- const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
4538
- if (override)
4539
- return [override];
4540
- const home = os2.homedir();
4541
- return [
4542
- path2.join(home, ".ascenda", "live.sock"),
4543
- path2.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4544
- path2.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4545
- ];
4546
- }
4547
- function existingSocketCandidates() {
4548
- const candidates = liveBusSocketCandidates();
4549
- if (process.env.ASCENDA_LIVE_BUS_SOCKET)
4550
- return candidates;
4551
- return candidates.filter((candidate) => {
4552
- try {
4553
- return fs.statSync(candidate).isSocket();
4554
- } catch {
4555
- return false;
4556
- }
4557
- });
4558
- }
4559
- function liveBusSocketPath() {
4560
- return existingSocketCandidates()[0] ?? liveBusSocketCandidates()[0];
4561
- }
4562
- function bucketPromptSize2(text) {
4563
- const length = typeof text === "string" ? text.length : 0;
4564
- if (length <= 280)
4565
- return "s";
4566
- if (length <= 2e3)
4567
- return "m";
4568
- if (length <= 8e3)
4569
- return "l";
4570
- return "xl";
4571
- }
4572
- var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4573
- function onTheWire(signal) {
4574
- const out = { ...signal };
4575
- if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4576
- delete out.hookSet;
4577
- if ("viaPlugin" in out && out.viaPlugin !== true)
4578
- delete out.viaPlugin;
4579
- return out;
4580
- }
4581
- function emitLiveSignal2(signal) {
4582
- return new Promise((resolve) => {
4583
- const candidates = existingSocketCandidates();
4584
- if (candidates.length === 0) {
4585
- resolve();
4586
- return;
4587
- }
4588
- let settled = false;
4589
- let socket;
4590
- const drop = () => {
4591
- try {
4592
- socket?.destroy();
4593
- } catch {
4594
- }
4595
- socket = void 0;
4596
- };
4597
- const done = () => {
4598
- if (settled)
4599
- return;
4600
- settled = true;
4601
- clearTimeout(timer);
4602
- drop();
4603
- resolve();
4604
- };
4605
- const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4606
- if (typeof timer.unref === "function")
4607
- timer.unref();
4608
- const tryFrom = (index) => {
4609
- if (settled)
4610
- return;
4611
- if (index >= candidates.length) {
4612
- done();
4613
- return;
4614
- }
4615
- let attempt;
4616
- try {
4617
- attempt = net.createConnection(candidates[index]);
4618
- } catch {
4619
- tryFrom(index + 1);
4620
- return;
4621
- }
4622
- socket = attempt;
4623
- if (typeof attempt.unref === "function")
4624
- attempt.unref();
4625
- let connected = false;
4626
- attempt.on("error", (error) => {
4627
- if (settled || socket !== attempt)
4628
- return;
4629
- if (!connected && error.code && NOBODY_LISTENING.has(error.code)) {
4630
- drop();
4631
- tryFrom(index + 1);
4632
- return;
4633
- }
4634
- done();
4635
- });
4636
- attempt.on("connect", () => {
4637
- if (settled || socket !== attempt)
4638
- return;
4639
- connected = true;
4640
- try {
4641
- attempt.write(`${JSON.stringify(onTheWire(signal))}
4642
- `, done);
4643
- } catch {
4644
- done();
4645
- }
4646
- });
4647
- };
4648
- tryFrom(0);
4649
- });
4650
- }
4651
- }
4652
- });
4653
-
4654
5595
  // ../packages/tool-kit/out/agentProcess.js
4655
5596
  var require_agentProcess = __commonJS({
4656
5597
  "../packages/tool-kit/out/agentProcess.js"(exports) {
@@ -4791,13 +5732,14 @@ var require_agentProcess = __commonJS({
4791
5732
  });
4792
5733
 
4793
5734
  // ../packages/tool-kit/out/index.js
4794
- var require_out2 = __commonJS({
5735
+ var require_out3 = __commonJS({
4795
5736
  "../packages/tool-kit/out/index.js"(exports) {
4796
5737
  "use strict";
4797
5738
  Object.defineProperty(exports, "__esModule", { value: true });
4798
- 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;
4799
- 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;
4800
- 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;
5739
+ 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;
5740
+ 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;
5741
+ 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;
5742
+ 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;
4801
5743
  var commandClassifier_1 = require_commandClassifier();
4802
5744
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
4803
5745
  return commandClassifier_1.classifyCommand;
@@ -4898,19 +5840,41 @@ var require_out2 = __commonJS({
4898
5840
  Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
4899
5841
  return eventSender_1.TOKEN_RENEW_LEAD_MS;
4900
5842
  } });
5843
+ Object.defineProperty(exports, "buildEventBody", { enumerable: true, get: function() {
5844
+ return eventSender_1.buildEventBody;
5845
+ } });
4901
5846
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
4902
5847
  return eventSender_1.buildEventPayload;
4903
5848
  } });
5849
+ var agentEvent_1 = require_agentEvent();
5850
+ Object.defineProperty(exports, "toAgentEvent", { enumerable: true, get: function() {
5851
+ return agentEvent_1.toAgentEvent;
5852
+ } });
4904
5853
  var eventLog_1 = require_eventLog();
4905
5854
  Object.defineProperty(exports, "EVENT_LOG_ENV_VAR", { enumerable: true, get: function() {
4906
5855
  return eventLog_1.EVENT_LOG_ENV_VAR;
4907
5856
  } });
5857
+ Object.defineProperty(exports, "EVENT_LOG_OFF", { enumerable: true, get: function() {
5858
+ return eventLog_1.EVENT_LOG_OFF;
5859
+ } });
4908
5860
  Object.defineProperty(exports, "appendEventLog", { enumerable: true, get: function() {
4909
5861
  return eventLog_1.appendEventLog;
4910
5862
  } });
5863
+ Object.defineProperty(exports, "defaultEventLogPath", { enumerable: true, get: function() {
5864
+ return eventLog_1.defaultEventLogPath;
5865
+ } });
5866
+ Object.defineProperty(exports, "describeEventLog", { enumerable: true, get: function() {
5867
+ return eventLog_1.describeEventLog;
5868
+ } });
4911
5869
  Object.defineProperty(exports, "expandUserPath", { enumerable: true, get: function() {
4912
5870
  return eventLog_1.expandUserPath;
4913
5871
  } });
5872
+ Object.defineProperty(exports, "parseEventLogFlag", { enumerable: true, get: function() {
5873
+ return eventLog_1.parseEventLogFlag;
5874
+ } });
5875
+ Object.defineProperty(exports, "resolveEventLog", { enumerable: true, get: function() {
5876
+ return eventLog_1.resolveEventLog;
5877
+ } });
4914
5878
  Object.defineProperty(exports, "resolveEventLogPath", { enumerable: true, get: function() {
4915
5879
  return eventLog_1.resolveEventLogPath;
4916
5880
  } });
@@ -4987,6 +5951,9 @@ var require_out2 = __commonJS({
4987
5951
  Object.defineProperty(exports, "writeHostCredentials", { enumerable: true, get: function() {
4988
5952
  return credentials_1.writeHostCredentials;
4989
5953
  } });
5954
+ Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
5955
+ return credentials_1.writeEventLogSetting;
5956
+ } });
4990
5957
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
4991
5958
  return credentials_1.writeMachineCredentials;
4992
5959
  } });
@@ -5147,6 +6114,9 @@ var require_out2 = __commonJS({
5147
6114
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
5148
6115
  return liveBus_1.emitLiveSignal;
5149
6116
  } });
6117
+ Object.defineProperty(exports, "deliverLine", { enumerable: true, get: function() {
6118
+ return liveBus_1.deliverLine;
6119
+ } });
5150
6120
  Object.defineProperty(exports, "bucketPromptSize", { enumerable: true, get: function() {
5151
6121
  return liveBus_1.bucketPromptSize;
5152
6122
  } });
@@ -5159,6 +6129,85 @@ var require_out2 = __commonJS({
5159
6129
  Object.defineProperty(exports, "LIVE_BUS_BACKGROUND_TRUST_MS", { enumerable: true, get: function() {
5160
6130
  return liveBus_1.LIVE_BUS_BACKGROUND_TRUST_MS;
5161
6131
  } });
6132
+ var saverHandoff_1 = require_saverHandoff();
6133
+ Object.defineProperty(exports, "holdForSaver", { enumerable: true, get: function() {
6134
+ return saverHandoff_1.holdForSaver;
6135
+ } });
6136
+ Object.defineProperty(exports, "heldForSaver", { enumerable: true, get: function() {
6137
+ return saverHandoff_1.heldForSaver;
6138
+ } });
6139
+ Object.defineProperty(exports, "probeSocket", { enumerable: true, get: function() {
6140
+ return saverHandoff_1.probeSocket;
6141
+ } });
6142
+ Object.defineProperty(exports, "readSaverStatuses", { enumerable: true, get: function() {
6143
+ return saverHandoff_1.readSaverStatuses;
6144
+ } });
6145
+ Object.defineProperty(exports, "saverContainerDir", { enumerable: true, get: function() {
6146
+ return saverHandoff_1.saverContainerDir;
6147
+ } });
6148
+ Object.defineProperty(exports, "saverReplayPath", { enumerable: true, get: function() {
6149
+ return saverHandoff_1.saverReplayPath;
6150
+ } });
6151
+ Object.defineProperty(exports, "saverStatusDir", { enumerable: true, get: function() {
6152
+ return saverHandoff_1.saverStatusDir;
6153
+ } });
6154
+ Object.defineProperty(exports, "saverSupportDir", { enumerable: true, get: function() {
6155
+ return saverHandoff_1.saverSupportDir;
6156
+ } });
6157
+ Object.defineProperty(exports, "SAVER_REPLAY_WINDOW_MS", { enumerable: true, get: function() {
6158
+ return saverHandoff_1.SAVER_REPLAY_WINDOW_MS;
6159
+ } });
6160
+ var terminalStyle_1 = require_terminalStyle();
6161
+ Object.defineProperty(exports, "colourEnabled", { enumerable: true, get: function() {
6162
+ return terminalStyle_1.colourEnabled;
6163
+ } });
6164
+ Object.defineProperty(exports, "terminalStyle", { enumerable: true, get: function() {
6165
+ return terminalStyle_1.terminalStyle;
6166
+ } });
6167
+ var hookRunner_1 = require_hookRunner();
6168
+ Object.defineProperty(exports, "describeAge", { enumerable: true, get: function() {
6169
+ return hookRunner_1.describeAge;
6170
+ } });
6171
+ Object.defineProperty(exports, "hookLauncherScript", { enumerable: true, get: function() {
6172
+ return hookRunner_1.hookLauncherScript;
6173
+ } });
6174
+ Object.defineProperty(exports, "hookRunnerCommand", { enumerable: true, get: function() {
6175
+ return hookRunner_1.hookRunnerCommand;
6176
+ } });
6177
+ Object.defineProperty(exports, "hookRunnerPaths", { enumerable: true, get: function() {
6178
+ return hookRunner_1.hookRunnerPaths;
6179
+ } });
6180
+ Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
6181
+ return hookRunner_1.installHookRunner;
6182
+ } });
6183
+ Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
6184
+ return hookRunner_1.lastHookPath;
6185
+ } });
6186
+ Object.defineProperty(exports, "readLastHook", { enumerable: true, get: function() {
6187
+ return hookRunner_1.readLastHook;
6188
+ } });
6189
+ Object.defineProperty(exports, "removeHookRunner", { enumerable: true, get: function() {
6190
+ return hookRunner_1.removeHookRunner;
6191
+ } });
6192
+ Object.defineProperty(exports, "resolveHookNode", { enumerable: true, get: function() {
6193
+ return hookRunner_1.resolveHookNode;
6194
+ } });
6195
+ Object.defineProperty(exports, "stampLastHook", { enumerable: true, get: function() {
6196
+ return hookRunner_1.stampLastHook;
6197
+ } });
6198
+ Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
6199
+ return hookRunner_1.tidyHomePath;
6200
+ } });
6201
+ var liveSignalDoctor_1 = require_liveSignalDoctor();
6202
+ Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
6203
+ return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
6204
+ } });
6205
+ Object.defineProperty(exports, "doctorRow", { enumerable: true, get: function() {
6206
+ return liveSignalDoctor_1.doctorRow;
6207
+ } });
6208
+ Object.defineProperty(exports, "liveSignalDoctorLines", { enumerable: true, get: function() {
6209
+ return liveSignalDoctor_1.liveSignalDoctorLines;
6210
+ } });
5162
6211
  var hookSet_1 = require_hookSet();
5163
6212
  Object.defineProperty(exports, "HOOK_SET_FLAG", { enumerable: true, get: function() {
5164
6213
  return hookSet_1.HOOK_SET_FLAG;
@@ -5283,10 +6332,10 @@ var require_out2 = __commonJS({
5283
6332
  });
5284
6333
 
5285
6334
  // src/cli.ts
5286
- var import_tool_kit3 = __toESM(require_out2(), 1);
6335
+ var import_tool_kit3 = __toESM(require_out3(), 1);
5287
6336
 
5288
6337
  // src/mapCodexEvent.ts
5289
- var import_tool_kit = __toESM(require_out2(), 1);
6338
+ var import_tool_kit = __toESM(require_out3(), 1);
5290
6339
 
5291
6340
  // src/types.ts
5292
6341
  var ASCENDA_TOOL_TYPE = "cli_agent";
@@ -5431,7 +6480,7 @@ function withHost(metadata) {
5431
6480
  }
5432
6481
 
5433
6482
  // src/liveSignal.ts
5434
- var import_tool_kit2 = __toESM(require_out2(), 1);
6483
+ var import_tool_kit2 = __toESM(require_out3(), 1);
5435
6484
  function liveSignalFor(hookName, input) {
5436
6485
  switch (hookName) {
5437
6486
  case "UserPromptSubmit": {
@@ -5474,7 +6523,7 @@ var SETUP = {
5474
6523
  packageName: "@ascenda-one/codex-hooks",
5475
6524
  binaryName: "ascenda-codex-hook",
5476
6525
  hookEvents: HOOK_EVENTS,
5477
- restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not enable execution. After a session, verify the cli_agent send journal and metadata.host: codex in the event log.",
6526
+ restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not run them.",
5478
6527
  // Codex reports the posture it was working under and its approval gate; it
5479
6528
  // sends no model, no git action and no per-file change size.
5480
6529
  sends: ["posture", "waiting"],
@@ -5507,6 +6556,7 @@ async function main() {
5507
6556
  const input = await readJsonFromStdin();
5508
6557
  const sessionId = typeof input.session_id === "string" ? input.session_id : void 0;
5509
6558
  let turnDurationMs;
6559
+ (0, import_tool_kit3.stampLastHook)(CODEX_HOST, hookName);
5510
6560
  if (hookName === "UserPromptSubmit") (0, import_tool_kit3.recordTurnStart)(CODEX_HOST, sessionId);
5511
6561
  if (hookName === "Stop") turnDurationMs = (0, import_tool_kit3.consumeTurnDurationMs)(CODEX_HOST, sessionId);
5512
6562
  await emitLive(hookName, input, sessionId);