@ascenda-one/github-collector 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
@@ -149,25 +149,66 @@ var require_gitActionClassifier = __commonJS({
149
149
  if (!/\bgit\b/.test(value))
150
150
  return void 0;
151
151
  const heads = (0, commandHeads_1.commandHeads)(value);
152
- if (heads.some((h) => /^git\s+commit\b/.test(h) && /\s--amend\b/.test(h)))
152
+ const commands = heads.map(parseGitCommand).filter((c) => c !== void 0);
153
+ if (commands.some((c) => c.verb === "commit" && c.args.includes("--amend")))
153
154
  return "amend";
154
- if (heads.some((h) => /^git\s+revert\b/.test(h)))
155
+ if (commands.some((c) => c.verb === "revert"))
155
156
  return "revert";
156
- if (heads.some((h) => /^git\s+reset\b/.test(h) && /\s--hard\b/.test(h)))
157
+ if (commands.some((c) => c.verb === "reset" && c.args.includes("--hard")))
157
158
  return "reset_hard";
158
- if (heads.some((h) => /^git\s+restore\b/.test(h) && !/\s--staged\b/.test(h)))
159
+ if (commands.some(discardsWork))
159
160
  return "restore";
160
- if (heads.some((h) => /^git\s+checkout\b.*\s--\s/.test(h)))
161
- return "restore";
162
- if (heads.some((h) => /^git\s+push\b/.test(h)))
161
+ if (commands.some((c) => c.verb === "push"))
163
162
  return "push";
164
- if (heads.some((h) => /^git\s+commit\b/.test(h)))
163
+ if (commands.some((c) => c.verb === "commit"))
165
164
  return "commit";
166
165
  return void 0;
167
166
  }
168
167
  function isReworkGitAction(action) {
169
168
  return action === "revert" || action === "reset_hard" || action === "restore";
170
169
  }
170
+ var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path"]);
171
+ function parseGitCommand(head) {
172
+ const words = head.split(/\s+/);
173
+ if (words[0] !== "git")
174
+ return void 0;
175
+ let i = 1;
176
+ while (i < words.length && words[i].startsWith("-")) {
177
+ i += GLOBAL_OPTIONS_WITH_VALUE.has(words[i]) ? 2 : 1;
178
+ }
179
+ if (i >= words.length)
180
+ return void 0;
181
+ return { verb: words[i], args: words.slice(i + 1) };
182
+ }
183
+ function discardsWork({ verb, args }) {
184
+ switch (verb) {
185
+ case "restore":
186
+ return !args.includes("--staged");
187
+ case "switch":
188
+ return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
189
+ case "clean": {
190
+ const flags = args.filter((a) => /^-[a-z]+$/.test(a)).join("");
191
+ const dryRun = args.includes("--dry-run") || flags.includes("n");
192
+ return !dryRun && (args.includes("--force") || flags.includes("f"));
193
+ }
194
+ case "checkout":
195
+ return checkoutDiscards(args);
196
+ default:
197
+ return false;
198
+ }
199
+ }
200
+ function checkoutDiscards(args) {
201
+ if (args.includes("--"))
202
+ return true;
203
+ if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
204
+ return false;
205
+ const words = args.filter((a) => !a.startsWith("-"));
206
+ if (words.length >= 2)
207
+ return true;
208
+ if (words.length === 1)
209
+ return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
210
+ return false;
211
+ }
171
212
  }
172
213
  });
173
214
 
@@ -178,6 +219,7 @@ var require_workMilestoneClassifier = __commonJS({
178
219
  Object.defineProperty(exports, "__esModule", { value: true });
179
220
  exports.classifyWorkMilestone = classifyWorkMilestone;
180
221
  exports.invitesDebrief = invitesDebrief;
222
+ exports.classifyMcpWorkMilestone = classifyMcpWorkMilestone;
181
223
  var commandHeads_1 = require_commandHeads();
182
224
  function classifyWorkMilestone(command) {
183
225
  if (!command)
@@ -197,6 +239,41 @@ var require_workMilestoneClassifier = __commonJS({
197
239
  function invitesDebrief(kind) {
198
240
  return kind === "pr_merged" || kind === "issue_closed";
199
241
  }
242
+ function classifyMcpWorkMilestone(toolName) {
243
+ if (!toolName)
244
+ return void 0;
245
+ const parts = toolName.toLowerCase().split("__");
246
+ if (parts[0] !== "mcp" || parts.length < 3)
247
+ return void 0;
248
+ const tool = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
249
+ if (/^(merge|accept)(pullrequest|mergerequest)$/.test(tool))
250
+ return "pr_merged";
251
+ if (/^closeissue$/.test(tool))
252
+ return "issue_closed";
253
+ if (/^(create|open)(pullrequest|mergerequest)$/.test(tool))
254
+ return "pr_opened";
255
+ return void 0;
256
+ }
257
+ }
258
+ });
259
+
260
+ // ../packages/tool-kit/out/shellFacts.js
261
+ var require_shellFacts = __commonJS({
262
+ "../packages/tool-kit/out/shellFacts.js"(exports) {
263
+ "use strict";
264
+ Object.defineProperty(exports, "__esModule", { value: true });
265
+ exports.shellCommandFacts = shellCommandFacts;
266
+ var gitActionClassifier_1 = require_gitActionClassifier();
267
+ var workMilestoneClassifier_1 = require_workMilestoneClassifier();
268
+ function shellCommandFacts(command) {
269
+ const gitAction = (0, gitActionClassifier_1.classifyGitAction)(command);
270
+ const milestoneKind = (0, workMilestoneClassifier_1.classifyWorkMilestone)(command);
271
+ return {
272
+ ...gitAction !== void 0 ? { gitAction } : {},
273
+ ...(0, gitActionClassifier_1.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
274
+ ...milestoneKind !== void 0 ? { milestoneKind } : {}
275
+ };
276
+ }
200
277
  }
201
278
  });
202
279
 
@@ -590,6 +667,61 @@ var require_metricKeys = __commonJS({
590
667
  subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
591
668
  subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
592
669
  subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
670
+ advisorMessageCount: {
671
+ family: "counts",
672
+ readBy: ["diagnostic"],
673
+ 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."
674
+ },
675
+ advisorTokensTotal: {
676
+ family: "context",
677
+ readBy: ["diagnostic"],
678
+ unit: "tokens",
679
+ note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
680
+ },
681
+ cacheCreationTokens: {
682
+ family: "context",
683
+ readBy: ["diagnostic"],
684
+ unit: "tokens",
685
+ 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."
686
+ },
687
+ cacheCreation5mTokens: {
688
+ family: "context",
689
+ readBy: ["diagnostic"],
690
+ unit: "tokens",
691
+ note: "The part of cacheCreationTokens written with the 5-minute lifetime. Absent on transcripts that only record the total."
692
+ },
693
+ cacheCreation1hTokens: {
694
+ family: "context",
695
+ readBy: ["diagnostic"],
696
+ unit: "tokens",
697
+ note: "The part of cacheCreationTokens written with the 1-hour lifetime. Absent on transcripts that only record the total."
698
+ },
699
+ headlessPromptLines: {
700
+ family: "reading",
701
+ readBy: ["diagnostic"],
702
+ unit: "lines",
703
+ 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."
704
+ },
705
+ tokensNotCollected: {
706
+ family: "context",
707
+ readBy: ["diagnostic"],
708
+ 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."
709
+ },
710
+ unattributedSubagentTranscripts: {
711
+ family: "reading",
712
+ readBy: ["diagnostic"],
713
+ note: "Claude Code only: flat subagent transcripts whose lines name no parent session, so they could not be folded anywhere."
714
+ },
715
+ duplicateChatSessions: {
716
+ family: "reading",
717
+ readBy: ["diagnostic"],
718
+ note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
719
+ },
720
+ sessionsStartedFromBubble: {
721
+ family: "reading",
722
+ readBy: ["diagnostic"],
723
+ note: "Cursor only: sessions whose start is the earliest message rather than the header's createdAt, which can sit months before anyone typed."
724
+ },
593
725
  toolName: {
594
726
  family: "tools",
595
727
  readBy: ["backend"],
@@ -629,9 +761,11 @@ var require_out = __commonJS({
629
761
  "../packages/tool-contract/out/index.js"(exports) {
630
762
  "use strict";
631
763
  Object.defineProperty(exports, "__esModule", { value: true });
632
- exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
764
+ exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.DELIVERY_ENVELOPE_KEYS = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
633
765
  exports.combineDisjointHalves = combineDisjointHalves;
634
766
  exports.requireComparableQuantities = requireComparableQuantities;
767
+ exports.joinEventPayload = joinEventPayload;
768
+ exports.splitEventPayload = splitEventPayload;
635
769
  exports.ASCENDA_TELEMETRY_SOURCES = [
636
770
  "vscode_extension",
637
771
  "cursor_mcp",
@@ -695,7 +829,9 @@ var require_out = __commonJS({
695
829
  exports.COLLABORATION_EVENT_TYPES = [
696
830
  "review_requested_of_me",
697
831
  "review_given",
698
- "pull_request_opened"
832
+ "pull_request_opened",
833
+ "pull_request_closed",
834
+ "pull_request_merged"
699
835
  ];
700
836
  exports.EVENT_METADATA_DISCLOSURE = {
701
837
  language: "edits",
@@ -707,6 +843,13 @@ var require_out = __commonJS({
707
843
  gitAction: "git",
708
844
  milestoneKind: "git",
709
845
  branchHash: "repo",
846
+ repoKey: "forge",
847
+ headRepoKey: "forge",
848
+ prCreatedAt: "git",
849
+ prClosedAt: "git",
850
+ prMergedAt: "git",
851
+ branchKey: "forge",
852
+ promptId: "turns",
710
853
  autonomyMode: "posture",
711
854
  modelClass: "model",
712
855
  modelId: "model",
@@ -756,6 +899,13 @@ var require_out = __commonJS({
756
899
  "gitAction",
757
900
  "milestoneKind",
758
901
  "branchHash",
902
+ "repoKey",
903
+ "headRepoKey",
904
+ "prCreatedAt",
905
+ "prClosedAt",
906
+ "prMergedAt",
907
+ "branchKey",
908
+ "promptId",
759
909
  "autonomyMode",
760
910
  "modelClass",
761
911
  "modelId",
@@ -783,6 +933,24 @@ var require_out = __commonJS({
783
933
  "importSchema",
784
934
  "collectorVersion"
785
935
  ];
936
+ exports.DELIVERY_ENVELOPE_KEYS = ["toolInstallationId", "idempotencyKey"];
937
+ function joinEventPayload(envelope, body) {
938
+ const payload = { toolInstallationId: envelope.toolInstallationId };
939
+ for (const [key, value] of Object.entries(body)) {
940
+ payload[key] = value;
941
+ if (key === "occurredAt" && envelope.idempotencyKey !== void 0) {
942
+ payload.idempotencyKey = envelope.idempotencyKey;
943
+ }
944
+ }
945
+ return payload;
946
+ }
947
+ function splitEventPayload(payload) {
948
+ const { toolInstallationId, idempotencyKey, ...body } = payload;
949
+ const envelope = { toolInstallationId };
950
+ if (idempotencyKey !== void 0)
951
+ envelope.idempotencyKey = idempotencyKey;
952
+ return { envelope, body };
953
+ }
786
954
  exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
787
955
  exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
788
956
  exports.EVENT_WORKLOAD_CATEGORY = {
@@ -807,6 +975,10 @@ var require_out = __commonJS({
807
975
  review_requested_of_me: "supervision",
808
976
  review_given: "supervision",
809
977
  pull_request_opened: "creation",
978
+ // Where a pull request of yours ended up. A boundary like a turn ending, not
979
+ // work in itself, so neutral: it must not weigh on any workload leg.
980
+ pull_request_closed: "neutral",
981
+ pull_request_merged: "neutral",
810
982
  context_pressure_high: "risk",
811
983
  agent_loop_long: "risk",
812
984
  after_hours_ai_session: "risk",
@@ -837,6 +1009,16 @@ var require_out = __commonJS({
837
1009
  // step toward an interruption count becoming a score, a streak, or something
838
1010
  // that fires on a miss. It must never become any of those.
839
1011
  supervision_interruption: "supervision",
1012
+ // The agent asked to run a tool, and the auto-mode classifier refused one.
1013
+ // Claude Code's `PermissionRequest` and `PermissionDenied` hooks. Neutral,
1014
+ // because the Notification for the same prompt is already counted above as
1015
+ // `supervision_interruption`, and counting both would weigh one prompt
1016
+ // twice. These rows exist for the public event stream: which tool asked, and
1017
+ // under which posture. `permission_requested` fires before the person
1018
+ // answers and no hook reports their answer, so neither event says whether
1019
+ // the request was granted.
1020
+ permission_requested: "neutral",
1021
+ permission_denied: "neutral",
840
1022
  // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
841
1023
  approach_churn_detected: "risk",
842
1024
  goal_drift_detected: "risk",
@@ -961,16 +1143,16 @@ var require_collectorVersion = __commonJS({
961
1143
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
962
1144
  exports.describeCollectorVersion = describeCollectorVersion;
963
1145
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
964
- exports.COLLECTOR_VERSION = "0.1.34" ? "0.1.34" : exports.UNRELEASED_COLLECTOR_VERSION;
1146
+ exports.COLLECTOR_VERSION = "0.1.36" ? "0.1.36" : exports.UNRELEASED_COLLECTOR_VERSION;
965
1147
  function describeCollectorVersion(version = exports.COLLECTOR_VERSION) {
966
1148
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
967
1149
  }
968
1150
  }
969
1151
  });
970
1152
 
971
- // ../packages/tool-kit/out/eventLog.js
972
- var require_eventLog = __commonJS({
973
- "../packages/tool-kit/out/eventLog.js"(exports) {
1153
+ // ../packages/tool-kit/out/tokenStore.js
1154
+ var require_tokenStore = __commonJS({
1155
+ "../packages/tool-kit/out/tokenStore.js"(exports) {
974
1156
  "use strict";
975
1157
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
976
1158
  if (k2 === void 0) k2 = k;
@@ -1010,306 +1192,105 @@ var require_eventLog = __commonJS({
1010
1192
  };
1011
1193
  }();
1012
1194
  Object.defineProperty(exports, "__esModule", { value: true });
1013
- exports.EVENT_LOG_ENV_VAR = void 0;
1014
- exports.expandUserPath = expandUserPath;
1015
- exports.resolveEventLogPath = resolveEventLogPath;
1016
- exports.appendEventLog = appendEventLog;
1195
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1196
+ exports.ascendaHome = ascendaHome;
1197
+ exports.defaultTokenFilePath = defaultTokenFilePath2;
1198
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1199
+ exports.persistEventWriteToken = persistEventWriteToken2;
1200
+ exports.readTokenExpiry = readTokenExpiry;
1201
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1202
+ exports.readTokenFile = readTokenFile2;
1203
+ exports.sanitizeFilePart = sanitizeFilePart;
1017
1204
  var fs = __importStar(__require("fs"));
1018
1205
  var os = __importStar(__require("os"));
1019
1206
  var path = __importStar(__require("path"));
1020
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1021
- var MAX_BYTES = 5 * 1024 * 1024;
1022
- function expandUserPath(configured) {
1023
- const value = configured?.trim();
1024
- if (!value)
1025
- return void 0;
1026
- if (value === "~")
1027
- return os.homedir();
1028
- if (value.startsWith("~/"))
1029
- return path.join(os.homedir(), value.slice(2));
1030
- return path.resolve(value);
1207
+ function ascendaHome(home = os.homedir()) {
1208
+ return process.env.ASCENDA_HOME ?? path.join(home, ".ascenda");
1031
1209
  }
1032
- function resolveEventLogPath() {
1033
- return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
1210
+ function defaultTokenFilePath2(toolInstallationId) {
1211
+ return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1034
1212
  }
1035
- function appendEventLog(logFilePath, entry) {
1213
+ function tokenExpiryFilePath(tokenFilePath) {
1214
+ return path.join(path.dirname(tokenFilePath), "expiry", path.basename(tokenFilePath));
1215
+ }
1216
+ function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
1217
+ const dir = path.dirname(tokenFilePath);
1218
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
1219
+ fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1220
+ if (process.platform !== "win32") {
1221
+ fs.chmodSync(dir, 448);
1222
+ fs.chmodSync(tokenFilePath, 384);
1223
+ }
1224
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1036
1225
  try {
1037
- rotateIfLarge(logFilePath);
1038
- const dir = path.dirname(logFilePath);
1039
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1040
- fs.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1041
- `, { encoding: "utf8", mode: 384 });
1042
- if (process.platform !== "win32")
1043
- fs.chmodSync(logFilePath, 384);
1226
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1227
+ fs.mkdirSync(path.dirname(expiryFile), { recursive: true, mode: 448 });
1228
+ fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1229
+ } else {
1230
+ fs.rmSync(expiryFile, { force: true });
1231
+ }
1044
1232
  } catch {
1045
1233
  }
1046
1234
  }
1047
- function rotateIfLarge(logFilePath) {
1235
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1236
+ function readTokenExpiry(tokenFilePath) {
1048
1237
  try {
1049
- if (fs.statSync(logFilePath).size < MAX_BYTES)
1050
- return;
1051
- fs.renameSync(logFilePath, `${logFilePath}.1`);
1238
+ const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1239
+ if (Number.isFinite(recorded))
1240
+ return recorded;
1052
1241
  } catch {
1053
1242
  }
1054
- }
1055
- }
1056
- });
1057
-
1058
- // ../packages/tool-kit/out/http.js
1059
- var require_http = __commonJS({
1060
- "../packages/tool-kit/out/http.js"(exports) {
1061
- "use strict";
1062
- Object.defineProperty(exports, "__esModule", { value: true });
1063
- exports.AscendaApiError = void 0;
1064
- exports.createPairingSession = createPairingSession;
1065
- exports.getPairingStatus = getPairingStatus;
1066
- exports.startStudyJoin = startStudyJoin;
1067
- exports.getStudyJoinStatus = getStudyJoinStatus;
1068
- exports.readInitiatives = readInitiatives;
1069
- exports.readStudyNotices = readStudyNotices;
1070
- exports.setStudyObjection = setStudyObjection;
1071
- exports.markStudyNoticeShown = markStudyNoticeShown;
1072
- exports.renewToolToken = renewToolToken;
1073
- exports.isRetryableStatus = isRetryableStatus;
1074
- exports.postToolEvent = postToolEvent;
1075
- exports.postToolEventsBatch = postToolEventsBatch;
1076
- exports.parseIngestResponse = parseIngestResponse;
1077
- var tool_contract_1 = require_out();
1078
- var AscendaApiError = class extends Error {
1079
- status;
1080
- errorCode;
1081
- constructor(status, errorCode, body) {
1082
- super(body ?? `Ascenda API error ${status}`);
1083
- this.status = status;
1084
- this.errorCode = errorCode;
1085
- this.name = "AscendaApiError";
1086
- }
1087
- };
1088
- exports.AscendaApiError = AscendaApiError;
1089
- async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
1090
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1091
- method: "POST",
1092
- headers: { "Content-Type": "application/json" },
1093
- body: JSON.stringify({ toolInstallationId, toolType, displayName })
1094
- });
1095
- if (!response.ok)
1096
- throw new AscendaApiError(response.status, void 0, await response.text());
1097
- return await response.json();
1098
- }
1099
- async function getPairingStatus(apiBaseUrl, pairingSessionId) {
1100
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1101
- method: "GET",
1102
- headers: { Accept: "application/json" }
1103
- });
1104
- if (!response.ok)
1105
- throw new AscendaApiError(response.status, void 0, await response.text());
1106
- return await response.json();
1107
- }
1108
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1109
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1110
- method: "POST",
1111
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1112
- body: JSON.stringify({ joinCode, mode })
1113
- });
1114
- if (!response.ok)
1115
- throw await apiError(response);
1116
- return await response.json();
1117
- }
1118
- async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1119
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1120
- method: "GET",
1121
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1122
- });
1123
- if (!response.ok)
1124
- throw await apiError(response);
1125
- return await response.json();
1126
- }
1127
- async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1128
- let response;
1129
1243
  try {
1130
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1131
- method: "GET",
1132
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1133
- signal
1134
- });
1135
- } catch (error) {
1136
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1244
+ return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1245
+ } catch {
1246
+ return void 0;
1137
1247
  }
1138
- if (response.status === 401)
1139
- return { kind: "rejected", httpStatus: 401 };
1140
- if (!response.ok)
1141
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1142
- let body;
1248
+ }
1249
+ function listPersistedToolInstallationIds(toolType) {
1250
+ const prefix = `${sanitizeFilePart(toolType)}_`;
1251
+ const dir = path.join(ascendaHome(), "tokens");
1252
+ let names;
1143
1253
  try {
1144
- body = await response.json();
1254
+ names = fs.readdirSync(dir);
1145
1255
  } catch {
1146
- return { kind: "failed", reason: "the reply was not readable" };
1256
+ return [];
1147
1257
  }
1148
- if (!Array.isArray(body))
1149
- return { kind: "failed", reason: "the reply was not a list" };
1150
- return { kind: "ok", initiatives: body };
1258
+ const ids = [];
1259
+ for (const name of names.sort()) {
1260
+ if (!name.startsWith(prefix) || name.length === prefix.length)
1261
+ continue;
1262
+ const file = path.join(dir, name);
1263
+ try {
1264
+ if (!fs.statSync(file).isFile())
1265
+ continue;
1266
+ } catch {
1267
+ continue;
1268
+ }
1269
+ if (readTokenFile2(file) === void 0)
1270
+ continue;
1271
+ ids.push(`${toolType}:${name.slice(prefix.length)}`);
1272
+ }
1273
+ return ids;
1151
1274
  }
1152
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1153
- let response;
1275
+ function readTokenFile2(tokenFilePath) {
1154
1276
  try {
1155
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1156
- method: "GET",
1157
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1158
- signal
1159
- });
1160
- } catch (error) {
1161
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1162
- }
1163
- if (response.status === 404)
1164
- return { kind: "absent" };
1165
- if (response.status === 401)
1166
- return { kind: "rejected", httpStatus: 401 };
1167
- if (!response.ok)
1168
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1169
- let body;
1170
- try {
1171
- body = await response.json();
1172
- } catch {
1173
- return { kind: "absent" };
1174
- }
1175
- if (!Array.isArray(body))
1176
- return { kind: "absent" };
1177
- return { kind: "ok", notices: body };
1178
- }
1179
- async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1180
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1181
- method: objected ? "POST" : "DELETE",
1182
- headers: { Authorization: `Bearer ${eventWriteToken}` }
1183
- });
1184
- if (!response.ok)
1185
- throw await apiError(response);
1186
- }
1187
- async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1188
- try {
1189
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1190
- method: "POST",
1191
- headers: { Authorization: `Bearer ${eventWriteToken}` },
1192
- signal
1193
- });
1194
- return response.ok;
1195
- } catch {
1196
- return false;
1197
- }
1198
- }
1199
- async function apiError(response) {
1200
- const body = await response.text();
1201
- let errorCode;
1202
- try {
1203
- const parsed = JSON.parse(body);
1204
- errorCode = parsed.code ?? parsed.error;
1205
- } catch {
1206
- errorCode = void 0;
1207
- }
1208
- return new AscendaApiError(response.status, errorCode, body);
1209
- }
1210
- async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1211
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1212
- method: "POST",
1213
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1214
- signal
1215
- });
1216
- if (response.status === 401)
1217
- return null;
1218
- if (!response.ok)
1219
- throw new AscendaApiError(response.status, void 0, await response.text());
1220
- return await response.json();
1221
- }
1222
- function isDeliveredStatus(value) {
1223
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1224
- }
1225
- function readSuccessBody(body) {
1226
- let parsed;
1227
- try {
1228
- parsed = JSON.parse(body);
1277
+ if (!fs.existsSync(tokenFilePath))
1278
+ return void 0;
1279
+ const value = fs.readFileSync(tokenFilePath, "utf8").trim();
1280
+ return value || void 0;
1229
1281
  } catch {
1230
- return { duplicates: 0 };
1231
- }
1232
- if (!parsed || typeof parsed !== "object")
1233
- return { duplicates: 0 };
1234
- const single = parsed.status;
1235
- if (isDeliveredStatus(single))
1236
- return { duplicates: single === "duplicate" ? 1 : 0 };
1237
- const raw = parsed.results;
1238
- if (!Array.isArray(raw))
1239
- return { duplicates: 0 };
1240
- const results = [];
1241
- for (const item of raw) {
1242
- if (!item || typeof item !== "object")
1243
- continue;
1244
- const { index, status, reason } = item;
1245
- if (typeof index !== "number" || typeof status !== "string")
1246
- continue;
1247
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1248
- }
1249
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1250
- }
1251
- function isRetryableStatus(status) {
1252
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1253
- }
1254
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1255
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1256
- }
1257
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1258
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1259
- }
1260
- async function sendIngest(url, eventWriteToken, body, signal) {
1261
- try {
1262
- const response = await fetch(url, {
1263
- method: "POST",
1264
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1265
- body,
1266
- signal
1267
- });
1268
- return parseIngestResponse(response);
1269
- } catch (error) {
1270
- return {
1271
- result: "transport_error",
1272
- detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1273
- };
1282
+ return void 0;
1274
1283
  }
1275
1284
  }
1276
- async function parseIngestResponse(response) {
1277
- if (response.ok) {
1278
- const outcome = { result: "accepted", httpStatus: response.status };
1279
- let read = { duplicates: 0 };
1280
- try {
1281
- read = readSuccessBody(await response.text());
1282
- } catch {
1283
- read = { duplicates: 0 };
1284
- }
1285
- return {
1286
- ...outcome,
1287
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1288
- ...read.results !== void 0 ? { results: read.results } : {}
1289
- };
1290
- }
1291
- const body = await response.text();
1292
- let errorCode;
1293
- try {
1294
- errorCode = JSON.parse(body).error;
1295
- } catch {
1296
- errorCode = void 0;
1297
- }
1298
- const base2 = { httpStatus: response.status, errorCode, detail: body || void 0 };
1299
- if (response.status === 401)
1300
- return { ...base2, result: "auth_failed" };
1301
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1302
- return { ...base2, result: "consent_missing" };
1303
- if (response.status === 400 || response.status === 422)
1304
- return { ...base2, result: "validation_failed" };
1305
- return { ...base2, result: "transport_error" };
1285
+ function sanitizeFilePart(value) {
1286
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1306
1287
  }
1307
1288
  }
1308
1289
  });
1309
1290
 
1310
- // ../packages/tool-kit/out/tokenStore.js
1311
- var require_tokenStore = __commonJS({
1312
- "../packages/tool-kit/out/tokenStore.js"(exports) {
1291
+ // ../packages/tool-kit/out/stateStore.js
1292
+ var require_stateStore = __commonJS({
1293
+ "../packages/tool-kit/out/stateStore.js"(exports) {
1313
1294
  "use strict";
1314
1295
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1315
1296
  if (k2 === void 0) k2 = k;
@@ -1349,177 +1330,39 @@ var require_tokenStore = __commonJS({
1349
1330
  };
1350
1331
  }();
1351
1332
  Object.defineProperty(exports, "__esModule", { value: true });
1352
- exports.EVENT_TOKEN_TTL_MS = void 0;
1353
- exports.ascendaHome = ascendaHome;
1354
- exports.defaultTokenFilePath = defaultTokenFilePath2;
1355
- exports.tokenExpiryFilePath = tokenExpiryFilePath;
1356
- exports.persistEventWriteToken = persistEventWriteToken2;
1357
- exports.readTokenExpiry = readTokenExpiry;
1358
- exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1359
- exports.readTokenFile = readTokenFile2;
1360
- exports.sanitizeFilePart = sanitizeFilePart;
1333
+ exports.defaultStateFilePath = defaultStateFilePath;
1334
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
1335
+ exports.unresolvedStateFilePath = unresolvedStateFilePath;
1336
+ exports.readCollectorState = readCollectorState;
1337
+ exports.recordSendOutcome = recordSendOutcome;
1338
+ exports.recordOutboxDiscard = recordOutboxDiscard;
1339
+ exports.shouldAnnounceFailure = shouldAnnounceFailure;
1340
+ exports.markFailureNotified = markFailureNotified;
1361
1341
  var fs = __importStar(__require("fs"));
1362
- var os = __importStar(__require("os"));
1363
1342
  var path = __importStar(__require("path"));
1364
- function ascendaHome(home = os.homedir()) {
1365
- return process.env.ASCENDA_HOME ?? path.join(home, ".ascenda");
1366
- }
1367
- function defaultTokenFilePath2(toolInstallationId) {
1368
- return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1343
+ var tokenStore_1 = require_tokenStore();
1344
+ function defaultStateFilePath(toolInstallationId) {
1345
+ const dir = process.env.ASCENDA_STATE_DIR?.trim();
1346
+ const base2 = dir ? dir : path.join((0, tokenStore_1.ascendaHome)(), "state");
1347
+ return path.join(base2, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1369
1348
  }
1370
- function tokenExpiryFilePath(tokenFilePath) {
1371
- return path.join(path.dirname(tokenFilePath), "expiry", path.basename(tokenFilePath));
1349
+ function unresolvedToolInstallationId(toolType) {
1350
+ return `${toolType}:unresolved`;
1372
1351
  }
1373
- function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
1374
- const dir = path.dirname(tokenFilePath);
1375
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1376
- fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1377
- if (process.platform !== "win32") {
1378
- fs.chmodSync(dir, 448);
1379
- fs.chmodSync(tokenFilePath, 384);
1380
- }
1381
- const expiryFile = tokenExpiryFilePath(tokenFilePath);
1382
- try {
1383
- if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1384
- fs.mkdirSync(path.dirname(expiryFile), { recursive: true, mode: 448 });
1385
- fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1386
- } else {
1387
- fs.rmSync(expiryFile, { force: true });
1388
- }
1389
- } catch {
1390
- }
1352
+ function unresolvedStateFilePath(toolType) {
1353
+ return defaultStateFilePath(unresolvedToolInstallationId(toolType));
1391
1354
  }
1392
- exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1393
- function readTokenExpiry(tokenFilePath) {
1394
- try {
1395
- const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1396
- if (Number.isFinite(recorded))
1397
- return recorded;
1398
- } catch {
1399
- }
1355
+ function readCollectorState(stateFilePath) {
1400
1356
  try {
1401
- return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1402
- } catch {
1403
- return void 0;
1404
- }
1405
- }
1406
- function listPersistedToolInstallationIds(toolType) {
1407
- const prefix = `${sanitizeFilePart(toolType)}_`;
1408
- const dir = path.join(ascendaHome(), "tokens");
1409
- let names;
1410
- try {
1411
- names = fs.readdirSync(dir);
1412
- } catch {
1413
- return [];
1414
- }
1415
- const ids = [];
1416
- for (const name of names.sort()) {
1417
- if (!name.startsWith(prefix) || name.length === prefix.length)
1418
- continue;
1419
- const file = path.join(dir, name);
1420
- try {
1421
- if (!fs.statSync(file).isFile())
1422
- continue;
1423
- } catch {
1424
- continue;
1425
- }
1426
- if (readTokenFile2(file) === void 0)
1427
- continue;
1428
- ids.push(`${toolType}:${name.slice(prefix.length)}`);
1429
- }
1430
- return ids;
1431
- }
1432
- function readTokenFile2(tokenFilePath) {
1433
- try {
1434
- if (!fs.existsSync(tokenFilePath))
1435
- return void 0;
1436
- const value = fs.readFileSync(tokenFilePath, "utf8").trim();
1437
- return value || void 0;
1438
- } catch {
1439
- return void 0;
1440
- }
1441
- }
1442
- function sanitizeFilePart(value) {
1443
- return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1444
- }
1445
- }
1446
- });
1447
-
1448
- // ../packages/tool-kit/out/stateStore.js
1449
- var require_stateStore = __commonJS({
1450
- "../packages/tool-kit/out/stateStore.js"(exports) {
1451
- "use strict";
1452
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1453
- if (k2 === void 0) k2 = k;
1454
- var desc = Object.getOwnPropertyDescriptor(m, k);
1455
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1456
- desc = { enumerable: true, get: function() {
1457
- return m[k];
1458
- } };
1459
- }
1460
- Object.defineProperty(o, k2, desc);
1461
- } : function(o, m, k, k2) {
1462
- if (k2 === void 0) k2 = k;
1463
- o[k2] = m[k];
1464
- });
1465
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1466
- Object.defineProperty(o, "default", { enumerable: true, value: v });
1467
- } : function(o, v) {
1468
- o["default"] = v;
1469
- });
1470
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1471
- var ownKeys = function(o) {
1472
- ownKeys = Object.getOwnPropertyNames || function(o2) {
1473
- var ar = [];
1474
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1475
- return ar;
1476
- };
1477
- return ownKeys(o);
1478
- };
1479
- return function(mod) {
1480
- if (mod && mod.__esModule) return mod;
1481
- var result = {};
1482
- if (mod != null) {
1483
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1484
- }
1485
- __setModuleDefault(result, mod);
1486
- return result;
1487
- };
1488
- }();
1489
- Object.defineProperty(exports, "__esModule", { value: true });
1490
- exports.defaultStateFilePath = defaultStateFilePath;
1491
- exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
1492
- exports.unresolvedStateFilePath = unresolvedStateFilePath;
1493
- exports.readCollectorState = readCollectorState;
1494
- exports.recordSendOutcome = recordSendOutcome;
1495
- exports.recordOutboxDiscard = recordOutboxDiscard;
1496
- exports.shouldAnnounceFailure = shouldAnnounceFailure;
1497
- exports.markFailureNotified = markFailureNotified;
1498
- var fs = __importStar(__require("fs"));
1499
- var path = __importStar(__require("path"));
1500
- var tokenStore_1 = require_tokenStore();
1501
- function defaultStateFilePath(toolInstallationId) {
1502
- const dir = process.env.ASCENDA_STATE_DIR?.trim();
1503
- const base2 = dir ? dir : path.join((0, tokenStore_1.ascendaHome)(), "state");
1504
- return path.join(base2, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1505
- }
1506
- function unresolvedToolInstallationId(toolType) {
1507
- return `${toolType}:unresolved`;
1508
- }
1509
- function unresolvedStateFilePath(toolType) {
1510
- return defaultStateFilePath(unresolvedToolInstallationId(toolType));
1511
- }
1512
- function readCollectorState(stateFilePath) {
1513
- try {
1514
- if (!fs.existsSync(stateFilePath))
1515
- return void 0;
1516
- const raw = fs.readFileSync(stateFilePath, "utf8").trim();
1517
- if (!raw)
1518
- return void 0;
1519
- const parsed = JSON.parse(raw);
1520
- if (!parsed || typeof parsed !== "object")
1521
- return void 0;
1522
- return parsed;
1357
+ if (!fs.existsSync(stateFilePath))
1358
+ return void 0;
1359
+ const raw = fs.readFileSync(stateFilePath, "utf8").trim();
1360
+ if (!raw)
1361
+ return void 0;
1362
+ const parsed = JSON.parse(raw);
1363
+ if (!parsed || typeof parsed !== "object")
1364
+ return void 0;
1365
+ return parsed;
1523
1366
  } catch {
1524
1367
  return void 0;
1525
1368
  }
@@ -1783,43 +1626,868 @@ var require_outbox = __commonJS({
1783
1626
  if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1784
1627
  oldestQueuedAt = first;
1785
1628
  }
1786
- const kept = excess > 0 ? fresh.slice(excess) : fresh;
1787
- const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1788
- return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1629
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1630
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1631
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1632
+ }
1633
+ function listClaimFiles(outboxFilePath) {
1634
+ const dir = path.dirname(outboxFilePath);
1635
+ const prefix = `${path.basename(outboxFilePath)}.`;
1636
+ try {
1637
+ return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
1638
+ } catch {
1639
+ return [];
1640
+ }
1641
+ }
1642
+ function readEntries(file) {
1643
+ let raw;
1644
+ try {
1645
+ raw = fs.readFileSync(file, "utf8");
1646
+ } catch {
1647
+ return { entries: [], unreadable: 0 };
1648
+ }
1649
+ const entries = [];
1650
+ let unreadable = 0;
1651
+ for (const line of raw.split("\n")) {
1652
+ if (!line.trim())
1653
+ continue;
1654
+ try {
1655
+ const parsed = JSON.parse(line);
1656
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1657
+ unreadable += 1;
1658
+ continue;
1659
+ }
1660
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1661
+ } catch {
1662
+ unreadable += 1;
1663
+ }
1664
+ }
1665
+ return { entries, unreadable };
1666
+ }
1667
+ }
1668
+ });
1669
+
1670
+ // ../packages/tool-kit/out/backgroundDelivery.js
1671
+ var require_backgroundDelivery = __commonJS({
1672
+ "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
1673
+ "use strict";
1674
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1675
+ if (k2 === void 0) k2 = k;
1676
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1677
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1678
+ desc = { enumerable: true, get: function() {
1679
+ return m[k];
1680
+ } };
1681
+ }
1682
+ Object.defineProperty(o, k2, desc);
1683
+ } : function(o, m, k, k2) {
1684
+ if (k2 === void 0) k2 = k;
1685
+ o[k2] = m[k];
1686
+ });
1687
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1688
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1689
+ } : function(o, v) {
1690
+ o["default"] = v;
1691
+ });
1692
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1693
+ var ownKeys = function(o) {
1694
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1695
+ var ar = [];
1696
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1697
+ return ar;
1698
+ };
1699
+ return ownKeys(o);
1700
+ };
1701
+ return function(mod) {
1702
+ if (mod && mod.__esModule) return mod;
1703
+ var result = {};
1704
+ if (mod != null) {
1705
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1706
+ }
1707
+ __setModuleDefault(result, mod);
1708
+ return result;
1709
+ };
1710
+ }();
1711
+ Object.defineProperty(exports, "__esModule", { value: true });
1712
+ exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
1713
+ exports.hookDeliveryInline = hookDeliveryInline;
1714
+ exports.flushLockPath = flushLockPath;
1715
+ exports.startBackgroundFlush = startBackgroundFlush;
1716
+ exports.runOutboxFlush = runOutboxFlush;
1717
+ var fs = __importStar(__require("fs"));
1718
+ var child_process_1 = __require("child_process");
1719
+ var outbox_1 = require_outbox();
1720
+ exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
1721
+ exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
1722
+ exports.FLUSH_LOCK_FRESH_MS = 2e4;
1723
+ var FLUSH_MAX_PASSES = 20;
1724
+ var FLUSH_MAX_RUN_MS = 6e4;
1725
+ function hookDeliveryInline(env = process.env) {
1726
+ return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
1727
+ }
1728
+ function flushLockPath(outboxFilePath) {
1729
+ return `${outboxFilePath}.flushing`;
1730
+ }
1731
+ function lockIsFresh(lockPath, now) {
1732
+ try {
1733
+ return now - fs.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1734
+ } catch {
1735
+ return false;
1736
+ }
1737
+ }
1738
+ function touchLock(lockPath) {
1739
+ try {
1740
+ fs.writeFileSync(lockPath, `${process.pid}
1741
+ `, { encoding: "utf8", mode: 384 });
1742
+ } catch {
1743
+ }
1744
+ }
1745
+ function removeLock(lockPath) {
1746
+ try {
1747
+ fs.unlinkSync(lockPath);
1748
+ } catch {
1749
+ }
1750
+ }
1751
+ function outboxHasEntries(outboxFilePath) {
1752
+ try {
1753
+ return fs.statSync(outboxFilePath).size > 0;
1754
+ } catch {
1755
+ return false;
1756
+ }
1757
+ }
1758
+ function startBackgroundFlush(options) {
1759
+ const lockPath = flushLockPath(options.outboxFilePath);
1760
+ const now = options.now ?? Date.now();
1761
+ if (lockIsFresh(lockPath, now))
1762
+ return false;
1763
+ const script = options.script ?? process.argv[1];
1764
+ if (!script)
1765
+ return false;
1766
+ try {
1767
+ touchLock(lockPath);
1768
+ const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
1769
+ detached: true,
1770
+ stdio: "ignore",
1771
+ windowsHide: true,
1772
+ env: process.env
1773
+ });
1774
+ child.on("error", () => removeLock(lockPath));
1775
+ child.unref();
1776
+ return true;
1777
+ } catch {
1778
+ removeLock(lockPath);
1779
+ return false;
1780
+ }
1781
+ }
1782
+ async function runOutboxFlush(sender, now = Date.now) {
1783
+ const outboxFilePath = sender.outboxFilePath();
1784
+ const lockPath = flushLockPath(outboxFilePath);
1785
+ const started = now();
1786
+ let last;
1787
+ let passes = 0;
1788
+ const drain = async () => {
1789
+ while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
1790
+ passes += 1;
1791
+ touchLock(lockPath);
1792
+ last = await sender.flushOutbox();
1793
+ if (!last || last.found === 0 || last.halted || !last.sendEnabled)
1794
+ return;
1795
+ if (last.delivered === 0 && last.discarded === 0)
1796
+ return;
1797
+ }
1798
+ };
1799
+ try {
1800
+ await drain();
1801
+ removeLock(lockPath);
1802
+ if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
1803
+ touchLock(lockPath);
1804
+ await drain();
1805
+ removeLock(lockPath);
1806
+ }
1807
+ } catch {
1808
+ removeLock(lockPath);
1809
+ }
1810
+ return last;
1811
+ }
1812
+ }
1813
+ });
1814
+
1815
+ // ../packages/agent-events/out/index.js
1816
+ var require_out2 = __commonJS({
1817
+ "../packages/agent-events/out/index.js"(exports) {
1818
+ "use strict";
1819
+ Object.defineProperty(exports, "__esModule", { value: true });
1820
+ exports.KNOWN_AGENTS = exports.WAIT_REASONS = exports.VCS_ACTIONS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1821
+ exports.isAgentEventV0 = isAgentEventV0;
1822
+ exports.parseEventLogLine = parseEventLogLine;
1823
+ exports.normaliseKind = normaliseKind;
1824
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1825
+ exports.AGENT_EVENT_KINDS = [
1826
+ "session.started",
1827
+ "session.ended",
1828
+ "prompt.submitted",
1829
+ "tool.started",
1830
+ "tool.completed",
1831
+ "tool.failed",
1832
+ "turn.completed",
1833
+ "agent.waiting",
1834
+ "permission.requested",
1835
+ "permission.denied",
1836
+ "context.compacted",
1837
+ "subagent.started",
1838
+ "subagent.stopped",
1839
+ "pull_request.opened",
1840
+ "pull_request.closed",
1841
+ "pull_request.merged",
1842
+ "other"
1843
+ ];
1844
+ exports.VCS_ACTIONS = ["commit", "push", "pr_created", "pr_merged"];
1845
+ exports.WAIT_REASONS = ["permission", "idle", "input", "other"];
1846
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1847
+ function isAgentEventV0(value) {
1848
+ if (!value || typeof value !== "object")
1849
+ return false;
1850
+ const e = value;
1851
+ 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";
1852
+ }
1853
+ function parseEventLogLine(line) {
1854
+ if (!line.trim())
1855
+ return void 0;
1856
+ try {
1857
+ const parsed = JSON.parse(line);
1858
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1859
+ } catch {
1860
+ return void 0;
1861
+ }
1862
+ }
1863
+ function normaliseKind(kind) {
1864
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1865
+ }
1866
+ }
1867
+ });
1868
+
1869
+ // ../packages/tool-kit/out/agentEvent.js
1870
+ var require_agentEvent = __commonJS({
1871
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1872
+ "use strict";
1873
+ Object.defineProperty(exports, "__esModule", { value: true });
1874
+ exports.toAgentEvent = toAgentEvent;
1875
+ var agent_events_1 = require_out2();
1876
+ var KIND_BY_TYPE = {
1877
+ create_focus_session: "session.started",
1878
+ recovery_offline_period: "session.ended",
1879
+ ai_prompt_submitted: "prompt.submitted",
1880
+ ai_tool_call_started: "tool.started",
1881
+ ai_tool_call_completed: "tool.completed",
1882
+ ai_file_write: "tool.completed",
1883
+ ai_file_edit: "tool.completed",
1884
+ editor_verification_activity: "tool.completed",
1885
+ ai_tool_call_failed: "tool.failed",
1886
+ compile_error: "tool.failed",
1887
+ tool_failure: "tool.failed",
1888
+ ai_turn_completed: "turn.completed",
1889
+ supervision_interruption: "agent.waiting",
1890
+ permission_requested: "permission.requested",
1891
+ permission_denied: "permission.denied",
1892
+ context_compression_manual: "context.compacted",
1893
+ context_compression_auto: "context.compacted",
1894
+ subagent_started: "subagent.started",
1895
+ subagent_stopped: "subagent.stopped",
1896
+ pull_request_opened: "pull_request.opened",
1897
+ pull_request_closed: "pull_request.closed",
1898
+ pull_request_merged: "pull_request.merged"
1899
+ };
1900
+ function agentOf(payload) {
1901
+ const host = stringField(payload.metadata?.host);
1902
+ if (host)
1903
+ return host;
1904
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1905
+ }
1906
+ function vcsActionOf(metadata) {
1907
+ const milestone = stringField(metadata.milestoneKind);
1908
+ if (milestone === "pr_opened")
1909
+ return "pr_created";
1910
+ if (milestone === "pr_merged")
1911
+ return "pr_merged";
1912
+ const git = stringField(metadata.gitAction);
1913
+ return git === "commit" || git === "push" ? git : void 0;
1914
+ }
1915
+ function waitReasonOf(metadata) {
1916
+ switch (stringField(metadata.interruptionKind)) {
1917
+ case "permission_request":
1918
+ return "permission";
1919
+ case "input_request":
1920
+ return "input";
1921
+ case "idle_prompt":
1922
+ return "idle";
1923
+ case void 0:
1924
+ return void 0;
1925
+ default:
1926
+ return "other";
1927
+ }
1928
+ }
1929
+ function stringField(value) {
1930
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1931
+ }
1932
+ function toAgentEvent(payload) {
1933
+ const metadata = payload.metadata ?? {};
1934
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1935
+ const tool = kind.startsWith("tool.") || kind.startsWith("permission.") ? stringField(metadata.toolName) : void 0;
1936
+ const outcome = stringField(metadata.outcome);
1937
+ const vcsAction = kind === "tool.completed" ? vcsActionOf(metadata) : void 0;
1938
+ const reason = kind === "agent.waiting" ? waitReasonOf(metadata) : void 0;
1939
+ const model = kind === "session.started" ? stringField(metadata.modelId) : void 0;
1940
+ return {
1941
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1942
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1943
+ time: payload.occurredAt,
1944
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1945
+ // writes anyway; without it the event in memory and the one on disk differ.
1946
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1947
+ agent: agentOf(payload),
1948
+ kind,
1949
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1950
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1951
+ ...tool ? { tool } : {},
1952
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1953
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1954
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1955
+ ...stringField(metadata.repoKey) ? { repoKey: metadata.repoKey } : {},
1956
+ ...stringField(metadata.branchKey) ? { branchKey: metadata.branchKey } : {},
1957
+ ...stringField(metadata.autonomyMode) ? { permissionMode: metadata.autonomyMode } : {},
1958
+ ...stringField(metadata.headRepoKey) ? { headRepoKey: metadata.headRepoKey } : {},
1959
+ ...stringField(metadata.prCreatedAt) ? { prCreatedAt: metadata.prCreatedAt } : {},
1960
+ ...stringField(metadata.prClosedAt) ? { prClosedAt: metadata.prClosedAt } : {},
1961
+ ...stringField(metadata.prMergedAt) ? { prMergedAt: metadata.prMergedAt } : {},
1962
+ ...stringField(metadata.promptId) ? { promptId: metadata.promptId } : {},
1963
+ ...vcsAction ? { vcsAction } : {},
1964
+ ...reason ? { reason } : {},
1965
+ ...model ? { model } : {},
1966
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1967
+ sourceType: payload.eventType
1968
+ };
1969
+ }
1970
+ }
1971
+ });
1972
+
1973
+ // ../packages/tool-kit/out/credentials.js
1974
+ var require_credentials = __commonJS({
1975
+ "../packages/tool-kit/out/credentials.js"(exports) {
1976
+ "use strict";
1977
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1978
+ if (k2 === void 0) k2 = k;
1979
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1980
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1981
+ desc = { enumerable: true, get: function() {
1982
+ return m[k];
1983
+ } };
1984
+ }
1985
+ Object.defineProperty(o, k2, desc);
1986
+ } : function(o, m, k, k2) {
1987
+ if (k2 === void 0) k2 = k;
1988
+ o[k2] = m[k];
1989
+ });
1990
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1991
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1992
+ } : function(o, v) {
1993
+ o["default"] = v;
1994
+ });
1995
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1996
+ var ownKeys = function(o) {
1997
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1998
+ var ar = [];
1999
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2000
+ return ar;
2001
+ };
2002
+ return ownKeys(o);
2003
+ };
2004
+ return function(mod) {
2005
+ if (mod && mod.__esModule) return mod;
2006
+ var result = {};
2007
+ if (mod != null) {
2008
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2009
+ }
2010
+ __setModuleDefault(result, mod);
2011
+ return result;
2012
+ };
2013
+ }();
2014
+ Object.defineProperty(exports, "__esModule", { value: true });
2015
+ exports.credentialsFilePath = credentialsFilePath;
2016
+ exports.readMachineCredentials = readMachineCredentials;
2017
+ exports.writeMachineCredentials = writeMachineCredentials;
2018
+ exports.writeTopLevelCredentials = writeTopLevelCredentials;
2019
+ exports.writeRepoKeysSetting = writeRepoKeysSetting;
2020
+ exports.writeEventLogSetting = writeEventLogSetting;
2021
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2022
+ exports.readHostCredentials = readHostCredentials;
2023
+ exports.writeHostCredentials = writeHostCredentials;
2024
+ exports.removeHostCredentials = removeHostCredentials;
2025
+ var fs = __importStar(__require("fs"));
2026
+ var path = __importStar(__require("path"));
2027
+ var tokenStore_1 = require_tokenStore();
2028
+ function credentialsFilePath() {
2029
+ return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2030
+ }
2031
+ function readMachineCredentials() {
2032
+ try {
2033
+ const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
2034
+ if (!raw)
2035
+ return void 0;
2036
+ const parsed = JSON.parse(raw);
2037
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2038
+ return void 0;
2039
+ return parsed;
2040
+ } catch {
2041
+ return void 0;
2042
+ }
2043
+ }
2044
+ function writeMachineCredentials(credentials) {
2045
+ const file = credentialsFilePath();
2046
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2047
+ fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2048
+ `, { encoding: "utf8", mode: 384 });
2049
+ if (process.platform !== "win32") {
2050
+ fs.chmodSync(path.dirname(file), 448);
2051
+ fs.chmodSync(file, 384);
2052
+ }
2053
+ }
2054
+ function writeTopLevelCredentials(credentials) {
2055
+ const existing = readMachineCredentials();
2056
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
2057
+ const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
2058
+ writeMachineCredentials({
2059
+ ...credentials,
2060
+ ...eventLogPath ? { eventLogPath } : {},
2061
+ ...repoKeys === false ? { repoKeys } : {},
2062
+ ...existing?.tools ? { tools: existing.tools } : {}
2063
+ });
2064
+ }
2065
+ function writeRepoKeysSetting(on) {
2066
+ const existing = readMachineCredentials() ?? {};
2067
+ const { repoKeys: _dropped, ...rest } = existing;
2068
+ writeMachineCredentials(on ? rest : { ...rest, repoKeys: false });
2069
+ }
2070
+ function writeEventLogSetting(value) {
2071
+ const existing = readMachineCredentials() ?? {};
2072
+ writeMachineCredentials({ ...existing, eventLogPath: value });
2073
+ }
2074
+ function isLocalOnlyHostInstall(host, hasToken) {
2075
+ const credentials = readHostCredentials(host);
2076
+ if (!credentials?.localOnly)
2077
+ return false;
2078
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2079
+ return false;
2080
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2081
+ }
2082
+ function readHostCredentials(host) {
2083
+ const entry = readMachineCredentials()?.tools?.[host];
2084
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
2085
+ return void 0;
2086
+ return entry;
2087
+ }
2088
+ function writeHostCredentials(host, credentials) {
2089
+ const existing = readMachineCredentials() ?? {};
2090
+ writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2091
+ }
2092
+ function removeHostCredentials(host) {
2093
+ const existing = readMachineCredentials();
2094
+ if (!existing?.tools || !(host in existing.tools))
2095
+ return;
2096
+ const tools = { ...existing.tools };
2097
+ delete tools[host];
2098
+ const next = { ...existing };
2099
+ if (Object.keys(tools).length)
2100
+ next.tools = tools;
2101
+ else
2102
+ delete next.tools;
2103
+ writeMachineCredentials(next);
2104
+ }
2105
+ }
2106
+ });
2107
+
2108
+ // ../packages/tool-kit/out/eventLog.js
2109
+ var require_eventLog = __commonJS({
2110
+ "../packages/tool-kit/out/eventLog.js"(exports) {
2111
+ "use strict";
2112
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2113
+ if (k2 === void 0) k2 = k;
2114
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2115
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2116
+ desc = { enumerable: true, get: function() {
2117
+ return m[k];
2118
+ } };
2119
+ }
2120
+ Object.defineProperty(o, k2, desc);
2121
+ } : function(o, m, k, k2) {
2122
+ if (k2 === void 0) k2 = k;
2123
+ o[k2] = m[k];
2124
+ });
2125
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2126
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2127
+ } : function(o, v) {
2128
+ o["default"] = v;
2129
+ });
2130
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2131
+ var ownKeys = function(o) {
2132
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2133
+ var ar = [];
2134
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2135
+ return ar;
2136
+ };
2137
+ return ownKeys(o);
2138
+ };
2139
+ return function(mod) {
2140
+ if (mod && mod.__esModule) return mod;
2141
+ var result = {};
2142
+ if (mod != null) {
2143
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2144
+ }
2145
+ __setModuleDefault(result, mod);
2146
+ return result;
2147
+ };
2148
+ }();
2149
+ Object.defineProperty(exports, "__esModule", { value: true });
2150
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
2151
+ exports.expandUserPath = expandUserPath;
2152
+ exports.defaultEventLogPath = defaultEventLogPath;
2153
+ exports.resolveEventLog = resolveEventLog;
2154
+ exports.resolveEventLogPath = resolveEventLogPath;
2155
+ exports.describeEventLog = describeEventLog;
2156
+ exports.parseEventLogFlag = parseEventLogFlag;
2157
+ exports.appendEventLog = appendEventLog;
2158
+ var fs = __importStar(__require("fs"));
2159
+ var os = __importStar(__require("os"));
2160
+ var path = __importStar(__require("path"));
2161
+ var agentEvent_1 = require_agentEvent();
2162
+ var credentials_1 = require_credentials();
2163
+ var tokenStore_1 = require_tokenStore();
2164
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
2165
+ exports.EVENT_LOG_OFF = "off";
2166
+ var MAX_BYTES = 5 * 1024 * 1024;
2167
+ function expandUserPath(configured) {
2168
+ const value = configured?.trim();
2169
+ if (!value)
2170
+ return void 0;
2171
+ if (value === "~")
2172
+ return os.homedir();
2173
+ if (value.startsWith("~/"))
2174
+ return path.join(os.homedir(), value.slice(2));
2175
+ return path.resolve(value);
2176
+ }
2177
+ function defaultEventLogPath() {
2178
+ return path.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
2179
+ }
2180
+ function resolveEventLog(options = {}) {
2181
+ for (const [source, raw] of [
2182
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
2183
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
2184
+ ]) {
2185
+ const value = raw?.trim();
2186
+ if (!value)
2187
+ continue;
2188
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
2189
+ return { path: void 0, source: "disabled" };
2190
+ return { path: expandUserPath(value), source };
2191
+ }
2192
+ if (options.localOnly)
2193
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
2194
+ return { path: void 0, source: "off" };
2195
+ }
2196
+ function resolveEventLogPath(options = {}) {
2197
+ return resolveEventLog(options).path;
2198
+ }
2199
+ function describeEventLog(setting, command) {
2200
+ switch (setting.source) {
2201
+ case "env":
2202
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
2203
+ case "credentials":
2204
+ return `${setting.path} (set by ${command} --event-log)`;
2205
+ case "unpaired-default":
2206
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
2207
+ case "disabled":
2208
+ return `off (turned off; ${command} --event-log to turn it on)`;
2209
+ case "off":
2210
+ return `off (${command} --event-log to keep a local copy of every event)`;
2211
+ }
2212
+ }
2213
+ function parseEventLogFlag(argv, index) {
2214
+ const peek = argv[index + 1];
2215
+ if (peek !== void 0 && !peek.startsWith("-"))
2216
+ return { value: peek, consumed: 1 };
2217
+ return { value: defaultEventLogPath(), consumed: 0 };
2218
+ }
2219
+ function appendEventLog(logFilePath, entry) {
2220
+ try {
2221
+ rotateIfLarge(logFilePath);
2222
+ const dir = path.dirname(logFilePath);
2223
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
2224
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
2225
+ fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
2226
+ `, { encoding: "utf8", mode: 384 });
2227
+ if (process.platform !== "win32")
2228
+ fs.chmodSync(logFilePath, 384);
2229
+ } catch {
2230
+ }
2231
+ }
2232
+ function rotateIfLarge(logFilePath) {
2233
+ try {
2234
+ if (fs.statSync(logFilePath).size < MAX_BYTES)
2235
+ return;
2236
+ fs.renameSync(logFilePath, `${logFilePath}.1`);
2237
+ } catch {
2238
+ }
2239
+ }
2240
+ }
2241
+ });
2242
+
2243
+ // ../packages/tool-kit/out/http.js
2244
+ var require_http = __commonJS({
2245
+ "../packages/tool-kit/out/http.js"(exports) {
2246
+ "use strict";
2247
+ Object.defineProperty(exports, "__esModule", { value: true });
2248
+ exports.AscendaApiError = void 0;
2249
+ exports.createPairingSession = createPairingSession;
2250
+ exports.getPairingStatus = getPairingStatus;
2251
+ exports.startStudyJoin = startStudyJoin;
2252
+ exports.getStudyJoinStatus = getStudyJoinStatus;
2253
+ exports.readInitiatives = readInitiatives;
2254
+ exports.readStudyNotices = readStudyNotices;
2255
+ exports.setStudyObjection = setStudyObjection;
2256
+ exports.markStudyNoticeShown = markStudyNoticeShown;
2257
+ exports.renewToolToken = renewToolToken;
2258
+ exports.isRetryableStatus = isRetryableStatus;
2259
+ exports.postToolEvent = postToolEvent;
2260
+ exports.postToolEventsBatch = postToolEventsBatch;
2261
+ exports.parseIngestResponse = parseIngestResponse;
2262
+ var tool_contract_1 = require_out();
2263
+ var AscendaApiError = class extends Error {
2264
+ status;
2265
+ errorCode;
2266
+ constructor(status, errorCode, body) {
2267
+ super(body ?? `Ascenda API error ${status}`);
2268
+ this.status = status;
2269
+ this.errorCode = errorCode;
2270
+ this.name = "AscendaApiError";
2271
+ }
2272
+ };
2273
+ exports.AscendaApiError = AscendaApiError;
2274
+ async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
2275
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
2276
+ method: "POST",
2277
+ headers: { "Content-Type": "application/json" },
2278
+ body: JSON.stringify({ toolInstallationId, toolType, displayName })
2279
+ });
2280
+ if (!response.ok)
2281
+ throw new AscendaApiError(response.status, void 0, await response.text());
2282
+ return await response.json();
2283
+ }
2284
+ async function getPairingStatus(apiBaseUrl, pairingSessionId) {
2285
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
2286
+ method: "GET",
2287
+ headers: { Accept: "application/json" }
2288
+ });
2289
+ if (!response.ok)
2290
+ throw new AscendaApiError(response.status, void 0, await response.text());
2291
+ return await response.json();
2292
+ }
2293
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
2294
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2295
+ method: "POST",
2296
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2297
+ body: JSON.stringify({ joinCode, mode })
2298
+ });
2299
+ if (!response.ok)
2300
+ throw await apiError(response);
2301
+ return await response.json();
2302
+ }
2303
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
2304
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
2305
+ method: "GET",
2306
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
2307
+ });
2308
+ if (!response.ok)
2309
+ throw await apiError(response);
2310
+ return await response.json();
2311
+ }
2312
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
2313
+ let response;
2314
+ try {
2315
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
2316
+ method: "GET",
2317
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2318
+ signal
2319
+ });
2320
+ } catch (error) {
2321
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2322
+ }
2323
+ if (response.status === 401)
2324
+ return { kind: "rejected", httpStatus: 401 };
2325
+ if (!response.ok)
2326
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2327
+ let body;
2328
+ try {
2329
+ body = await response.json();
2330
+ } catch {
2331
+ return { kind: "failed", reason: "the reply was not readable" };
2332
+ }
2333
+ if (!Array.isArray(body))
2334
+ return { kind: "failed", reason: "the reply was not a list" };
2335
+ return { kind: "ok", initiatives: body };
2336
+ }
2337
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
2338
+ let response;
2339
+ try {
2340
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
2341
+ method: "GET",
2342
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2343
+ signal
2344
+ });
2345
+ } catch (error) {
2346
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2347
+ }
2348
+ if (response.status === 404)
2349
+ return { kind: "absent" };
2350
+ if (response.status === 401)
2351
+ return { kind: "rejected", httpStatus: 401 };
2352
+ if (!response.ok)
2353
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2354
+ let body;
2355
+ try {
2356
+ body = await response.json();
2357
+ } catch {
2358
+ return { kind: "absent" };
2359
+ }
2360
+ if (!Array.isArray(body))
2361
+ return { kind: "absent" };
2362
+ return { kind: "ok", notices: body };
1789
2363
  }
1790
- function listClaimFiles(outboxFilePath) {
1791
- const dir = path.dirname(outboxFilePath);
1792
- const prefix = `${path.basename(outboxFilePath)}.`;
2364
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
2365
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
2366
+ method: objected ? "POST" : "DELETE",
2367
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
2368
+ });
2369
+ if (!response.ok)
2370
+ throw await apiError(response);
2371
+ }
2372
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1793
2373
  try {
1794
- return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
2374
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
2375
+ method: "POST",
2376
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
2377
+ signal
2378
+ });
2379
+ return response.ok;
1795
2380
  } catch {
1796
- return [];
2381
+ return false;
1797
2382
  }
1798
2383
  }
1799
- function readEntries(file) {
1800
- let raw;
2384
+ async function apiError(response) {
2385
+ const body = await response.text();
2386
+ let errorCode;
1801
2387
  try {
1802
- raw = fs.readFileSync(file, "utf8");
2388
+ const parsed = JSON.parse(body);
2389
+ errorCode = parsed.code ?? parsed.error;
1803
2390
  } catch {
1804
- return { entries: [], unreadable: 0 };
2391
+ errorCode = void 0;
1805
2392
  }
1806
- const entries = [];
1807
- let unreadable = 0;
1808
- for (const line of raw.split("\n")) {
1809
- if (!line.trim())
2393
+ return new AscendaApiError(response.status, errorCode, body);
2394
+ }
2395
+ async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
2396
+ const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
2397
+ method: "POST",
2398
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2399
+ signal
2400
+ });
2401
+ if (response.status === 401)
2402
+ return null;
2403
+ if (!response.ok)
2404
+ throw new AscendaApiError(response.status, void 0, await response.text());
2405
+ return await response.json();
2406
+ }
2407
+ function isDeliveredStatus(value) {
2408
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
2409
+ }
2410
+ function readSuccessBody(body) {
2411
+ let parsed;
2412
+ try {
2413
+ parsed = JSON.parse(body);
2414
+ } catch {
2415
+ return { duplicates: 0 };
2416
+ }
2417
+ if (!parsed || typeof parsed !== "object")
2418
+ return { duplicates: 0 };
2419
+ const single = parsed.status;
2420
+ if (isDeliveredStatus(single))
2421
+ return { duplicates: single === "duplicate" ? 1 : 0 };
2422
+ const raw = parsed.results;
2423
+ if (!Array.isArray(raw))
2424
+ return { duplicates: 0 };
2425
+ const results = [];
2426
+ for (const item of raw) {
2427
+ if (!item || typeof item !== "object")
1810
2428
  continue;
2429
+ const { index, status, reason } = item;
2430
+ if (typeof index !== "number" || typeof status !== "string")
2431
+ continue;
2432
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
2433
+ }
2434
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
2435
+ }
2436
+ function isRetryableStatus(status) {
2437
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
2438
+ }
2439
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
2440
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
2441
+ }
2442
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
2443
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
2444
+ }
2445
+ async function sendIngest(url, eventWriteToken, body, signal) {
2446
+ try {
2447
+ const response = await fetch(url, {
2448
+ method: "POST",
2449
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2450
+ body,
2451
+ signal
2452
+ });
2453
+ return parseIngestResponse(response);
2454
+ } catch (error) {
2455
+ return {
2456
+ result: "transport_error",
2457
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
2458
+ };
2459
+ }
2460
+ }
2461
+ async function parseIngestResponse(response) {
2462
+ if (response.ok) {
2463
+ const outcome = { result: "accepted", httpStatus: response.status };
2464
+ let read = { duplicates: 0 };
1811
2465
  try {
1812
- const parsed = JSON.parse(line);
1813
- if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1814
- unreadable += 1;
1815
- continue;
1816
- }
1817
- entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
2466
+ read = readSuccessBody(await response.text());
1818
2467
  } catch {
1819
- unreadable += 1;
2468
+ read = { duplicates: 0 };
1820
2469
  }
2470
+ return {
2471
+ ...outcome,
2472
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
2473
+ ...read.results !== void 0 ? { results: read.results } : {}
2474
+ };
1821
2475
  }
1822
- return { entries, unreadable };
2476
+ const body = await response.text();
2477
+ let errorCode;
2478
+ try {
2479
+ errorCode = JSON.parse(body).error;
2480
+ } catch {
2481
+ errorCode = void 0;
2482
+ }
2483
+ const base2 = { httpStatus: response.status, errorCode, detail: body || void 0 };
2484
+ if (response.status === 401)
2485
+ return { ...base2, result: "auth_failed" };
2486
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
2487
+ return { ...base2, result: "consent_missing" };
2488
+ if (response.status === 400 || response.status === 422)
2489
+ return { ...base2, result: "validation_failed" };
2490
+ return { ...base2, result: "transport_error" };
1823
2491
  }
1824
2492
  }
1825
2493
  });
@@ -1849,6 +2517,7 @@ var require_eventSender = __commonJS({
1849
2517
  "use strict";
1850
2518
  Object.defineProperty(exports, "__esModule", { value: true });
1851
2519
  exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
2520
+ exports.buildEventBody = buildEventBody;
1852
2521
  exports.buildEventPayload = buildEventPayload;
1853
2522
  var afterHours_1 = require_afterHours();
1854
2523
  var tool_contract_1 = require_out();
@@ -1867,12 +2536,10 @@ var require_eventSender = __commonJS({
1867
2536
  }
1868
2537
  };
1869
2538
  exports.AscendaSemanticEventError = AscendaSemanticEventError;
1870
- function buildEventPayload(identity, mapped) {
2539
+ function buildEventBody(identity, mapped) {
1871
2540
  return {
1872
- toolInstallationId: identity.toolInstallationId,
1873
2541
  source: identity.source,
1874
2542
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1875
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1876
2543
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1877
2544
  sessionId: identity.sessionId ?? void 0,
1878
2545
  workspaceHash: identity.workspaceHash ?? void 0,
@@ -1884,6 +2551,9 @@ var require_eventSender = __commonJS({
1884
2551
  metadata: withCollectorVersion(mapped.metadata)
1885
2552
  };
1886
2553
  }
2554
+ function buildEventPayload(identity, mapped) {
2555
+ return (0, tool_contract_1.joinEventPayload)({ toolInstallationId: identity.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() }, buildEventBody(identity, mapped));
2556
+ }
1887
2557
  function withCollectorVersion(metadata) {
1888
2558
  return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION };
1889
2559
  }
@@ -1959,12 +2629,10 @@ var require_eventSender = __commonJS({
1959
2629
  if (!mapped.metadata.skillVersion || !mapped.metadata.skillVersion.trim()) {
1960
2630
  throw new AscendaSemanticEventError(`metadata.skillVersion is required for semantic event "${mapped.eventType}".`);
1961
2631
  }
1962
- const payload = {
1963
- toolInstallationId: this.config.toolInstallationId,
2632
+ const body = {
1964
2633
  source: this.config.source,
1965
2634
  eventType: mapped.eventType,
1966
2635
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1967
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1968
2636
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1969
2637
  severity: "low",
1970
2638
  sessionId: this.config.sessionId ?? void 0,
@@ -1975,7 +2643,7 @@ var require_eventSender = __commonJS({
1975
2643
  privacyMode: "metadata_only",
1976
2644
  metadata: withCollectorVersion(mapped.metadata)
1977
2645
  };
1978
- return this.post(payload);
2646
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
1979
2647
  }
1980
2648
  /**
1981
2649
  * Sends a collaboration event under `workflow_telemetry`.
@@ -1990,12 +2658,10 @@ var require_eventSender = __commonJS({
1990
2658
  if (!tool_contract_1.COLLABORATION_EVENT_TYPES.includes(mapped.eventType)) {
1991
2659
  throw new AscendaSemanticEventError(`"${mapped.eventType}" is not a collaboration event type. Use send() for a deterministic host event.`);
1992
2660
  }
1993
- const payload = {
1994
- toolInstallationId: this.config.toolInstallationId,
2661
+ const body = {
1995
2662
  source: this.config.source,
1996
2663
  eventType: mapped.eventType,
1997
2664
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1998
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1999
2665
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
2000
2666
  severity: "low",
2001
2667
  sessionId: this.config.sessionId ?? void 0,
@@ -2006,7 +2672,11 @@ var require_eventSender = __commonJS({
2006
2672
  privacyMode: "metadata_only",
2007
2673
  metadata: withCollectorVersion(mapped.metadata)
2008
2674
  };
2009
- return this.post(payload);
2675
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
2676
+ }
2677
+ /** A fresh envelope per event: the key belongs to the event, so every retry of it reuses this one. */
2678
+ envelope() {
2679
+ return { toolInstallationId: this.config.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() };
2010
2680
  }
2011
2681
  /**
2012
2682
  * The single choke point every event passes through, and therefore the only
@@ -2070,6 +2740,29 @@ var require_eventSender = __commonJS({
2070
2740
  }
2071
2741
  return outcome;
2072
2742
  }
2743
+ /**
2744
+ * One outbox pass with nothing live to send: what a background flusher runs,
2745
+ * once per batch. Unlike the pass {@link post} makes, it may run more than
2746
+ * once per sender, because a flusher isn't on anyone's critical path.
2747
+ *
2748
+ * A halted pass is journaled here. Inside {@link post} the live send that
2749
+ * follows journals it, and a flusher has no live send, so without this an
2750
+ * outage would never reach the journal `doctor` and the notices read.
2751
+ */
2752
+ async flushOutbox() {
2753
+ await this.renewIfExpiring();
2754
+ this.outboxServiced = false;
2755
+ this.lastDrain = void 0;
2756
+ const halted = await this.serviceOutbox();
2757
+ if (halted) {
2758
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, halted.result, {
2759
+ httpStatus: halted.httpStatus,
2760
+ errorCode: halted.errorCode,
2761
+ detail: withNote(halted.detail, "kept in outbox")
2762
+ });
2763
+ }
2764
+ return this.lastDrain;
2765
+ }
2073
2766
  /** A failure that never reached a verdict. Replaying can change the answer. */
2074
2767
  isRetryable(outcome) {
2075
2768
  return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
@@ -2395,151 +3088,34 @@ var require_contextRegistry = __commonJS({
2395
3088
  if (existing.paths.length < MAX_PATHS_PER_ENTRY)
2396
3089
  existing.paths.push(update.observedPath);
2397
3090
  dirty = true;
2398
- }
2399
- if (dayOf(existing.lastSeenAt) !== dayOf(nowIso)) {
2400
- existing.lastSeenAt = nowIso;
2401
- dirty = true;
2402
- }
2403
- }
2404
- if (!dirty)
2405
- return false;
2406
- writeRegistry(registryFilePath, registry);
2407
- return true;
2408
- } catch {
2409
- return false;
2410
- }
2411
- }
2412
- function dayOf(iso) {
2413
- return iso.slice(0, 10);
2414
- }
2415
- function writeRegistry(registryFilePath, registry) {
2416
- const dir = path.dirname(registryFilePath);
2417
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
2418
- const tmp = `${registryFilePath}.${process.pid}.tmp`;
2419
- fs.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2420
- `, { encoding: "utf8", mode: 384 });
2421
- fs.renameSync(tmp, registryFilePath);
2422
- if (process.platform !== "win32") {
2423
- fs.chmodSync(registryFilePath, 384);
2424
- }
2425
- }
2426
- }
2427
- });
2428
-
2429
- // ../packages/tool-kit/out/credentials.js
2430
- var require_credentials = __commonJS({
2431
- "../packages/tool-kit/out/credentials.js"(exports) {
2432
- "use strict";
2433
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2434
- if (k2 === void 0) k2 = k;
2435
- var desc = Object.getOwnPropertyDescriptor(m, k);
2436
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2437
- desc = { enumerable: true, get: function() {
2438
- return m[k];
2439
- } };
2440
- }
2441
- Object.defineProperty(o, k2, desc);
2442
- } : function(o, m, k, k2) {
2443
- if (k2 === void 0) k2 = k;
2444
- o[k2] = m[k];
2445
- });
2446
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2447
- Object.defineProperty(o, "default", { enumerable: true, value: v });
2448
- } : function(o, v) {
2449
- o["default"] = v;
2450
- });
2451
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2452
- var ownKeys = function(o) {
2453
- ownKeys = Object.getOwnPropertyNames || function(o2) {
2454
- var ar = [];
2455
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2456
- return ar;
2457
- };
2458
- return ownKeys(o);
2459
- };
2460
- return function(mod) {
2461
- if (mod && mod.__esModule) return mod;
2462
- var result = {};
2463
- if (mod != null) {
2464
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2465
- }
2466
- __setModuleDefault(result, mod);
2467
- return result;
2468
- };
2469
- }();
2470
- Object.defineProperty(exports, "__esModule", { value: true });
2471
- exports.credentialsFilePath = credentialsFilePath;
2472
- exports.readMachineCredentials = readMachineCredentials;
2473
- exports.writeMachineCredentials = writeMachineCredentials;
2474
- exports.writeTopLevelCredentials = writeTopLevelCredentials;
2475
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2476
- exports.readHostCredentials = readHostCredentials;
2477
- exports.writeHostCredentials = writeHostCredentials;
2478
- exports.removeHostCredentials = removeHostCredentials;
2479
- var fs = __importStar(__require("fs"));
2480
- var path = __importStar(__require("path"));
2481
- var tokenStore_1 = require_tokenStore();
2482
- function credentialsFilePath() {
2483
- return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2484
- }
2485
- function readMachineCredentials() {
2486
- try {
2487
- const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
2488
- if (!raw)
2489
- return void 0;
2490
- const parsed = JSON.parse(raw);
2491
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2492
- return void 0;
2493
- return parsed;
3091
+ }
3092
+ if (dayOf(existing.lastSeenAt) !== dayOf(nowIso)) {
3093
+ existing.lastSeenAt = nowIso;
3094
+ dirty = true;
3095
+ }
3096
+ }
3097
+ if (!dirty)
3098
+ return false;
3099
+ writeRegistry(registryFilePath, registry);
3100
+ return true;
2494
3101
  } catch {
2495
- return void 0;
3102
+ return false;
2496
3103
  }
2497
3104
  }
2498
- function writeMachineCredentials(credentials) {
2499
- const file = credentialsFilePath();
2500
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2501
- fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
3105
+ function dayOf(iso) {
3106
+ return iso.slice(0, 10);
3107
+ }
3108
+ function writeRegistry(registryFilePath, registry) {
3109
+ const dir = path.dirname(registryFilePath);
3110
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
3111
+ const tmp = `${registryFilePath}.${process.pid}.tmp`;
3112
+ fs.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2502
3113
  `, { encoding: "utf8", mode: 384 });
3114
+ fs.renameSync(tmp, registryFilePath);
2503
3115
  if (process.platform !== "win32") {
2504
- fs.chmodSync(path.dirname(file), 448);
2505
- fs.chmodSync(file, 384);
3116
+ fs.chmodSync(registryFilePath, 384);
2506
3117
  }
2507
3118
  }
2508
- function writeTopLevelCredentials(credentials) {
2509
- const existing = readMachineCredentials();
2510
- writeMachineCredentials({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2511
- }
2512
- function isLocalOnlyHostInstall(host, hasToken) {
2513
- const credentials = readHostCredentials(host);
2514
- if (!credentials?.localOnly)
2515
- return false;
2516
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2517
- return false;
2518
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2519
- }
2520
- function readHostCredentials(host) {
2521
- const entry = readMachineCredentials()?.tools?.[host];
2522
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
2523
- return void 0;
2524
- return entry;
2525
- }
2526
- function writeHostCredentials(host, credentials) {
2527
- const existing = readMachineCredentials() ?? {};
2528
- writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2529
- }
2530
- function removeHostCredentials(host) {
2531
- const existing = readMachineCredentials();
2532
- if (!existing?.tools || !(host in existing.tools))
2533
- return;
2534
- const tools = { ...existing.tools };
2535
- delete tools[host];
2536
- const next = { ...existing };
2537
- if (Object.keys(tools).length)
2538
- next.tools = tools;
2539
- else
2540
- delete next.tools;
2541
- writeMachineCredentials(next);
2542
- }
2543
3119
  }
2544
3120
  });
2545
3121
 
@@ -2586,6 +3162,8 @@ var require_forgeProject = __commonJS({
2586
3162
  }();
2587
3163
  Object.defineProperty(exports, "__esModule", { value: true });
2588
3164
  exports.forgeProjectHash = forgeProjectHash2;
3165
+ exports.forgeRepoKey = forgeRepoKey2;
3166
+ exports.forgeBranchKey = forgeBranchKey2;
2589
3167
  exports.parseForgeFullName = parseForgeFullName;
2590
3168
  exports.readForgeFullName = readForgeFullName;
2591
3169
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
@@ -2601,6 +3179,19 @@ var require_forgeProject = __commonJS({
2601
3179
  }
2602
3180
  return h.toString(16).padStart(8, "0");
2603
3181
  }
3182
+ function forgeRepoKey2(fullName) {
3183
+ return forgeProjectHash2(fullName.toLowerCase());
3184
+ }
3185
+ function forgeBranchKey2(fullName, branch) {
3186
+ const input = `${fullName.toLowerCase()}
3187
+ ${branch}`;
3188
+ let h = 0xcbf29ce484222325n;
3189
+ for (const byte of Buffer.from(input, "utf8")) {
3190
+ h ^= BigInt(byte);
3191
+ h = BigInt.asUintN(64, h * 0x100000001b3n);
3192
+ }
3193
+ return h.toString(16).padStart(16, "0");
3194
+ }
2604
3195
  function parseForgeFullName(remoteUrl) {
2605
3196
  if (!remoteUrl)
2606
3197
  return null;
@@ -2987,6 +3578,95 @@ var require_workContext = __commonJS({
2987
3578
  }
2988
3579
  });
2989
3580
 
3581
+ // ../packages/tool-kit/out/forgeKeys.js
3582
+ var require_forgeKeys = __commonJS({
3583
+ "../packages/tool-kit/out/forgeKeys.js"(exports) {
3584
+ "use strict";
3585
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3586
+ if (k2 === void 0) k2 = k;
3587
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3588
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3589
+ desc = { enumerable: true, get: function() {
3590
+ return m[k];
3591
+ } };
3592
+ }
3593
+ Object.defineProperty(o, k2, desc);
3594
+ } : function(o, m, k, k2) {
3595
+ if (k2 === void 0) k2 = k;
3596
+ o[k2] = m[k];
3597
+ });
3598
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3599
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3600
+ } : function(o, v) {
3601
+ o["default"] = v;
3602
+ });
3603
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3604
+ var ownKeys = function(o) {
3605
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3606
+ var ar = [];
3607
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3608
+ return ar;
3609
+ };
3610
+ return ownKeys(o);
3611
+ };
3612
+ return function(mod) {
3613
+ if (mod && mod.__esModule) return mod;
3614
+ var result = {};
3615
+ if (mod != null) {
3616
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3617
+ }
3618
+ __setModuleDefault(result, mod);
3619
+ return result;
3620
+ };
3621
+ }();
3622
+ Object.defineProperty(exports, "__esModule", { value: true });
3623
+ exports.REPO_KEYS_ENV_VAR = void 0;
3624
+ exports.repoKeysEnabled = repoKeysEnabled2;
3625
+ exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd;
3626
+ var fs = __importStar(__require("fs"));
3627
+ var path = __importStar(__require("path"));
3628
+ var credentials_1 = require_credentials();
3629
+ var forgeProject_1 = require_forgeProject();
3630
+ var workContext_1 = require_workContext();
3631
+ exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
3632
+ function repoKeysEnabled2() {
3633
+ const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
3634
+ if (env === "off" || env === "0" || env === "false")
3635
+ return false;
3636
+ if (env === "on" || env === "1" || env === "true")
3637
+ return true;
3638
+ return (0, credentials_1.readMachineCredentials)()?.repoKeys !== false;
3639
+ }
3640
+ function readDefaultBranch(repositoryRoot) {
3641
+ try {
3642
+ const head = fs.readFileSync(path.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
3643
+ const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
3644
+ return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
3645
+ } catch {
3646
+ return null;
3647
+ }
3648
+ }
3649
+ function deriveForgeKeysForCwd(cwd) {
3650
+ try {
3651
+ if (!cwd || !repoKeysEnabled2())
3652
+ return {};
3653
+ const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
3654
+ const fullName = (0, forgeProject_1.readForgeFullName)(root);
3655
+ if (!root || !fullName)
3656
+ return {};
3657
+ const branch = (0, workContext_1.readBranchName)(cwd);
3658
+ const onDefault = branch !== null && branch === readDefaultBranch(root);
3659
+ return {
3660
+ repoKey: (0, forgeProject_1.forgeRepoKey)(fullName),
3661
+ ...branch && !onDefault ? { branchKey: (0, forgeProject_1.forgeBranchKey)(fullName, branch) } : {}
3662
+ };
3663
+ } catch {
3664
+ return {};
3665
+ }
3666
+ }
3667
+ }
3668
+ });
3669
+
2990
3670
  // ../packages/tool-kit/out/hookAdapter.js
2991
3671
  var require_hookAdapter = __commonJS({
2992
3672
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
@@ -2996,13 +3676,18 @@ var require_hookAdapter = __commonJS({
2996
3676
  exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
2997
3677
  exports.resolveContextHashes = resolveContextHashes;
2998
3678
  exports.loadCliAgentConfig = loadCliAgentConfig;
3679
+ exports.withForgeKeys = withForgeKeys;
3680
+ exports.withPromptId = withPromptId;
2999
3681
  exports.deliverHookEvents = deliverHookEvents;
3682
+ exports.flushHookOutbox = flushHookOutbox;
3000
3683
  var contextRegistry_1 = require_contextRegistry();
3001
3684
  var credentials_1 = require_credentials();
3002
3685
  var forgeProject_1 = require_forgeProject();
3003
3686
  var eventLog_1 = require_eventLog();
3687
+ var forgeKeys_1 = require_forgeKeys();
3004
3688
  var eventSender_1 = require_eventSender();
3005
3689
  var stateStore_1 = require_stateStore();
3690
+ var backgroundDelivery_1 = require_backgroundDelivery();
3006
3691
  var tokenStore_1 = require_tokenStore();
3007
3692
  var workContext_1 = require_workContext();
3008
3693
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -3055,6 +3740,19 @@ var require_hookAdapter = __commonJS({
3055
3740
  };
3056
3741
  }
3057
3742
  function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
3743
+ const pairing = loadCliAgentPairing(toolType, identity);
3744
+ const contextHashes = resolveContextHashes(cwd);
3745
+ return {
3746
+ ...pairing,
3747
+ // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3748
+ // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3749
+ // an empty string, grouping unrelated rows under a value naming no session.
3750
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3751
+ workspaceHash: contextHashes.workspaceHash,
3752
+ projectHash: contextHashes.projectHash
3753
+ };
3754
+ }
3755
+ function loadCliAgentPairing(toolType, identity) {
3058
3756
  const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
3059
3757
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3060
3758
  const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
@@ -3065,29 +3763,40 @@ var require_hookAdapter = __commonJS({
3065
3763
  throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
3066
3764
  if (!fileToken)
3067
3765
  (0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3068
- const contextHashes = resolveContextHashes(cwd);
3069
3766
  return {
3070
3767
  apiBaseUrl,
3071
3768
  toolInstallationId,
3072
3769
  eventWriteToken,
3073
3770
  tokenFilePath,
3074
- // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3075
- // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3076
- // an empty string, grouping unrelated rows under a value naming no session.
3077
- sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3078
- workspaceHash: contextHashes.workspaceHash,
3079
- projectHash: contextHashes.projectHash,
3080
3771
  // Agents await command hooks; fail fast rather than stall the user's turn.
3081
3772
  timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
3082
3773
  };
3083
3774
  }
3775
+ function withForgeKeys(events, cwd) {
3776
+ const keys = (0, forgeKeys_1.deriveForgeKeysForCwd)(cwd ?? process.cwd());
3777
+ if (!keys.repoKey)
3778
+ return events;
3779
+ return events.map((event) => ({ ...event, metadata: { ...keys, ...event.metadata } }));
3780
+ }
3781
+ function withPromptId(events, promptId) {
3782
+ if (!promptId)
3783
+ return events;
3784
+ return events.map((event) => ({ ...event, metadata: { promptId, ...event.metadata } }));
3785
+ }
3084
3786
  async function deliverHookEvents(events, options) {
3085
3787
  if (events.length === 0)
3086
3788
  return;
3087
- const notice = options.onNotice ?? ((message) => console.error(message));
3789
+ events = withPromptId(events, options.promptId);
3790
+ if (options.forgeKeys)
3791
+ events = withForgeKeys(events, options.cwd);
3792
+ const notice = options.onNotice ?? ((message2) => console.error(message2));
3088
3793
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3089
- if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken))
3794
+ if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3795
+ const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
3796
+ if (logFile)
3797
+ logUnsent(logFile, events, options);
3090
3798
  return;
3799
+ }
3091
3800
  let config;
3092
3801
  try {
3093
3802
  config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
@@ -3097,20 +3806,7 @@ var require_hookAdapter = __commonJS({
3097
3806
  const logFile = (0, eventLog_1.resolveEventLogPath)();
3098
3807
  if (!logFile)
3099
3808
  throw error;
3100
- const contextHashes = resolveContextHashes(options.cwd);
3101
- for (const event of events) {
3102
- (0, eventLog_1.appendEventLog)(logFile, {
3103
- loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3104
- delivery: "not_sent",
3105
- payload: (0, eventSender_1.buildEventPayload)({
3106
- toolInstallationId: `${options.toolType}:unpaired`,
3107
- source: options.source,
3108
- sessionId: options.sessionId ?? null,
3109
- workspaceHash: contextHashes.workspaceHash,
3110
- projectHash: contextHashes.projectHash
3111
- }, event)
3112
- });
3113
- }
3809
+ logUnsent(logFile, events, options);
3114
3810
  return;
3115
3811
  }
3116
3812
  const sender = new eventSender_1.AscendaEventSender({
@@ -3124,21 +3820,71 @@ var require_hookAdapter = __commonJS({
3124
3820
  projectHash: config.projectHash,
3125
3821
  timeoutMs: config.timeoutMs
3126
3822
  });
3127
- for (const event of events) {
3128
- const result = await sender.send(event);
3129
- if (result === "accepted")
3130
- continue;
3131
- if (result === "consent_missing") {
3132
- notice("Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.");
3133
- } else if (result === "auth_failed") {
3134
- notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
3135
- } else if (result === "transport_error") {
3136
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
3137
- } else {
3138
- notice(`Ascenda telemetry rejected: ${result}`);
3823
+ if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
3824
+ for (const event of events) {
3825
+ const result = await sender.send(event);
3826
+ if (result === "accepted")
3827
+ continue;
3828
+ const message2 = noticeFor(result);
3829
+ if (message2)
3830
+ notice(message2);
3831
+ return;
3139
3832
  }
3140
3833
  return;
3141
3834
  }
3835
+ for (const event of events)
3836
+ sender.queue(event);
3837
+ (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
3838
+ const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
3839
+ const message = last ? noticeFor(last) : void 0;
3840
+ if (message)
3841
+ notice(message);
3842
+ }
3843
+ function noticeFor(result) {
3844
+ if (result === "accepted" || result === "duplicate")
3845
+ return void 0;
3846
+ if (result === "consent_missing")
3847
+ return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
3848
+ if (result === "auth_failed")
3849
+ return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
3850
+ if (result === "transport_error")
3851
+ return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
3852
+ if (result === "outbox_discarded")
3853
+ return void 0;
3854
+ return `Ascenda telemetry rejected: ${result}`;
3855
+ }
3856
+ async function flushHookOutbox(options) {
3857
+ let config;
3858
+ try {
3859
+ config = loadCliAgentPairing(options.toolType, options);
3860
+ } catch {
3861
+ return;
3862
+ }
3863
+ const sender = new eventSender_1.AscendaEventSender({
3864
+ apiBaseUrl: config.apiBaseUrl,
3865
+ toolInstallationId: config.toolInstallationId,
3866
+ source: options.source,
3867
+ eventWriteToken: config.eventWriteToken,
3868
+ tokenFilePath: config.tokenFilePath,
3869
+ timeoutMs: config.timeoutMs
3870
+ });
3871
+ await (0, backgroundDelivery_1.runOutboxFlush)(sender);
3872
+ }
3873
+ function logUnsent(logFile, events, options) {
3874
+ const contextHashes = resolveContextHashes(options.cwd);
3875
+ for (const event of events) {
3876
+ (0, eventLog_1.appendEventLog)(logFile, {
3877
+ loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3878
+ delivery: "not_sent",
3879
+ payload: (0, eventSender_1.buildEventPayload)({
3880
+ toolInstallationId: `${options.toolType}:unpaired`,
3881
+ source: options.source,
3882
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || options.sessionId || null,
3883
+ workspaceHash: contextHashes.workspaceHash,
3884
+ projectHash: contextHashes.projectHash
3885
+ }, event)
3886
+ });
3887
+ }
3142
3888
  }
3143
3889
  function journalSkippedSend(host, error) {
3144
3890
  const who = host ? `${host}: ` : "";
@@ -3585,87 +4331,41 @@ var require_initiatives = __commonJS({
3585
4331
  organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3586
4332
  title: o.title,
3587
4333
  summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3588
- measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3589
- scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3590
- scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3591
- withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3592
- status: o.status,
3593
- direction: typeof o.direction === "string" ? o.direction : null,
3594
- result: asResult(o.result)
3595
- };
3596
- }
3597
- function asResult(value) {
3598
- if (!value || typeof value !== "object")
3599
- return null;
3600
- const r = value;
3601
- const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
3602
- return {
3603
- scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3604
- value: num(r.value),
3605
- baselineValue: num(r.baselineValue),
3606
- delta: num(r.delta),
3607
- movement: typeof r.movement === "string" ? r.movement : null,
3608
- outcome: typeof r.outcome === "string" ? r.outcome : "",
3609
- withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3610
- basis: typeof r.basis === "string" ? r.basis : null
3611
- };
3612
- }
3613
- function formatWindowOrRaw(startUtc, endUtc) {
3614
- if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3615
- return "not given";
3616
- return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3617
- }
3618
- function formatDay(iso) {
3619
- const date = new Date(iso);
3620
- if (Number.isNaN(date.getTime()))
3621
- return iso;
3622
- return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
3623
- }
3624
- }
3625
- });
3626
-
3627
- // ../packages/tool-kit/out/setupDisclosure.js
3628
- var require_setupDisclosure = __commonJS({
3629
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3630
- "use strict";
3631
- Object.defineProperty(exports, "__esModule", { value: true });
3632
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3633
- exports.renderSetupDisclosure = renderSetupDisclosure;
3634
- exports.FAMILY_SENTENCES = {
3635
- session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
3636
- counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
3637
- tools: "the name of each tool your agent calls",
3638
- outcome: "whether a call succeeded, failed, or was interrupted",
3639
- clock: "your machine's offset from UTC, so an evening is read as an evening",
3640
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3641
- model: "which model served the session, by name and by tier",
3642
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3643
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
3644
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3645
- context: "how full the context window got",
3646
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3647
- subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
3648
- reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
3649
- };
3650
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3651
- exports.REFUSALS = [
3652
- "Never your prompts, your agent's replies, or anything inside a file.",
3653
- "Never a file path, a command line, or a repository or branch name.",
3654
- "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
3655
- ];
3656
- exports.FREE_TEXT_KEYS = ["message"];
3657
- function renderSetupDisclosure({ sends, displayName }) {
3658
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3659
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3660
- const lines = [
3661
- `What this sends from ${displayName}, once paired:`,
3662
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3663
- "",
3664
- ...exports.REFUSALS.map((line) => ` ${line}`),
3665
- "",
3666
- " Turn it off by revoking this tool in the Ascenda app."
3667
- ];
3668
- return lines.join("\n");
4334
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
4335
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
4336
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
4337
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
4338
+ status: o.status,
4339
+ direction: typeof o.direction === "string" ? o.direction : null,
4340
+ result: asResult(o.result)
4341
+ };
4342
+ }
4343
+ function asResult(value) {
4344
+ if (!value || typeof value !== "object")
4345
+ return null;
4346
+ const r = value;
4347
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
4348
+ return {
4349
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
4350
+ value: num(r.value),
4351
+ baselineValue: num(r.baselineValue),
4352
+ delta: num(r.delta),
4353
+ movement: typeof r.movement === "string" ? r.movement : null,
4354
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
4355
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
4356
+ basis: typeof r.basis === "string" ? r.basis : null
4357
+ };
4358
+ }
4359
+ function formatWindowOrRaw(startUtc, endUtc) {
4360
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
4361
+ return "not given";
4362
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
4363
+ }
4364
+ function formatDay(iso) {
4365
+ const date = new Date(iso);
4366
+ if (Number.isNaN(date.getTime()))
4367
+ return iso;
4368
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
3669
4369
  }
3670
4370
  }
3671
4371
  });
@@ -3714,9 +4414,11 @@ var require_hookRunner = __commonJS({
3714
4414
  Object.defineProperty(exports, "__esModule", { value: true });
3715
4415
  exports.hookRunnerPaths = hookRunnerPaths;
3716
4416
  exports.hookLauncherScript = hookLauncherScript;
4417
+ exports.isDowngrade = isDowngrade;
3717
4418
  exports.installHookRunner = installHookRunner;
3718
4419
  exports.removeHookRunner = removeHookRunner;
3719
4420
  exports.hookRunnerCommand = hookRunnerCommand;
4421
+ exports.writeAtomically = writeAtomically;
3720
4422
  exports.lastHookPath = lastHookPath;
3721
4423
  exports.stampLastHook = stampLastHook;
3722
4424
  exports.readLastHook = readLastHook;
@@ -3726,10 +4428,11 @@ var require_hookRunner = __commonJS({
3726
4428
  var child_process_1 = __require("child_process");
3727
4429
  var fs = __importStar(__require("fs"));
3728
4430
  var path = __importStar(__require("path"));
4431
+ var collectorVersion_1 = require_collectorVersion();
3729
4432
  var tokenStore_1 = require_tokenStore();
3730
4433
  function hookRunnerPaths(binaryName) {
3731
4434
  const launcher = path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3732
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
4435
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
3733
4436
  }
3734
4437
  var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3735
4438
  function hookLauncherScript(options) {
@@ -3823,21 +4526,57 @@ var require_hookRunner = __commonJS({
3823
4526
  ""
3824
4527
  ].join("\n");
3825
4528
  }
4529
+ function releaseOf(version) {
4530
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version ?? "").trim());
4531
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
4532
+ }
4533
+ function isDowngrade(installed, incoming) {
4534
+ const have = releaseOf(installed);
4535
+ const want = releaseOf(incoming);
4536
+ if (!have || !want)
4537
+ return false;
4538
+ for (let i = 0; i < 3; i++) {
4539
+ if (have[i] !== want[i])
4540
+ return have[i] > want[i];
4541
+ }
4542
+ return false;
4543
+ }
4544
+ function readInstalledVersion(file) {
4545
+ try {
4546
+ return fs.readFileSync(file, "utf8").trim() || void 0;
4547
+ } catch {
4548
+ return void 0;
4549
+ }
4550
+ }
3826
4551
  function installHookRunner(options) {
3827
4552
  const paths = hookRunnerPaths(options.binaryName);
3828
4553
  if (options.dryRun)
3829
4554
  return paths.launcher;
3830
4555
  const source = path.resolve(options.source ?? process.argv[1]);
4556
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
4557
+ const installed = readInstalledVersion(paths.version);
4558
+ const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
4559
+ if (installed && fs.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4560
+ options.onKeptNewer?.(installed, incoming);
4561
+ if (process.platform !== "win32" && !fs.existsSync(paths.launcher))
4562
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4563
+ return paths.launcher;
4564
+ }
3831
4565
  fs.mkdirSync(path.dirname(paths.launcher), { recursive: true });
3832
4566
  if (process.platform === "win32") {
3833
4567
  if (source !== path.resolve(paths.launcher))
3834
4568
  fs.copyFileSync(source, paths.launcher);
4569
+ writeAtomically(paths.version, `${incoming}
4570
+ `, 420);
3835
4571
  return paths.launcher;
3836
4572
  }
3837
4573
  if (source !== path.resolve(paths.bundle))
3838
4574
  writeAtomically(paths.bundle, fs.readFileSync(source), 493);
3839
4575
  writeAtomically(paths.launcher, hookLauncherScript(options), 493);
3840
4576
  writeAtomically(paths.record, `${process.execPath}
4577
+ `, 420);
4578
+ if (source !== path.resolve(paths.bundle))
4579
+ writeAtomically(paths.version, `${incoming}
3841
4580
  `, 420);
3842
4581
  fs.rmSync(paths.noNode, { force: true });
3843
4582
  return paths.launcher;
@@ -3852,8 +4591,8 @@ var require_hookRunner = __commonJS({
3852
4591
  }
3853
4592
  return removed;
3854
4593
  }
3855
- function hookRunnerCommand(launcher) {
3856
- return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4594
+ function hookRunnerCommand(launcher, platform = process.platform) {
4595
+ return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
3857
4596
  }
3858
4597
  function writeAtomically(target, contents, mode) {
3859
4598
  const tmp = `${target}.${process.pid}.tmp`;
@@ -3923,6 +4662,115 @@ var require_hookRunner = __commonJS({
3923
4662
  }
3924
4663
  });
3925
4664
 
4665
+ // ../packages/tool-kit/out/settingsFile.js
4666
+ var require_settingsFile = __commonJS({
4667
+ "../packages/tool-kit/out/settingsFile.js"(exports) {
4668
+ "use strict";
4669
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4670
+ if (k2 === void 0) k2 = k;
4671
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4672
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4673
+ desc = { enumerable: true, get: function() {
4674
+ return m[k];
4675
+ } };
4676
+ }
4677
+ Object.defineProperty(o, k2, desc);
4678
+ } : function(o, m, k, k2) {
4679
+ if (k2 === void 0) k2 = k;
4680
+ o[k2] = m[k];
4681
+ });
4682
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4683
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4684
+ } : function(o, v) {
4685
+ o["default"] = v;
4686
+ });
4687
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4688
+ var ownKeys = function(o) {
4689
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4690
+ var ar = [];
4691
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4692
+ return ar;
4693
+ };
4694
+ return ownKeys(o);
4695
+ };
4696
+ return function(mod) {
4697
+ if (mod && mod.__esModule) return mod;
4698
+ var result = {};
4699
+ if (mod != null) {
4700
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4701
+ }
4702
+ __setModuleDefault(result, mod);
4703
+ return result;
4704
+ };
4705
+ }();
4706
+ Object.defineProperty(exports, "__esModule", { value: true });
4707
+ exports.replaceSettingsFile = replaceSettingsFile;
4708
+ var fs = __importStar(__require("fs"));
4709
+ var path = __importStar(__require("path"));
4710
+ var hookRunner_1 = require_hookRunner();
4711
+ function replaceSettingsFile(settingsFile, contents) {
4712
+ const exists = fs.existsSync(settingsFile);
4713
+ const target = exists ? fs.realpathSync(settingsFile) : settingsFile;
4714
+ if (exists) {
4715
+ const backup = `${settingsFile}.ascenda-backup`;
4716
+ if (!fs.existsSync(backup))
4717
+ fs.copyFileSync(target, backup);
4718
+ }
4719
+ fs.mkdirSync(path.dirname(target), { recursive: true });
4720
+ const mode = exists ? fs.statSync(target).mode & 511 : 420;
4721
+ (0, hookRunner_1.writeAtomically)(target, contents, mode);
4722
+ }
4723
+ }
4724
+ });
4725
+
4726
+ // ../packages/tool-kit/out/setupDisclosure.js
4727
+ var require_setupDisclosure = __commonJS({
4728
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
4729
+ "use strict";
4730
+ Object.defineProperty(exports, "__esModule", { value: true });
4731
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
4732
+ exports.renderSetupDisclosure = renderSetupDisclosure;
4733
+ exports.FAMILY_SENTENCES = {
4734
+ 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",
4735
+ 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",
4736
+ tools: "the name of each tool your agent calls",
4737
+ outcome: "whether a call succeeded, failed, or was interrupted",
4738
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
4739
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
4740
+ model: "which model served the session, by name and by tier",
4741
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
4742
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
4743
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
4744
+ context: "how full the context window got",
4745
+ 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",
4746
+ 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",
4747
+ 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)",
4748
+ turns: "an opaque id your agent gives each prompt, so one turn's events group together",
4749
+ 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"
4750
+ };
4751
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
4752
+ exports.REFUSALS = [
4753
+ "Never your prompts, your agent's replies, or anything inside a file.",
4754
+ "Never a file path, a command line, or a repository or branch name.",
4755
+ "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."
4756
+ ];
4757
+ exports.FREE_TEXT_KEYS = ["message"];
4758
+ function renderSetupDisclosure({ sends, displayName }) {
4759
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
4760
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
4761
+ const lines = [
4762
+ `What this sends from ${displayName}, once paired:`,
4763
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
4764
+ "",
4765
+ ...exports.REFUSALS.map((line) => ` ${line}`),
4766
+ "",
4767
+ " Turn it off by revoking this tool in the Ascenda app."
4768
+ ];
4769
+ return lines.join("\n");
4770
+ }
4771
+ }
4772
+ });
4773
+
3926
4774
  // ../packages/tool-kit/out/saverHandoff.js
3927
4775
  var require_saverHandoff = __commonJS({
3928
4776
  "../packages/tool-kit/out/saverHandoff.js"(exports) {
@@ -4688,6 +5536,8 @@ var require_cliAgentSetup = __commonJS({
4688
5536
  exports.runCliAgentSetup = runCliAgentSetup;
4689
5537
  exports.writeHookSettings = writeHookSettings;
4690
5538
  exports.registeredHookSets = registeredHookSets;
5539
+ exports.ourHookPositions = ourHookPositions;
5540
+ exports.trustProblemLines = trustProblemLines;
4691
5541
  exports.findStaleHookCommands = findStaleHookCommands;
4692
5542
  exports.cliAgentRegistrations = cliAgentRegistrations;
4693
5543
  var crypto = __importStar(__require("crypto"));
@@ -4696,10 +5546,12 @@ var require_cliAgentSetup = __commonJS({
4696
5546
  var path = __importStar(__require("path"));
4697
5547
  var collectorVersion_1 = require_collectorVersion();
4698
5548
  var credentials_1 = require_credentials();
5549
+ var eventLog_1 = require_eventLog();
4699
5550
  var hookAdapter_1 = require_hookAdapter();
4700
5551
  var http_1 = require_http();
4701
5552
  var hookSet_1 = require_hookSet();
4702
5553
  var initiatives_1 = require_initiatives();
5554
+ var settingsFile_1 = require_settingsFile();
4703
5555
  var setupDisclosure_1 = require_setupDisclosure();
4704
5556
  var hookRunner_1 = require_hookRunner();
4705
5557
  var liveSignalDoctor_1 = require_liveSignalDoctor();
@@ -4734,6 +5586,12 @@ Options
4734
5586
  --tool-installation-id <id> reuse an existing pairing instead of creating one
4735
5587
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
4736
5588
  --no-pair install without pairing: local features on, nothing sent
5589
+ --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
5590
+ On by default when not paired; machine-wide, shared by every agent
5591
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
5592
+ repository gets a key and, off its default branch, a branch key, so a pull
5593
+ request can be matched to a session. They are digests anyone who guesses the
5594
+ names can reproduce. Machine-wide. --repo-keys turns them back on
4737
5595
  --scope user|project where hooks are registered (default user: every project)
4738
5596
  --project-dir <path> project root for --scope project (default cwd)
4739
5597
  --dry-run print what would change, write nothing
@@ -4788,6 +5646,10 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4788
5646
  toolInstallationId,
4789
5647
  ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4790
5648
  });
5649
+ if (options.eventLog !== void 0)
5650
+ (0, credentials_1.writeEventLogSetting)(options.eventLog);
5651
+ if (options.repoKeys !== void 0)
5652
+ (0, credentials_1.writeRepoKeysSetting)(options.repoKeys);
4791
5653
  }
4792
5654
  if (isHomeProject(options)) {
4793
5655
  detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
@@ -4822,6 +5684,11 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4822
5684
  else
4823
5685
  row("warn", "pairing", "not paired: pairing did not finish");
4824
5686
  detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os.homedir())} (tools.${spec.host})`);
5687
+ const eventLog = (0, eventLog_1.resolveEventLog)({ localOnly: !identity });
5688
+ if (eventLog.path)
5689
+ row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path, os.homedir())} ${ui.dim("(on this machine only)")}`);
5690
+ else if (options.eventLog !== void 0)
5691
+ row("info", "events", "off");
4825
5692
  if (options.dryRun) {
4826
5693
  console.log("\nDry run. Nothing was written.");
4827
5694
  return 0;
@@ -4832,6 +5699,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4832
5699
  if (chosenLocal) {
4833
5700
  console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
4834
5701
  console.log(" They run on this machine and need no account or pairing.");
5702
+ if (eventLog.path)
5703
+ console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os.homedir())}, for you or any tool to read.`);
4835
5704
  } else if (!identity) {
4836
5705
  console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
4837
5706
  console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
@@ -4914,6 +5783,18 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4914
5783
  case "--dry-run":
4915
5784
  options.dryRun = true;
4916
5785
  break;
5786
+ case "--event-log": {
5787
+ const { value, consumed } = (0, eventLog_1.parseEventLogFlag)(argv, i);
5788
+ options.eventLog = value;
5789
+ i += consumed;
5790
+ break;
5791
+ }
5792
+ case "--repo-keys":
5793
+ options.repoKeys = true;
5794
+ break;
5795
+ case "--no-repo-keys":
5796
+ options.repoKeys = false;
5797
+ break;
4917
5798
  case "--no-pair":
4918
5799
  // `--no-pairing` is the spelling this landed under first. Both appeared
4919
5800
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -5043,7 +5924,12 @@ Pairing ${status.status}. Run setup again.`);
5043
5924
  return void 0;
5044
5925
  }
5045
5926
  function installBinary(spec, dryRun) {
5046
- return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
5927
+ return (0, hookRunner_1.installHookRunner)({
5928
+ binaryName: spec.binaryName,
5929
+ setupCommand: `npx ${spec.packageName} setup`,
5930
+ dryRun,
5931
+ 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.`)
5932
+ });
5047
5933
  }
5048
5934
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
5049
5935
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -5063,8 +5949,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5063
5949
  const command = hookCommand(binary, spec);
5064
5950
  const hooks = { ...settings.hooks ?? {} };
5065
5951
  for (const event of spec.hookEvents) {
5066
- const kept = (hooks[event] ?? []).filter((entry) => !isOurs(entry, spec));
5067
- hooks[event] = [...kept, spec.settings.entry(command, event)];
5952
+ hooks[event] = placeOurEntry(hooks[event] ?? [], spec.settings.entry(command, event), spec);
5068
5953
  }
5069
5954
  const updated = { ...settings, hooks };
5070
5955
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -5077,10 +5962,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5077
5962
  ${serialised}`);
5078
5963
  return true;
5079
5964
  }
5080
- if (exists)
5081
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5082
- fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
5083
- fs.writeFileSync(settingsFile, serialised, "utf8");
5965
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
5084
5966
  return true;
5085
5967
  }
5086
5968
  function hookCommand(binary, spec) {
@@ -5090,28 +5972,130 @@ ${serialised}`);
5090
5972
  const sets = /* @__PURE__ */ new Map();
5091
5973
  for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
5092
5974
  for (const entry of entries ?? []) {
5093
- if (!isOurs(entry, spec))
5094
- continue;
5095
- const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
5096
- sets.set(event, Math.min(set, sets.get(event) ?? set));
5975
+ for (const command of commandsOf(entry, spec)) {
5976
+ if (!isOurCommand(command, spec))
5977
+ continue;
5978
+ const set = (0, hookSet_1.hookSetOfCommand)(command);
5979
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5980
+ }
5097
5981
  }
5098
5982
  }
5099
5983
  return sets;
5100
5984
  }
5101
- function isOurs(entry, spec) {
5985
+ function ourHookPositions(settings, spec) {
5986
+ const found = [];
5987
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5988
+ (groups ?? []).forEach((group, groupIndex) => {
5989
+ const handlers = group?.hooks;
5990
+ if (Array.isArray(handlers)) {
5991
+ handlers.forEach((handler, handlerIndex) => {
5992
+ if (isOurs({ hooks: [handler] }, spec))
5993
+ found.push({ event, group: groupIndex, handler: handlerIndex });
5994
+ });
5995
+ } else if (isOurs(group, spec)) {
5996
+ found.push({ event, group: groupIndex, handler: 0 });
5997
+ }
5998
+ });
5999
+ }
6000
+ return found;
6001
+ }
6002
+ function trustProblemLines(spec, settingsFile, settings, indent) {
6003
+ if (!spec.trust)
6004
+ return [];
6005
+ const ours = ourHookPositions(settings, spec);
6006
+ if (ours.length === 0)
6007
+ return [];
6008
+ const report = spec.trust.check(settingsFile, ours);
6009
+ const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os.homedir());
6010
+ const lines = [];
6011
+ if (report.unreadable) {
6012
+ lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
6013
+ }
6014
+ if (report.untrusted.length) {
6015
+ const names = [...new Set(report.untrusted.map((position) => position.event))].join(", ");
6016
+ 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.`);
6017
+ }
6018
+ for (const entry of report.stale)
6019
+ lines.push(entry);
6020
+ if (lines.length)
6021
+ lines.push(spec.trust.fix);
6022
+ return lines.map((line) => `${indent}${line}`);
6023
+ }
6024
+ function commandsOf(entry, spec) {
6025
+ if (spec.settings.grouped) {
6026
+ return innerHooks(entry).map(commandOfHook).filter((command2) => typeof command2 === "string");
6027
+ }
5102
6028
  const command = spec.settings.commandOf(entry);
5103
- return typeof command === "string" && command.includes(spec.binaryName);
6029
+ return typeof command === "string" ? [command] : [];
6030
+ }
6031
+ function innerHooks(entry) {
6032
+ const hooks = entry && typeof entry === "object" ? entry.hooks : void 0;
6033
+ return Array.isArray(hooks) ? hooks : [];
6034
+ }
6035
+ function commandOfHook(hook) {
6036
+ return hook && typeof hook === "object" ? hook.command : void 0;
6037
+ }
6038
+ function isOurCommand(command, spec) {
6039
+ return command.includes(spec.binaryName);
6040
+ }
6041
+ function isOurs(entry, spec) {
6042
+ return commandsOf(entry, spec).some((command) => isOurCommand(command, spec));
6043
+ }
6044
+ function isOurInnerHook(hook, spec) {
6045
+ const command = commandOfHook(hook);
6046
+ return typeof command === "string" && isOurCommand(command, spec);
6047
+ }
6048
+ function withoutOurEntries(entries, spec) {
6049
+ if (!spec.settings.grouped)
6050
+ return entries.filter((entry) => !isOurs(entry, spec));
6051
+ const kept = [];
6052
+ for (const entry of entries) {
6053
+ if (!isOurs(entry, spec)) {
6054
+ kept.push(entry);
6055
+ continue;
6056
+ }
6057
+ const others = innerHooks(entry).filter((hook) => !isOurInnerHook(hook, spec));
6058
+ if (others.length)
6059
+ kept.push({ ...entry, hooks: others });
6060
+ }
6061
+ return kept;
6062
+ }
6063
+ function placeOurEntry(entries, wanted, spec) {
6064
+ if (!spec.settings.grouped)
6065
+ return [...withoutOurEntries(entries, spec), wanted];
6066
+ const replacements = innerHooks(wanted);
6067
+ let placed = false;
6068
+ const result = [];
6069
+ for (const entry of entries) {
6070
+ if (!isOurs(entry, spec)) {
6071
+ result.push(entry);
6072
+ continue;
6073
+ }
6074
+ const matcher = entry.matcher;
6075
+ const matchesAll = matcher === void 0 || matcher === "";
6076
+ const next = [];
6077
+ for (const hook of innerHooks(entry)) {
6078
+ if (!isOurInnerHook(hook, spec))
6079
+ next.push(hook);
6080
+ else if (!placed && matchesAll) {
6081
+ next.push(...replacements);
6082
+ placed = true;
6083
+ }
6084
+ }
6085
+ if (next.length)
6086
+ result.push({ ...entry, hooks: next });
6087
+ }
6088
+ return placed ? result : [...result, wanted];
5104
6089
  }
5105
6090
  function findStaleHookCommands(settings, binary, spec) {
5106
6091
  const stale = /* @__PURE__ */ new Set();
5107
6092
  for (const entries of Object.values(settings.hooks ?? {})) {
5108
6093
  for (const entry of entries ?? []) {
5109
- const command = spec.settings.commandOf(entry);
5110
- if (typeof command !== "string")
5111
- continue;
5112
- if (!/ascenda/i.test(command) || command.includes(binary))
5113
- continue;
5114
- stale.add(command);
6094
+ for (const command of commandsOf(entry, spec)) {
6095
+ if (!/ascenda/i.test(command) || command.includes(binary))
6096
+ continue;
6097
+ stale.add(command);
6098
+ }
5115
6099
  }
5116
6100
  }
5117
6101
  return [...stale];
@@ -5136,6 +6120,7 @@ ${serialised}`);
5136
6120
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
5137
6121
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
5138
6122
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
6123
+ console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5139
6124
  console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
5140
6125
  const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5141
6126
  if (node) {
@@ -5154,6 +6139,14 @@ ${serialised}`);
5154
6139
  const oldest = Math.min(...sets);
5155
6140
  console.log(oldest < spec.hookSet ? `hook set ${oldest}, this version registers ${spec.hookSet}. Upgrade: npx ${spec.packageName} setup${options.scope === "user" ? " --scope user" : ""}` : `hook set ${spec.hookSet} (current)`);
5156
6141
  }
6142
+ const trustLines = trustProblemLines(spec, settingsFile, settings, "");
6143
+ if (trustLines.length) {
6144
+ console.log(`not trusted ${trustLines[0]}`);
6145
+ for (const line of trustLines.slice(1))
6146
+ console.log(` ${line}`);
6147
+ } else if (spec.trust && registered > 0) {
6148
+ console.log("trust every registered hook is approved");
6149
+ }
5157
6150
  if (stale.length) {
5158
6151
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
5159
6152
  for (const command of stale)
@@ -5175,7 +6168,7 @@ ${serialised}`);
5175
6168
  await notices.markShown();
5176
6169
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
5177
6170
  const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5178
- const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
6171
+ const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
5179
6172
  return healthy ? 0 : 1;
5180
6173
  }
5181
6174
  function countRegistered(settings, spec) {
@@ -5218,10 +6211,37 @@ ${serialised}`);
5218
6211
  } catch (error) {
5219
6212
  lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
5220
6213
  }
6214
+ if (spec.trust) {
6215
+ const found = trustDoctorLines(spec, options.projectDir, ui);
6216
+ if (found.length)
6217
+ lines.push("", ...found);
6218
+ }
5221
6219
  lines.push("", ...accountLines(ui, spec));
6220
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
6221
+ lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5222
6222
  console.log(lines.join("\n"));
5223
6223
  return 0;
5224
6224
  }
6225
+ function trustDoctorLines(spec, projectDir, ui) {
6226
+ const userFile = spec.settings.settingsPath("user", projectDir);
6227
+ const projectFile = spec.settings.settingsPath("project", projectDir);
6228
+ const files = userFile === projectFile ? [userFile] : [userFile, projectFile];
6229
+ const out = [];
6230
+ for (const file of files) {
6231
+ const settings = readSettings(file);
6232
+ if (ourHookPositions(settings, spec).length === 0)
6233
+ continue;
6234
+ const problems = trustProblemLines(spec, file, settings, "");
6235
+ if (problems.length === 0) {
6236
+ out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os.homedir())} is approved`);
6237
+ continue;
6238
+ }
6239
+ out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
6240
+ for (const line of problems.slice(1))
6241
+ out.push(`${" ".repeat(25)}${line}`);
6242
+ }
6243
+ return out;
6244
+ }
5225
6245
  function accountLines(ui, spec) {
5226
6246
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5227
6247
  const id = credentials?.toolInstallationId;
@@ -5232,9 +6252,9 @@ ${serialised}`);
5232
6252
  ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}`,
5233
6253
  ...id ? [ui.dim(row("info", "Installation id", id))] : [],
5234
6254
  "",
5235
- " Not paired, which is fine: the screen saver and the live view above work",
5236
- " without it. Nothing leaves this machine and nothing is queued. To send your",
5237
- " sessions to Ascenda's servers, so they appear in the app:",
6255
+ " Not paired, which is fine: the screen saver, the live view and the local",
6256
+ " event log work without it. Nothing leaves this machine and nothing is queued.",
6257
+ " To send your sessions to Ascenda's servers, so they appear in the app:",
5238
6258
  ` ${ui.cyan(`${cliAgentSelfCommand(spec)} setup`)}`
5239
6259
  ];
5240
6260
  }
@@ -5255,7 +6275,7 @@ ${serialised}`);
5255
6275
  const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
5256
6276
  const hooks = { ...settings.hooks ?? {} };
5257
6277
  for (const event of Object.keys(hooks)) {
5258
- const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
6278
+ const kept = withoutOurEntries(hooks[event], spec);
5259
6279
  if (kept.length)
5260
6280
  hooks[event] = kept;
5261
6281
  else
@@ -5264,9 +6284,8 @@ ${serialised}`);
5264
6284
  const updated = { ...settings, hooks };
5265
6285
  if (!Object.keys(hooks).length)
5266
6286
  delete updated.hooks;
5267
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5268
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5269
- `, "utf8");
6287
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
6288
+ `);
5270
6289
  return true;
5271
6290
  } catch {
5272
6291
  return false;
@@ -5338,7 +6357,9 @@ var require_turnState = __commonJS({
5338
6357
  }();
5339
6358
  Object.defineProperty(exports, "__esModule", { value: true });
5340
6359
  exports.recordTurnStart = recordTurnStart;
6360
+ exports.readTurnPromptId = readTurnPromptId;
5341
6361
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
6362
+ var crypto_1 = __require("crypto");
5342
6363
  var fs = __importStar(__require("fs"));
5343
6364
  var path = __importStar(__require("path"));
5344
6365
  var tokenStore_1 = require_tokenStore();
@@ -5351,11 +6372,24 @@ var require_turnState = __commonJS({
5351
6372
  }
5352
6373
  function recordTurnStart(agent, sessionId, now = Date.now()) {
5353
6374
  if (!sessionId)
5354
- return;
6375
+ return void 0;
5355
6376
  try {
6377
+ const promptId = (0, crypto_1.randomUUID)();
5356
6378
  fs.mkdirSync(stateDir(), { recursive: true });
5357
- fs.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
6379
+ fs.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
6380
+ return promptId;
5358
6381
  } catch {
6382
+ return void 0;
6383
+ }
6384
+ }
6385
+ function readTurnPromptId(agent, sessionId) {
6386
+ if (!sessionId)
6387
+ return void 0;
6388
+ try {
6389
+ const id = fs.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
6390
+ return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
6391
+ } catch {
6392
+ return void 0;
5359
6393
  }
5360
6394
  }
5361
6395
  function consumeTurnDurationMs(agent, sessionId, now = Date.now()) {
@@ -5363,7 +6397,7 @@ var require_turnState = __commonJS({
5363
6397
  return void 0;
5364
6398
  const file = turnFile(agent, sessionId);
5365
6399
  try {
5366
- const started = Number(fs.readFileSync(file, "utf8").trim());
6400
+ const started = Number(fs.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
5367
6401
  fs.rmSync(file, { force: true });
5368
6402
  if (!Number.isFinite(started) || started <= 0 || started > now)
5369
6403
  return void 0;
@@ -5515,14 +6549,15 @@ var require_agentProcess = __commonJS({
5515
6549
  });
5516
6550
 
5517
6551
  // ../packages/tool-kit/out/index.js
5518
- var require_out2 = __commonJS({
6552
+ var require_out3 = __commonJS({
5519
6553
  "../packages/tool-kit/out/index.js"(exports) {
5520
6554
  "use strict";
5521
6555
  Object.defineProperty(exports, "__esModule", { value: true });
5522
- exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
5523
- exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = void 0;
5524
- exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
5525
- exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = void 0;
6556
+ 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;
6557
+ 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;
6558
+ 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;
6559
+ 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;
6560
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = void 0;
5526
6561
  var commandClassifier_1 = require_commandClassifier();
5527
6562
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5528
6563
  return commandClassifier_1.classifyCommand;
@@ -5541,9 +6576,16 @@ var require_out2 = __commonJS({
5541
6576
  Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
5542
6577
  return workMilestoneClassifier_1.classifyWorkMilestone;
5543
6578
  } });
6579
+ Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
6580
+ return workMilestoneClassifier_1.classifyMcpWorkMilestone;
6581
+ } });
5544
6582
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
5545
6583
  return workMilestoneClassifier_1.invitesDebrief;
5546
6584
  } });
6585
+ var shellFacts_1 = require_shellFacts();
6586
+ Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
6587
+ return shellFacts_1.shellCommandFacts;
6588
+ } });
5547
6589
  var autonomyBand_1 = require_autonomyBand();
5548
6590
  Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
5549
6591
  return autonomyBand_1.autonomyBand;
@@ -5613,6 +6655,28 @@ var require_out2 = __commonJS({
5613
6655
  Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
5614
6656
  return collectorVersion_1.describeCollectorVersion;
5615
6657
  } });
6658
+ var backgroundDelivery_1 = require_backgroundDelivery();
6659
+ Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
6660
+ return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
6661
+ } });
6662
+ Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
6663
+ return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
6664
+ } });
6665
+ Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
6666
+ return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
6667
+ } });
6668
+ Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
6669
+ return backgroundDelivery_1.flushLockPath;
6670
+ } });
6671
+ Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
6672
+ return backgroundDelivery_1.hookDeliveryInline;
6673
+ } });
6674
+ Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
6675
+ return backgroundDelivery_1.runOutboxFlush;
6676
+ } });
6677
+ Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
6678
+ return backgroundDelivery_1.startBackgroundFlush;
6679
+ } });
5616
6680
  var eventSender_1 = require_eventSender();
5617
6681
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
5618
6682
  return eventSender_1.AscendaEventSender;
@@ -5623,19 +6687,41 @@ var require_out2 = __commonJS({
5623
6687
  Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
5624
6688
  return eventSender_1.TOKEN_RENEW_LEAD_MS;
5625
6689
  } });
6690
+ Object.defineProperty(exports, "buildEventBody", { enumerable: true, get: function() {
6691
+ return eventSender_1.buildEventBody;
6692
+ } });
5626
6693
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
5627
6694
  return eventSender_1.buildEventPayload;
5628
6695
  } });
6696
+ var agentEvent_1 = require_agentEvent();
6697
+ Object.defineProperty(exports, "toAgentEvent", { enumerable: true, get: function() {
6698
+ return agentEvent_1.toAgentEvent;
6699
+ } });
5629
6700
  var eventLog_1 = require_eventLog();
5630
6701
  Object.defineProperty(exports, "EVENT_LOG_ENV_VAR", { enumerable: true, get: function() {
5631
6702
  return eventLog_1.EVENT_LOG_ENV_VAR;
5632
6703
  } });
6704
+ Object.defineProperty(exports, "EVENT_LOG_OFF", { enumerable: true, get: function() {
6705
+ return eventLog_1.EVENT_LOG_OFF;
6706
+ } });
5633
6707
  Object.defineProperty(exports, "appendEventLog", { enumerable: true, get: function() {
5634
6708
  return eventLog_1.appendEventLog;
5635
6709
  } });
6710
+ Object.defineProperty(exports, "defaultEventLogPath", { enumerable: true, get: function() {
6711
+ return eventLog_1.defaultEventLogPath;
6712
+ } });
6713
+ Object.defineProperty(exports, "describeEventLog", { enumerable: true, get: function() {
6714
+ return eventLog_1.describeEventLog;
6715
+ } });
5636
6716
  Object.defineProperty(exports, "expandUserPath", { enumerable: true, get: function() {
5637
6717
  return eventLog_1.expandUserPath;
5638
6718
  } });
6719
+ Object.defineProperty(exports, "parseEventLogFlag", { enumerable: true, get: function() {
6720
+ return eventLog_1.parseEventLogFlag;
6721
+ } });
6722
+ Object.defineProperty(exports, "resolveEventLog", { enumerable: true, get: function() {
6723
+ return eventLog_1.resolveEventLog;
6724
+ } });
5639
6725
  Object.defineProperty(exports, "resolveEventLogPath", { enumerable: true, get: function() {
5640
6726
  return eventLog_1.resolveEventLogPath;
5641
6727
  } });
@@ -5649,9 +6735,18 @@ var require_out2 = __commonJS({
5649
6735
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
5650
6736
  return hookAdapter_1.deliverHookEvents;
5651
6737
  } });
6738
+ Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
6739
+ return hookAdapter_1.flushHookOutbox;
6740
+ } });
5652
6741
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
5653
6742
  return hookAdapter_1.loadCliAgentConfig;
5654
6743
  } });
6744
+ Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
6745
+ return hookAdapter_1.withForgeKeys;
6746
+ } });
6747
+ Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
6748
+ return hookAdapter_1.withPromptId;
6749
+ } });
5655
6750
  Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
5656
6751
  return hookAdapter_1.resolveCliAgentInstallationId;
5657
6752
  } });
@@ -5668,12 +6763,18 @@ var require_out2 = __commonJS({
5668
6763
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
5669
6764
  return cliAgentSetup_1.isCliAgentManagementCommand;
5670
6765
  } });
6766
+ Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
6767
+ return cliAgentSetup_1.ourHookPositions;
6768
+ } });
5671
6769
  Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5672
6770
  return cliAgentSetup_1.registeredHookSets;
5673
6771
  } });
5674
6772
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
5675
6773
  return cliAgentSetup_1.runCliAgentSetup;
5676
6774
  } });
6775
+ Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
6776
+ return cliAgentSetup_1.trustProblemLines;
6777
+ } });
5677
6778
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
5678
6779
  return cliAgentSetup_1.writeHookSettings;
5679
6780
  } });
@@ -5712,6 +6813,12 @@ var require_out2 = __commonJS({
5712
6813
  Object.defineProperty(exports, "writeHostCredentials", { enumerable: true, get: function() {
5713
6814
  return credentials_1.writeHostCredentials;
5714
6815
  } });
6816
+ Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
6817
+ return credentials_1.writeEventLogSetting;
6818
+ } });
6819
+ Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
6820
+ return credentials_1.writeRepoKeysSetting;
6821
+ } });
5715
6822
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5716
6823
  return credentials_1.writeMachineCredentials;
5717
6824
  } });
@@ -5722,6 +6829,9 @@ var require_out2 = __commonJS({
5722
6829
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
5723
6830
  return turnState_1.consumeTurnDurationMs;
5724
6831
  } });
6832
+ Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
6833
+ return turnState_1.readTurnPromptId;
6834
+ } });
5725
6835
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
5726
6836
  return turnState_1.recordTurnStart;
5727
6837
  } });
@@ -5856,6 +6966,12 @@ var require_out2 = __commonJS({
5856
6966
  Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
5857
6967
  return forgeProject_1.forgeProjectHash;
5858
6968
  } });
6969
+ Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
6970
+ return forgeProject_1.forgeRepoKey;
6971
+ } });
6972
+ Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
6973
+ return forgeProject_1.forgeBranchKey;
6974
+ } });
5859
6975
  Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
5860
6976
  return forgeProject_1.parseForgeFullName;
5861
6977
  } });
@@ -5868,6 +6984,16 @@ var require_out2 = __commonJS({
5868
6984
  Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
5869
6985
  return forgeProject_1.recordForgeProjectAlias;
5870
6986
  } });
6987
+ var forgeKeys_1 = require_forgeKeys();
6988
+ Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
6989
+ return forgeKeys_1.REPO_KEYS_ENV_VAR;
6990
+ } });
6991
+ Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
6992
+ return forgeKeys_1.deriveForgeKeysForCwd;
6993
+ } });
6994
+ Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
6995
+ return forgeKeys_1.repoKeysEnabled;
6996
+ } });
5871
6997
  var liveBus_1 = require_liveBus();
5872
6998
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
5873
6999
  return liveBus_1.emitLiveSignal;
@@ -5938,6 +7064,9 @@ var require_out2 = __commonJS({
5938
7064
  Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
5939
7065
  return hookRunner_1.installHookRunner;
5940
7066
  } });
7067
+ Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
7068
+ return hookRunner_1.isDowngrade;
7069
+ } });
5941
7070
  Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
5942
7071
  return hookRunner_1.lastHookPath;
5943
7072
  } });
@@ -5956,6 +7085,13 @@ var require_out2 = __commonJS({
5956
7085
  Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
5957
7086
  return hookRunner_1.tidyHomePath;
5958
7087
  } });
7088
+ Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
7089
+ return hookRunner_1.writeAtomically;
7090
+ } });
7091
+ var settingsFile_1 = require_settingsFile();
7092
+ Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
7093
+ return settingsFile_1.replaceSettingsFile;
7094
+ } });
5959
7095
  var liveSignalDoctor_1 = require_liveSignalDoctor();
5960
7096
  Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
5961
7097
  return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
@@ -6090,11 +7226,11 @@ var require_out2 = __commonJS({
6090
7226
  });
6091
7227
 
6092
7228
  // src/cli.ts
6093
- var import_tool_kit3 = __toESM(require_out2(), 1);
7229
+ var import_tool_kit3 = __toESM(require_out3(), 1);
6094
7230
  import { readFile } from "node:fs/promises";
6095
7231
 
6096
7232
  // src/config.ts
6097
- var import_tool_kit = __toESM(require_out2(), 1);
7233
+ var import_tool_kit = __toESM(require_out3(), 1);
6098
7234
  var ASCENDA_TOOL_TYPE = "github_collector";
6099
7235
  function loadConfigFromEnv() {
6100
7236
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
@@ -6120,9 +7256,10 @@ function normalizeToolInstallationId(value) {
6120
7256
  }
6121
7257
 
6122
7258
  // src/mapForgeEvent.ts
6123
- var import_tool_kit2 = __toESM(require_out2(), 1);
6124
- function mapForgeEvent(eventName, payload, viewerLogin) {
7259
+ var import_tool_kit2 = __toESM(require_out3(), 1);
7260
+ function mapForgeEvent(eventName, payload, viewerLogin, options = {}) {
6125
7261
  if (!eventName || !viewerLogin) return [];
7262
+ const keys = options.repoKeys !== false;
6126
7263
  const action = str(payload["action"]);
6127
7264
  const viewer = viewerLogin.toLowerCase();
6128
7265
  if (eventName === "pull_request") {
@@ -6132,7 +7269,15 @@ function mapForgeEvent(eventName, payload, viewerLogin) {
6132
7269
  return [{
6133
7270
  eventType: "pull_request_opened",
6134
7271
  severity: "low",
6135
- metadata: base(payload)
7272
+ metadata: { ...base(payload, keys), ...pullRequestKeys(payload, pr, keys) }
7273
+ }];
7274
+ }
7275
+ if (action === "closed" && author === viewer) {
7276
+ const merged = pr["merged"] === true;
7277
+ return [{
7278
+ eventType: merged ? "pull_request_merged" : "pull_request_closed",
7279
+ severity: "low",
7280
+ metadata: { ...base(payload, keys), ...pullRequestKeys(payload, pr, keys), ...pullRequestTimes(pr, merged) }
6136
7281
  }];
6137
7282
  }
6138
7283
  if (action === "review_requested") {
@@ -6141,7 +7286,7 @@ function mapForgeEvent(eventName, payload, viewerLogin) {
6141
7286
  return [{
6142
7287
  eventType: "review_requested_of_me",
6143
7288
  severity: "low",
6144
- metadata: base(payload)
7289
+ metadata: { ...base(payload, keys), ...pullRequestKeys(payload, pr, keys) }
6145
7290
  }];
6146
7291
  }
6147
7292
  }
@@ -6155,7 +7300,8 @@ function mapForgeEvent(eventName, payload, viewerLogin) {
6155
7300
  eventType: "review_given",
6156
7301
  severity: "low",
6157
7302
  metadata: {
6158
- ...base(payload),
7303
+ ...base(payload, keys),
7304
+ ...pullRequestKeys(payload, obj(payload["pull_request"]), keys),
6159
7305
  // The verdict is a property of the checking work, not of the author,
6160
7306
  // and it is the closest thing to a "how heavy was this review" signal
6161
7307
  // that carries no content. `commented` and `changes_requested` are
@@ -6166,7 +7312,7 @@ function mapForgeEvent(eventName, payload, viewerLogin) {
6166
7312
  }
6167
7313
  return [];
6168
7314
  }
6169
- function base(payload) {
7315
+ function base(payload, keys) {
6170
7316
  const repo = str(obj(payload["repository"])["full_name"]);
6171
7317
  return {
6172
7318
  host: "github",
@@ -6180,9 +7326,49 @@ function base(payload) {
6180
7326
  // function now lives in tool-kit so a developer's own machine, which holds
6181
7327
  // both identities, can compute this exact digest and file it beside its
6182
7328
  // own; nothing about what this step emits has changed.
6183
- ...repo ? { projectHash: (0, import_tool_kit2.forgeProjectHash)(repo) } : {}
7329
+ ...repo ? { projectHash: (0, import_tool_kit2.forgeProjectHash)(repo) } : {},
7330
+ ...keys && repo && onGithub(obj(payload["repository"])) ? { repoKey: (0, import_tool_kit2.forgeRepoKey)(repo) } : {}
7331
+ };
7332
+ }
7333
+ function pullRequestKeys(payload, pr, keys) {
7334
+ if (!keys || !onGithub(obj(payload["repository"]))) return {};
7335
+ const head = obj(pr["head"]);
7336
+ const headRepo = obj(head["repo"]);
7337
+ const base2 = str(obj(obj(pr["base"])["repo"])["full_name"]) ?? str(obj(payload["repository"])["full_name"]);
7338
+ const headName = head["repo"] === void 0 ? base2 : str(headRepo["full_name"]);
7339
+ const branch = str(head["ref"]);
7340
+ const defaultBranch = head["repo"] === void 0 ? str(obj(payload["repository"])["default_branch"]) : str(headRepo["default_branch"]);
7341
+ const onDefault = branch !== void 0 && branch === defaultBranch;
7342
+ return {
7343
+ ...headName && base2 && headName.toLowerCase() !== base2.toLowerCase() ? { headRepoKey: (0, import_tool_kit2.forgeRepoKey)(headName) } : {},
7344
+ ...headName && branch && !onDefault ? { branchKey: (0, import_tool_kit2.forgeBranchKey)(headName, branch) } : {}
6184
7345
  };
6185
7346
  }
7347
+ function onGithub(repository) {
7348
+ const url = str(repository["html_url"]);
7349
+ if (!url) return true;
7350
+ try {
7351
+ return new URL(url).hostname.toLowerCase().replace(/^www\./, "") === "github.com";
7352
+ } catch {
7353
+ return false;
7354
+ }
7355
+ }
7356
+ function pullRequestTimes(pr, merged) {
7357
+ const created = timestamp(pr["created_at"]);
7358
+ const closed = timestamp(pr["closed_at"]);
7359
+ const mergedAt = merged ? timestamp(pr["merged_at"]) : void 0;
7360
+ return {
7361
+ ...created ? { prCreatedAt: created } : {},
7362
+ ...closed ? { prClosedAt: closed } : {},
7363
+ ...mergedAt ? { prMergedAt: mergedAt } : {}
7364
+ };
7365
+ }
7366
+ function timestamp(value) {
7367
+ const text = str(value);
7368
+ if (!text) return void 0;
7369
+ const ms = Date.parse(text);
7370
+ return Number.isNaN(ms) ? void 0 : new Date(ms).toISOString();
7371
+ }
6186
7372
  function reviewState(state) {
6187
7373
  return state?.toLowerCase() === "approved" ? "success" : "unknown";
6188
7374
  }
@@ -6196,10 +7382,12 @@ function str(value) {
6196
7382
  // src/cli.ts
6197
7383
  async function main() {
6198
7384
  const config = loadConfigFromEnv();
6199
- const eventName = process.env.GITHUB_EVENT_NAME ?? process.argv[2];
7385
+ const args = process.argv.slice(2);
7386
+ const repoKeys = !args.includes("--no-repo-keys") && (0, import_tool_kit3.repoKeysEnabled)();
7387
+ const eventName = process.env.GITHUB_EVENT_NAME ?? args.find((arg) => !arg.startsWith("--"));
6200
7388
  const payload = await readPayload();
6201
7389
  if (!payload) return;
6202
- const events = mapForgeEvent(eventName, payload, config.viewerLogin);
7390
+ const events = mapForgeEvent(eventName, payload, config.viewerLogin, { repoKeys });
6203
7391
  if (events.length === 0) return;
6204
7392
  const sender = new import_tool_kit3.AscendaEventSender({
6205
7393
  apiBaseUrl: config.apiBaseUrl,