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

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
@@ -156,25 +156,66 @@ var require_gitActionClassifier = __commonJS({
156
156
  if (!/\bgit\b/.test(value))
157
157
  return void 0;
158
158
  const heads = (0, commandHeads_1.commandHeads)(value);
159
- if (heads.some((h) => /^git\s+commit\b/.test(h) && /\s--amend\b/.test(h)))
159
+ const commands = heads.map(parseGitCommand).filter((c) => c !== void 0);
160
+ if (commands.some((c) => c.verb === "commit" && c.args.includes("--amend")))
160
161
  return "amend";
161
- if (heads.some((h) => /^git\s+revert\b/.test(h)))
162
+ if (commands.some((c) => c.verb === "revert"))
162
163
  return "revert";
163
- if (heads.some((h) => /^git\s+reset\b/.test(h) && /\s--hard\b/.test(h)))
164
+ if (commands.some((c) => c.verb === "reset" && c.args.includes("--hard")))
164
165
  return "reset_hard";
165
- if (heads.some((h) => /^git\s+restore\b/.test(h) && !/\s--staged\b/.test(h)))
166
+ if (commands.some(discardsWork))
166
167
  return "restore";
167
- if (heads.some((h) => /^git\s+checkout\b.*\s--\s/.test(h)))
168
- return "restore";
169
- if (heads.some((h) => /^git\s+push\b/.test(h)))
168
+ if (commands.some((c) => c.verb === "push"))
170
169
  return "push";
171
- if (heads.some((h) => /^git\s+commit\b/.test(h)))
170
+ if (commands.some((c) => c.verb === "commit"))
172
171
  return "commit";
173
172
  return void 0;
174
173
  }
175
174
  function isReworkGitAction2(action) {
176
175
  return action === "revert" || action === "reset_hard" || action === "restore";
177
176
  }
177
+ var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path"]);
178
+ function parseGitCommand(head) {
179
+ const words = head.split(/\s+/);
180
+ if (words[0] !== "git")
181
+ return void 0;
182
+ let i = 1;
183
+ while (i < words.length && words[i].startsWith("-")) {
184
+ i += GLOBAL_OPTIONS_WITH_VALUE.has(words[i]) ? 2 : 1;
185
+ }
186
+ if (i >= words.length)
187
+ return void 0;
188
+ return { verb: words[i], args: words.slice(i + 1) };
189
+ }
190
+ function discardsWork({ verb, args }) {
191
+ switch (verb) {
192
+ case "restore":
193
+ return !args.includes("--staged");
194
+ case "switch":
195
+ return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
196
+ case "clean": {
197
+ const flags = args.filter((a) => /^-[a-z]+$/.test(a)).join("");
198
+ const dryRun = args.includes("--dry-run") || flags.includes("n");
199
+ return !dryRun && (args.includes("--force") || flags.includes("f"));
200
+ }
201
+ case "checkout":
202
+ return checkoutDiscards(args);
203
+ default:
204
+ return false;
205
+ }
206
+ }
207
+ function checkoutDiscards(args) {
208
+ if (args.includes("--"))
209
+ return true;
210
+ if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
211
+ return false;
212
+ const words = args.filter((a) => !a.startsWith("-"));
213
+ if (words.length >= 2)
214
+ return true;
215
+ if (words.length === 1)
216
+ return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
217
+ return false;
218
+ }
178
219
  }
179
220
  });
180
221
 
@@ -185,6 +226,7 @@ var require_workMilestoneClassifier = __commonJS({
185
226
  Object.defineProperty(exports, "__esModule", { value: true });
186
227
  exports.classifyWorkMilestone = classifyWorkMilestone2;
187
228
  exports.invitesDebrief = invitesDebrief2;
229
+ exports.classifyMcpWorkMilestone = classifyMcpWorkMilestone2;
188
230
  var commandHeads_1 = require_commandHeads();
189
231
  function classifyWorkMilestone2(command) {
190
232
  if (!command)
@@ -204,6 +246,41 @@ var require_workMilestoneClassifier = __commonJS({
204
246
  function invitesDebrief2(kind) {
205
247
  return kind === "pr_merged" || kind === "issue_closed";
206
248
  }
249
+ function classifyMcpWorkMilestone2(toolName) {
250
+ if (!toolName)
251
+ return void 0;
252
+ const parts = toolName.toLowerCase().split("__");
253
+ if (parts[0] !== "mcp" || parts.length < 3)
254
+ return void 0;
255
+ const tool = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
256
+ if (/^(merge|accept)(pullrequest|mergerequest)$/.test(tool))
257
+ return "pr_merged";
258
+ if (/^closeissue$/.test(tool))
259
+ return "issue_closed";
260
+ if (/^(create|open)(pullrequest|mergerequest)$/.test(tool))
261
+ return "pr_opened";
262
+ return void 0;
263
+ }
264
+ }
265
+ });
266
+
267
+ // ../packages/tool-kit/out/shellFacts.js
268
+ var require_shellFacts = __commonJS({
269
+ "../packages/tool-kit/out/shellFacts.js"(exports) {
270
+ "use strict";
271
+ Object.defineProperty(exports, "__esModule", { value: true });
272
+ exports.shellCommandFacts = shellCommandFacts;
273
+ var gitActionClassifier_1 = require_gitActionClassifier();
274
+ var workMilestoneClassifier_1 = require_workMilestoneClassifier();
275
+ function shellCommandFacts(command) {
276
+ const gitAction = (0, gitActionClassifier_1.classifyGitAction)(command);
277
+ const milestoneKind = (0, workMilestoneClassifier_1.classifyWorkMilestone)(command);
278
+ return {
279
+ ...gitAction !== void 0 ? { gitAction } : {},
280
+ ...(0, gitActionClassifier_1.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
281
+ ...milestoneKind !== void 0 ? { milestoneKind } : {}
282
+ };
283
+ }
207
284
  }
208
285
  });
209
286
 
@@ -597,6 +674,61 @@ var require_metricKeys = __commonJS({
597
674
  subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
598
675
  subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
599
676
  subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
677
+ advisorMessageCount: {
678
+ family: "counts",
679
+ readBy: ["diagnostic"],
680
+ note: "Claude Code only: advisor calls (a second model consulted inside one API message). Their tokens and models are already folded into the session totals and model mix, and this is the receipt for how much of that they are."
681
+ },
682
+ advisorTokensTotal: {
683
+ family: "context",
684
+ readBy: ["diagnostic"],
685
+ unit: "tokens",
686
+ note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
687
+ },
688
+ cacheCreationTokens: {
689
+ family: "context",
690
+ readBy: ["diagnostic"],
691
+ unit: "tokens",
692
+ note: "Prompt-cache writes, summed once per API message. Absent where the store never wrote the figure, which is not the same as none written."
693
+ },
694
+ cacheCreation5mTokens: {
695
+ family: "context",
696
+ readBy: ["diagnostic"],
697
+ unit: "tokens",
698
+ note: "The part of cacheCreationTokens written with the 5-minute lifetime. Absent on transcripts that only record the total."
699
+ },
700
+ cacheCreation1hTokens: {
701
+ family: "context",
702
+ readBy: ["diagnostic"],
703
+ unit: "tokens",
704
+ note: "The part of cacheCreationTokens written with the 1-hour lifetime. Absent on transcripts that only record the total."
705
+ },
706
+ headlessPromptLines: {
707
+ family: "reading",
708
+ readBy: ["diagnostic"],
709
+ unit: "lines",
710
+ note: "Claude Code only: user lines written by the Agent SDK or a headless run (entrypoint sdk-*). Nobody typed them, so promptCount leaves them out. Counted once per line across the store."
711
+ },
712
+ tokensNotCollected: {
713
+ family: "context",
714
+ readBy: ["diagnostic"],
715
+ note: "True when the store recorded no token figures for this session (Cursor builds that write a zero tokenCount, Codex rollouts from before token_count events). The token keys are then left off the event instead of being sent as 0, so absent and zero stay apart. Metrics are flat scalars with no null, so a flag beside the missing keys is the marker the contract allows."
716
+ },
717
+ unattributedSubagentTranscripts: {
718
+ family: "reading",
719
+ readBy: ["diagnostic"],
720
+ note: "Claude Code only: flat subagent transcripts whose lines name no parent session, so they could not be folded anywhere."
721
+ },
722
+ duplicateChatSessions: {
723
+ family: "reading",
724
+ readBy: ["diagnostic"],
725
+ note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
726
+ },
727
+ sessionsStartedFromBubble: {
728
+ family: "reading",
729
+ readBy: ["diagnostic"],
730
+ note: "Cursor only: sessions whose start is the earliest message rather than the header's createdAt, which can sit months before anyone typed."
731
+ },
600
732
  toolName: {
601
733
  family: "tools",
602
734
  readBy: ["backend"],
@@ -636,9 +768,11 @@ var require_out = __commonJS({
636
768
  "../packages/tool-contract/out/index.js"(exports) {
637
769
  "use strict";
638
770
  Object.defineProperty(exports, "__esModule", { value: true });
639
- exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
771
+ exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.DELIVERY_ENVELOPE_KEYS = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
640
772
  exports.combineDisjointHalves = combineDisjointHalves;
641
773
  exports.requireComparableQuantities = requireComparableQuantities;
774
+ exports.joinEventPayload = joinEventPayload;
775
+ exports.splitEventPayload = splitEventPayload;
642
776
  exports.ASCENDA_TELEMETRY_SOURCES = [
643
777
  "vscode_extension",
644
778
  "cursor_mcp",
@@ -702,7 +836,9 @@ var require_out = __commonJS({
702
836
  exports.COLLABORATION_EVENT_TYPES = [
703
837
  "review_requested_of_me",
704
838
  "review_given",
705
- "pull_request_opened"
839
+ "pull_request_opened",
840
+ "pull_request_closed",
841
+ "pull_request_merged"
706
842
  ];
707
843
  exports.EVENT_METADATA_DISCLOSURE = {
708
844
  language: "edits",
@@ -714,6 +850,13 @@ var require_out = __commonJS({
714
850
  gitAction: "git",
715
851
  milestoneKind: "git",
716
852
  branchHash: "repo",
853
+ repoKey: "forge",
854
+ headRepoKey: "forge",
855
+ prCreatedAt: "git",
856
+ prClosedAt: "git",
857
+ prMergedAt: "git",
858
+ branchKey: "forge",
859
+ promptId: "turns",
717
860
  autonomyMode: "posture",
718
861
  modelClass: "model",
719
862
  modelId: "model",
@@ -763,6 +906,13 @@ var require_out = __commonJS({
763
906
  "gitAction",
764
907
  "milestoneKind",
765
908
  "branchHash",
909
+ "repoKey",
910
+ "headRepoKey",
911
+ "prCreatedAt",
912
+ "prClosedAt",
913
+ "prMergedAt",
914
+ "branchKey",
915
+ "promptId",
766
916
  "autonomyMode",
767
917
  "modelClass",
768
918
  "modelId",
@@ -790,6 +940,24 @@ var require_out = __commonJS({
790
940
  "importSchema",
791
941
  "collectorVersion"
792
942
  ];
943
+ exports.DELIVERY_ENVELOPE_KEYS = ["toolInstallationId", "idempotencyKey"];
944
+ function joinEventPayload(envelope, body) {
945
+ const payload = { toolInstallationId: envelope.toolInstallationId };
946
+ for (const [key, value] of Object.entries(body)) {
947
+ payload[key] = value;
948
+ if (key === "occurredAt" && envelope.idempotencyKey !== void 0) {
949
+ payload.idempotencyKey = envelope.idempotencyKey;
950
+ }
951
+ }
952
+ return payload;
953
+ }
954
+ function splitEventPayload(payload) {
955
+ const { toolInstallationId, idempotencyKey, ...body } = payload;
956
+ const envelope = { toolInstallationId };
957
+ if (idempotencyKey !== void 0)
958
+ envelope.idempotencyKey = idempotencyKey;
959
+ return { envelope, body };
960
+ }
793
961
  exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
794
962
  exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
795
963
  exports.EVENT_WORKLOAD_CATEGORY = {
@@ -814,6 +982,10 @@ var require_out = __commonJS({
814
982
  review_requested_of_me: "supervision",
815
983
  review_given: "supervision",
816
984
  pull_request_opened: "creation",
985
+ // Where a pull request of yours ended up. A boundary like a turn ending, not
986
+ // work in itself, so neutral: it must not weigh on any workload leg.
987
+ pull_request_closed: "neutral",
988
+ pull_request_merged: "neutral",
817
989
  context_pressure_high: "risk",
818
990
  agent_loop_long: "risk",
819
991
  after_hours_ai_session: "risk",
@@ -844,6 +1016,16 @@ var require_out = __commonJS({
844
1016
  // step toward an interruption count becoming a score, a streak, or something
845
1017
  // that fires on a miss. It must never become any of those.
846
1018
  supervision_interruption: "supervision",
1019
+ // The agent asked to run a tool, and the auto-mode classifier refused one.
1020
+ // Claude Code's `PermissionRequest` and `PermissionDenied` hooks. Neutral,
1021
+ // because the Notification for the same prompt is already counted above as
1022
+ // `supervision_interruption`, and counting both would weigh one prompt
1023
+ // twice. These rows exist for the public event stream: which tool asked, and
1024
+ // under which posture. `permission_requested` fires before the person
1025
+ // answers and no hook reports their answer, so neither event says whether
1026
+ // the request was granted.
1027
+ permission_requested: "neutral",
1028
+ permission_denied: "neutral",
847
1029
  // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
848
1030
  approach_churn_detected: "risk",
849
1031
  goal_drift_detected: "risk",
@@ -968,16 +1150,16 @@ var require_collectorVersion = __commonJS({
968
1150
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
969
1151
  exports.describeCollectorVersion = describeCollectorVersion2;
970
1152
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
971
- exports.COLLECTOR_VERSION = "0.1.34" ? "0.1.34" : exports.UNRELEASED_COLLECTOR_VERSION;
1153
+ exports.COLLECTOR_VERSION = "0.1.36" ? "0.1.36" : exports.UNRELEASED_COLLECTOR_VERSION;
972
1154
  function describeCollectorVersion2(version = exports.COLLECTOR_VERSION) {
973
1155
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
974
1156
  }
975
1157
  }
976
1158
  });
977
1159
 
978
- // ../packages/tool-kit/out/eventLog.js
979
- var require_eventLog = __commonJS({
980
- "../packages/tool-kit/out/eventLog.js"(exports) {
1160
+ // ../packages/tool-kit/out/tokenStore.js
1161
+ var require_tokenStore = __commonJS({
1162
+ "../packages/tool-kit/out/tokenStore.js"(exports) {
981
1163
  "use strict";
982
1164
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
983
1165
  if (k2 === void 0) k2 = k;
@@ -1017,306 +1199,484 @@ var require_eventLog = __commonJS({
1017
1199
  };
1018
1200
  }();
1019
1201
  Object.defineProperty(exports, "__esModule", { value: true });
1020
- exports.EVENT_LOG_ENV_VAR = void 0;
1021
- exports.expandUserPath = expandUserPath;
1022
- exports.resolveEventLogPath = resolveEventLogPath2;
1023
- exports.appendEventLog = appendEventLog2;
1202
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1203
+ exports.ascendaHome = ascendaHome3;
1204
+ exports.defaultTokenFilePath = defaultTokenFilePath4;
1205
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1206
+ exports.persistEventWriteToken = persistEventWriteToken4;
1207
+ exports.readTokenExpiry = readTokenExpiry;
1208
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
1209
+ exports.readTokenFile = readTokenFile3;
1210
+ exports.sanitizeFilePart = sanitizeFilePart;
1024
1211
  var fs5 = __importStar(__require("fs"));
1025
- var os5 = __importStar(__require("os"));
1212
+ var os4 = __importStar(__require("os"));
1026
1213
  var path4 = __importStar(__require("path"));
1027
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1028
- var MAX_BYTES = 5 * 1024 * 1024;
1029
- function expandUserPath(configured) {
1030
- const value = configured?.trim();
1031
- if (!value)
1032
- return void 0;
1033
- if (value === "~")
1034
- return os5.homedir();
1035
- if (value.startsWith("~/"))
1036
- return path4.join(os5.homedir(), value.slice(2));
1037
- return path4.resolve(value);
1214
+ function ascendaHome3(home = os4.homedir()) {
1215
+ return process.env.ASCENDA_HOME ?? path4.join(home, ".ascenda");
1038
1216
  }
1039
- function resolveEventLogPath2() {
1040
- return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
1217
+ function defaultTokenFilePath4(toolInstallationId) {
1218
+ return path4.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1041
1219
  }
1042
- function appendEventLog2(logFilePath, entry) {
1220
+ function tokenExpiryFilePath(tokenFilePath) {
1221
+ return path4.join(path4.dirname(tokenFilePath), "expiry", path4.basename(tokenFilePath));
1222
+ }
1223
+ function persistEventWriteToken4(tokenFilePath, token, expiresAt) {
1224
+ const dir = path4.dirname(tokenFilePath);
1225
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1226
+ fs5.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1227
+ if (process.platform !== "win32") {
1228
+ fs5.chmodSync(dir, 448);
1229
+ fs5.chmodSync(tokenFilePath, 384);
1230
+ }
1231
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1043
1232
  try {
1044
- rotateIfLarge(logFilePath);
1045
- const dir = path4.dirname(logFilePath);
1046
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1047
- fs5.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1048
- `, { encoding: "utf8", mode: 384 });
1049
- if (process.platform !== "win32")
1050
- fs5.chmodSync(logFilePath, 384);
1233
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1234
+ fs5.mkdirSync(path4.dirname(expiryFile), { recursive: true, mode: 448 });
1235
+ fs5.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1236
+ } else {
1237
+ fs5.rmSync(expiryFile, { force: true });
1238
+ }
1051
1239
  } catch {
1052
1240
  }
1053
1241
  }
1054
- function rotateIfLarge(logFilePath) {
1242
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1243
+ function readTokenExpiry(tokenFilePath) {
1055
1244
  try {
1056
- if (fs5.statSync(logFilePath).size < MAX_BYTES)
1057
- return;
1058
- fs5.renameSync(logFilePath, `${logFilePath}.1`);
1245
+ const recorded = Date.parse(fs5.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1246
+ if (Number.isFinite(recorded))
1247
+ return recorded;
1059
1248
  } catch {
1060
1249
  }
1061
- }
1062
- }
1063
- });
1064
-
1065
- // ../packages/tool-kit/out/http.js
1066
- var require_http = __commonJS({
1067
- "../packages/tool-kit/out/http.js"(exports) {
1068
- "use strict";
1069
- Object.defineProperty(exports, "__esModule", { value: true });
1070
- exports.AscendaApiError = void 0;
1071
- exports.createPairingSession = createPairingSession3;
1072
- exports.getPairingStatus = getPairingStatus3;
1073
- exports.startStudyJoin = startStudyJoin;
1074
- exports.getStudyJoinStatus = getStudyJoinStatus;
1075
- exports.readInitiatives = readInitiatives;
1076
- exports.readStudyNotices = readStudyNotices;
1077
- exports.setStudyObjection = setStudyObjection;
1078
- exports.markStudyNoticeShown = markStudyNoticeShown;
1079
- exports.renewToolToken = renewToolToken;
1080
- exports.isRetryableStatus = isRetryableStatus;
1081
- exports.postToolEvent = postToolEvent;
1082
- exports.postToolEventsBatch = postToolEventsBatch;
1083
- exports.parseIngestResponse = parseIngestResponse;
1084
- var tool_contract_1 = require_out();
1085
- var AscendaApiError2 = class extends Error {
1086
- status;
1087
- errorCode;
1088
- constructor(status, errorCode, body) {
1089
- super(body ?? `Ascenda API error ${status}`);
1090
- this.status = status;
1091
- this.errorCode = errorCode;
1092
- this.name = "AscendaApiError";
1250
+ try {
1251
+ return fs5.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1252
+ } catch {
1253
+ return void 0;
1093
1254
  }
1094
- };
1095
- exports.AscendaApiError = AscendaApiError2;
1096
- async function createPairingSession3(apiBaseUrl, toolInstallationId, toolType, displayName) {
1097
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1098
- method: "POST",
1099
- headers: { "Content-Type": "application/json" },
1100
- body: JSON.stringify({ toolInstallationId, toolType, displayName })
1101
- });
1102
- if (!response.ok)
1103
- throw new AscendaApiError2(response.status, void 0, await response.text());
1104
- return await response.json();
1105
- }
1106
- async function getPairingStatus3(apiBaseUrl, pairingSessionId) {
1107
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1108
- method: "GET",
1109
- headers: { Accept: "application/json" }
1110
- });
1111
- if (!response.ok)
1112
- throw new AscendaApiError2(response.status, void 0, await response.text());
1113
- return await response.json();
1114
- }
1115
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1116
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1117
- method: "POST",
1118
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1119
- body: JSON.stringify({ joinCode, mode })
1120
- });
1121
- if (!response.ok)
1122
- throw await apiError(response);
1123
- return await response.json();
1124
- }
1125
- async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1126
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1127
- method: "GET",
1128
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1129
- });
1130
- if (!response.ok)
1131
- throw await apiError(response);
1132
- return await response.json();
1133
1255
  }
1134
- async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1135
- let response;
1256
+ function listPersistedToolInstallationIds2(toolType) {
1257
+ const prefix = `${sanitizeFilePart(toolType)}_`;
1258
+ const dir = path4.join(ascendaHome3(), "tokens");
1259
+ let names;
1136
1260
  try {
1137
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1138
- method: "GET",
1139
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1140
- signal
1141
- });
1142
- } catch (error) {
1143
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1261
+ names = fs5.readdirSync(dir);
1262
+ } catch {
1263
+ return [];
1144
1264
  }
1145
- if (response.status === 401)
1146
- return { kind: "rejected", httpStatus: 401 };
1147
- if (!response.ok)
1148
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1149
- let body;
1265
+ const ids = [];
1266
+ for (const name of names.sort()) {
1267
+ if (!name.startsWith(prefix) || name.length === prefix.length)
1268
+ continue;
1269
+ const file = path4.join(dir, name);
1270
+ try {
1271
+ if (!fs5.statSync(file).isFile())
1272
+ continue;
1273
+ } catch {
1274
+ continue;
1275
+ }
1276
+ if (readTokenFile3(file) === void 0)
1277
+ continue;
1278
+ ids.push(`${toolType}:${name.slice(prefix.length)}`);
1279
+ }
1280
+ return ids;
1281
+ }
1282
+ function readTokenFile3(tokenFilePath) {
1150
1283
  try {
1151
- body = await response.json();
1284
+ if (!fs5.existsSync(tokenFilePath))
1285
+ return void 0;
1286
+ const value = fs5.readFileSync(tokenFilePath, "utf8").trim();
1287
+ return value || void 0;
1152
1288
  } catch {
1153
- return { kind: "failed", reason: "the reply was not readable" };
1289
+ return void 0;
1154
1290
  }
1155
- if (!Array.isArray(body))
1156
- return { kind: "failed", reason: "the reply was not a list" };
1157
- return { kind: "ok", initiatives: body };
1158
1291
  }
1159
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1160
- let response;
1161
- try {
1162
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1163
- method: "GET",
1164
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1165
- signal
1166
- });
1167
- } catch (error) {
1168
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1292
+ function sanitizeFilePart(value) {
1293
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1294
+ }
1295
+ }
1296
+ });
1297
+
1298
+ // ../packages/tool-kit/out/stateStore.js
1299
+ var require_stateStore = __commonJS({
1300
+ "../packages/tool-kit/out/stateStore.js"(exports) {
1301
+ "use strict";
1302
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1303
+ if (k2 === void 0) k2 = k;
1304
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1305
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1306
+ desc = { enumerable: true, get: function() {
1307
+ return m[k];
1308
+ } };
1169
1309
  }
1170
- if (response.status === 404)
1171
- return { kind: "absent" };
1172
- if (response.status === 401)
1173
- return { kind: "rejected", httpStatus: 401 };
1174
- if (!response.ok)
1175
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1176
- let body;
1310
+ Object.defineProperty(o, k2, desc);
1311
+ } : function(o, m, k, k2) {
1312
+ if (k2 === void 0) k2 = k;
1313
+ o[k2] = m[k];
1314
+ });
1315
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1316
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1317
+ } : function(o, v) {
1318
+ o["default"] = v;
1319
+ });
1320
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1321
+ var ownKeys = function(o) {
1322
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1323
+ var ar = [];
1324
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1325
+ return ar;
1326
+ };
1327
+ return ownKeys(o);
1328
+ };
1329
+ return function(mod) {
1330
+ if (mod && mod.__esModule) return mod;
1331
+ var result = {};
1332
+ if (mod != null) {
1333
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1334
+ }
1335
+ __setModuleDefault(result, mod);
1336
+ return result;
1337
+ };
1338
+ }();
1339
+ Object.defineProperty(exports, "__esModule", { value: true });
1340
+ exports.defaultStateFilePath = defaultStateFilePath2;
1341
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId2;
1342
+ exports.unresolvedStateFilePath = unresolvedStateFilePath2;
1343
+ exports.readCollectorState = readCollectorState2;
1344
+ exports.recordSendOutcome = recordSendOutcome2;
1345
+ exports.recordOutboxDiscard = recordOutboxDiscard;
1346
+ exports.shouldAnnounceFailure = shouldAnnounceFailure2;
1347
+ exports.markFailureNotified = markFailureNotified2;
1348
+ var fs5 = __importStar(__require("fs"));
1349
+ var path4 = __importStar(__require("path"));
1350
+ var tokenStore_1 = require_tokenStore();
1351
+ function defaultStateFilePath2(toolInstallationId) {
1352
+ const dir = process.env.ASCENDA_STATE_DIR?.trim();
1353
+ const base = dir ? dir : path4.join((0, tokenStore_1.ascendaHome)(), "state");
1354
+ return path4.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1355
+ }
1356
+ function unresolvedToolInstallationId2(toolType) {
1357
+ return `${toolType}:unresolved`;
1358
+ }
1359
+ function unresolvedStateFilePath2(toolType) {
1360
+ return defaultStateFilePath2(unresolvedToolInstallationId2(toolType));
1361
+ }
1362
+ function readCollectorState2(stateFilePath) {
1177
1363
  try {
1178
- body = await response.json();
1364
+ if (!fs5.existsSync(stateFilePath))
1365
+ return void 0;
1366
+ const raw = fs5.readFileSync(stateFilePath, "utf8").trim();
1367
+ if (!raw)
1368
+ return void 0;
1369
+ const parsed = JSON.parse(raw);
1370
+ if (!parsed || typeof parsed !== "object")
1371
+ return void 0;
1372
+ return parsed;
1179
1373
  } catch {
1180
- return { kind: "absent" };
1374
+ return void 0;
1181
1375
  }
1182
- if (!Array.isArray(body))
1183
- return { kind: "absent" };
1184
- return { kind: "ok", notices: body };
1185
1376
  }
1186
- async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1187
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1188
- method: objected ? "POST" : "DELETE",
1189
- headers: { Authorization: `Bearer ${eventWriteToken}` }
1190
- });
1191
- if (!response.ok)
1192
- throw await apiError(response);
1377
+ function recordSendOutcome2(stateFilePath, toolInstallationId, outcome, detail = {}) {
1378
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1379
+ const previous = readCollectorState2(stateFilePath);
1380
+ const accepted = outcome === "accepted";
1381
+ const next = {
1382
+ toolInstallationId,
1383
+ lastAttemptAt: now,
1384
+ lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1385
+ lastOutcome: outcome,
1386
+ consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1387
+ ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1388
+ ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1389
+ ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1390
+ // A success closes the episode; a failure either opens one or continues
1391
+ // the one already open. Carrying `notifiedFailingSince` across a
1392
+ // continuing episode is what keeps the notice to once per outage.
1393
+ ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1394
+ ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1395
+ // Cumulative by design: a send outcome, success included, never erases
1396
+ // the record of what the outbox had to throw away.
1397
+ ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1398
+ };
1399
+ writeStateFile(stateFilePath, next);
1400
+ return next;
1193
1401
  }
1194
- async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1402
+ function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1403
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1404
+ const previous = readCollectorState2(stateFilePath);
1405
+ const next = {
1406
+ ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1407
+ toolInstallationId,
1408
+ lastOutcome: "outbox_discarded",
1409
+ outboxDiscarded: {
1410
+ total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1411
+ lastAt: now,
1412
+ lastCount: discard.count,
1413
+ lastReasons: discard.reasons,
1414
+ ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1415
+ }
1416
+ };
1417
+ writeStateFile(stateFilePath, next);
1418
+ return next;
1419
+ }
1420
+ function shouldAnnounceFailure2(state) {
1421
+ if (!state || state.consecutiveFailures === 0 || !state.failingSince)
1422
+ return false;
1423
+ return state.notifiedFailingSince !== state.failingSince;
1424
+ }
1425
+ function markFailureNotified2(stateFilePath, state) {
1426
+ if (!state.failingSince)
1427
+ return;
1428
+ writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
1429
+ }
1430
+ function writeStateFile(stateFilePath, state) {
1431
+ const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1195
1432
  try {
1196
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1197
- method: "POST",
1198
- headers: { Authorization: `Bearer ${eventWriteToken}` },
1199
- signal
1200
- });
1201
- return response.ok;
1433
+ const dir = path4.dirname(stateFilePath);
1434
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1435
+ fs5.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1436
+ `, { encoding: "utf8", mode: 384 });
1437
+ fs5.renameSync(temporaryPath, stateFilePath);
1438
+ if (process.platform !== "win32")
1439
+ fs5.chmodSync(stateFilePath, 384);
1202
1440
  } catch {
1203
- return false;
1441
+ try {
1442
+ if (fs5.existsSync(temporaryPath))
1443
+ fs5.unlinkSync(temporaryPath);
1444
+ } catch {
1445
+ }
1204
1446
  }
1205
1447
  }
1206
- async function apiError(response) {
1207
- const body = await response.text();
1208
- let errorCode;
1448
+ function truncate(value) {
1449
+ const collapsed = value.replace(/\s+/g, " ").trim();
1450
+ return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
1451
+ }
1452
+ }
1453
+ });
1454
+
1455
+ // ../packages/tool-kit/out/outbox.js
1456
+ var require_outbox = __commonJS({
1457
+ "../packages/tool-kit/out/outbox.js"(exports) {
1458
+ "use strict";
1459
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1460
+ if (k2 === void 0) k2 = k;
1461
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1462
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1463
+ desc = { enumerable: true, get: function() {
1464
+ return m[k];
1465
+ } };
1466
+ }
1467
+ Object.defineProperty(o, k2, desc);
1468
+ } : function(o, m, k, k2) {
1469
+ if (k2 === void 0) k2 = k;
1470
+ o[k2] = m[k];
1471
+ });
1472
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1473
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1474
+ } : function(o, v) {
1475
+ o["default"] = v;
1476
+ });
1477
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1478
+ var ownKeys = function(o) {
1479
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1480
+ var ar = [];
1481
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1482
+ return ar;
1483
+ };
1484
+ return ownKeys(o);
1485
+ };
1486
+ return function(mod) {
1487
+ if (mod && mod.__esModule) return mod;
1488
+ var result = {};
1489
+ if (mod != null) {
1490
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1491
+ }
1492
+ __setModuleDefault(result, mod);
1493
+ return result;
1494
+ };
1495
+ }();
1496
+ Object.defineProperty(exports, "__esModule", { value: true });
1497
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1498
+ exports.outboxDrainEnabled = outboxDrainEnabled2;
1499
+ exports.defaultOutboxFilePath = defaultOutboxFilePath2;
1500
+ exports.appendToOutbox = appendToOutbox;
1501
+ exports.readOutboxSummary = readOutboxSummary2;
1502
+ exports.claimOutbox = claimOutbox;
1503
+ exports.enforceOutboxBounds = enforceOutboxBounds;
1504
+ var fs5 = __importStar(__require("fs"));
1505
+ var path4 = __importStar(__require("path"));
1506
+ var stateStore_1 = require_stateStore();
1507
+ var tokenStore_1 = require_tokenStore();
1508
+ exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1509
+ exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1510
+ exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1511
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1512
+ var ORPHANED_CLAIM_AGE_MS = 6e4;
1513
+ var CLAIM_SUFFIX = ".draining";
1514
+ function outboxDrainEnabled2(env = process.env) {
1515
+ const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1516
+ if (value === void 0 || value === "")
1517
+ return true;
1518
+ return !(value === "0" || value === "false" || value === "no" || value === "off");
1519
+ }
1520
+ function defaultOutboxFilePath2(toolInstallationId) {
1521
+ const dir = path4.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1522
+ return path4.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1523
+ }
1524
+ function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1209
1525
  try {
1210
- const parsed = JSON.parse(body);
1211
- errorCode = parsed.code ?? parsed.error;
1526
+ const dir = path4.dirname(outboxFilePath);
1527
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1528
+ const entry = { queuedAt: now.toISOString(), payload };
1529
+ fs5.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1530
+ `, { encoding: "utf8", mode: 384 });
1531
+ if (process.platform !== "win32")
1532
+ fs5.chmodSync(outboxFilePath, 384);
1533
+ return true;
1212
1534
  } catch {
1213
- errorCode = void 0;
1535
+ return false;
1214
1536
  }
1215
- return new AscendaApiError2(response.status, errorCode, body);
1216
1537
  }
1217
- async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1218
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1219
- method: "POST",
1220
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1221
- signal
1222
- });
1223
- if (response.status === 401)
1224
- return null;
1225
- if (!response.ok)
1226
- throw new AscendaApiError2(response.status, void 0, await response.text());
1227
- return await response.json();
1228
- }
1229
- function isDeliveredStatus(value) {
1230
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1538
+ function readOutboxSummary2(outboxFilePath) {
1539
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs5.existsSync(file));
1540
+ if (files.length === 0)
1541
+ return void 0;
1542
+ let depth = 0;
1543
+ let unreadableLines = 0;
1544
+ let oldestQueuedAt;
1545
+ for (const file of files) {
1546
+ const { entries, unreadable } = readEntries(file);
1547
+ depth += entries.length;
1548
+ unreadableLines += unreadable;
1549
+ for (const entry of entries) {
1550
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1551
+ oldestQueuedAt = entry.queuedAt;
1552
+ }
1553
+ }
1554
+ return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1231
1555
  }
1232
- function readSuccessBody(body) {
1233
- let parsed;
1556
+ function claimOutbox(outboxFilePath, now = Date.now()) {
1557
+ const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1558
+ const claimed = [];
1234
1559
  try {
1235
- parsed = JSON.parse(body);
1560
+ fs5.renameSync(outboxFilePath, claimPath);
1561
+ claimed.push(claimPath);
1236
1562
  } catch {
1237
- return { duplicates: 0 };
1238
1563
  }
1239
- if (!parsed || typeof parsed !== "object")
1240
- return { duplicates: 0 };
1241
- const single = parsed.status;
1242
- if (isDeliveredStatus(single))
1243
- return { duplicates: single === "duplicate" ? 1 : 0 };
1244
- const raw = parsed.results;
1245
- if (!Array.isArray(raw))
1246
- return { duplicates: 0 };
1247
- const results = [];
1248
- for (const item of raw) {
1249
- if (!item || typeof item !== "object")
1250
- continue;
1251
- const { index, status, reason } = item;
1252
- if (typeof index !== "number" || typeof status !== "string")
1564
+ let orphanIndex = 0;
1565
+ for (const orphan of listClaimFiles(outboxFilePath)) {
1566
+ if (claimed.includes(orphan))
1253
1567
  continue;
1254
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1568
+ try {
1569
+ if (now - fs5.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1570
+ continue;
1571
+ const mine = `${claimPath}.${orphanIndex++}`;
1572
+ fs5.renameSync(orphan, mine);
1573
+ claimed.push(mine);
1574
+ } catch {
1575
+ }
1255
1576
  }
1256
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1257
- }
1258
- function isRetryableStatus(status) {
1259
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1260
- }
1261
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1262
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1577
+ if (claimed.length === 0)
1578
+ return void 0;
1579
+ const entries = [];
1580
+ let unreadable = 0;
1581
+ for (const file of claimed) {
1582
+ const read = readEntries(file);
1583
+ entries.push(...read.entries);
1584
+ unreadable += read.unreadable;
1585
+ }
1586
+ entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1587
+ let released = false;
1588
+ return {
1589
+ entries,
1590
+ unreadable,
1591
+ release(remainder) {
1592
+ if (released)
1593
+ return;
1594
+ released = true;
1595
+ if (remainder.length > 0) {
1596
+ try {
1597
+ fs5.mkdirSync(path4.dirname(outboxFilePath), { recursive: true, mode: 448 });
1598
+ fs5.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1599
+ `).join(""), { encoding: "utf8", mode: 384 });
1600
+ if (process.platform !== "win32")
1601
+ fs5.chmodSync(outboxFilePath, 384);
1602
+ } catch {
1603
+ return;
1604
+ }
1605
+ }
1606
+ for (const file of claimed) {
1607
+ try {
1608
+ fs5.unlinkSync(file);
1609
+ } catch {
1610
+ }
1611
+ }
1612
+ }
1613
+ };
1263
1614
  }
1264
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1265
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1615
+ function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1616
+ const reasons = {};
1617
+ let oldestQueuedAt;
1618
+ const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1619
+ const fresh = [];
1620
+ for (const entry of entries) {
1621
+ if (entry.queuedAt < cutoff) {
1622
+ reasons.age = (reasons.age ?? 0) + 1;
1623
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1624
+ oldestQueuedAt = entry.queuedAt;
1625
+ } else {
1626
+ fresh.push(entry);
1627
+ }
1628
+ }
1629
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1630
+ if (excess > 0) {
1631
+ reasons.count = excess;
1632
+ const first = fresh[0]?.queuedAt;
1633
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1634
+ oldestQueuedAt = first;
1635
+ }
1636
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1637
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1638
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1266
1639
  }
1267
- async function sendIngest(url, eventWriteToken, body, signal) {
1640
+ function listClaimFiles(outboxFilePath) {
1641
+ const dir = path4.dirname(outboxFilePath);
1642
+ const prefix = `${path4.basename(outboxFilePath)}.`;
1268
1643
  try {
1269
- const response = await fetch(url, {
1270
- method: "POST",
1271
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1272
- body,
1273
- signal
1274
- });
1275
- return parseIngestResponse(response);
1276
- } catch (error) {
1277
- return {
1278
- result: "transport_error",
1279
- detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1280
- };
1644
+ return fs5.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path4.join(dir, name)).sort();
1645
+ } catch {
1646
+ return [];
1281
1647
  }
1282
1648
  }
1283
- async function parseIngestResponse(response) {
1284
- if (response.ok) {
1285
- const outcome = { result: "accepted", httpStatus: response.status };
1286
- let read = { duplicates: 0 };
1649
+ function readEntries(file) {
1650
+ let raw;
1651
+ try {
1652
+ raw = fs5.readFileSync(file, "utf8");
1653
+ } catch {
1654
+ return { entries: [], unreadable: 0 };
1655
+ }
1656
+ const entries = [];
1657
+ let unreadable = 0;
1658
+ for (const line of raw.split("\n")) {
1659
+ if (!line.trim())
1660
+ continue;
1287
1661
  try {
1288
- read = readSuccessBody(await response.text());
1662
+ const parsed = JSON.parse(line);
1663
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1664
+ unreadable += 1;
1665
+ continue;
1666
+ }
1667
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1289
1668
  } catch {
1290
- read = { duplicates: 0 };
1669
+ unreadable += 1;
1291
1670
  }
1292
- return {
1293
- ...outcome,
1294
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1295
- ...read.results !== void 0 ? { results: read.results } : {}
1296
- };
1297
- }
1298
- const body = await response.text();
1299
- let errorCode;
1300
- try {
1301
- errorCode = JSON.parse(body).error;
1302
- } catch {
1303
- errorCode = void 0;
1304
1671
  }
1305
- const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1306
- if (response.status === 401)
1307
- return { ...base, result: "auth_failed" };
1308
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1309
- return { ...base, result: "consent_missing" };
1310
- if (response.status === 400 || response.status === 422)
1311
- return { ...base, result: "validation_failed" };
1312
- return { ...base, result: "transport_error" };
1672
+ return { entries, unreadable };
1313
1673
  }
1314
1674
  }
1315
1675
  });
1316
1676
 
1317
- // ../packages/tool-kit/out/tokenStore.js
1318
- var require_tokenStore = __commonJS({
1319
- "../packages/tool-kit/out/tokenStore.js"(exports) {
1677
+ // ../packages/tool-kit/out/backgroundDelivery.js
1678
+ var require_backgroundDelivery = __commonJS({
1679
+ "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
1320
1680
  "use strict";
1321
1681
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1322
1682
  if (k2 === void 0) k2 = k;
@@ -1356,105 +1716,270 @@ var require_tokenStore = __commonJS({
1356
1716
  };
1357
1717
  }();
1358
1718
  Object.defineProperty(exports, "__esModule", { value: true });
1359
- exports.EVENT_TOKEN_TTL_MS = void 0;
1360
- exports.ascendaHome = ascendaHome3;
1361
- exports.defaultTokenFilePath = defaultTokenFilePath4;
1362
- exports.tokenExpiryFilePath = tokenExpiryFilePath;
1363
- exports.persistEventWriteToken = persistEventWriteToken4;
1364
- exports.readTokenExpiry = readTokenExpiry;
1365
- exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
1366
- exports.readTokenFile = readTokenFile3;
1367
- exports.sanitizeFilePart = sanitizeFilePart;
1719
+ exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
1720
+ exports.hookDeliveryInline = hookDeliveryInline2;
1721
+ exports.flushLockPath = flushLockPath;
1722
+ exports.startBackgroundFlush = startBackgroundFlush2;
1723
+ exports.runOutboxFlush = runOutboxFlush3;
1368
1724
  var fs5 = __importStar(__require("fs"));
1369
- var os5 = __importStar(__require("os"));
1370
- var path4 = __importStar(__require("path"));
1371
- function ascendaHome3(home = os5.homedir()) {
1372
- return process.env.ASCENDA_HOME ?? path4.join(home, ".ascenda");
1373
- }
1374
- function defaultTokenFilePath4(toolInstallationId) {
1375
- return path4.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1376
- }
1377
- function tokenExpiryFilePath(tokenFilePath) {
1378
- return path4.join(path4.dirname(tokenFilePath), "expiry", path4.basename(tokenFilePath));
1379
- }
1380
- function persistEventWriteToken4(tokenFilePath, token, expiresAt) {
1381
- const dir = path4.dirname(tokenFilePath);
1382
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1383
- fs5.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1384
- if (process.platform !== "win32") {
1385
- fs5.chmodSync(dir, 448);
1386
- fs5.chmodSync(tokenFilePath, 384);
1725
+ var child_process_1 = __require("child_process");
1726
+ var outbox_1 = require_outbox();
1727
+ exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
1728
+ exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
1729
+ exports.FLUSH_LOCK_FRESH_MS = 2e4;
1730
+ var FLUSH_MAX_PASSES = 20;
1731
+ var FLUSH_MAX_RUN_MS = 6e4;
1732
+ function hookDeliveryInline2(env = process.env) {
1733
+ return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
1734
+ }
1735
+ function flushLockPath(outboxFilePath) {
1736
+ return `${outboxFilePath}.flushing`;
1737
+ }
1738
+ function lockIsFresh(lockPath, now) {
1739
+ try {
1740
+ return now - fs5.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1741
+ } catch {
1742
+ return false;
1387
1743
  }
1388
- const expiryFile = tokenExpiryFilePath(tokenFilePath);
1744
+ }
1745
+ function touchLock(lockPath) {
1389
1746
  try {
1390
- if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1391
- fs5.mkdirSync(path4.dirname(expiryFile), { recursive: true, mode: 448 });
1392
- fs5.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1393
- } else {
1394
- fs5.rmSync(expiryFile, { force: true });
1395
- }
1747
+ fs5.writeFileSync(lockPath, `${process.pid}
1748
+ `, { encoding: "utf8", mode: 384 });
1396
1749
  } catch {
1397
1750
  }
1398
1751
  }
1399
- exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1400
- function readTokenExpiry(tokenFilePath) {
1752
+ function removeLock(lockPath) {
1401
1753
  try {
1402
- const recorded = Date.parse(fs5.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1403
- if (Number.isFinite(recorded))
1404
- return recorded;
1754
+ fs5.unlinkSync(lockPath);
1405
1755
  } catch {
1406
1756
  }
1757
+ }
1758
+ function outboxHasEntries(outboxFilePath) {
1407
1759
  try {
1408
- return fs5.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1760
+ return fs5.statSync(outboxFilePath).size > 0;
1409
1761
  } catch {
1410
- return void 0;
1762
+ return false;
1411
1763
  }
1412
1764
  }
1413
- function listPersistedToolInstallationIds2(toolType) {
1414
- const prefix = `${sanitizeFilePart(toolType)}_`;
1415
- const dir = path4.join(ascendaHome3(), "tokens");
1416
- let names;
1765
+ function startBackgroundFlush2(options) {
1766
+ const lockPath = flushLockPath(options.outboxFilePath);
1767
+ const now = options.now ?? Date.now();
1768
+ if (lockIsFresh(lockPath, now))
1769
+ return false;
1770
+ const script = options.script ?? process.argv[1];
1771
+ if (!script)
1772
+ return false;
1417
1773
  try {
1418
- names = fs5.readdirSync(dir);
1774
+ touchLock(lockPath);
1775
+ const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
1776
+ detached: true,
1777
+ stdio: "ignore",
1778
+ windowsHide: true,
1779
+ env: process.env
1780
+ });
1781
+ child.on("error", () => removeLock(lockPath));
1782
+ child.unref();
1783
+ return true;
1419
1784
  } catch {
1420
- return [];
1785
+ removeLock(lockPath);
1786
+ return false;
1421
1787
  }
1422
- const ids = [];
1423
- for (const name of names.sort()) {
1424
- if (!name.startsWith(prefix) || name.length === prefix.length)
1425
- continue;
1426
- const file = path4.join(dir, name);
1427
- try {
1428
- if (!fs5.statSync(file).isFile())
1429
- continue;
1430
- } catch {
1431
- continue;
1788
+ }
1789
+ async function runOutboxFlush3(sender, now = Date.now) {
1790
+ const outboxFilePath = sender.outboxFilePath();
1791
+ const lockPath = flushLockPath(outboxFilePath);
1792
+ const started = now();
1793
+ let last;
1794
+ let passes = 0;
1795
+ const drain = async () => {
1796
+ while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
1797
+ passes += 1;
1798
+ touchLock(lockPath);
1799
+ last = await sender.flushOutbox();
1800
+ if (!last || last.found === 0 || last.halted || !last.sendEnabled)
1801
+ return;
1802
+ if (last.delivered === 0 && last.discarded === 0)
1803
+ return;
1432
1804
  }
1433
- if (readTokenFile3(file) === void 0)
1434
- continue;
1435
- ids.push(`${toolType}:${name.slice(prefix.length)}`);
1805
+ };
1806
+ try {
1807
+ await drain();
1808
+ removeLock(lockPath);
1809
+ if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
1810
+ touchLock(lockPath);
1811
+ await drain();
1812
+ removeLock(lockPath);
1813
+ }
1814
+ } catch {
1815
+ removeLock(lockPath);
1436
1816
  }
1437
- return ids;
1817
+ return last;
1438
1818
  }
1439
- function readTokenFile3(tokenFilePath) {
1819
+ }
1820
+ });
1821
+
1822
+ // ../packages/agent-events/out/index.js
1823
+ var require_out2 = __commonJS({
1824
+ "../packages/agent-events/out/index.js"(exports) {
1825
+ "use strict";
1826
+ Object.defineProperty(exports, "__esModule", { value: true });
1827
+ exports.KNOWN_AGENTS = exports.WAIT_REASONS = exports.VCS_ACTIONS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1828
+ exports.isAgentEventV0 = isAgentEventV0;
1829
+ exports.parseEventLogLine = parseEventLogLine;
1830
+ exports.normaliseKind = normaliseKind;
1831
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1832
+ exports.AGENT_EVENT_KINDS = [
1833
+ "session.started",
1834
+ "session.ended",
1835
+ "prompt.submitted",
1836
+ "tool.started",
1837
+ "tool.completed",
1838
+ "tool.failed",
1839
+ "turn.completed",
1840
+ "agent.waiting",
1841
+ "permission.requested",
1842
+ "permission.denied",
1843
+ "context.compacted",
1844
+ "subagent.started",
1845
+ "subagent.stopped",
1846
+ "pull_request.opened",
1847
+ "pull_request.closed",
1848
+ "pull_request.merged",
1849
+ "other"
1850
+ ];
1851
+ exports.VCS_ACTIONS = ["commit", "push", "pr_created", "pr_merged"];
1852
+ exports.WAIT_REASONS = ["permission", "idle", "input", "other"];
1853
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1854
+ function isAgentEventV0(value) {
1855
+ if (!value || typeof value !== "object")
1856
+ return false;
1857
+ const e = value;
1858
+ 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";
1859
+ }
1860
+ function parseEventLogLine(line) {
1861
+ if (!line.trim())
1862
+ return void 0;
1440
1863
  try {
1441
- if (!fs5.existsSync(tokenFilePath))
1442
- return void 0;
1443
- const value = fs5.readFileSync(tokenFilePath, "utf8").trim();
1444
- return value || void 0;
1864
+ const parsed = JSON.parse(line);
1865
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1445
1866
  } catch {
1446
1867
  return void 0;
1447
1868
  }
1448
1869
  }
1449
- function sanitizeFilePart(value) {
1450
- return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1870
+ function normaliseKind(kind) {
1871
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1451
1872
  }
1452
1873
  }
1453
1874
  });
1454
1875
 
1455
- // ../packages/tool-kit/out/stateStore.js
1456
- var require_stateStore = __commonJS({
1457
- "../packages/tool-kit/out/stateStore.js"(exports) {
1876
+ // ../packages/tool-kit/out/agentEvent.js
1877
+ var require_agentEvent = __commonJS({
1878
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1879
+ "use strict";
1880
+ Object.defineProperty(exports, "__esModule", { value: true });
1881
+ exports.toAgentEvent = toAgentEvent;
1882
+ var agent_events_1 = require_out2();
1883
+ var KIND_BY_TYPE = {
1884
+ create_focus_session: "session.started",
1885
+ recovery_offline_period: "session.ended",
1886
+ ai_prompt_submitted: "prompt.submitted",
1887
+ ai_tool_call_started: "tool.started",
1888
+ ai_tool_call_completed: "tool.completed",
1889
+ ai_file_write: "tool.completed",
1890
+ ai_file_edit: "tool.completed",
1891
+ editor_verification_activity: "tool.completed",
1892
+ ai_tool_call_failed: "tool.failed",
1893
+ compile_error: "tool.failed",
1894
+ tool_failure: "tool.failed",
1895
+ ai_turn_completed: "turn.completed",
1896
+ supervision_interruption: "agent.waiting",
1897
+ permission_requested: "permission.requested",
1898
+ permission_denied: "permission.denied",
1899
+ context_compression_manual: "context.compacted",
1900
+ context_compression_auto: "context.compacted",
1901
+ subagent_started: "subagent.started",
1902
+ subagent_stopped: "subagent.stopped",
1903
+ pull_request_opened: "pull_request.opened",
1904
+ pull_request_closed: "pull_request.closed",
1905
+ pull_request_merged: "pull_request.merged"
1906
+ };
1907
+ function agentOf(payload) {
1908
+ const host = stringField(payload.metadata?.host);
1909
+ if (host)
1910
+ return host;
1911
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1912
+ }
1913
+ function vcsActionOf(metadata) {
1914
+ const milestone = stringField(metadata.milestoneKind);
1915
+ if (milestone === "pr_opened")
1916
+ return "pr_created";
1917
+ if (milestone === "pr_merged")
1918
+ return "pr_merged";
1919
+ const git = stringField(metadata.gitAction);
1920
+ return git === "commit" || git === "push" ? git : void 0;
1921
+ }
1922
+ function waitReasonOf(metadata) {
1923
+ switch (stringField(metadata.interruptionKind)) {
1924
+ case "permission_request":
1925
+ return "permission";
1926
+ case "input_request":
1927
+ return "input";
1928
+ case "idle_prompt":
1929
+ return "idle";
1930
+ case void 0:
1931
+ return void 0;
1932
+ default:
1933
+ return "other";
1934
+ }
1935
+ }
1936
+ function stringField(value) {
1937
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1938
+ }
1939
+ function toAgentEvent(payload) {
1940
+ const metadata = payload.metadata ?? {};
1941
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1942
+ const tool = kind.startsWith("tool.") || kind.startsWith("permission.") ? stringField(metadata.toolName) : void 0;
1943
+ const outcome = stringField(metadata.outcome);
1944
+ const vcsAction = kind === "tool.completed" ? vcsActionOf(metadata) : void 0;
1945
+ const reason = kind === "agent.waiting" ? waitReasonOf(metadata) : void 0;
1946
+ const model = kind === "session.started" ? stringField(metadata.modelId) : void 0;
1947
+ return {
1948
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1949
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1950
+ time: payload.occurredAt,
1951
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1952
+ // writes anyway; without it the event in memory and the one on disk differ.
1953
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1954
+ agent: agentOf(payload),
1955
+ kind,
1956
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1957
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1958
+ ...tool ? { tool } : {},
1959
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1960
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1961
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1962
+ ...stringField(metadata.repoKey) ? { repoKey: metadata.repoKey } : {},
1963
+ ...stringField(metadata.branchKey) ? { branchKey: metadata.branchKey } : {},
1964
+ ...stringField(metadata.autonomyMode) ? { permissionMode: metadata.autonomyMode } : {},
1965
+ ...stringField(metadata.headRepoKey) ? { headRepoKey: metadata.headRepoKey } : {},
1966
+ ...stringField(metadata.prCreatedAt) ? { prCreatedAt: metadata.prCreatedAt } : {},
1967
+ ...stringField(metadata.prClosedAt) ? { prClosedAt: metadata.prClosedAt } : {},
1968
+ ...stringField(metadata.prMergedAt) ? { prMergedAt: metadata.prMergedAt } : {},
1969
+ ...stringField(metadata.promptId) ? { promptId: metadata.promptId } : {},
1970
+ ...vcsAction ? { vcsAction } : {},
1971
+ ...reason ? { reason } : {},
1972
+ ...model ? { model } : {},
1973
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1974
+ sourceType: payload.eventType
1975
+ };
1976
+ }
1977
+ }
1978
+ });
1979
+
1980
+ // ../packages/tool-kit/out/credentials.js
1981
+ var require_credentials = __commonJS({
1982
+ "../packages/tool-kit/out/credentials.js"(exports) {
1458
1983
  "use strict";
1459
1984
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1460
1985
  if (k2 === void 0) k2 = k;
@@ -1494,124 +2019,102 @@ var require_stateStore = __commonJS({
1494
2019
  };
1495
2020
  }();
1496
2021
  Object.defineProperty(exports, "__esModule", { value: true });
1497
- exports.defaultStateFilePath = defaultStateFilePath2;
1498
- exports.unresolvedToolInstallationId = unresolvedToolInstallationId2;
1499
- exports.unresolvedStateFilePath = unresolvedStateFilePath2;
1500
- exports.readCollectorState = readCollectorState2;
1501
- exports.recordSendOutcome = recordSendOutcome2;
1502
- exports.recordOutboxDiscard = recordOutboxDiscard;
1503
- exports.shouldAnnounceFailure = shouldAnnounceFailure2;
1504
- exports.markFailureNotified = markFailureNotified2;
2022
+ exports.credentialsFilePath = credentialsFilePath2;
2023
+ exports.readMachineCredentials = readMachineCredentials2;
2024
+ exports.writeMachineCredentials = writeMachineCredentials2;
2025
+ exports.writeTopLevelCredentials = writeTopLevelCredentials2;
2026
+ exports.writeRepoKeysSetting = writeRepoKeysSetting2;
2027
+ exports.writeEventLogSetting = writeEventLogSetting2;
2028
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2029
+ exports.readHostCredentials = readHostCredentials;
2030
+ exports.writeHostCredentials = writeHostCredentials;
2031
+ exports.removeHostCredentials = removeHostCredentials;
1505
2032
  var fs5 = __importStar(__require("fs"));
1506
2033
  var path4 = __importStar(__require("path"));
1507
2034
  var tokenStore_1 = require_tokenStore();
1508
- function defaultStateFilePath2(toolInstallationId) {
1509
- const dir = process.env.ASCENDA_STATE_DIR?.trim();
1510
- const base = dir ? dir : path4.join((0, tokenStore_1.ascendaHome)(), "state");
1511
- return path4.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1512
- }
1513
- function unresolvedToolInstallationId2(toolType) {
1514
- return `${toolType}:unresolved`;
1515
- }
1516
- function unresolvedStateFilePath2(toolType) {
1517
- return defaultStateFilePath2(unresolvedToolInstallationId2(toolType));
2035
+ function credentialsFilePath2() {
2036
+ return path4.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1518
2037
  }
1519
- function readCollectorState2(stateFilePath) {
2038
+ function readMachineCredentials2() {
1520
2039
  try {
1521
- if (!fs5.existsSync(stateFilePath))
1522
- return void 0;
1523
- const raw = fs5.readFileSync(stateFilePath, "utf8").trim();
2040
+ const raw = fs5.readFileSync(credentialsFilePath2(), "utf8").trim();
1524
2041
  if (!raw)
1525
2042
  return void 0;
1526
2043
  const parsed = JSON.parse(raw);
1527
- if (!parsed || typeof parsed !== "object")
2044
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1528
2045
  return void 0;
1529
2046
  return parsed;
1530
2047
  } catch {
1531
2048
  return void 0;
1532
2049
  }
1533
2050
  }
1534
- function recordSendOutcome2(stateFilePath, toolInstallationId, outcome, detail = {}) {
1535
- const now = (/* @__PURE__ */ new Date()).toISOString();
1536
- const previous = readCollectorState2(stateFilePath);
1537
- const accepted = outcome === "accepted";
1538
- const next = {
1539
- toolInstallationId,
1540
- lastAttemptAt: now,
1541
- lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1542
- lastOutcome: outcome,
1543
- consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1544
- ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1545
- ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1546
- ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1547
- // A success closes the episode; a failure either opens one or continues
1548
- // the one already open. Carrying `notifiedFailingSince` across a
1549
- // continuing episode is what keeps the notice to once per outage.
1550
- ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1551
- ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1552
- // Cumulative by design: a send outcome, success included, never erases
1553
- // the record of what the outbox had to throw away.
1554
- ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1555
- };
1556
- writeStateFile(stateFilePath, next);
1557
- return next;
2051
+ function writeMachineCredentials2(credentials) {
2052
+ const file = credentialsFilePath2();
2053
+ fs5.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
2054
+ fs5.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2055
+ `, { encoding: "utf8", mode: 384 });
2056
+ if (process.platform !== "win32") {
2057
+ fs5.chmodSync(path4.dirname(file), 448);
2058
+ fs5.chmodSync(file, 384);
2059
+ }
1558
2060
  }
1559
- function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1560
- const now = (/* @__PURE__ */ new Date()).toISOString();
1561
- const previous = readCollectorState2(stateFilePath);
1562
- const next = {
1563
- ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1564
- toolInstallationId,
1565
- lastOutcome: "outbox_discarded",
1566
- outboxDiscarded: {
1567
- total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1568
- lastAt: now,
1569
- lastCount: discard.count,
1570
- lastReasons: discard.reasons,
1571
- ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1572
- }
1573
- };
1574
- writeStateFile(stateFilePath, next);
1575
- return next;
2061
+ function writeTopLevelCredentials2(credentials) {
2062
+ const existing = readMachineCredentials2();
2063
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
2064
+ const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
2065
+ writeMachineCredentials2({
2066
+ ...credentials,
2067
+ ...eventLogPath ? { eventLogPath } : {},
2068
+ ...repoKeys === false ? { repoKeys } : {},
2069
+ ...existing?.tools ? { tools: existing.tools } : {}
2070
+ });
1576
2071
  }
1577
- function shouldAnnounceFailure2(state) {
1578
- if (!state || state.consecutiveFailures === 0 || !state.failingSince)
1579
- return false;
1580
- return state.notifiedFailingSince !== state.failingSince;
2072
+ function writeRepoKeysSetting2(on) {
2073
+ const existing = readMachineCredentials2() ?? {};
2074
+ const { repoKeys: _dropped, ...rest } = existing;
2075
+ writeMachineCredentials2(on ? rest : { ...rest, repoKeys: false });
1581
2076
  }
1582
- function markFailureNotified2(stateFilePath, state) {
1583
- if (!state.failingSince)
1584
- return;
1585
- writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
2077
+ function writeEventLogSetting2(value) {
2078
+ const existing = readMachineCredentials2() ?? {};
2079
+ writeMachineCredentials2({ ...existing, eventLogPath: value });
1586
2080
  }
1587
- function writeStateFile(stateFilePath, state) {
1588
- const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1589
- try {
1590
- const dir = path4.dirname(stateFilePath);
1591
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1592
- fs5.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1593
- `, { encoding: "utf8", mode: 384 });
1594
- fs5.renameSync(temporaryPath, stateFilePath);
1595
- if (process.platform !== "win32")
1596
- fs5.chmodSync(stateFilePath, 384);
1597
- } catch {
1598
- try {
1599
- if (fs5.existsSync(temporaryPath))
1600
- fs5.unlinkSync(temporaryPath);
1601
- } catch {
1602
- }
1603
- }
2081
+ function isLocalOnlyHostInstall(host, hasToken) {
2082
+ const credentials = readHostCredentials(host);
2083
+ if (!credentials?.localOnly)
2084
+ return false;
2085
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2086
+ return false;
2087
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2088
+ }
2089
+ function readHostCredentials(host) {
2090
+ const entry = readMachineCredentials2()?.tools?.[host];
2091
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
2092
+ return void 0;
2093
+ return entry;
1604
2094
  }
1605
- function truncate(value) {
1606
- const collapsed = value.replace(/\s+/g, " ").trim();
1607
- return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
2095
+ function writeHostCredentials(host, credentials) {
2096
+ const existing = readMachineCredentials2() ?? {};
2097
+ writeMachineCredentials2({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2098
+ }
2099
+ function removeHostCredentials(host) {
2100
+ const existing = readMachineCredentials2();
2101
+ if (!existing?.tools || !(host in existing.tools))
2102
+ return;
2103
+ const tools = { ...existing.tools };
2104
+ delete tools[host];
2105
+ const next = { ...existing };
2106
+ if (Object.keys(tools).length)
2107
+ next.tools = tools;
2108
+ else
2109
+ delete next.tools;
2110
+ writeMachineCredentials2(next);
1608
2111
  }
1609
2112
  }
1610
2113
  });
1611
2114
 
1612
- // ../packages/tool-kit/out/outbox.js
1613
- var require_outbox = __commonJS({
1614
- "../packages/tool-kit/out/outbox.js"(exports) {
2115
+ // ../packages/tool-kit/out/eventLog.js
2116
+ var require_eventLog = __commonJS({
2117
+ "../packages/tool-kit/out/eventLog.js"(exports) {
1615
2118
  "use strict";
1616
2119
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1617
2120
  if (k2 === void 0) k2 = k;
@@ -1651,182 +2154,347 @@ var require_outbox = __commonJS({
1651
2154
  };
1652
2155
  }();
1653
2156
  Object.defineProperty(exports, "__esModule", { value: true });
1654
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1655
- exports.outboxDrainEnabled = outboxDrainEnabled2;
1656
- exports.defaultOutboxFilePath = defaultOutboxFilePath2;
1657
- exports.appendToOutbox = appendToOutbox;
1658
- exports.readOutboxSummary = readOutboxSummary2;
1659
- exports.claimOutbox = claimOutbox;
1660
- exports.enforceOutboxBounds = enforceOutboxBounds;
2157
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
2158
+ exports.expandUserPath = expandUserPath;
2159
+ exports.defaultEventLogPath = defaultEventLogPath;
2160
+ exports.resolveEventLog = resolveEventLog3;
2161
+ exports.resolveEventLogPath = resolveEventLogPath2;
2162
+ exports.describeEventLog = describeEventLog3;
2163
+ exports.parseEventLogFlag = parseEventLogFlag2;
2164
+ exports.appendEventLog = appendEventLog2;
1661
2165
  var fs5 = __importStar(__require("fs"));
2166
+ var os4 = __importStar(__require("os"));
1662
2167
  var path4 = __importStar(__require("path"));
1663
- var stateStore_1 = require_stateStore();
2168
+ var agentEvent_1 = require_agentEvent();
2169
+ var credentials_1 = require_credentials();
1664
2170
  var tokenStore_1 = require_tokenStore();
1665
- exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1666
- exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1667
- exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1668
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1669
- var ORPHANED_CLAIM_AGE_MS = 6e4;
1670
- var CLAIM_SUFFIX = ".draining";
1671
- function outboxDrainEnabled2(env = process.env) {
1672
- const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1673
- if (value === void 0 || value === "")
1674
- return true;
1675
- return !(value === "0" || value === "false" || value === "no" || value === "off");
2171
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
2172
+ exports.EVENT_LOG_OFF = "off";
2173
+ var MAX_BYTES = 5 * 1024 * 1024;
2174
+ function expandUserPath(configured) {
2175
+ const value = configured?.trim();
2176
+ if (!value)
2177
+ return void 0;
2178
+ if (value === "~")
2179
+ return os4.homedir();
2180
+ if (value.startsWith("~/"))
2181
+ return path4.join(os4.homedir(), value.slice(2));
2182
+ return path4.resolve(value);
1676
2183
  }
1677
- function defaultOutboxFilePath2(toolInstallationId) {
1678
- const dir = path4.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1679
- return path4.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
2184
+ function defaultEventLogPath() {
2185
+ return path4.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1680
2186
  }
1681
- function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
2187
+ function resolveEventLog3(options = {}) {
2188
+ for (const [source, raw] of [
2189
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
2190
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
2191
+ ]) {
2192
+ const value = raw?.trim();
2193
+ if (!value)
2194
+ continue;
2195
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
2196
+ return { path: void 0, source: "disabled" };
2197
+ return { path: expandUserPath(value), source };
2198
+ }
2199
+ if (options.localOnly)
2200
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
2201
+ return { path: void 0, source: "off" };
2202
+ }
2203
+ function resolveEventLogPath2(options = {}) {
2204
+ return resolveEventLog3(options).path;
2205
+ }
2206
+ function describeEventLog3(setting, command) {
2207
+ switch (setting.source) {
2208
+ case "env":
2209
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
2210
+ case "credentials":
2211
+ return `${setting.path} (set by ${command} --event-log)`;
2212
+ case "unpaired-default":
2213
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
2214
+ case "disabled":
2215
+ return `off (turned off; ${command} --event-log to turn it on)`;
2216
+ case "off":
2217
+ return `off (${command} --event-log to keep a local copy of every event)`;
2218
+ }
2219
+ }
2220
+ function parseEventLogFlag2(argv, index) {
2221
+ const peek = argv[index + 1];
2222
+ if (peek !== void 0 && !peek.startsWith("-"))
2223
+ return { value: peek, consumed: 1 };
2224
+ return { value: defaultEventLogPath(), consumed: 0 };
2225
+ }
2226
+ function appendEventLog2(logFilePath, entry) {
1682
2227
  try {
1683
- const dir = path4.dirname(outboxFilePath);
2228
+ rotateIfLarge(logFilePath);
2229
+ const dir = path4.dirname(logFilePath);
1684
2230
  fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1685
- const entry = { queuedAt: now.toISOString(), payload };
1686
- fs5.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
2231
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
2232
+ fs5.appendFileSync(logFilePath, `${JSON.stringify(line)}
1687
2233
  `, { encoding: "utf8", mode: 384 });
1688
2234
  if (process.platform !== "win32")
1689
- fs5.chmodSync(outboxFilePath, 384);
1690
- return true;
2235
+ fs5.chmodSync(logFilePath, 384);
1691
2236
  } catch {
1692
- return false;
1693
- }
1694
- }
1695
- function readOutboxSummary2(outboxFilePath) {
1696
- const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs5.existsSync(file));
1697
- if (files.length === 0)
1698
- return void 0;
1699
- let depth = 0;
1700
- let unreadableLines = 0;
1701
- let oldestQueuedAt;
1702
- for (const file of files) {
1703
- const { entries, unreadable } = readEntries(file);
1704
- depth += entries.length;
1705
- unreadableLines += unreadable;
1706
- for (const entry of entries) {
1707
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1708
- oldestQueuedAt = entry.queuedAt;
1709
- }
1710
2237
  }
1711
- return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1712
2238
  }
1713
- function claimOutbox(outboxFilePath, now = Date.now()) {
1714
- const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1715
- const claimed = [];
2239
+ function rotateIfLarge(logFilePath) {
1716
2240
  try {
1717
- fs5.renameSync(outboxFilePath, claimPath);
1718
- claimed.push(claimPath);
2241
+ if (fs5.statSync(logFilePath).size < MAX_BYTES)
2242
+ return;
2243
+ fs5.renameSync(logFilePath, `${logFilePath}.1`);
1719
2244
  } catch {
1720
2245
  }
1721
- let orphanIndex = 0;
1722
- for (const orphan of listClaimFiles(outboxFilePath)) {
1723
- if (claimed.includes(orphan))
1724
- continue;
1725
- try {
1726
- if (now - fs5.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1727
- continue;
1728
- const mine = `${claimPath}.${orphanIndex++}`;
1729
- fs5.renameSync(orphan, mine);
1730
- claimed.push(mine);
1731
- } catch {
1732
- }
1733
- }
1734
- if (claimed.length === 0)
1735
- return void 0;
1736
- const entries = [];
1737
- let unreadable = 0;
1738
- for (const file of claimed) {
1739
- const read = readEntries(file);
1740
- entries.push(...read.entries);
1741
- unreadable += read.unreadable;
2246
+ }
2247
+ }
2248
+ });
2249
+
2250
+ // ../packages/tool-kit/out/http.js
2251
+ var require_http = __commonJS({
2252
+ "../packages/tool-kit/out/http.js"(exports) {
2253
+ "use strict";
2254
+ Object.defineProperty(exports, "__esModule", { value: true });
2255
+ exports.AscendaApiError = void 0;
2256
+ exports.createPairingSession = createPairingSession3;
2257
+ exports.getPairingStatus = getPairingStatus3;
2258
+ exports.startStudyJoin = startStudyJoin;
2259
+ exports.getStudyJoinStatus = getStudyJoinStatus;
2260
+ exports.readInitiatives = readInitiatives;
2261
+ exports.readStudyNotices = readStudyNotices;
2262
+ exports.setStudyObjection = setStudyObjection;
2263
+ exports.markStudyNoticeShown = markStudyNoticeShown;
2264
+ exports.renewToolToken = renewToolToken;
2265
+ exports.isRetryableStatus = isRetryableStatus;
2266
+ exports.postToolEvent = postToolEvent;
2267
+ exports.postToolEventsBatch = postToolEventsBatch;
2268
+ exports.parseIngestResponse = parseIngestResponse;
2269
+ var tool_contract_1 = require_out();
2270
+ var AscendaApiError2 = class extends Error {
2271
+ status;
2272
+ errorCode;
2273
+ constructor(status, errorCode, body) {
2274
+ super(body ?? `Ascenda API error ${status}`);
2275
+ this.status = status;
2276
+ this.errorCode = errorCode;
2277
+ this.name = "AscendaApiError";
1742
2278
  }
1743
- entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1744
- let released = false;
1745
- return {
1746
- entries,
1747
- unreadable,
1748
- release(remainder) {
1749
- if (released)
1750
- return;
1751
- released = true;
1752
- if (remainder.length > 0) {
1753
- try {
1754
- fs5.mkdirSync(path4.dirname(outboxFilePath), { recursive: true, mode: 448 });
1755
- fs5.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1756
- `).join(""), { encoding: "utf8", mode: 384 });
1757
- if (process.platform !== "win32")
1758
- fs5.chmodSync(outboxFilePath, 384);
1759
- } catch {
1760
- return;
1761
- }
1762
- }
1763
- for (const file of claimed) {
1764
- try {
1765
- fs5.unlinkSync(file);
1766
- } catch {
1767
- }
1768
- }
1769
- }
1770
- };
2279
+ };
2280
+ exports.AscendaApiError = AscendaApiError2;
2281
+ async function createPairingSession3(apiBaseUrl, toolInstallationId, toolType, displayName) {
2282
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
2283
+ method: "POST",
2284
+ headers: { "Content-Type": "application/json" },
2285
+ body: JSON.stringify({ toolInstallationId, toolType, displayName })
2286
+ });
2287
+ if (!response.ok)
2288
+ throw new AscendaApiError2(response.status, void 0, await response.text());
2289
+ return await response.json();
1771
2290
  }
1772
- function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1773
- const reasons = {};
1774
- let oldestQueuedAt;
1775
- const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1776
- const fresh = [];
1777
- for (const entry of entries) {
1778
- if (entry.queuedAt < cutoff) {
1779
- reasons.age = (reasons.age ?? 0) + 1;
1780
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1781
- oldestQueuedAt = entry.queuedAt;
1782
- } else {
1783
- fresh.push(entry);
1784
- }
2291
+ async function getPairingStatus3(apiBaseUrl, pairingSessionId) {
2292
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
2293
+ method: "GET",
2294
+ headers: { Accept: "application/json" }
2295
+ });
2296
+ if (!response.ok)
2297
+ throw new AscendaApiError2(response.status, void 0, await response.text());
2298
+ return await response.json();
2299
+ }
2300
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
2301
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2302
+ method: "POST",
2303
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2304
+ body: JSON.stringify({ joinCode, mode })
2305
+ });
2306
+ if (!response.ok)
2307
+ throw await apiError(response);
2308
+ return await response.json();
2309
+ }
2310
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
2311
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
2312
+ method: "GET",
2313
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
2314
+ });
2315
+ if (!response.ok)
2316
+ throw await apiError(response);
2317
+ return await response.json();
2318
+ }
2319
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
2320
+ let response;
2321
+ try {
2322
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
2323
+ method: "GET",
2324
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2325
+ signal
2326
+ });
2327
+ } catch (error) {
2328
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2329
+ }
2330
+ if (response.status === 401)
2331
+ return { kind: "rejected", httpStatus: 401 };
2332
+ if (!response.ok)
2333
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2334
+ let body;
2335
+ try {
2336
+ body = await response.json();
2337
+ } catch {
2338
+ return { kind: "failed", reason: "the reply was not readable" };
1785
2339
  }
1786
- const excess = Math.max(0, fresh.length - bounds.maxEntries);
1787
- if (excess > 0) {
1788
- reasons.count = excess;
1789
- const first = fresh[0]?.queuedAt;
1790
- if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1791
- oldestQueuedAt = first;
2340
+ if (!Array.isArray(body))
2341
+ return { kind: "failed", reason: "the reply was not a list" };
2342
+ return { kind: "ok", initiatives: body };
2343
+ }
2344
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
2345
+ let response;
2346
+ try {
2347
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
2348
+ method: "GET",
2349
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2350
+ signal
2351
+ });
2352
+ } catch (error) {
2353
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1792
2354
  }
1793
- const kept = excess > 0 ? fresh.slice(excess) : fresh;
1794
- const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1795
- return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
2355
+ if (response.status === 404)
2356
+ return { kind: "absent" };
2357
+ if (response.status === 401)
2358
+ return { kind: "rejected", httpStatus: 401 };
2359
+ if (!response.ok)
2360
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2361
+ let body;
2362
+ try {
2363
+ body = await response.json();
2364
+ } catch {
2365
+ return { kind: "absent" };
2366
+ }
2367
+ if (!Array.isArray(body))
2368
+ return { kind: "absent" };
2369
+ return { kind: "ok", notices: body };
1796
2370
  }
1797
- function listClaimFiles(outboxFilePath) {
1798
- const dir = path4.dirname(outboxFilePath);
1799
- const prefix = `${path4.basename(outboxFilePath)}.`;
2371
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
2372
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
2373
+ method: objected ? "POST" : "DELETE",
2374
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
2375
+ });
2376
+ if (!response.ok)
2377
+ throw await apiError(response);
2378
+ }
2379
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1800
2380
  try {
1801
- return fs5.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path4.join(dir, name)).sort();
2381
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
2382
+ method: "POST",
2383
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
2384
+ signal
2385
+ });
2386
+ return response.ok;
1802
2387
  } catch {
1803
- return [];
2388
+ return false;
1804
2389
  }
1805
2390
  }
1806
- function readEntries(file) {
1807
- let raw;
2391
+ async function apiError(response) {
2392
+ const body = await response.text();
2393
+ let errorCode;
1808
2394
  try {
1809
- raw = fs5.readFileSync(file, "utf8");
2395
+ const parsed = JSON.parse(body);
2396
+ errorCode = parsed.code ?? parsed.error;
1810
2397
  } catch {
1811
- return { entries: [], unreadable: 0 };
2398
+ errorCode = void 0;
1812
2399
  }
1813
- const entries = [];
1814
- let unreadable = 0;
1815
- for (const line of raw.split("\n")) {
1816
- if (!line.trim())
2400
+ return new AscendaApiError2(response.status, errorCode, body);
2401
+ }
2402
+ async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
2403
+ const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
2404
+ method: "POST",
2405
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2406
+ signal
2407
+ });
2408
+ if (response.status === 401)
2409
+ return null;
2410
+ if (!response.ok)
2411
+ throw new AscendaApiError2(response.status, void 0, await response.text());
2412
+ return await response.json();
2413
+ }
2414
+ function isDeliveredStatus(value) {
2415
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
2416
+ }
2417
+ function readSuccessBody(body) {
2418
+ let parsed;
2419
+ try {
2420
+ parsed = JSON.parse(body);
2421
+ } catch {
2422
+ return { duplicates: 0 };
2423
+ }
2424
+ if (!parsed || typeof parsed !== "object")
2425
+ return { duplicates: 0 };
2426
+ const single = parsed.status;
2427
+ if (isDeliveredStatus(single))
2428
+ return { duplicates: single === "duplicate" ? 1 : 0 };
2429
+ const raw = parsed.results;
2430
+ if (!Array.isArray(raw))
2431
+ return { duplicates: 0 };
2432
+ const results = [];
2433
+ for (const item of raw) {
2434
+ if (!item || typeof item !== "object")
2435
+ continue;
2436
+ const { index, status, reason } = item;
2437
+ if (typeof index !== "number" || typeof status !== "string")
1817
2438
  continue;
2439
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
2440
+ }
2441
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
2442
+ }
2443
+ function isRetryableStatus(status) {
2444
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
2445
+ }
2446
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
2447
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
2448
+ }
2449
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
2450
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
2451
+ }
2452
+ async function sendIngest(url, eventWriteToken, body, signal) {
2453
+ try {
2454
+ const response = await fetch(url, {
2455
+ method: "POST",
2456
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2457
+ body,
2458
+ signal
2459
+ });
2460
+ return parseIngestResponse(response);
2461
+ } catch (error) {
2462
+ return {
2463
+ result: "transport_error",
2464
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
2465
+ };
2466
+ }
2467
+ }
2468
+ async function parseIngestResponse(response) {
2469
+ if (response.ok) {
2470
+ const outcome = { result: "accepted", httpStatus: response.status };
2471
+ let read = { duplicates: 0 };
1818
2472
  try {
1819
- const parsed = JSON.parse(line);
1820
- if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1821
- unreadable += 1;
1822
- continue;
1823
- }
1824
- entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
2473
+ read = readSuccessBody(await response.text());
1825
2474
  } catch {
1826
- unreadable += 1;
2475
+ read = { duplicates: 0 };
1827
2476
  }
2477
+ return {
2478
+ ...outcome,
2479
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
2480
+ ...read.results !== void 0 ? { results: read.results } : {}
2481
+ };
1828
2482
  }
1829
- return { entries, unreadable };
2483
+ const body = await response.text();
2484
+ let errorCode;
2485
+ try {
2486
+ errorCode = JSON.parse(body).error;
2487
+ } catch {
2488
+ errorCode = void 0;
2489
+ }
2490
+ const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
2491
+ if (response.status === 401)
2492
+ return { ...base, result: "auth_failed" };
2493
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
2494
+ return { ...base, result: "consent_missing" };
2495
+ if (response.status === 400 || response.status === 422)
2496
+ return { ...base, result: "validation_failed" };
2497
+ return { ...base, result: "transport_error" };
1830
2498
  }
1831
2499
  }
1832
2500
  });
@@ -1856,6 +2524,7 @@ var require_eventSender = __commonJS({
1856
2524
  "use strict";
1857
2525
  Object.defineProperty(exports, "__esModule", { value: true });
1858
2526
  exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
2527
+ exports.buildEventBody = buildEventBody;
1859
2528
  exports.buildEventPayload = buildEventPayload2;
1860
2529
  var afterHours_1 = require_afterHours();
1861
2530
  var tool_contract_1 = require_out();
@@ -1874,12 +2543,10 @@ var require_eventSender = __commonJS({
1874
2543
  }
1875
2544
  };
1876
2545
  exports.AscendaSemanticEventError = AscendaSemanticEventError;
1877
- function buildEventPayload2(identity, mapped) {
2546
+ function buildEventBody(identity, mapped) {
1878
2547
  return {
1879
- toolInstallationId: identity.toolInstallationId,
1880
2548
  source: identity.source,
1881
2549
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1882
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1883
2550
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1884
2551
  sessionId: identity.sessionId ?? void 0,
1885
2552
  workspaceHash: identity.workspaceHash ?? void 0,
@@ -1891,6 +2558,9 @@ var require_eventSender = __commonJS({
1891
2558
  metadata: withCollectorVersion(mapped.metadata)
1892
2559
  };
1893
2560
  }
2561
+ function buildEventPayload2(identity, mapped) {
2562
+ return (0, tool_contract_1.joinEventPayload)({ toolInstallationId: identity.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() }, buildEventBody(identity, mapped));
2563
+ }
1894
2564
  function withCollectorVersion(metadata) {
1895
2565
  return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION };
1896
2566
  }
@@ -1966,12 +2636,10 @@ var require_eventSender = __commonJS({
1966
2636
  if (!mapped.metadata.skillVersion || !mapped.metadata.skillVersion.trim()) {
1967
2637
  throw new AscendaSemanticEventError(`metadata.skillVersion is required for semantic event "${mapped.eventType}".`);
1968
2638
  }
1969
- const payload = {
1970
- toolInstallationId: this.config.toolInstallationId,
2639
+ const body = {
1971
2640
  source: this.config.source,
1972
2641
  eventType: mapped.eventType,
1973
2642
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1974
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1975
2643
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1976
2644
  severity: "low",
1977
2645
  sessionId: this.config.sessionId ?? void 0,
@@ -1982,7 +2650,7 @@ var require_eventSender = __commonJS({
1982
2650
  privacyMode: "metadata_only",
1983
2651
  metadata: withCollectorVersion(mapped.metadata)
1984
2652
  };
1985
- return this.post(payload);
2653
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
1986
2654
  }
1987
2655
  /**
1988
2656
  * Sends a collaboration event under `workflow_telemetry`.
@@ -1997,12 +2665,10 @@ var require_eventSender = __commonJS({
1997
2665
  if (!tool_contract_1.COLLABORATION_EVENT_TYPES.includes(mapped.eventType)) {
1998
2666
  throw new AscendaSemanticEventError(`"${mapped.eventType}" is not a collaboration event type. Use send() for a deterministic host event.`);
1999
2667
  }
2000
- const payload = {
2001
- toolInstallationId: this.config.toolInstallationId,
2668
+ const body = {
2002
2669
  source: this.config.source,
2003
2670
  eventType: mapped.eventType,
2004
2671
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
2005
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
2006
2672
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
2007
2673
  severity: "low",
2008
2674
  sessionId: this.config.sessionId ?? void 0,
@@ -2013,7 +2679,11 @@ var require_eventSender = __commonJS({
2013
2679
  privacyMode: "metadata_only",
2014
2680
  metadata: withCollectorVersion(mapped.metadata)
2015
2681
  };
2016
- return this.post(payload);
2682
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
2683
+ }
2684
+ /** A fresh envelope per event: the key belongs to the event, so every retry of it reuses this one. */
2685
+ envelope() {
2686
+ return { toolInstallationId: this.config.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() };
2017
2687
  }
2018
2688
  /**
2019
2689
  * The single choke point every event passes through, and therefore the only
@@ -2072,11 +2742,34 @@ var require_eventSender = __commonJS({
2072
2742
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
2073
2743
  }
2074
2744
  if (this.isRetryable(outcome)) {
2075
- await new Promise((resolve2) => setTimeout(resolve2, RETRY_DELAY_MS));
2745
+ await new Promise((resolve3) => setTimeout(resolve3, RETRY_DELAY_MS));
2076
2746
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
2077
2747
  }
2078
2748
  return outcome;
2079
2749
  }
2750
+ /**
2751
+ * One outbox pass with nothing live to send: what a background flusher runs,
2752
+ * once per batch. Unlike the pass {@link post} makes, it may run more than
2753
+ * once per sender, because a flusher isn't on anyone's critical path.
2754
+ *
2755
+ * A halted pass is journaled here. Inside {@link post} the live send that
2756
+ * follows journals it, and a flusher has no live send, so without this an
2757
+ * outage would never reach the journal `doctor` and the notices read.
2758
+ */
2759
+ async flushOutbox() {
2760
+ await this.renewIfExpiring();
2761
+ this.outboxServiced = false;
2762
+ this.lastDrain = void 0;
2763
+ const halted = await this.serviceOutbox();
2764
+ if (halted) {
2765
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, halted.result, {
2766
+ httpStatus: halted.httpStatus,
2767
+ errorCode: halted.errorCode,
2768
+ detail: withNote(halted.detail, "kept in outbox")
2769
+ });
2770
+ }
2771
+ return this.lastDrain;
2772
+ }
2080
2773
  /** A failure that never reached a verdict. Replaying can change the answer. */
2081
2774
  isRetryable(outcome) {
2082
2775
  return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
@@ -2336,11 +3029,11 @@ var require_contextRegistry = __commonJS({
2336
3029
  exports.recordWorkContext = recordWorkContext2;
2337
3030
  exports.recordWorkContextAlias = recordWorkContextAlias;
2338
3031
  var fs5 = __importStar(__require("fs"));
2339
- var os5 = __importStar(__require("os"));
3032
+ var os4 = __importStar(__require("os"));
2340
3033
  var path4 = __importStar(__require("path"));
2341
3034
  var MAX_PATHS_PER_ENTRY = 8;
2342
3035
  function workContextRegistryFilePath() {
2343
- return path4.join(os5.homedir(), ".ascenda", "work-contexts.json");
3036
+ return path4.join(os4.homedir(), ".ascenda", "work-contexts.json");
2344
3037
  }
2345
3038
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
2346
3039
  try {
@@ -2403,150 +3096,33 @@ var require_contextRegistry = __commonJS({
2403
3096
  existing.paths.push(update.observedPath);
2404
3097
  dirty = true;
2405
3098
  }
2406
- if (dayOf(existing.lastSeenAt) !== dayOf(nowIso)) {
2407
- existing.lastSeenAt = nowIso;
2408
- dirty = true;
2409
- }
2410
- }
2411
- if (!dirty)
2412
- return false;
2413
- writeRegistry(registryFilePath, registry);
2414
- return true;
2415
- } catch {
2416
- return false;
2417
- }
2418
- }
2419
- function dayOf(iso) {
2420
- return iso.slice(0, 10);
2421
- }
2422
- function writeRegistry(registryFilePath, registry) {
2423
- const dir = path4.dirname(registryFilePath);
2424
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
2425
- const tmp = `${registryFilePath}.${process.pid}.tmp`;
2426
- fs5.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2427
- `, { encoding: "utf8", mode: 384 });
2428
- fs5.renameSync(tmp, registryFilePath);
2429
- if (process.platform !== "win32") {
2430
- fs5.chmodSync(registryFilePath, 384);
2431
- }
2432
- }
2433
- }
2434
- });
2435
-
2436
- // ../packages/tool-kit/out/credentials.js
2437
- var require_credentials = __commonJS({
2438
- "../packages/tool-kit/out/credentials.js"(exports) {
2439
- "use strict";
2440
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2441
- if (k2 === void 0) k2 = k;
2442
- var desc = Object.getOwnPropertyDescriptor(m, k);
2443
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2444
- desc = { enumerable: true, get: function() {
2445
- return m[k];
2446
- } };
2447
- }
2448
- Object.defineProperty(o, k2, desc);
2449
- } : function(o, m, k, k2) {
2450
- if (k2 === void 0) k2 = k;
2451
- o[k2] = m[k];
2452
- });
2453
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2454
- Object.defineProperty(o, "default", { enumerable: true, value: v });
2455
- } : function(o, v) {
2456
- o["default"] = v;
2457
- });
2458
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2459
- var ownKeys = function(o) {
2460
- ownKeys = Object.getOwnPropertyNames || function(o2) {
2461
- var ar = [];
2462
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2463
- return ar;
2464
- };
2465
- return ownKeys(o);
2466
- };
2467
- return function(mod) {
2468
- if (mod && mod.__esModule) return mod;
2469
- var result = {};
2470
- if (mod != null) {
2471
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3099
+ if (dayOf(existing.lastSeenAt) !== dayOf(nowIso)) {
3100
+ existing.lastSeenAt = nowIso;
3101
+ dirty = true;
3102
+ }
2472
3103
  }
2473
- __setModuleDefault(result, mod);
2474
- return result;
2475
- };
2476
- }();
2477
- Object.defineProperty(exports, "__esModule", { value: true });
2478
- exports.credentialsFilePath = credentialsFilePath2;
2479
- exports.readMachineCredentials = readMachineCredentials2;
2480
- exports.writeMachineCredentials = writeMachineCredentials2;
2481
- exports.writeTopLevelCredentials = writeTopLevelCredentials2;
2482
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2483
- exports.readHostCredentials = readHostCredentials;
2484
- exports.writeHostCredentials = writeHostCredentials;
2485
- exports.removeHostCredentials = removeHostCredentials;
2486
- var fs5 = __importStar(__require("fs"));
2487
- var path4 = __importStar(__require("path"));
2488
- var tokenStore_1 = require_tokenStore();
2489
- function credentialsFilePath2() {
2490
- return path4.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2491
- }
2492
- function readMachineCredentials2() {
2493
- try {
2494
- const raw = fs5.readFileSync(credentialsFilePath2(), "utf8").trim();
2495
- if (!raw)
2496
- return void 0;
2497
- const parsed = JSON.parse(raw);
2498
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2499
- return void 0;
2500
- return parsed;
3104
+ if (!dirty)
3105
+ return false;
3106
+ writeRegistry(registryFilePath, registry);
3107
+ return true;
2501
3108
  } catch {
2502
- return void 0;
3109
+ return false;
2503
3110
  }
2504
3111
  }
2505
- function writeMachineCredentials2(credentials) {
2506
- const file = credentialsFilePath2();
2507
- fs5.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
2508
- fs5.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
3112
+ function dayOf(iso) {
3113
+ return iso.slice(0, 10);
3114
+ }
3115
+ function writeRegistry(registryFilePath, registry) {
3116
+ const dir = path4.dirname(registryFilePath);
3117
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
3118
+ const tmp = `${registryFilePath}.${process.pid}.tmp`;
3119
+ fs5.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2509
3120
  `, { encoding: "utf8", mode: 384 });
3121
+ fs5.renameSync(tmp, registryFilePath);
2510
3122
  if (process.platform !== "win32") {
2511
- fs5.chmodSync(path4.dirname(file), 448);
2512
- fs5.chmodSync(file, 384);
3123
+ fs5.chmodSync(registryFilePath, 384);
2513
3124
  }
2514
3125
  }
2515
- function writeTopLevelCredentials2(credentials) {
2516
- const existing = readMachineCredentials2();
2517
- writeMachineCredentials2({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2518
- }
2519
- function isLocalOnlyHostInstall(host, hasToken) {
2520
- const credentials = readHostCredentials(host);
2521
- if (!credentials?.localOnly)
2522
- return false;
2523
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2524
- return false;
2525
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2526
- }
2527
- function readHostCredentials(host) {
2528
- const entry = readMachineCredentials2()?.tools?.[host];
2529
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
2530
- return void 0;
2531
- return entry;
2532
- }
2533
- function writeHostCredentials(host, credentials) {
2534
- const existing = readMachineCredentials2() ?? {};
2535
- writeMachineCredentials2({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2536
- }
2537
- function removeHostCredentials(host) {
2538
- const existing = readMachineCredentials2();
2539
- if (!existing?.tools || !(host in existing.tools))
2540
- return;
2541
- const tools = { ...existing.tools };
2542
- delete tools[host];
2543
- const next = { ...existing };
2544
- if (Object.keys(tools).length)
2545
- next.tools = tools;
2546
- else
2547
- delete next.tools;
2548
- writeMachineCredentials2(next);
2549
- }
2550
3126
  }
2551
3127
  });
2552
3128
 
@@ -2593,6 +3169,8 @@ var require_forgeProject = __commonJS({
2593
3169
  }();
2594
3170
  Object.defineProperty(exports, "__esModule", { value: true });
2595
3171
  exports.forgeProjectHash = forgeProjectHash;
3172
+ exports.forgeRepoKey = forgeRepoKey;
3173
+ exports.forgeBranchKey = forgeBranchKey;
2596
3174
  exports.parseForgeFullName = parseForgeFullName;
2597
3175
  exports.readForgeFullName = readForgeFullName;
2598
3176
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
@@ -2608,6 +3186,19 @@ var require_forgeProject = __commonJS({
2608
3186
  }
2609
3187
  return h.toString(16).padStart(8, "0");
2610
3188
  }
3189
+ function forgeRepoKey(fullName) {
3190
+ return forgeProjectHash(fullName.toLowerCase());
3191
+ }
3192
+ function forgeBranchKey(fullName, branch) {
3193
+ const input = `${fullName.toLowerCase()}
3194
+ ${branch}`;
3195
+ let h = 0xcbf29ce484222325n;
3196
+ for (const byte of Buffer.from(input, "utf8")) {
3197
+ h ^= BigInt(byte);
3198
+ h = BigInt.asUintN(64, h * 0x100000001b3n);
3199
+ }
3200
+ return h.toString(16).padStart(16, "0");
3201
+ }
2611
3202
  function parseForgeFullName(remoteUrl) {
2612
3203
  if (!remoteUrl)
2613
3204
  return null;
@@ -2994,6 +3585,95 @@ var require_workContext = __commonJS({
2994
3585
  }
2995
3586
  });
2996
3587
 
3588
+ // ../packages/tool-kit/out/forgeKeys.js
3589
+ var require_forgeKeys = __commonJS({
3590
+ "../packages/tool-kit/out/forgeKeys.js"(exports) {
3591
+ "use strict";
3592
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3593
+ if (k2 === void 0) k2 = k;
3594
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3595
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3596
+ desc = { enumerable: true, get: function() {
3597
+ return m[k];
3598
+ } };
3599
+ }
3600
+ Object.defineProperty(o, k2, desc);
3601
+ } : function(o, m, k, k2) {
3602
+ if (k2 === void 0) k2 = k;
3603
+ o[k2] = m[k];
3604
+ });
3605
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3606
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3607
+ } : function(o, v) {
3608
+ o["default"] = v;
3609
+ });
3610
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3611
+ var ownKeys = function(o) {
3612
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3613
+ var ar = [];
3614
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3615
+ return ar;
3616
+ };
3617
+ return ownKeys(o);
3618
+ };
3619
+ return function(mod) {
3620
+ if (mod && mod.__esModule) return mod;
3621
+ var result = {};
3622
+ if (mod != null) {
3623
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3624
+ }
3625
+ __setModuleDefault(result, mod);
3626
+ return result;
3627
+ };
3628
+ }();
3629
+ Object.defineProperty(exports, "__esModule", { value: true });
3630
+ exports.REPO_KEYS_ENV_VAR = void 0;
3631
+ exports.repoKeysEnabled = repoKeysEnabled;
3632
+ exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd2;
3633
+ var fs5 = __importStar(__require("fs"));
3634
+ var path4 = __importStar(__require("path"));
3635
+ var credentials_1 = require_credentials();
3636
+ var forgeProject_1 = require_forgeProject();
3637
+ var workContext_1 = require_workContext();
3638
+ exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
3639
+ function repoKeysEnabled() {
3640
+ const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
3641
+ if (env === "off" || env === "0" || env === "false")
3642
+ return false;
3643
+ if (env === "on" || env === "1" || env === "true")
3644
+ return true;
3645
+ return (0, credentials_1.readMachineCredentials)()?.repoKeys !== false;
3646
+ }
3647
+ function readDefaultBranch(repositoryRoot) {
3648
+ try {
3649
+ const head = fs5.readFileSync(path4.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
3650
+ const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
3651
+ return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
3652
+ } catch {
3653
+ return null;
3654
+ }
3655
+ }
3656
+ function deriveForgeKeysForCwd2(cwd) {
3657
+ try {
3658
+ if (!cwd || !repoKeysEnabled())
3659
+ return {};
3660
+ const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
3661
+ const fullName = (0, forgeProject_1.readForgeFullName)(root);
3662
+ if (!root || !fullName)
3663
+ return {};
3664
+ const branch = (0, workContext_1.readBranchName)(cwd);
3665
+ const onDefault = branch !== null && branch === readDefaultBranch(root);
3666
+ return {
3667
+ repoKey: (0, forgeProject_1.forgeRepoKey)(fullName),
3668
+ ...branch && !onDefault ? { branchKey: (0, forgeProject_1.forgeBranchKey)(fullName, branch) } : {}
3669
+ };
3670
+ } catch {
3671
+ return {};
3672
+ }
3673
+ }
3674
+ }
3675
+ });
3676
+
2997
3677
  // ../packages/tool-kit/out/hookAdapter.js
2998
3678
  var require_hookAdapter = __commonJS({
2999
3679
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
@@ -3003,13 +3683,18 @@ var require_hookAdapter = __commonJS({
3003
3683
  exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
3004
3684
  exports.resolveContextHashes = resolveContextHashes;
3005
3685
  exports.loadCliAgentConfig = loadCliAgentConfig;
3686
+ exports.withForgeKeys = withForgeKeys;
3687
+ exports.withPromptId = withPromptId;
3006
3688
  exports.deliverHookEvents = deliverHookEvents;
3689
+ exports.flushHookOutbox = flushHookOutbox;
3007
3690
  var contextRegistry_1 = require_contextRegistry();
3008
3691
  var credentials_1 = require_credentials();
3009
3692
  var forgeProject_1 = require_forgeProject();
3010
3693
  var eventLog_1 = require_eventLog();
3694
+ var forgeKeys_1 = require_forgeKeys();
3011
3695
  var eventSender_1 = require_eventSender();
3012
3696
  var stateStore_1 = require_stateStore();
3697
+ var backgroundDelivery_1 = require_backgroundDelivery();
3013
3698
  var tokenStore_1 = require_tokenStore();
3014
3699
  var workContext_1 = require_workContext();
3015
3700
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -3062,6 +3747,19 @@ var require_hookAdapter = __commonJS({
3062
3747
  };
3063
3748
  }
3064
3749
  function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
3750
+ const pairing = loadCliAgentPairing(toolType, identity);
3751
+ const contextHashes = resolveContextHashes(cwd);
3752
+ return {
3753
+ ...pairing,
3754
+ // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3755
+ // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3756
+ // an empty string, grouping unrelated rows under a value naming no session.
3757
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3758
+ workspaceHash: contextHashes.workspaceHash,
3759
+ projectHash: contextHashes.projectHash
3760
+ };
3761
+ }
3762
+ function loadCliAgentPairing(toolType, identity) {
3065
3763
  const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
3066
3764
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3067
3765
  const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
@@ -3072,29 +3770,40 @@ var require_hookAdapter = __commonJS({
3072
3770
  throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
3073
3771
  if (!fileToken)
3074
3772
  (0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3075
- const contextHashes = resolveContextHashes(cwd);
3076
3773
  return {
3077
3774
  apiBaseUrl,
3078
3775
  toolInstallationId,
3079
3776
  eventWriteToken,
3080
3777
  tokenFilePath,
3081
- // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3082
- // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3083
- // an empty string, grouping unrelated rows under a value naming no session.
3084
- sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3085
- workspaceHash: contextHashes.workspaceHash,
3086
- projectHash: contextHashes.projectHash,
3087
3778
  // Agents await command hooks; fail fast rather than stall the user's turn.
3088
3779
  timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
3089
3780
  };
3090
3781
  }
3782
+ function withForgeKeys(events, cwd) {
3783
+ const keys = (0, forgeKeys_1.deriveForgeKeysForCwd)(cwd ?? process.cwd());
3784
+ if (!keys.repoKey)
3785
+ return events;
3786
+ return events.map((event) => ({ ...event, metadata: { ...keys, ...event.metadata } }));
3787
+ }
3788
+ function withPromptId(events, promptId) {
3789
+ if (!promptId)
3790
+ return events;
3791
+ return events.map((event) => ({ ...event, metadata: { promptId, ...event.metadata } }));
3792
+ }
3091
3793
  async function deliverHookEvents(events, options) {
3092
3794
  if (events.length === 0)
3093
3795
  return;
3094
- const notice = options.onNotice ?? ((message) => console.error(message));
3796
+ events = withPromptId(events, options.promptId);
3797
+ if (options.forgeKeys)
3798
+ events = withForgeKeys(events, options.cwd);
3799
+ const notice = options.onNotice ?? ((message2) => console.error(message2));
3095
3800
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3096
- if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken))
3801
+ if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3802
+ const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
3803
+ if (logFile)
3804
+ logUnsent2(logFile, events, options);
3097
3805
  return;
3806
+ }
3098
3807
  let config;
3099
3808
  try {
3100
3809
  config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
@@ -3104,20 +3813,7 @@ var require_hookAdapter = __commonJS({
3104
3813
  const logFile = (0, eventLog_1.resolveEventLogPath)();
3105
3814
  if (!logFile)
3106
3815
  throw error;
3107
- const contextHashes = resolveContextHashes(options.cwd);
3108
- for (const event of events) {
3109
- (0, eventLog_1.appendEventLog)(logFile, {
3110
- loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3111
- delivery: "not_sent",
3112
- payload: (0, eventSender_1.buildEventPayload)({
3113
- toolInstallationId: `${options.toolType}:unpaired`,
3114
- source: options.source,
3115
- sessionId: options.sessionId ?? null,
3116
- workspaceHash: contextHashes.workspaceHash,
3117
- projectHash: contextHashes.projectHash
3118
- }, event)
3119
- });
3120
- }
3816
+ logUnsent2(logFile, events, options);
3121
3817
  return;
3122
3818
  }
3123
3819
  const sender = new eventSender_1.AscendaEventSender({
@@ -3131,21 +3827,71 @@ var require_hookAdapter = __commonJS({
3131
3827
  projectHash: config.projectHash,
3132
3828
  timeoutMs: config.timeoutMs
3133
3829
  });
3134
- for (const event of events) {
3135
- const result = await sender.send(event);
3136
- if (result === "accepted")
3137
- continue;
3138
- if (result === "consent_missing") {
3139
- notice("Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.");
3140
- } else if (result === "auth_failed") {
3141
- notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
3142
- } else if (result === "transport_error") {
3143
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
3144
- } else {
3145
- notice(`Ascenda telemetry rejected: ${result}`);
3830
+ if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
3831
+ for (const event of events) {
3832
+ const result = await sender.send(event);
3833
+ if (result === "accepted")
3834
+ continue;
3835
+ const message2 = noticeFor(result);
3836
+ if (message2)
3837
+ notice(message2);
3838
+ return;
3146
3839
  }
3147
3840
  return;
3148
3841
  }
3842
+ for (const event of events)
3843
+ sender.queue(event);
3844
+ (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
3845
+ const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
3846
+ const message = last ? noticeFor(last) : void 0;
3847
+ if (message)
3848
+ notice(message);
3849
+ }
3850
+ function noticeFor(result) {
3851
+ if (result === "accepted" || result === "duplicate")
3852
+ return void 0;
3853
+ if (result === "consent_missing")
3854
+ return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
3855
+ if (result === "auth_failed")
3856
+ return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
3857
+ if (result === "transport_error")
3858
+ return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
3859
+ if (result === "outbox_discarded")
3860
+ return void 0;
3861
+ return `Ascenda telemetry rejected: ${result}`;
3862
+ }
3863
+ async function flushHookOutbox(options) {
3864
+ let config;
3865
+ try {
3866
+ config = loadCliAgentPairing(options.toolType, options);
3867
+ } catch {
3868
+ return;
3869
+ }
3870
+ const sender = new eventSender_1.AscendaEventSender({
3871
+ apiBaseUrl: config.apiBaseUrl,
3872
+ toolInstallationId: config.toolInstallationId,
3873
+ source: options.source,
3874
+ eventWriteToken: config.eventWriteToken,
3875
+ tokenFilePath: config.tokenFilePath,
3876
+ timeoutMs: config.timeoutMs
3877
+ });
3878
+ await (0, backgroundDelivery_1.runOutboxFlush)(sender);
3879
+ }
3880
+ function logUnsent2(logFile, events, options) {
3881
+ const contextHashes = resolveContextHashes(options.cwd);
3882
+ for (const event of events) {
3883
+ (0, eventLog_1.appendEventLog)(logFile, {
3884
+ loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3885
+ delivery: "not_sent",
3886
+ payload: (0, eventSender_1.buildEventPayload)({
3887
+ toolInstallationId: `${options.toolType}:unpaired`,
3888
+ source: options.source,
3889
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || options.sessionId || null,
3890
+ workspaceHash: contextHashes.workspaceHash,
3891
+ projectHash: contextHashes.projectHash
3892
+ }, event)
3893
+ });
3894
+ }
3149
3895
  }
3150
3896
  function journalSkippedSend2(host, error) {
3151
3897
  const who = host ? `${host}: ` : "";
@@ -3312,7 +4058,7 @@ var require_studyJoin = __commonJS({
3312
4058
  const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3313
4059
  const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3314
4060
  while (Date.now() < deadline) {
3315
- await new Promise((resolve2) => setTimeout(resolve2, pollIntervalMs));
4061
+ await new Promise((resolve3) => setTimeout(resolve3, pollIntervalMs));
3316
4062
  let poll;
3317
4063
  try {
3318
4064
  poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
@@ -3375,7 +4121,7 @@ var require_studyJoin = __commonJS({
3375
4121
  return true;
3376
4122
  }
3377
4123
  function askChoice(stdin, stdout) {
3378
- return new Promise((resolve2) => {
4124
+ return new Promise((resolve3) => {
3379
4125
  const rl = readline.createInterface({ input: stdin, output: stdout });
3380
4126
  let settled = false;
3381
4127
  const finish = (value) => {
@@ -3383,7 +4129,7 @@ var require_studyJoin = __commonJS({
3383
4129
  return;
3384
4130
  settled = true;
3385
4131
  rl.close();
3386
- resolve2(value.trim());
4132
+ resolve3(value.trim());
3387
4133
  };
3388
4134
  rl.question("Choice [Not now]: ", finish);
3389
4135
  rl.once("close", () => finish(""));
@@ -3631,52 +4377,6 @@ var require_initiatives = __commonJS({
3631
4377
  }
3632
4378
  });
3633
4379
 
3634
- // ../packages/tool-kit/out/setupDisclosure.js
3635
- var require_setupDisclosure = __commonJS({
3636
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3637
- "use strict";
3638
- Object.defineProperty(exports, "__esModule", { value: true });
3639
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3640
- exports.renderSetupDisclosure = renderSetupDisclosure3;
3641
- exports.FAMILY_SENTENCES = {
3642
- session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
3643
- counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
3644
- tools: "the name of each tool your agent calls",
3645
- outcome: "whether a call succeeded, failed, or was interrupted",
3646
- clock: "your machine's offset from UTC, so an evening is read as an evening",
3647
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3648
- model: "which model served the session, by name and by tier",
3649
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3650
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
3651
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3652
- context: "how full the context window got",
3653
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3654
- subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
3655
- reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
3656
- };
3657
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3658
- exports.REFUSALS = [
3659
- "Never your prompts, your agent's replies, or anything inside a file.",
3660
- "Never a file path, a command line, or a repository or branch name.",
3661
- "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
3662
- ];
3663
- exports.FREE_TEXT_KEYS = ["message"];
3664
- function renderSetupDisclosure3({ sends, displayName }) {
3665
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3666
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3667
- const lines = [
3668
- `What this sends from ${displayName}, once paired:`,
3669
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3670
- "",
3671
- ...exports.REFUSALS.map((line) => ` ${line}`),
3672
- "",
3673
- " Turn it off by revoking this tool in the Ascenda app."
3674
- ];
3675
- return lines.join("\n");
3676
- }
3677
- }
3678
- });
3679
-
3680
4380
  // ../packages/tool-kit/out/hookRunner.js
3681
4381
  var require_hookRunner = __commonJS({
3682
4382
  "../packages/tool-kit/out/hookRunner.js"(exports) {
@@ -3721,9 +4421,11 @@ var require_hookRunner = __commonJS({
3721
4421
  Object.defineProperty(exports, "__esModule", { value: true });
3722
4422
  exports.hookRunnerPaths = hookRunnerPaths;
3723
4423
  exports.hookLauncherScript = hookLauncherScript2;
4424
+ exports.isDowngrade = isDowngrade;
3724
4425
  exports.installHookRunner = installHookRunner2;
3725
4426
  exports.removeHookRunner = removeHookRunner;
3726
4427
  exports.hookRunnerCommand = hookRunnerCommand2;
4428
+ exports.writeAtomically = writeAtomically;
3727
4429
  exports.lastHookPath = lastHookPath;
3728
4430
  exports.stampLastHook = stampLastHook2;
3729
4431
  exports.readLastHook = readLastHook2;
@@ -3733,10 +4435,11 @@ var require_hookRunner = __commonJS({
3733
4435
  var child_process_1 = __require("child_process");
3734
4436
  var fs5 = __importStar(__require("fs"));
3735
4437
  var path4 = __importStar(__require("path"));
4438
+ var collectorVersion_1 = require_collectorVersion();
3736
4439
  var tokenStore_1 = require_tokenStore();
3737
4440
  function hookRunnerPaths(binaryName) {
3738
4441
  const launcher = path4.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3739
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
4442
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
3740
4443
  }
3741
4444
  var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3742
4445
  function hookLauncherScript2(options) {
@@ -3830,21 +4533,57 @@ var require_hookRunner = __commonJS({
3830
4533
  ""
3831
4534
  ].join("\n");
3832
4535
  }
4536
+ function releaseOf(version) {
4537
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version ?? "").trim());
4538
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
4539
+ }
4540
+ function isDowngrade(installed, incoming) {
4541
+ const have = releaseOf(installed);
4542
+ const want = releaseOf(incoming);
4543
+ if (!have || !want)
4544
+ return false;
4545
+ for (let i = 0; i < 3; i++) {
4546
+ if (have[i] !== want[i])
4547
+ return have[i] > want[i];
4548
+ }
4549
+ return false;
4550
+ }
4551
+ function readInstalledVersion(file) {
4552
+ try {
4553
+ return fs5.readFileSync(file, "utf8").trim() || void 0;
4554
+ } catch {
4555
+ return void 0;
4556
+ }
4557
+ }
3833
4558
  function installHookRunner2(options) {
3834
4559
  const paths = hookRunnerPaths(options.binaryName);
3835
4560
  if (options.dryRun)
3836
4561
  return paths.launcher;
3837
4562
  const source = path4.resolve(options.source ?? process.argv[1]);
4563
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
4564
+ const installed = readInstalledVersion(paths.version);
4565
+ const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
4566
+ if (installed && fs5.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4567
+ options.onKeptNewer?.(installed, incoming);
4568
+ if (process.platform !== "win32" && !fs5.existsSync(paths.launcher))
4569
+ writeAtomically(paths.launcher, hookLauncherScript2(options), 493);
4570
+ return paths.launcher;
4571
+ }
3838
4572
  fs5.mkdirSync(path4.dirname(paths.launcher), { recursive: true });
3839
4573
  if (process.platform === "win32") {
3840
4574
  if (source !== path4.resolve(paths.launcher))
3841
4575
  fs5.copyFileSync(source, paths.launcher);
4576
+ writeAtomically(paths.version, `${incoming}
4577
+ `, 420);
3842
4578
  return paths.launcher;
3843
4579
  }
3844
4580
  if (source !== path4.resolve(paths.bundle))
3845
4581
  writeAtomically(paths.bundle, fs5.readFileSync(source), 493);
3846
4582
  writeAtomically(paths.launcher, hookLauncherScript2(options), 493);
3847
4583
  writeAtomically(paths.record, `${process.execPath}
4584
+ `, 420);
4585
+ if (source !== path4.resolve(paths.bundle))
4586
+ writeAtomically(paths.version, `${incoming}
3848
4587
  `, 420);
3849
4588
  fs5.rmSync(paths.noNode, { force: true });
3850
4589
  return paths.launcher;
@@ -3859,8 +4598,8 @@ var require_hookRunner = __commonJS({
3859
4598
  }
3860
4599
  return removed;
3861
4600
  }
3862
- function hookRunnerCommand2(launcher) {
3863
- return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4601
+ function hookRunnerCommand2(launcher, platform = process.platform) {
4602
+ return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
3864
4603
  }
3865
4604
  function writeAtomically(target, contents, mode) {
3866
4605
  const tmp = `${target}.${process.pid}.tmp`;
@@ -3930,6 +4669,115 @@ var require_hookRunner = __commonJS({
3930
4669
  }
3931
4670
  });
3932
4671
 
4672
+ // ../packages/tool-kit/out/settingsFile.js
4673
+ var require_settingsFile = __commonJS({
4674
+ "../packages/tool-kit/out/settingsFile.js"(exports) {
4675
+ "use strict";
4676
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4677
+ if (k2 === void 0) k2 = k;
4678
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4679
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4680
+ desc = { enumerable: true, get: function() {
4681
+ return m[k];
4682
+ } };
4683
+ }
4684
+ Object.defineProperty(o, k2, desc);
4685
+ } : function(o, m, k, k2) {
4686
+ if (k2 === void 0) k2 = k;
4687
+ o[k2] = m[k];
4688
+ });
4689
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4690
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4691
+ } : function(o, v) {
4692
+ o["default"] = v;
4693
+ });
4694
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4695
+ var ownKeys = function(o) {
4696
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4697
+ var ar = [];
4698
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4699
+ return ar;
4700
+ };
4701
+ return ownKeys(o);
4702
+ };
4703
+ return function(mod) {
4704
+ if (mod && mod.__esModule) return mod;
4705
+ var result = {};
4706
+ if (mod != null) {
4707
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4708
+ }
4709
+ __setModuleDefault(result, mod);
4710
+ return result;
4711
+ };
4712
+ }();
4713
+ Object.defineProperty(exports, "__esModule", { value: true });
4714
+ exports.replaceSettingsFile = replaceSettingsFile2;
4715
+ var fs5 = __importStar(__require("fs"));
4716
+ var path4 = __importStar(__require("path"));
4717
+ var hookRunner_1 = require_hookRunner();
4718
+ function replaceSettingsFile2(settingsFile, contents) {
4719
+ const exists = fs5.existsSync(settingsFile);
4720
+ const target = exists ? fs5.realpathSync(settingsFile) : settingsFile;
4721
+ if (exists) {
4722
+ const backup = `${settingsFile}.ascenda-backup`;
4723
+ if (!fs5.existsSync(backup))
4724
+ fs5.copyFileSync(target, backup);
4725
+ }
4726
+ fs5.mkdirSync(path4.dirname(target), { recursive: true });
4727
+ const mode = exists ? fs5.statSync(target).mode & 511 : 420;
4728
+ (0, hookRunner_1.writeAtomically)(target, contents, mode);
4729
+ }
4730
+ }
4731
+ });
4732
+
4733
+ // ../packages/tool-kit/out/setupDisclosure.js
4734
+ var require_setupDisclosure = __commonJS({
4735
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
4736
+ "use strict";
4737
+ Object.defineProperty(exports, "__esModule", { value: true });
4738
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
4739
+ exports.renderSetupDisclosure = renderSetupDisclosure3;
4740
+ exports.FAMILY_SENTENCES = {
4741
+ 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",
4742
+ 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",
4743
+ tools: "the name of each tool your agent calls",
4744
+ outcome: "whether a call succeeded, failed, or was interrupted",
4745
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
4746
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
4747
+ model: "which model served the session, by name and by tier",
4748
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
4749
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
4750
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
4751
+ context: "how full the context window got",
4752
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, input_request, idle_prompt, or other, and that it asked permission for a tool or had one refused in auto mode, with the tool's name",
4753
+ 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",
4754
+ forge: "for a GitHub repository, one digest of owner/repo and one of the branch, which anyone who guesses the names can reproduce, so a pull request can be matched to your session (turn off with setup --no-repo-keys)",
4755
+ turns: "an opaque id your agent gives each prompt, so one turn's events group together",
4756
+ 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"
4757
+ };
4758
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
4759
+ exports.REFUSALS = [
4760
+ "Never your prompts, your agent's replies, or anything inside a file.",
4761
+ "Never a file path, a command line, or a repository or branch name.",
4762
+ "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."
4763
+ ];
4764
+ exports.FREE_TEXT_KEYS = ["message"];
4765
+ function renderSetupDisclosure3({ sends, displayName }) {
4766
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
4767
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
4768
+ const lines = [
4769
+ `What this sends from ${displayName}, once paired:`,
4770
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
4771
+ "",
4772
+ ...exports.REFUSALS.map((line) => ` ${line}`),
4773
+ "",
4774
+ " Turn it off by revoking this tool in the Ascenda app."
4775
+ ];
4776
+ return lines.join("\n");
4777
+ }
4778
+ }
4779
+ });
4780
+
3933
4781
  // ../packages/tool-kit/out/saverHandoff.js
3934
4782
  var require_saverHandoff = __commonJS({
3935
4783
  "../packages/tool-kit/out/saverHandoff.js"(exports) {
@@ -3983,11 +4831,11 @@ var require_saverHandoff = __commonJS({
3983
4831
  exports.probeSocket = probeSocket;
3984
4832
  var fs5 = __importStar(__require("fs"));
3985
4833
  var net = __importStar(__require("net"));
3986
- var os5 = __importStar(__require("os"));
4834
+ var os4 = __importStar(__require("os"));
3987
4835
  var path4 = __importStar(__require("path"));
3988
4836
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3989
4837
  function saverContainerDir() {
3990
- return process.env.ASCENDA_SAVER_CONTAINER ?? path4.join(os5.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
4838
+ return process.env.ASCENDA_SAVER_CONTAINER ?? path4.join(os4.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
3991
4839
  }
3992
4840
  function saverSupportDir() {
3993
4841
  return path4.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
@@ -4069,14 +4917,14 @@ var require_saverHandoff = __commonJS({
4069
4917
  }
4070
4918
  }
4071
4919
  function probeSocket(socketPath, timeoutMs = 300) {
4072
- return new Promise((resolve2) => {
4920
+ return new Promise((resolve3) => {
4073
4921
  try {
4074
4922
  if (!fs5.statSync(socketPath).isSocket()) {
4075
- resolve2("absent");
4923
+ resolve3("absent");
4076
4924
  return;
4077
4925
  }
4078
4926
  } catch {
4079
- resolve2("absent");
4927
+ resolve3("absent");
4080
4928
  return;
4081
4929
  }
4082
4930
  let settled = false;
@@ -4086,7 +4934,7 @@ var require_saverHandoff = __commonJS({
4086
4934
  settled = true;
4087
4935
  clearTimeout(timer);
4088
4936
  socket.destroy();
4089
- resolve2(state);
4937
+ resolve3(state);
4090
4938
  };
4091
4939
  const socket = net.createConnection(socketPath);
4092
4940
  const timer = setTimeout(() => finish("unreachable"), timeoutMs);
@@ -4148,7 +4996,7 @@ var require_liveBus = __commonJS({
4148
4996
  exports.deliverLine = deliverLine;
4149
4997
  var fs5 = __importStar(__require("fs"));
4150
4998
  var net = __importStar(__require("net"));
4151
- var os5 = __importStar(__require("os"));
4999
+ var os4 = __importStar(__require("os"));
4152
5000
  var path4 = __importStar(__require("path"));
4153
5001
  var hookSet_1 = require_hookSet();
4154
5002
  var saverHandoff_1 = require_saverHandoff();
@@ -4160,7 +5008,7 @@ var require_liveBus = __commonJS({
4160
5008
  const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
4161
5009
  if (override)
4162
5010
  return [override];
4163
- const home = os5.homedir();
5011
+ const home = os4.homedir();
4164
5012
  return [
4165
5013
  path4.join(home, ".ascenda", "live.sock"),
4166
5014
  path4.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
@@ -4210,10 +5058,10 @@ var require_liveBus = __commonJS({
4210
5058
  });
4211
5059
  }
4212
5060
  function deliverLine(line) {
4213
- return new Promise((resolve2) => {
5061
+ return new Promise((resolve3) => {
4214
5062
  const candidates = existingSocketCandidates();
4215
5063
  if (candidates.length === 0) {
4216
- resolve2(void 0);
5064
+ resolve3(void 0);
4217
5065
  return;
4218
5066
  }
4219
5067
  let settled = false;
@@ -4232,7 +5080,7 @@ var require_liveBus = __commonJS({
4232
5080
  settled = true;
4233
5081
  clearTimeout(timer);
4234
5082
  drop();
4235
- resolve2(accepted);
5083
+ resolve3(accepted);
4236
5084
  };
4237
5085
  const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4238
5086
  const tryFrom = (index) => {
@@ -4432,7 +5280,7 @@ var require_liveSignalDoctor = __commonJS({
4432
5280
  if (accepted !== saverSocket)
4433
5281
  return { tone: "ok", text: `the desktop app took it (${accepted})` };
4434
5282
  for (let waited = 0; waited < 2e3; waited += 100) {
4435
- await new Promise((resolve2) => setTimeout(resolve2, 100));
5283
+ await new Promise((resolve3) => setTimeout(resolve3, 100));
4436
5284
  const answered = (0, saverHandoff_1.readSaverStatuses)().find((status) => status.lastPingSession === session);
4437
5285
  if (answered)
4438
5286
  return { tone: "ok", text: `OK. The screen saver (pid ${answered.pid}) received it` };
@@ -4695,18 +5543,22 @@ var require_cliAgentSetup = __commonJS({
4695
5543
  exports.runCliAgentSetup = runCliAgentSetup;
4696
5544
  exports.writeHookSettings = writeHookSettings;
4697
5545
  exports.registeredHookSets = registeredHookSets;
5546
+ exports.ourHookPositions = ourHookPositions;
5547
+ exports.trustProblemLines = trustProblemLines;
4698
5548
  exports.findStaleHookCommands = findStaleHookCommands2;
4699
5549
  exports.cliAgentRegistrations = cliAgentRegistrations;
4700
5550
  var crypto2 = __importStar(__require("crypto"));
4701
5551
  var fs5 = __importStar(__require("fs"));
4702
- var os5 = __importStar(__require("os"));
5552
+ var os4 = __importStar(__require("os"));
4703
5553
  var path4 = __importStar(__require("path"));
4704
5554
  var collectorVersion_1 = require_collectorVersion();
4705
5555
  var credentials_1 = require_credentials();
5556
+ var eventLog_1 = require_eventLog();
4706
5557
  var hookAdapter_1 = require_hookAdapter();
4707
5558
  var http_1 = require_http();
4708
5559
  var hookSet_1 = require_hookSet();
4709
5560
  var initiatives_1 = require_initiatives();
5561
+ var settingsFile_1 = require_settingsFile();
4710
5562
  var setupDisclosure_1 = require_setupDisclosure();
4711
5563
  var hookRunner_1 = require_hookRunner();
4712
5564
  var liveSignalDoctor_1 = require_liveSignalDoctor();
@@ -4723,7 +5575,7 @@ var require_cliAgentSetup = __commonJS({
4723
5575
  return (0, hookRunner_1.hookRunnerPaths)(binaryName).launcher;
4724
5576
  }
4725
5577
  function cliAgentSelfCommand(spec) {
4726
- return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName), os5.homedir());
5578
+ return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName), os4.homedir());
4727
5579
  }
4728
5580
  function usage(spec) {
4729
5581
  return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
@@ -4741,6 +5593,12 @@ Options
4741
5593
  --tool-installation-id <id> reuse an existing pairing instead of creating one
4742
5594
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
4743
5595
  --no-pair install without pairing: local features on, nothing sent
5596
+ --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
5597
+ On by default when not paired; machine-wide, shared by every agent
5598
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
5599
+ repository gets a key and, off its default branch, a branch key, so a pull
5600
+ request can be matched to a session. They are digests anyone who guesses the
5601
+ names can reproduce. Machine-wide. --repo-keys turns them back on
4744
5602
  --scope user|project where hooks are registered (default user: every project)
4745
5603
  --project-dir <path> project root for --scope project (default cwd)
4746
5604
  --dry-run print what would change, write nothing
@@ -4784,9 +5642,9 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4784
5642
  const binary = installBinary2(spec, options.dryRun);
4785
5643
  const node = options.dryRun || process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
4786
5644
  if (node?.problem)
4787
- row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os5.homedir())}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
5645
+ row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os4.homedir())}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
4788
5646
  else
4789
- row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os5.homedir())}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
5647
+ row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os4.homedir())}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
4790
5648
  if (!options.dryRun) {
4791
5649
  const now = (/* @__PURE__ */ new Date()).toISOString();
4792
5650
  const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
@@ -4795,6 +5653,10 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4795
5653
  toolInstallationId,
4796
5654
  ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4797
5655
  });
5656
+ if (options.eventLog !== void 0)
5657
+ (0, credentials_1.writeEventLogSetting)(options.eventLog);
5658
+ if (options.repoKeys !== void 0)
5659
+ (0, credentials_1.writeRepoKeysSetting)(options.repoKeys);
4798
5660
  }
4799
5661
  if (isHomeProject2(options)) {
4800
5662
  detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
@@ -4806,18 +5668,18 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4806
5668
  if (written === null)
4807
5669
  return 1;
4808
5670
  const reach = options.scope === "user" ? "every project" : "this project only";
4809
- row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile, os5.homedir())} ${ui.dim(`(${spec.hookEvents.length} events, ${reach}${written ? "" : ", already current"})`)}`);
5671
+ row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile, os4.homedir())} ${ui.dim(`(${spec.hookEvents.length} events, ${reach}${written ? "" : ", already current"})`)}`);
4810
5672
  const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
4811
5673
  if (changes)
4812
5674
  detail("", changes);
4813
5675
  const otherFile = spec.settings.settingsPath(options.scope === "user" ? "project" : "user", options.projectDir);
4814
5676
  if (otherFile !== settingsFile && registeredHookSets(readSettings(otherFile), spec).size > 0) {
4815
5677
  if (options.dryRun) {
4816
- row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os5.homedir())}, so each event runs once`);
5678
+ row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())}, so each event runs once`);
4817
5679
  } else if (removeOurHookEntries(otherFile, spec)) {
4818
- row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os5.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
5680
+ row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
4819
5681
  } else {
4820
- row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os5.homedir())} registers these hooks too, so each event runs twice.`);
5682
+ row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())} registers these hooks too, so each event runs twice.`);
4821
5683
  detail("", `Remove the ${spec.binaryName} entries from one of the two files.`);
4822
5684
  }
4823
5685
  }
@@ -4828,7 +5690,12 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4828
5690
  row("info", "pairing", `none, as asked ${ui.dim("(--no-pair)")}`);
4829
5691
  else
4830
5692
  row("warn", "pairing", "not paired: pairing did not finish");
4831
- detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os5.homedir())} (tools.${spec.host})`);
5693
+ detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os4.homedir())} (tools.${spec.host})`);
5694
+ const eventLog = (0, eventLog_1.resolveEventLog)({ localOnly: !identity });
5695
+ if (eventLog.path)
5696
+ row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path, os4.homedir())} ${ui.dim("(on this machine only)")}`);
5697
+ else if (options.eventLog !== void 0)
5698
+ row("info", "events", "off");
4832
5699
  if (options.dryRun) {
4833
5700
  console.log("\nDry run. Nothing was written.");
4834
5701
  return 0;
@@ -4839,6 +5706,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4839
5706
  if (chosenLocal) {
4840
5707
  console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
4841
5708
  console.log(" They run on this machine and need no account or pairing.");
5709
+ if (eventLog.path)
5710
+ console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os4.homedir())}, for you or any tool to read.`);
4842
5711
  } else if (!identity) {
4843
5712
  console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
4844
5713
  console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
@@ -4861,7 +5730,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4861
5730
  return 0;
4862
5731
  }
4863
5732
  function isHomeProject2(options) {
4864
- return options.scope === "project" && path4.resolve(options.projectDir) === path4.resolve(os5.homedir());
5733
+ return options.scope === "project" && path4.resolve(options.projectDir) === path4.resolve(os4.homedir());
4865
5734
  }
4866
5735
  function parseArgs2(argv, spec) {
4867
5736
  const options = {
@@ -4921,6 +5790,18 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4921
5790
  case "--dry-run":
4922
5791
  options.dryRun = true;
4923
5792
  break;
5793
+ case "--event-log": {
5794
+ const { value, consumed } = (0, eventLog_1.parseEventLogFlag)(argv, i);
5795
+ options.eventLog = value;
5796
+ i += consumed;
5797
+ break;
5798
+ }
5799
+ case "--repo-keys":
5800
+ options.repoKeys = true;
5801
+ break;
5802
+ case "--no-repo-keys":
5803
+ options.repoKeys = false;
5804
+ break;
4924
5805
  case "--no-pair":
4925
5806
  // `--no-pairing` is the spelling this landed under first. Both appeared
4926
5807
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -5001,7 +5882,7 @@ ${usage(spec)}`);
5001
5882
  const toolInstallationId = existingId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
5002
5883
  let session;
5003
5884
  try {
5004
- session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os5.hostname()}`);
5885
+ session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os4.hostname()}`);
5005
5886
  } catch (error) {
5006
5887
  console.error(`
5007
5888
  Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
@@ -5044,13 +5925,18 @@ Pairing ${status.status}. Run setup again.`);
5044
5925
  console.log(" Waiting...");
5045
5926
  announced = true;
5046
5927
  }
5047
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
5928
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
5048
5929
  }
5049
5930
  console.error("\nPairing timed out. Run setup again.");
5050
5931
  return void 0;
5051
5932
  }
5052
5933
  function installBinary2(spec, dryRun) {
5053
- return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
5934
+ return (0, hookRunner_1.installHookRunner)({
5935
+ binaryName: spec.binaryName,
5936
+ setupCommand: `npx ${spec.packageName} setup`,
5937
+ dryRun,
5938
+ onKeptNewer: (installed, incoming) => console.log(` Kept the installed hook bundle (${installed}) rather than replace it with this older ${incoming}. Run setup from the newer version to change it.`)
5939
+ });
5054
5940
  }
5055
5941
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
5056
5942
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -5070,8 +5956,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5070
5956
  const command = hookCommand2(binary, spec);
5071
5957
  const hooks = { ...settings.hooks ?? {} };
5072
5958
  for (const event of spec.hookEvents) {
5073
- const kept = (hooks[event] ?? []).filter((entry) => !isOurs2(entry, spec));
5074
- hooks[event] = [...kept, spec.settings.entry(command, event)];
5959
+ hooks[event] = placeOurEntry2(hooks[event] ?? [], spec.settings.entry(command, event), spec);
5075
5960
  }
5076
5961
  const updated = { ...settings, hooks };
5077
5962
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -5084,10 +5969,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5084
5969
  ${serialised}`);
5085
5970
  return true;
5086
5971
  }
5087
- if (exists)
5088
- fs5.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5089
- fs5.mkdirSync(path4.dirname(settingsFile), { recursive: true });
5090
- fs5.writeFileSync(settingsFile, serialised, "utf8");
5972
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
5091
5973
  return true;
5092
5974
  }
5093
5975
  function hookCommand2(binary, spec) {
@@ -5097,28 +5979,130 @@ ${serialised}`);
5097
5979
  const sets = /* @__PURE__ */ new Map();
5098
5980
  for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
5099
5981
  for (const entry of entries ?? []) {
5100
- if (!isOurs2(entry, spec))
5101
- continue;
5102
- const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
5103
- sets.set(event, Math.min(set, sets.get(event) ?? set));
5982
+ for (const command of commandsOf(entry, spec)) {
5983
+ if (!isOurCommand(command, spec))
5984
+ continue;
5985
+ const set = (0, hookSet_1.hookSetOfCommand)(command);
5986
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5987
+ }
5104
5988
  }
5105
5989
  }
5106
5990
  return sets;
5107
5991
  }
5108
- function isOurs2(entry, spec) {
5992
+ function ourHookPositions(settings, spec) {
5993
+ const found = [];
5994
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5995
+ (groups ?? []).forEach((group, groupIndex) => {
5996
+ const handlers = group?.hooks;
5997
+ if (Array.isArray(handlers)) {
5998
+ handlers.forEach((handler, handlerIndex) => {
5999
+ if (isOurs2({ hooks: [handler] }, spec))
6000
+ found.push({ event, group: groupIndex, handler: handlerIndex });
6001
+ });
6002
+ } else if (isOurs2(group, spec)) {
6003
+ found.push({ event, group: groupIndex, handler: 0 });
6004
+ }
6005
+ });
6006
+ }
6007
+ return found;
6008
+ }
6009
+ function trustProblemLines(spec, settingsFile, settings, indent) {
6010
+ if (!spec.trust)
6011
+ return [];
6012
+ const ours = ourHookPositions(settings, spec);
6013
+ if (ours.length === 0)
6014
+ return [];
6015
+ const report = spec.trust.check(settingsFile, ours);
6016
+ const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os4.homedir());
6017
+ const lines = [];
6018
+ if (report.unreadable) {
6019
+ lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
6020
+ }
6021
+ if (report.untrusted.length) {
6022
+ const names = [...new Set(report.untrusted.map((position) => position.event))].join(", ");
6023
+ lines.push(`${report.untrusted.length} of ${ours.length} hooks are not approved in ${where} (${names}). ${spec.displayName} skips them without a message, so nothing is sent for those events.`);
6024
+ }
6025
+ for (const entry of report.stale)
6026
+ lines.push(entry);
6027
+ if (lines.length)
6028
+ lines.push(spec.trust.fix);
6029
+ return lines.map((line) => `${indent}${line}`);
6030
+ }
6031
+ function commandsOf(entry, spec) {
6032
+ if (spec.settings.grouped) {
6033
+ return innerHooks(entry).map(commandOfHook).filter((command2) => typeof command2 === "string");
6034
+ }
5109
6035
  const command = spec.settings.commandOf(entry);
5110
- return typeof command === "string" && command.includes(spec.binaryName);
6036
+ return typeof command === "string" ? [command] : [];
6037
+ }
6038
+ function innerHooks(entry) {
6039
+ const hooks = entry && typeof entry === "object" ? entry.hooks : void 0;
6040
+ return Array.isArray(hooks) ? hooks : [];
6041
+ }
6042
+ function commandOfHook(hook) {
6043
+ return hook && typeof hook === "object" ? hook.command : void 0;
6044
+ }
6045
+ function isOurCommand(command, spec) {
6046
+ return command.includes(spec.binaryName);
6047
+ }
6048
+ function isOurs2(entry, spec) {
6049
+ return commandsOf(entry, spec).some((command) => isOurCommand(command, spec));
6050
+ }
6051
+ function isOurInnerHook(hook, spec) {
6052
+ const command = commandOfHook(hook);
6053
+ return typeof command === "string" && isOurCommand(command, spec);
6054
+ }
6055
+ function withoutOurEntries2(entries, spec) {
6056
+ if (!spec.settings.grouped)
6057
+ return entries.filter((entry) => !isOurs2(entry, spec));
6058
+ const kept = [];
6059
+ for (const entry of entries) {
6060
+ if (!isOurs2(entry, spec)) {
6061
+ kept.push(entry);
6062
+ continue;
6063
+ }
6064
+ const others = innerHooks(entry).filter((hook) => !isOurInnerHook(hook, spec));
6065
+ if (others.length)
6066
+ kept.push({ ...entry, hooks: others });
6067
+ }
6068
+ return kept;
6069
+ }
6070
+ function placeOurEntry2(entries, wanted, spec) {
6071
+ if (!spec.settings.grouped)
6072
+ return [...withoutOurEntries2(entries, spec), wanted];
6073
+ const replacements = innerHooks(wanted);
6074
+ let placed = false;
6075
+ const result = [];
6076
+ for (const entry of entries) {
6077
+ if (!isOurs2(entry, spec)) {
6078
+ result.push(entry);
6079
+ continue;
6080
+ }
6081
+ const matcher = entry.matcher;
6082
+ const matchesAll = matcher === void 0 || matcher === "";
6083
+ const next = [];
6084
+ for (const hook of innerHooks(entry)) {
6085
+ if (!isOurInnerHook(hook, spec))
6086
+ next.push(hook);
6087
+ else if (!placed && matchesAll) {
6088
+ next.push(...replacements);
6089
+ placed = true;
6090
+ }
6091
+ }
6092
+ if (next.length)
6093
+ result.push({ ...entry, hooks: next });
6094
+ }
6095
+ return placed ? result : [...result, wanted];
5111
6096
  }
5112
6097
  function findStaleHookCommands2(settings, binary, spec) {
5113
6098
  const stale = /* @__PURE__ */ new Set();
5114
6099
  for (const entries of Object.values(settings.hooks ?? {})) {
5115
6100
  for (const entry of entries ?? []) {
5116
- const command = spec.settings.commandOf(entry);
5117
- if (typeof command !== "string")
5118
- continue;
5119
- if (!/ascenda/i.test(command) || command.includes(binary))
5120
- continue;
5121
- stale.add(command);
6101
+ for (const command of commandsOf(entry, spec)) {
6102
+ if (!/ascenda/i.test(command) || command.includes(binary))
6103
+ continue;
6104
+ stale.add(command);
6105
+ }
5122
6106
  }
5123
6107
  }
5124
6108
  return [...stale];
@@ -5143,6 +6127,7 @@ ${serialised}`);
5143
6127
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
5144
6128
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
5145
6129
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
6130
+ console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5146
6131
  console.log(`hook binary ${fs5.existsSync(binary) ? binary : "\u2014 not installed"}`);
5147
6132
  const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5148
6133
  if (node) {
@@ -5161,6 +6146,14 @@ ${serialised}`);
5161
6146
  const oldest = Math.min(...sets);
5162
6147
  console.log(oldest < spec.hookSet ? `hook set ${oldest}, this version registers ${spec.hookSet}. Upgrade: npx ${spec.packageName} setup${options.scope === "user" ? " --scope user" : ""}` : `hook set ${spec.hookSet} (current)`);
5163
6148
  }
6149
+ const trustLines = trustProblemLines(spec, settingsFile, settings, "");
6150
+ if (trustLines.length) {
6151
+ console.log(`not trusted ${trustLines[0]}`);
6152
+ for (const line of trustLines.slice(1))
6153
+ console.log(` ${line}`);
6154
+ } else if (spec.trust && registered > 0) {
6155
+ console.log("trust every registered hook is approved");
6156
+ }
5164
6157
  if (stale.length) {
5165
6158
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
5166
6159
  for (const command of stale)
@@ -5182,14 +6175,14 @@ ${serialised}`);
5182
6175
  await notices.markShown();
5183
6176
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
5184
6177
  const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5185
- const healthy = paired && wired && fs5.existsSync(binary) && !stale.length && !node?.problem;
6178
+ const healthy = paired && wired && fs5.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
5186
6179
  return healthy ? 0 : 1;
5187
6180
  }
5188
6181
  function countRegistered2(settings, spec) {
5189
6182
  return spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs2(entry, spec))).length;
5190
6183
  }
5191
6184
  function cliAgentRegistrations(spec, projectDir = process.cwd()) {
5192
- const home = os5.homedir();
6185
+ const home = os4.homedir();
5193
6186
  const userFile = spec.settings.settingsPath("user", projectDir);
5194
6187
  const projectFile = spec.settings.settingsPath("project", projectDir);
5195
6188
  const found = [];
@@ -5225,10 +6218,37 @@ ${serialised}`);
5225
6218
  } catch (error) {
5226
6219
  lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
5227
6220
  }
6221
+ if (spec.trust) {
6222
+ const found = trustDoctorLines(spec, options.projectDir, ui);
6223
+ if (found.length)
6224
+ lines.push("", ...found);
6225
+ }
5228
6226
  lines.push("", ...accountLines(ui, spec));
6227
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
6228
+ lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5229
6229
  console.log(lines.join("\n"));
5230
6230
  return 0;
5231
6231
  }
6232
+ function trustDoctorLines(spec, projectDir, ui) {
6233
+ const userFile = spec.settings.settingsPath("user", projectDir);
6234
+ const projectFile = spec.settings.settingsPath("project", projectDir);
6235
+ const files = userFile === projectFile ? [userFile] : [userFile, projectFile];
6236
+ const out = [];
6237
+ for (const file of files) {
6238
+ const settings = readSettings(file);
6239
+ if (ourHookPositions(settings, spec).length === 0)
6240
+ continue;
6241
+ const problems = trustProblemLines(spec, file, settings, "");
6242
+ if (problems.length === 0) {
6243
+ out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os4.homedir())} is approved`);
6244
+ continue;
6245
+ }
6246
+ out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
6247
+ for (const line of problems.slice(1))
6248
+ out.push(`${" ".repeat(25)}${line}`);
6249
+ }
6250
+ return out;
6251
+ }
5232
6252
  function accountLines(ui, spec) {
5233
6253
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5234
6254
  const id = credentials?.toolInstallationId;
@@ -5239,9 +6259,9 @@ ${serialised}`);
5239
6259
  ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}`,
5240
6260
  ...id ? [ui.dim(row("info", "Installation id", id))] : [],
5241
6261
  "",
5242
- " Not paired, which is fine: the screen saver and the live view above work",
5243
- " without it. Nothing leaves this machine and nothing is queued. To send your",
5244
- " sessions to Ascenda's servers, so they appear in the app:",
6262
+ " Not paired, which is fine: the screen saver, the live view and the local",
6263
+ " event log work without it. Nothing leaves this machine and nothing is queued.",
6264
+ " To send your sessions to Ascenda's servers, so they appear in the app:",
5245
6265
  ` ${ui.cyan(`${cliAgentSelfCommand(spec)} setup`)}`
5246
6266
  ];
5247
6267
  }
@@ -5262,7 +6282,7 @@ ${serialised}`);
5262
6282
  const settings = JSON.parse(fs5.readFileSync(settingsFile, "utf8"));
5263
6283
  const hooks = { ...settings.hooks ?? {} };
5264
6284
  for (const event of Object.keys(hooks)) {
5265
- const kept = hooks[event].filter((entry) => !isOurs2(entry, spec));
6285
+ const kept = withoutOurEntries2(hooks[event], spec);
5266
6286
  if (kept.length)
5267
6287
  hooks[event] = kept;
5268
6288
  else
@@ -5271,9 +6291,8 @@ ${serialised}`);
5271
6291
  const updated = { ...settings, hooks };
5272
6292
  if (!Object.keys(hooks).length)
5273
6293
  delete updated.hooks;
5274
- fs5.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5275
- fs5.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5276
- `, "utf8");
6294
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
6295
+ `);
5277
6296
  return true;
5278
6297
  } catch {
5279
6298
  return false;
@@ -5345,7 +6364,9 @@ var require_turnState = __commonJS({
5345
6364
  }();
5346
6365
  Object.defineProperty(exports, "__esModule", { value: true });
5347
6366
  exports.recordTurnStart = recordTurnStart;
6367
+ exports.readTurnPromptId = readTurnPromptId;
5348
6368
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
6369
+ var crypto_1 = __require("crypto");
5349
6370
  var fs5 = __importStar(__require("fs"));
5350
6371
  var path4 = __importStar(__require("path"));
5351
6372
  var tokenStore_1 = require_tokenStore();
@@ -5358,11 +6379,24 @@ var require_turnState = __commonJS({
5358
6379
  }
5359
6380
  function recordTurnStart(agent, sessionId, now = Date.now()) {
5360
6381
  if (!sessionId)
5361
- return;
6382
+ return void 0;
5362
6383
  try {
6384
+ const promptId = (0, crypto_1.randomUUID)();
5363
6385
  fs5.mkdirSync(stateDir(), { recursive: true });
5364
- fs5.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
6386
+ fs5.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
6387
+ return promptId;
6388
+ } catch {
6389
+ return void 0;
6390
+ }
6391
+ }
6392
+ function readTurnPromptId(agent, sessionId) {
6393
+ if (!sessionId)
6394
+ return void 0;
6395
+ try {
6396
+ const id = fs5.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
6397
+ return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
5365
6398
  } catch {
6399
+ return void 0;
5366
6400
  }
5367
6401
  }
5368
6402
  function consumeTurnDurationMs(agent, sessionId, now = Date.now()) {
@@ -5370,7 +6404,7 @@ var require_turnState = __commonJS({
5370
6404
  return void 0;
5371
6405
  const file = turnFile(agent, sessionId);
5372
6406
  try {
5373
- const started = Number(fs5.readFileSync(file, "utf8").trim());
6407
+ const started = Number(fs5.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
5374
6408
  fs5.rmSync(file, { force: true });
5375
6409
  if (!Number.isFinite(started) || started <= 0 || started > now)
5376
6410
  return void 0;
@@ -5522,14 +6556,15 @@ var require_agentProcess = __commonJS({
5522
6556
  });
5523
6557
 
5524
6558
  // ../packages/tool-kit/out/index.js
5525
- var require_out2 = __commonJS({
6559
+ var require_out3 = __commonJS({
5526
6560
  "../packages/tool-kit/out/index.js"(exports) {
5527
6561
  "use strict";
5528
6562
  Object.defineProperty(exports, "__esModule", { value: true });
5529
- exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
5530
- exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = void 0;
5531
- exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
5532
- exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = void 0;
6563
+ 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.startBackgroundFlush = exports.runOutboxFlush = exports.hookDeliveryInline = exports.flushLockPath = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = exports.FLUSH_LOCK_FRESH_MS = 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.shellCommandFacts = exports.invitesDebrief = exports.classifyMcpWorkMilestone = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
6564
+ 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.readTurnPromptId = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeRepoKeysSetting = 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.trustProblemLines = exports.runCliAgentSetup = exports.registeredHookSets = exports.ourHookPositions = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.withPromptId = exports.withForgeKeys = exports.loadCliAgentConfig = exports.flushHookOutbox = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = void 0;
6565
+ 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.repoKeysEnabled = exports.deriveForgeKeysForCwd = exports.REPO_KEYS_ENV_VAR = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeBranchKey = exports.forgeRepoKey = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = void 0;
6566
+ 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.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.replaceSettingsFile = exports.writeAtomically = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.isDowngrade = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = void 0;
6567
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = void 0;
5533
6568
  var commandClassifier_1 = require_commandClassifier();
5534
6569
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5535
6570
  return commandClassifier_1.classifyCommand;
@@ -5548,9 +6583,16 @@ var require_out2 = __commonJS({
5548
6583
  Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
5549
6584
  return workMilestoneClassifier_1.classifyWorkMilestone;
5550
6585
  } });
6586
+ Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
6587
+ return workMilestoneClassifier_1.classifyMcpWorkMilestone;
6588
+ } });
5551
6589
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
5552
6590
  return workMilestoneClassifier_1.invitesDebrief;
5553
6591
  } });
6592
+ var shellFacts_1 = require_shellFacts();
6593
+ Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
6594
+ return shellFacts_1.shellCommandFacts;
6595
+ } });
5554
6596
  var autonomyBand_1 = require_autonomyBand();
5555
6597
  Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
5556
6598
  return autonomyBand_1.autonomyBand;
@@ -5620,6 +6662,28 @@ var require_out2 = __commonJS({
5620
6662
  Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
5621
6663
  return collectorVersion_1.describeCollectorVersion;
5622
6664
  } });
6665
+ var backgroundDelivery_1 = require_backgroundDelivery();
6666
+ Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
6667
+ return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
6668
+ } });
6669
+ Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
6670
+ return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
6671
+ } });
6672
+ Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
6673
+ return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
6674
+ } });
6675
+ Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
6676
+ return backgroundDelivery_1.flushLockPath;
6677
+ } });
6678
+ Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
6679
+ return backgroundDelivery_1.hookDeliveryInline;
6680
+ } });
6681
+ Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
6682
+ return backgroundDelivery_1.runOutboxFlush;
6683
+ } });
6684
+ Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
6685
+ return backgroundDelivery_1.startBackgroundFlush;
6686
+ } });
5623
6687
  var eventSender_1 = require_eventSender();
5624
6688
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
5625
6689
  return eventSender_1.AscendaEventSender;
@@ -5630,19 +6694,41 @@ var require_out2 = __commonJS({
5630
6694
  Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
5631
6695
  return eventSender_1.TOKEN_RENEW_LEAD_MS;
5632
6696
  } });
6697
+ Object.defineProperty(exports, "buildEventBody", { enumerable: true, get: function() {
6698
+ return eventSender_1.buildEventBody;
6699
+ } });
5633
6700
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
5634
6701
  return eventSender_1.buildEventPayload;
5635
6702
  } });
6703
+ var agentEvent_1 = require_agentEvent();
6704
+ Object.defineProperty(exports, "toAgentEvent", { enumerable: true, get: function() {
6705
+ return agentEvent_1.toAgentEvent;
6706
+ } });
5636
6707
  var eventLog_1 = require_eventLog();
5637
6708
  Object.defineProperty(exports, "EVENT_LOG_ENV_VAR", { enumerable: true, get: function() {
5638
6709
  return eventLog_1.EVENT_LOG_ENV_VAR;
5639
6710
  } });
6711
+ Object.defineProperty(exports, "EVENT_LOG_OFF", { enumerable: true, get: function() {
6712
+ return eventLog_1.EVENT_LOG_OFF;
6713
+ } });
5640
6714
  Object.defineProperty(exports, "appendEventLog", { enumerable: true, get: function() {
5641
6715
  return eventLog_1.appendEventLog;
5642
6716
  } });
6717
+ Object.defineProperty(exports, "defaultEventLogPath", { enumerable: true, get: function() {
6718
+ return eventLog_1.defaultEventLogPath;
6719
+ } });
6720
+ Object.defineProperty(exports, "describeEventLog", { enumerable: true, get: function() {
6721
+ return eventLog_1.describeEventLog;
6722
+ } });
5643
6723
  Object.defineProperty(exports, "expandUserPath", { enumerable: true, get: function() {
5644
6724
  return eventLog_1.expandUserPath;
5645
6725
  } });
6726
+ Object.defineProperty(exports, "parseEventLogFlag", { enumerable: true, get: function() {
6727
+ return eventLog_1.parseEventLogFlag;
6728
+ } });
6729
+ Object.defineProperty(exports, "resolveEventLog", { enumerable: true, get: function() {
6730
+ return eventLog_1.resolveEventLog;
6731
+ } });
5646
6732
  Object.defineProperty(exports, "resolveEventLogPath", { enumerable: true, get: function() {
5647
6733
  return eventLog_1.resolveEventLogPath;
5648
6734
  } });
@@ -5656,9 +6742,18 @@ var require_out2 = __commonJS({
5656
6742
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
5657
6743
  return hookAdapter_1.deliverHookEvents;
5658
6744
  } });
6745
+ Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
6746
+ return hookAdapter_1.flushHookOutbox;
6747
+ } });
5659
6748
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
5660
6749
  return hookAdapter_1.loadCliAgentConfig;
5661
6750
  } });
6751
+ Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
6752
+ return hookAdapter_1.withForgeKeys;
6753
+ } });
6754
+ Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
6755
+ return hookAdapter_1.withPromptId;
6756
+ } });
5662
6757
  Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
5663
6758
  return hookAdapter_1.resolveCliAgentInstallationId;
5664
6759
  } });
@@ -5675,12 +6770,18 @@ var require_out2 = __commonJS({
5675
6770
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
5676
6771
  return cliAgentSetup_1.isCliAgentManagementCommand;
5677
6772
  } });
6773
+ Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
6774
+ return cliAgentSetup_1.ourHookPositions;
6775
+ } });
5678
6776
  Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5679
6777
  return cliAgentSetup_1.registeredHookSets;
5680
6778
  } });
5681
6779
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
5682
6780
  return cliAgentSetup_1.runCliAgentSetup;
5683
6781
  } });
6782
+ Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
6783
+ return cliAgentSetup_1.trustProblemLines;
6784
+ } });
5684
6785
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
5685
6786
  return cliAgentSetup_1.writeHookSettings;
5686
6787
  } });
@@ -5719,6 +6820,12 @@ var require_out2 = __commonJS({
5719
6820
  Object.defineProperty(exports, "writeHostCredentials", { enumerable: true, get: function() {
5720
6821
  return credentials_1.writeHostCredentials;
5721
6822
  } });
6823
+ Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
6824
+ return credentials_1.writeEventLogSetting;
6825
+ } });
6826
+ Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
6827
+ return credentials_1.writeRepoKeysSetting;
6828
+ } });
5722
6829
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5723
6830
  return credentials_1.writeMachineCredentials;
5724
6831
  } });
@@ -5729,6 +6836,9 @@ var require_out2 = __commonJS({
5729
6836
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
5730
6837
  return turnState_1.consumeTurnDurationMs;
5731
6838
  } });
6839
+ Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
6840
+ return turnState_1.readTurnPromptId;
6841
+ } });
5732
6842
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
5733
6843
  return turnState_1.recordTurnStart;
5734
6844
  } });
@@ -5863,6 +6973,12 @@ var require_out2 = __commonJS({
5863
6973
  Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
5864
6974
  return forgeProject_1.forgeProjectHash;
5865
6975
  } });
6976
+ Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
6977
+ return forgeProject_1.forgeRepoKey;
6978
+ } });
6979
+ Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
6980
+ return forgeProject_1.forgeBranchKey;
6981
+ } });
5866
6982
  Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
5867
6983
  return forgeProject_1.parseForgeFullName;
5868
6984
  } });
@@ -5875,6 +6991,16 @@ var require_out2 = __commonJS({
5875
6991
  Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
5876
6992
  return forgeProject_1.recordForgeProjectAlias;
5877
6993
  } });
6994
+ var forgeKeys_1 = require_forgeKeys();
6995
+ Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
6996
+ return forgeKeys_1.REPO_KEYS_ENV_VAR;
6997
+ } });
6998
+ Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
6999
+ return forgeKeys_1.deriveForgeKeysForCwd;
7000
+ } });
7001
+ Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
7002
+ return forgeKeys_1.repoKeysEnabled;
7003
+ } });
5878
7004
  var liveBus_1 = require_liveBus();
5879
7005
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
5880
7006
  return liveBus_1.emitLiveSignal;
@@ -5945,6 +7071,9 @@ var require_out2 = __commonJS({
5945
7071
  Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
5946
7072
  return hookRunner_1.installHookRunner;
5947
7073
  } });
7074
+ Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
7075
+ return hookRunner_1.isDowngrade;
7076
+ } });
5948
7077
  Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
5949
7078
  return hookRunner_1.lastHookPath;
5950
7079
  } });
@@ -5963,6 +7092,13 @@ var require_out2 = __commonJS({
5963
7092
  Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
5964
7093
  return hookRunner_1.tidyHomePath;
5965
7094
  } });
7095
+ Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
7096
+ return hookRunner_1.writeAtomically;
7097
+ } });
7098
+ var settingsFile_1 = require_settingsFile();
7099
+ Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
7100
+ return settingsFile_1.replaceSettingsFile;
7101
+ } });
5966
7102
  var liveSignalDoctor_1 = require_liveSignalDoctor();
5967
7103
  Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
5968
7104
  return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
@@ -6122,7 +7258,9 @@ var init_types = __esm({
6122
7258
  "Notification",
6123
7259
  "SessionEnd",
6124
7260
  "SubagentStart",
6125
- "SubagentStop"
7261
+ "SubagentStop",
7262
+ "PermissionRequest",
7263
+ "PermissionDenied"
6126
7264
  ];
6127
7265
  ASCENDA_TOOL_TYPE = "claude_code";
6128
7266
  CLAUDE_HOST = "claude_code";
@@ -6130,20 +7268,24 @@ var init_types = __esm({
6130
7268
  });
6131
7269
 
6132
7270
  // src/paths.ts
6133
- import * as fs2 from "fs";
6134
- import * as os2 from "os";
6135
- import * as path2 from "path";
7271
+ import * as fs from "fs";
7272
+ import * as os from "os";
7273
+ import * as path from "path";
7274
+ function claudeConfigDir() {
7275
+ const configured = process.env.CLAUDE_CONFIG_DIR?.trim();
7276
+ return configured ? path.resolve(configured) : path.join(os.homedir(), ".claude");
7277
+ }
6136
7278
  function hookBinPath() {
6137
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook");
7279
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook");
6138
7280
  }
6139
7281
  function hookBundlePath() {
6140
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.mjs");
7282
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.mjs");
6141
7283
  }
6142
7284
  function hookNodeRecordPath() {
6143
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.node");
7285
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.node");
6144
7286
  }
6145
7287
  function hookNoNodePath() {
6146
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.no-node");
7288
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.no-node");
6147
7289
  }
6148
7290
  function readCredentials() {
6149
7291
  const credentials = (0, import_tool_kit5.readMachineCredentials)();
@@ -6161,11 +7303,11 @@ function removeCredentials() {
6161
7303
  (0, import_tool_kit5.writeMachineCredentials)({ tools: credentials.tools });
6162
7304
  return;
6163
7305
  }
6164
- fs2.rmSync((0, import_tool_kit5.credentialsFilePath)(), { force: true });
7306
+ fs.rmSync((0, import_tool_kit5.credentialsFilePath)(), { force: true });
6165
7307
  }
6166
7308
  function selfCommand() {
6167
7309
  if (process.platform === "win32") return "npx @ascenda-one/claude-code-hooks";
6168
- const home = os2.homedir();
7310
+ const home = os.homedir();
6169
7311
  const bin = hookBinPath();
6170
7312
  return bin.startsWith(`${home}/`) ? `~${bin.slice(home.length)}` : bin;
6171
7313
  }
@@ -6173,8 +7315,8 @@ var import_tool_kit5, import_tool_kit6;
6173
7315
  var init_paths = __esm({
6174
7316
  "src/paths.ts"() {
6175
7317
  "use strict";
6176
- import_tool_kit5 = __toESM(require_out2(), 1);
6177
- import_tool_kit6 = __toESM(require_out2(), 1);
7318
+ import_tool_kit5 = __toESM(require_out3(), 1);
7319
+ import_tool_kit6 = __toESM(require_out3(), 1);
6178
7320
  }
6179
7321
  });
6180
7322
 
@@ -6250,7 +7392,7 @@ var import_tool_kit7, DEFAULT_API_BASE_URL, MissingInstallationIdError;
6250
7392
  var init_config = __esm({
6251
7393
  "src/config.ts"() {
6252
7394
  "use strict";
6253
- import_tool_kit7 = __toESM(require_out2(), 1);
7395
+ import_tool_kit7 = __toESM(require_out3(), 1);
6254
7396
  init_paths();
6255
7397
  init_types();
6256
7398
  DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -6282,9 +7424,9 @@ var import_tool_kit8, import_tool_kit9, TOOL;
6282
7424
  var init_hookHealth = __esm({
6283
7425
  "src/hookHealth.ts"() {
6284
7426
  "use strict";
6285
- import_tool_kit8 = __toESM(require_out2(), 1);
7427
+ import_tool_kit8 = __toESM(require_out3(), 1);
6286
7428
  init_paths();
6287
- import_tool_kit9 = __toESM(require_out2(), 1);
7429
+ import_tool_kit9 = __toESM(require_out3(), 1);
6288
7430
  TOOL = "claude_code";
6289
7431
  }
6290
7432
  });
@@ -6294,7 +7436,7 @@ var import_tool_kit10, LAUNCHER_OPTIONS, LAUNCHER_SCRIPT;
6294
7436
  var init_launcher = __esm({
6295
7437
  "src/launcher.ts"() {
6296
7438
  "use strict";
6297
- import_tool_kit10 = __toESM(require_out2(), 1);
7439
+ import_tool_kit10 = __toESM(require_out3(), 1);
6298
7440
  LAUNCHER_OPTIONS = {
6299
7441
  binaryName: "ascenda-claude-hook",
6300
7442
  setupCommand: "npx @ascenda-one/claude-code-hooks setup",
@@ -6318,7 +7460,7 @@ __export(setup_exports, {
6318
7460
  });
6319
7461
  import * as crypto from "crypto";
6320
7462
  import * as fs3 from "fs";
6321
- import * as os3 from "os";
7463
+ import * as os2 from "os";
6322
7464
  import * as path3 from "path";
6323
7465
  async function runSetup(argv) {
6324
7466
  let options;
@@ -6360,6 +7502,8 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6360
7502
  // picks up.
6361
7503
  ...unpaired ? { localOnly: true, installedAt: now } : { pairedAt: now }
6362
7504
  });
7505
+ if (options.eventLog !== void 0) (0, import_tool_kit11.writeEventLogSetting)(options.eventLog);
7506
+ if (options.repoKeys !== void 0) (0, import_tool_kit11.writeRepoKeysSetting)(options.repoKeys);
6363
7507
  }
6364
7508
  if (isHomeProject(options)) {
6365
7509
  detail("scope", "user (a project install in the home folder only loads when Claude Code starts there)");
@@ -6377,7 +7521,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6377
7521
  settingsPath({ ...options, scope: options.scope === "user" ? "project" : "user" }),
6378
7522
  // The home folder's project file, where a project-scope setup run from
6379
7523
  // `~` used to put them.
6380
- path3.join(os3.homedir(), ".claude", "settings.local.json")
7524
+ homeProjectSettingsPath()
6381
7525
  ]);
6382
7526
  otherFiles.delete(settingsFile);
6383
7527
  for (const otherFile of otherFiles) {
@@ -6401,6 +7545,9 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6401
7545
  }
6402
7546
  if (unpaired) detail("installation", `${identity.toolInstallationId} (kept, so pairing later attaches to it)`);
6403
7547
  detail("credentials", tidyHome((0, import_tool_kit6.credentialsFilePath)()));
7548
+ const eventLog = (0, import_tool_kit11.resolveEventLog)({ localOnly: unpaired });
7549
+ if (eventLog.path) row("ok", "events", `${tidyHome(eventLog.path)} ${ui.dim("(on this machine only)")}`);
7550
+ else if (options.eventLog !== void 0) row("info", "events", "off");
6404
7551
  if (options.dryRun) {
6405
7552
  console.log("\nDry run. Nothing was written.");
6406
7553
  return 0;
@@ -6411,6 +7558,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6411
7558
  if (chosenLocal) {
6412
7559
  console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
6413
7560
  console.log(" They run on this machine and need no account or pairing.");
7561
+ if (eventLog.path) console.log(` Every event is also written to ${tidyHome(eventLog.path)}, for you or any tool to read.`);
6414
7562
  } else if (unpaired) {
6415
7563
  console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
6416
7564
  console.log(` Your sessions won't reach Ascenda's servers until pairing completes.`);
@@ -6481,6 +7629,18 @@ function parseArgs(argv) {
6481
7629
  case "--project-dir":
6482
7630
  options.projectDir = path3.resolve(next());
6483
7631
  break;
7632
+ case "--event-log": {
7633
+ const { value, consumed } = (0, import_tool_kit11.parseEventLogFlag)(argv, i);
7634
+ options.eventLog = value;
7635
+ i += consumed;
7636
+ break;
7637
+ }
7638
+ case "--repo-keys":
7639
+ options.repoKeys = true;
7640
+ break;
7641
+ case "--no-repo-keys":
7642
+ options.repoKeys = false;
7643
+ break;
6484
7644
  case "--no-pair":
6485
7645
  // `--no-pairing` is the spelling the CLI agents' setup landed under
6486
7646
  // first, and the one their README still showed for a day. Both parse
@@ -6505,7 +7665,7 @@ ${USAGE}`);
6505
7665
  return options;
6506
7666
  }
6507
7667
  function isHomeProject(options) {
6508
- return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os3.homedir());
7668
+ return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os2.homedir());
6509
7669
  }
6510
7670
  async function resolveIdentity(apiBaseUrl, options) {
6511
7671
  const existingId = options.toolInstallationId ?? readCredentials()?.toolInstallationId;
@@ -6525,7 +7685,7 @@ async function resolveIdentity(apiBaseUrl, options) {
6525
7685
  }
6526
7686
  let session;
6527
7687
  try {
6528
- session = await (0, import_tool_kit11.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os3.hostname()}`);
7688
+ session = await (0, import_tool_kit11.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os2.hostname()}`);
6529
7689
  } catch (error) {
6530
7690
  return {
6531
7691
  toolInstallationId,
@@ -6552,7 +7712,7 @@ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
6552
7712
  if (++failures >= POLL_ERROR_TOLERANCE) {
6553
7713
  return { reason: `lost contact while waiting (${error instanceof Error ? error.message : String(error)})` };
6554
7714
  }
6555
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
7715
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
6556
7716
  continue;
6557
7717
  }
6558
7718
  if (status.status === "paired" && status.eventWriteToken) return { token: status.eventWriteToken };
@@ -6563,22 +7723,29 @@ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
6563
7723
  console.log(" Waiting...");
6564
7724
  announced = true;
6565
7725
  }
6566
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
7726
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
6567
7727
  }
6568
7728
  return { reason: "no confirmation within 5 minutes" };
6569
7729
  }
6570
7730
  function tidyHome(file) {
6571
- const home = os3.homedir();
7731
+ const home = os2.homedir();
6572
7732
  return file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
6573
7733
  }
6574
7734
  function restartLine(options) {
6575
7735
  return options.scope === "user" ? "Restart Claude Code to load the hooks." : "Restart Claude Code in this project to load the hooks.";
6576
7736
  }
6577
7737
  function installBinary(dryRun) {
6578
- return (0, import_tool_kit11.installHookRunner)({ ...LAUNCHER_OPTIONS, dryRun });
7738
+ return (0, import_tool_kit11.installHookRunner)({
7739
+ ...LAUNCHER_OPTIONS,
7740
+ dryRun,
7741
+ onKeptNewer: (installed, incoming) => console.log(`Kept the installed hook bundle (${installed}) rather than replace it with this older ${incoming}. Run setup from the newer version to change it.`)
7742
+ });
6579
7743
  }
6580
7744
  function settingsPath(options) {
6581
- return options.scope === "user" ? path3.join(os3.homedir(), ".claude", "settings.json") : path3.join(options.projectDir, ".claude", "settings.local.json");
7745
+ return options.scope === "user" ? path3.join(claudeConfigDir(), "settings.json") : path3.join(options.projectDir, ".claude", "settings.local.json");
7746
+ }
7747
+ function homeProjectSettingsPath() {
7748
+ return path3.join(os2.homedir(), ".claude", "settings.local.json");
6582
7749
  }
6583
7750
  function writeSettings(settingsFile, binary, dryRun) {
6584
7751
  let settings = {};
@@ -6598,8 +7765,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
6598
7765
  const command = hookCommand(binary);
6599
7766
  const hooks = { ...settings.hooks ?? {} };
6600
7767
  for (const event of HOOK_EVENTS) {
6601
- const kept = (hooks[event] ?? []).filter((group) => !isOurs(group));
6602
- hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}${(0, import_tool_kit11.hookSetArgument)(HOOK_SET)}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
7768
+ hooks[event] = placeOurEntry(hooks[event] ?? [], { type: "command", command: `${command} ${event}${(0, import_tool_kit11.hookSetArgument)(HOOK_SET)}`, timeout: HOOK_TIMEOUT_SECONDS });
6603
7769
  }
6604
7770
  const updated = { ...settings, hooks };
6605
7771
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -6611,9 +7777,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
6611
7777
  ${serialised}`);
6612
7778
  return true;
6613
7779
  }
6614
- if (exists) fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
6615
- fs3.mkdirSync(path3.dirname(settingsFile), { recursive: true });
6616
- fs3.writeFileSync(settingsFile, serialised, "utf8");
7780
+ (0, import_tool_kit11.replaceSettingsFile)(settingsFile, serialised);
6617
7781
  return true;
6618
7782
  }
6619
7783
  function hookCommand(binary) {
@@ -6624,22 +7788,57 @@ function removeOurHooks(settingsFile) {
6624
7788
  const settings = JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
6625
7789
  const hooks = { ...settings.hooks ?? {} };
6626
7790
  for (const event of Object.keys(hooks)) {
6627
- const kept = hooks[event].filter((group) => !isOurs(group));
7791
+ const kept = withoutOurEntries(hooks[event]);
6628
7792
  if (kept.length) hooks[event] = kept;
6629
7793
  else delete hooks[event];
6630
7794
  }
6631
7795
  const updated = { ...settings, hooks };
6632
7796
  if (!Object.keys(hooks).length) delete updated.hooks;
6633
- fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
6634
- fs3.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
6635
- `, "utf8");
7797
+ (0, import_tool_kit11.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
7798
+ `);
6636
7799
  return true;
6637
7800
  } catch {
6638
7801
  return false;
6639
7802
  }
6640
7803
  }
7804
+ function isOurEntry(entry) {
7805
+ return typeof entry?.command === "string" && entry.command.includes(HOOK_MARKER);
7806
+ }
6641
7807
  function isOurs(group) {
6642
- return (group.hooks ?? []).some((entry) => typeof entry.command === "string" && entry.command.includes(HOOK_MARKER));
7808
+ return (group.hooks ?? []).some(isOurEntry);
7809
+ }
7810
+ function withoutOurEntries(groups) {
7811
+ const kept = [];
7812
+ for (const group of groups) {
7813
+ if (!isOurs(group)) {
7814
+ kept.push(group);
7815
+ continue;
7816
+ }
7817
+ const others = (group.hooks ?? []).filter((entry) => !isOurEntry(entry));
7818
+ if (others.length) kept.push({ ...group, hooks: others });
7819
+ }
7820
+ return kept;
7821
+ }
7822
+ function placeOurEntry(groups, wanted) {
7823
+ let placed = false;
7824
+ const result = [];
7825
+ for (const group of groups) {
7826
+ if (!isOurs(group)) {
7827
+ result.push(group);
7828
+ continue;
7829
+ }
7830
+ const matchesAll = group.matcher === void 0 || group.matcher === "";
7831
+ const next = [];
7832
+ for (const entry of group.hooks ?? []) {
7833
+ if (!isOurEntry(entry)) next.push(entry);
7834
+ else if (!placed && matchesAll) {
7835
+ next.push(wanted);
7836
+ placed = true;
7837
+ }
7838
+ }
7839
+ if (next.length) result.push({ ...group, hooks: next });
7840
+ }
7841
+ return placed ? result : [...result, { hooks: [wanted] }];
6643
7842
  }
6644
7843
  function findStaleHookCommands(settings, binary) {
6645
7844
  const stale = /* @__PURE__ */ new Set();
@@ -6666,9 +7865,8 @@ function ourHookSets(settings) {
6666
7865
  const sets = /* @__PURE__ */ new Map();
6667
7866
  for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
6668
7867
  for (const group of groups ?? []) {
6669
- if (!isOurs(group)) continue;
6670
7868
  for (const entry of group.hooks ?? []) {
6671
- if (typeof entry?.command !== "string") continue;
7869
+ if (!isOurEntry(entry)) continue;
6672
7870
  const set = (0, import_tool_kit11.hookSetOfCommand)(entry.command);
6673
7871
  sets.set(event, Math.min(set, sets.get(event) ?? set));
6674
7872
  }
@@ -6685,13 +7883,13 @@ function registrationSummary(projectDir) {
6685
7883
  const files = /* @__PURE__ */ new Map([
6686
7884
  [settingsPath({ scope: "user", projectDir }), "user"],
6687
7885
  [settingsPath({ scope: "project", projectDir }), "project"],
6688
- [path3.join(os3.homedir(), ".claude", "settings.local.json"), "project"]
7886
+ [homeProjectSettingsPath(), "project"]
6689
7887
  ]);
6690
7888
  const found = [];
6691
7889
  for (const [file, scope] of files) {
6692
7890
  const { registered } = countRegistered(file, binary);
6693
7891
  if (registered === 0) continue;
6694
- found.push({ file, scope, registered, homeProject: path3.resolve(file) === path3.resolve(os3.homedir(), ".claude", "settings.local.json") });
7892
+ found.push({ file, scope, registered, homeProject: path3.resolve(file) === path3.resolve(homeProjectSettingsPath()) });
6695
7893
  }
6696
7894
  return found;
6697
7895
  }
@@ -6716,6 +7914,7 @@ async function printStatus(options) {
6716
7914
  console.log(`token ${fileToken ? "present" : token ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : unpaired ? "\u2014 none until this install is paired" : "\u2014 missing"}`);
6717
7915
  console.log(`delivery ${token ? "active" : unpaired ? "inactive \u2014 nothing is sent, and nothing is queued for later" : "\u2014 no token for this pairing, so nothing can be sent"}`);
6718
7916
  console.log("local features active \u2014 the session prompts and the live socket signal need no pairing");
7917
+ console.log(`event log ${(0, import_tool_kit11.describeEventLog)((0, import_tool_kit11.resolveEventLog)({ localOnly: unpaired }), "npx @ascenda-one/claude-code-hooks setup")}`);
6719
7918
  console.log(`hook binary ${fs3.existsSync(binary) ? binary : "\u2014 not installed"}`);
6720
7919
  const node = process.platform === "win32" ? void 0 : resolveHookNode();
6721
7920
  if (node) {
@@ -6771,7 +7970,7 @@ function uninstall(options) {
6771
7970
  }
6772
7971
  console.log(`hooks removed from ${settingsFile}`);
6773
7972
  }
6774
- for (const file of [hookBinPath(), hookBundlePath(), hookNodeRecordPath(), hookNoNodePath()]) {
7973
+ for (const file of [hookBinPath(), hookBundlePath(), hookNodeRecordPath(), hookNoNodePath(), `${hookBinPath()}.version`]) {
6775
7974
  if (!fs3.existsSync(file)) continue;
6776
7975
  fs3.rmSync(file);
6777
7976
  if (file === hookBinPath() || file === hookBundlePath()) console.log(`removed ${file}`);
@@ -6788,17 +7987,17 @@ var import_tool_kit11, HOOK_EVENTS, HOOK_SET, HOOK_TIMEOUT_SECONDS, HOOK_MARKER,
6788
7987
  var init_setup = __esm({
6789
7988
  "src/setup.ts"() {
6790
7989
  "use strict";
6791
- import_tool_kit11 = __toESM(require_out2(), 1);
7990
+ import_tool_kit11 = __toESM(require_out3(), 1);
6792
7991
  init_config();
6793
7992
  init_hookHealth();
6794
7993
  init_launcher();
6795
7994
  init_paths();
6796
7995
  init_types();
6797
- HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop"];
6798
- HOOK_SET = 3;
7996
+ HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop", "PermissionRequest", "PermissionDenied"];
7997
+ HOOK_SET = 4;
6799
7998
  HOOK_TIMEOUT_SECONDS = 5;
6800
7999
  HOOK_MARKER = "ascenda-claude-hook";
6801
- SENDS = ["model", "posture", "git", "edits", "waiting", "subagents"];
8000
+ SENDS = ["model", "posture", "git", "edits", "waiting", "subagents", "forge", "turns"];
6802
8001
  USAGE = `ascenda-claude-hook setup \u2014 wire Claude Code to Ascenda telemetry
6803
8002
 
6804
8003
  npx @ascenda-one/claude-code-hooks setup [options]
@@ -6819,7 +8018,13 @@ Options
6819
8018
  --tool-installation-id <id> reuse an existing pairing instead of creating one
6820
8019
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
6821
8020
  --no-pair install without pairing: local features on, nothing sent
8021
+ --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
8022
+ On by default when not paired; machine-wide, shared by every agent
6822
8023
  (--no-pairing is accepted too)
8024
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
8025
+ repository gets a key and, off its default branch, a branch key, so a pull
8026
+ request can be matched to a session. They are digests anyone who guesses the
8027
+ names can reproduce. Machine-wide. --repo-keys turns them back on
6823
8028
  --scope user|project where hooks are registered (default user: every project)
6824
8029
  --project-dir <path> project root for --scope project (default cwd)
6825
8030
  --dry-run print what would change, write nothing
@@ -6831,14 +8036,14 @@ Options
6831
8036
  });
6832
8037
 
6833
8038
  // src/cli.ts
6834
- var import_tool_kit14 = __toESM(require_out2(), 1);
6835
- var import_tool_kit15 = __toESM(require_out2(), 1);
8039
+ var import_tool_kit14 = __toESM(require_out3(), 1);
8040
+ var import_tool_kit15 = __toESM(require_out3(), 1);
6836
8041
  import { randomUUID as randomUUID2 } from "node:crypto";
6837
8042
  import * as fs4 from "node:fs";
6838
8043
 
6839
8044
  // src/ascendaClient.ts
6840
- var import_tool_kit = __toESM(require_out2(), 1);
6841
- var import_tool_kit2 = __toESM(require_out2(), 1);
8045
+ var import_tool_kit = __toESM(require_out3(), 1);
8046
+ var import_tool_kit2 = __toESM(require_out3(), 1);
6842
8047
  var AscendaClient = class {
6843
8048
  sender;
6844
8049
  constructor(config) {
@@ -6867,28 +8072,38 @@ var AscendaClient = class {
6867
8072
  queue(mapped) {
6868
8073
  return this.sender.queue(mapped);
6869
8074
  }
8075
+ outboxFilePath() {
8076
+ return this.sender.outboxFilePath();
8077
+ }
8078
+ /** Drains the outbox until it's empty or the door refuses. What the background flusher runs. */
8079
+ async flushOutbox() {
8080
+ await (0, import_tool_kit.runOutboxFlush)(this.sender);
8081
+ }
6870
8082
  async renewEventToken() {
6871
8083
  return this.sender.renewEventToken();
6872
8084
  }
6873
8085
  };
6874
8086
 
6875
8087
  // src/mapClaudeEvent.ts
6876
- var import_tool_kit4 = __toESM(require_out2(), 1);
8088
+ var import_tool_kit4 = __toESM(require_out3(), 1);
6877
8089
  init_types();
6878
8090
 
6879
8091
  // src/safeExtract.ts
6880
- var import_tool_kit3 = __toESM(require_out2(), 1);
8092
+ var import_tool_kit3 = __toESM(require_out3(), 1);
6881
8093
 
6882
8094
  // src/mapClaudeEvent.ts
6883
8095
  function mapClaudeEvent(hookName, input) {
6884
8096
  const events = mapEvent(hookName, input);
6885
8097
  if (events.length === 0) return events;
6886
- const branchHash = (0, import_tool_kit4.deriveBranchHashForCwd)((0, import_tool_kit3.getString)(input, ["cwd"]) ?? process.cwd());
8098
+ const cwd = (0, import_tool_kit3.getString)(input, ["cwd"]) ?? process.cwd();
8099
+ const branchHash = (0, import_tool_kit4.deriveBranchHashForCwd)(cwd);
8100
+ const { repoKey, branchKey } = (0, import_tool_kit4.deriveForgeKeysForCwd)(cwd);
8101
+ const promptId = readPromptId(input);
6887
8102
  const runtime = claudeRuntime();
6888
8103
  const subagentId = readSubagentId(input);
6889
8104
  return events.map((event) => ({
6890
8105
  ...event,
6891
- metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...subagentId ? { subagentId } : {}, ...event.metadata }
8106
+ metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...repoKey ? { repoKey } : {}, ...branchKey ? { branchKey } : {}, ...promptId ? { promptId } : {}, ...subagentId ? { subagentId } : {}, ...event.metadata }
6892
8107
  }));
6893
8108
  }
6894
8109
  function mapEvent(hookName, input) {
@@ -6924,6 +8139,10 @@ function mapEvent(hookName, input) {
6924
8139
  return mapSubagent("subagent_started", input);
6925
8140
  case "SubagentStop":
6926
8141
  return mapSubagent("subagent_stopped", input);
8142
+ case "PermissionRequest":
8143
+ return mapPermission("permission_requested", input);
8144
+ case "PermissionDenied":
8145
+ return mapPermission("permission_denied", input);
6927
8146
  default:
6928
8147
  return [];
6929
8148
  }
@@ -6935,7 +8154,7 @@ function isNewSessionStart(input) {
6935
8154
  function milestoneInviting(input) {
6936
8155
  if ((0, import_tool_kit3.outcomeForHook)("PostToolUse", input) !== "success") return false;
6937
8156
  const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
6938
- return (0, import_tool_kit4.invitesDebrief)((0, import_tool_kit4.classifyWorkMilestone)(command));
8157
+ return (0, import_tool_kit4.invitesDebrief)((0, import_tool_kit4.classifyWorkMilestone)(command) ?? (0, import_tool_kit4.classifyMcpWorkMilestone)(getToolName(input)));
6939
8158
  }
6940
8159
  function mapSessionStart(input) {
6941
8160
  if (!isNewSessionStart(input)) return [];
@@ -6991,14 +8210,27 @@ var BUILT_IN_SUBAGENTS = {
6991
8210
  "statusline-setup": "statusline_setup",
6992
8211
  "claude-code-guide": "claude_code_guide"
6993
8212
  };
8213
+ function readPromptId(input) {
8214
+ const raw = input["prompt_id"];
8215
+ if (typeof raw !== "string") return void 0;
8216
+ const value = raw.trim();
8217
+ return /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : void 0;
8218
+ }
6994
8219
  function readSubagentId(input) {
6995
8220
  const raw = input["agent_id"];
6996
8221
  if (typeof raw !== "string") return void 0;
6997
8222
  const value = raw.trim();
6998
8223
  return /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : void 0;
6999
8224
  }
8225
+ function isTaskNotificationPrompt(prompt) {
8226
+ return prompt !== void 0 && prompt.trimStart().startsWith("<task-notification>");
8227
+ }
8228
+ function isBashModePrompt(prompt) {
8229
+ return prompt !== void 0 && prompt.trimStart().startsWith("<bash-input>");
8230
+ }
7000
8231
  function mapUserPromptSubmit(input) {
7001
8232
  const prompt = (0, import_tool_kit3.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit3.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
8233
+ if (isTaskNotificationPrompt(prompt) || isBashModePrompt(prompt)) return [];
7002
8234
  const autonomy = autonomyModeMetadata(input);
7003
8235
  const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...autonomy } }];
7004
8236
  if ((0, import_tool_kit3.looksLikeCorrection)(prompt)) {
@@ -7015,10 +8247,23 @@ function mapNotification(input) {
7015
8247
  // Low, always. Being asked is overhead to be counted, not a failure to be
7016
8248
  // flagged, and a severity that climbed would make this the input to a score.
7017
8249
  severity: "low",
7018
- metadata: { interruptionKind: notificationKind((0, import_tool_kit3.getString)(input, ["message"])) }
8250
+ metadata: { interruptionKind: notificationKind((0, import_tool_kit3.getString)(input, ["message"]), (0, import_tool_kit3.getString)(input, ["notification_type", "notificationType"])) }
8251
+ }];
8252
+ }
8253
+ function mapPermission(eventType, input) {
8254
+ return [{
8255
+ eventType,
8256
+ severity: "low",
8257
+ metadata: { toolName: sanitiseToolName(getToolName(input)), ...autonomyModeMetadata(input) }
7019
8258
  }];
7020
8259
  }
7021
- function notificationKind(message) {
8260
+ function notificationKind(message, notificationType) {
8261
+ if (notificationType !== void 0) {
8262
+ if (notificationType === "permission_prompt") return "permission_request";
8263
+ if (notificationType === "elicitation_dialog") return "input_request";
8264
+ if (notificationType === "idle_prompt") return "idle_prompt";
8265
+ return "other";
8266
+ }
7022
8267
  const text = message?.toLowerCase() ?? "";
7023
8268
  if (text.includes("permission")) return "permission_request";
7024
8269
  if (text.includes("waiting for your input")) return "idle_prompt";
@@ -7032,7 +8277,7 @@ function mapPostToolUse(hookName, input) {
7032
8277
  const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
7033
8278
  const commandClass = (0, import_tool_kit4.classifyCommand)(command);
7034
8279
  const gitAction = outcome === "success" ? (0, import_tool_kit4.classifyGitAction)(command) : void 0;
7035
- const milestoneKind = outcome === "success" ? (0, import_tool_kit4.classifyWorkMilestone)(command) : void 0;
8280
+ const milestoneKind = outcome === "success" ? (0, import_tool_kit4.classifyWorkMilestone)(command) ?? (0, import_tool_kit4.classifyMcpWorkMilestone)(toolName) : void 0;
7036
8281
  const autonomy = autonomyModeMetadata(input);
7037
8282
  if (outcome === "cancelled") {
7038
8283
  return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), reason: "manual_interrupt", ...autonomy } }];
@@ -7145,6 +8390,8 @@ function getToolName(input) {
7145
8390
  return (0, import_tool_kit3.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
7146
8391
  }
7147
8392
  function computeLinesChanged(toolName, input) {
8393
+ const patched = linesFromStructuredPatch((0, import_tool_kit3.getNested)(input, ["tool_response", "structuredPatch"]));
8394
+ if (patched !== void 0) return patched;
7148
8395
  const toolInput = (0, import_tool_kit3.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit3.getNested)(input, ["input"]) ?? (0, import_tool_kit3.getNested)(input, ["parameters"]);
7149
8396
  if (!toolInput || typeof toolInput !== "object") return void 0;
7150
8397
  const record = toolInput;
@@ -7174,16 +8421,33 @@ function computeLinesChanged(toolName, input) {
7174
8421
  }
7175
8422
  return sawOne ? total : void 0;
7176
8423
  }
8424
+ case "notebookedit": {
8425
+ if (record["edit_mode"] === "delete") return void 0;
8426
+ const source = record["new_source"];
8427
+ return typeof source === "string" ? countLines(source) : void 0;
8428
+ }
7177
8429
  default:
7178
8430
  return void 0;
7179
8431
  }
7180
8432
  }
8433
+ function linesFromStructuredPatch(patch) {
8434
+ if (!Array.isArray(patch) || patch.length === 0) return void 0;
8435
+ let count = 0;
8436
+ for (const hunk of patch) {
8437
+ const lines = hunk && typeof hunk === "object" ? hunk["lines"] : void 0;
8438
+ if (!Array.isArray(lines)) continue;
8439
+ for (const line of lines) {
8440
+ if (typeof line === "string" && (line.startsWith("+") || line.startsWith("-"))) count += 1;
8441
+ }
8442
+ }
8443
+ return count;
8444
+ }
7181
8445
  function countLines(text) {
7182
8446
  return text.length === 0 ? 0 : text.split("\n").length;
7183
8447
  }
7184
8448
  function isWriteTool(toolName) {
7185
8449
  const value = toolName?.toLowerCase();
7186
- return value === "write" || value === "edit" || value === "multiedit";
8450
+ return value === "write" || value === "edit" || value === "multiedit" || value === "notebookedit";
7187
8451
  }
7188
8452
  function sanitiseToolName(toolName) {
7189
8453
  if (!toolName) return "unknown";
@@ -7231,9 +8495,9 @@ function notificationLiveEvent(input) {
7231
8495
  }
7232
8496
 
7233
8497
  // src/usageLimitReset.ts
7234
- import * as fs from "node:fs";
7235
- import * as os from "node:os";
7236
- import * as path from "node:path";
8498
+ init_paths();
8499
+ import * as fs2 from "node:fs";
8500
+ import * as path2 from "node:path";
7237
8501
  var MAX_RESUME_AHEAD_MS = 6 * 60 * 60 * 1e3;
7238
8502
  var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
7239
8503
  var RESET_CLAUSE = new RegExp(
@@ -7341,11 +8605,10 @@ function managedSettingsPath() {
7341
8605
  return "/etc/claude-code/managed-settings.json";
7342
8606
  }
7343
8607
  function autoContinueEnabled(sources = {}) {
7344
- const home = sources.home ?? os.homedir();
7345
8608
  const files = [
7346
8609
  sources.managedPath ?? managedSettingsPath(),
7347
- ...sources.projectDir ? [path.join(sources.projectDir, ".claude", "settings.local.json"), path.join(sources.projectDir, ".claude", "settings.json")] : [],
7348
- path.join(home, ".claude", "settings.json")
8610
+ ...sources.projectDir ? [path2.join(sources.projectDir, ".claude", "settings.local.json"), path2.join(sources.projectDir, ".claude", "settings.json")] : [],
8611
+ path2.join(sources.configDir ?? claudeConfigDir(), "settings.json")
7349
8612
  ];
7350
8613
  for (const file of files) {
7351
8614
  const value = readSetting(file, "autoContinueAtUsageLimit");
@@ -7355,7 +8618,7 @@ function autoContinueEnabled(sources = {}) {
7355
8618
  }
7356
8619
  function readSetting(file, key) {
7357
8620
  try {
7358
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
8621
+ const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
7359
8622
  if (parsed && typeof parsed === "object" && key in parsed) return parsed[key];
7360
8623
  } catch {
7361
8624
  }
@@ -7369,10 +8632,10 @@ init_types();
7369
8632
  init_hookHealth();
7370
8633
 
7371
8634
  // src/liveDoctor.ts
7372
- var import_tool_kit12 = __toESM(require_out2(), 1);
8635
+ var import_tool_kit12 = __toESM(require_out3(), 1);
7373
8636
  init_paths();
7374
- var import_tool_kit13 = __toESM(require_out2(), 1);
7375
- import * as os4 from "os";
8637
+ var import_tool_kit13 = __toESM(require_out3(), 1);
8638
+ import * as os3 from "os";
7376
8639
  async function localSignalLines(projectDir = process.cwd()) {
7377
8640
  const { registrationSummary: registrationSummary2, REGISTERED_EVENT_COUNT: REGISTERED_EVENT_COUNT2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
7378
8641
  return (0, import_tool_kit12.liveSignalDoctorLines)({
@@ -7387,7 +8650,7 @@ async function localSignalLines(projectDir = process.cwd()) {
7387
8650
  });
7388
8651
  }
7389
8652
  function tidy(file) {
7390
- const home = os4.homedir();
8653
+ const home = os3.homedir();
7391
8654
  return file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
7392
8655
  }
7393
8656
 
@@ -7423,7 +8686,7 @@ Waiting for confirmation (expires ${session.expiresAt})...
7423
8686
  );
7424
8687
  const deadline = Date.now() + 11 * 60 * 1e3;
7425
8688
  while (Date.now() < deadline) {
7426
- await new Promise((resolve2) => setTimeout(resolve2, 3e3));
8689
+ await new Promise((resolve3) => setTimeout(resolve3, 3e3));
7427
8690
  const status = await (0, import_tool_kit14.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
7428
8691
  if (status.status === "pending") continue;
7429
8692
  if (status.status !== "paired") {
@@ -7515,6 +8778,10 @@ async function main() {
7515
8778
  await runDoctor();
7516
8779
  return;
7517
8780
  }
8781
+ if (command === import_tool_kit15.OUTBOX_FLUSH_COMMAND) {
8782
+ await runFlush();
8783
+ return;
8784
+ }
7518
8785
  if (MANAGEMENT_COMMANDS.has(command)) {
7519
8786
  const { runSetup: runSetup2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
7520
8787
  setupExitCode = await runSetup2(process.argv.slice(2));
@@ -7557,7 +8824,7 @@ async function main() {
7557
8824
  } catch (error) {
7558
8825
  const unpaired = localOnlyInstall();
7559
8826
  if (!unpaired && error instanceof MissingInstallationIdError) journalSkippedSend(error);
7560
- const logFile = (0, import_tool_kit14.resolveEventLogPath)();
8827
+ const logFile = (0, import_tool_kit14.resolveEventLogPath)({ localOnly: unpaired });
7561
8828
  if (!logFile) {
7562
8829
  if (unpaired) return;
7563
8830
  throw error;
@@ -7577,6 +8844,13 @@ async function main() {
7577
8844
  }
7578
8845
  return;
7579
8846
  }
8847
+ if (!(0, import_tool_kit15.hookDeliveryInline)() && claudeRuntime() !== "cloud") {
8848
+ for (const event of mappedEvents) {
8849
+ if (!client.queue(event)) console.error("Ascenda telemetry not kept: the event could not be written to the outbox.");
8850
+ }
8851
+ (0, import_tool_kit15.startBackgroundFlush)({ outboxFilePath: client.outboxFilePath() });
8852
+ return;
8853
+ }
7580
8854
  for (const event of mappedEvents) {
7581
8855
  const result = await client.send(event);
7582
8856
  if (result === "accepted") continue;
@@ -7584,6 +8858,15 @@ async function main() {
7584
8858
  return;
7585
8859
  }
7586
8860
  }
8861
+ async function runFlush() {
8862
+ let config;
8863
+ try {
8864
+ config = loadConfigFromEnv();
8865
+ } catch {
8866
+ return;
8867
+ }
8868
+ await new AscendaClient(config).flushOutbox();
8869
+ }
7587
8870
  function journalSkippedSend(error) {
7588
8871
  (0, import_tool_kit14.recordSendOutcome)(resolveStateFilePath(), (0, import_tool_kit14.unresolvedToolInstallationId)(ASCENDA_TOOL_TYPE), "skipped_no_installation_id", {
7589
8872
  detail: error.candidates.length === 0 ? "no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, no claude_code token file" : `no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, ${error.candidates.length} claude_code token files (${error.candidates.join(", ")})`
@@ -7694,8 +8977,8 @@ function describeOutcome(state) {
7694
8977
  }
7695
8978
  }
7696
8979
  function writeStdout(text) {
7697
- return new Promise((resolve2) => {
7698
- process.stdout.write(text, () => resolve2());
8980
+ return new Promise((resolve3) => {
8981
+ process.stdout.write(text, () => resolve3());
7699
8982
  });
7700
8983
  }
7701
8984
  async function runDoctor() {
@@ -7707,6 +8990,7 @@ async function runDoctor() {
7707
8990
  lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`, "");
7708
8991
  }
7709
8992
  const unpaired = localOnlyInstall();
8993
+ lines.push(` ${ui.bold("Local events")} ${(0, import_tool_kit14.describeEventLog)((0, import_tool_kit14.resolveEventLog)({ localOnly: unpaired }), "npx @ascenda-one/claude-code-hooks setup")}`, "");
7710
8994
  lines.push(unpaired ? ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}` : ` ${ui.bold("Account sync")} ${ui.dim("(Telemetry)")}`);
7711
8995
  const telemetryStart = lines.length;
7712
8996
  const finish = async () => {
@@ -7757,9 +9041,9 @@ async function runDoctor() {
7757
9041
  if (unpaired) {
7758
9042
  lines.push(
7759
9043
  "",
7760
- " Not paired, which is fine: the screen saver and the live view above work",
7761
- " without it. Nothing leaves this machine and nothing is queued. To send your",
7762
- " sessions to Ascenda's servers, so they appear in the app:",
9044
+ " Not paired, which is fine: the screen saver, the live view and the local",
9045
+ " event log work without it. Nothing leaves this machine and nothing is queued.",
9046
+ " To send your sessions to Ascenda's servers, so they appear in the app:",
7763
9047
  ` ${ui.cyan(`${selfCommand()} pair`)}`
7764
9048
  );
7765
9049
  await finish();
@@ -7827,6 +9111,7 @@ function outboxLines(toolInstallationId, state) {
7827
9111
  lines.push(` Outbox unreadable ${summary.unreadableLines} line(s) did not parse \u2014 discarded and journaled on the next hook`);
7828
9112
  }
7829
9113
  lines.push(` Outbox drain ${(0, import_tool_kit14.outboxDrainEnabled)() ? "on (queued events are replayed, oldest first)" : "off \u2014 queued events are kept and bounded, not sent"} \u2014 ${import_tool_kit14.OUTBOX_DRAIN_ENV_VAR}`);
9114
+ lines.push(` Delivery ${claudeRuntime() === "cloud" ? "inline (hosted session)" : (0, import_tool_kit15.hookDeliveryInline)() ? `inline \u2014 ${import_tool_kit15.HOOK_DELIVERY_ENV_VAR} or ${import_tool_kit14.OUTBOX_DRAIN_ENV_VAR}` : "background sender (the hook queues and returns)"}`);
7830
9115
  const discarded = state?.outboxDiscarded;
7831
9116
  if (discarded) {
7832
9117
  const reasons = Object.entries(discarded.lastReasons).map(([reason, count]) => `${count} ${reason}`).join(", ");