@ascenda-one/codex-hooks 0.1.34 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -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 = shellCommandFacts2;
266
+ var gitActionClassifier_1 = require_gitActionClassifier();
267
+ var workMilestoneClassifier_1 = require_workMilestoneClassifier();
268
+ function shellCommandFacts2(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",
@@ -899,9 +1081,9 @@ var require_payload = __commonJS({
899
1081
  }
900
1082
  return void 0;
901
1083
  }
902
- function getNested2(input, path2) {
1084
+ function getNested2(input, path3) {
903
1085
  let current = input;
904
- for (const segment of path2) {
1086
+ for (const segment of path3) {
905
1087
  if (!current || typeof current !== "object")
906
1088
  return void 0;
907
1089
  current = current[segment];
@@ -909,16 +1091,16 @@ var require_payload = __commonJS({
909
1091
  return current;
910
1092
  }
911
1093
  function getNestedString3(input, paths) {
912
- for (const path2 of paths) {
913
- const value = getNested2(input, path2);
1094
+ for (const path3 of paths) {
1095
+ const value = getNested2(input, path3);
914
1096
  if (typeof value === "string" && value.trim())
915
1097
  return value;
916
1098
  }
917
1099
  return void 0;
918
1100
  }
919
1101
  function getNestedNumber(input, paths) {
920
- for (const path2 of paths) {
921
- const value = getNested2(input, path2);
1102
+ for (const path3 of paths) {
1103
+ const value = getNested2(input, path3);
922
1104
  if (typeof value === "number" && Number.isFinite(value))
923
1105
  return value;
924
1106
  }
@@ -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,433 +1192,94 @@ 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;
1017
- var fs = __importStar(__require("fs"));
1195
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1196
+ exports.ascendaHome = ascendaHome;
1197
+ exports.defaultTokenFilePath = defaultTokenFilePath;
1198
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1199
+ exports.persistEventWriteToken = persistEventWriteToken;
1200
+ exports.readTokenExpiry = readTokenExpiry;
1201
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1202
+ exports.readTokenFile = readTokenFile;
1203
+ exports.sanitizeFilePart = sanitizeFilePart;
1204
+ var fs2 = __importStar(__require("fs"));
1018
1205
  var os2 = __importStar(__require("os"));
1019
- var path2 = __importStar(__require("path"));
1020
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1021
- var MAX_BYTES = 5 * 1024 * 1024;
1022
- function expandUserPath(configured) {
1023
- const value = configured?.trim();
1024
- if (!value)
1025
- return void 0;
1026
- if (value === "~")
1027
- return os2.homedir();
1028
- if (value.startsWith("~/"))
1029
- return path2.join(os2.homedir(), value.slice(2));
1030
- return path2.resolve(value);
1206
+ var path3 = __importStar(__require("path"));
1207
+ function ascendaHome(home = os2.homedir()) {
1208
+ return process.env.ASCENDA_HOME ?? path3.join(home, ".ascenda");
1031
1209
  }
1032
- function resolveEventLogPath() {
1033
- return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
1210
+ function defaultTokenFilePath(toolInstallationId) {
1211
+ return path3.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1034
1212
  }
1035
- function appendEventLog(logFilePath, entry) {
1036
- try {
1037
- rotateIfLarge(logFilePath);
1038
- const dir = path2.dirname(logFilePath);
1039
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1040
- fs.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1041
- `, { encoding: "utf8", mode: 384 });
1042
- if (process.platform !== "win32")
1043
- fs.chmodSync(logFilePath, 384);
1044
- } catch {
1045
- }
1213
+ function tokenExpiryFilePath(tokenFilePath) {
1214
+ return path3.join(path3.dirname(tokenFilePath), "expiry", path3.basename(tokenFilePath));
1046
1215
  }
1047
- function rotateIfLarge(logFilePath) {
1216
+ function persistEventWriteToken(tokenFilePath, token, expiresAt) {
1217
+ const dir = path3.dirname(tokenFilePath);
1218
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1219
+ fs2.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1220
+ if (process.platform !== "win32") {
1221
+ fs2.chmodSync(dir, 448);
1222
+ fs2.chmodSync(tokenFilePath, 384);
1223
+ }
1224
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1048
1225
  try {
1049
- if (fs.statSync(logFilePath).size < MAX_BYTES)
1050
- return;
1051
- fs.renameSync(logFilePath, `${logFilePath}.1`);
1226
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1227
+ fs2.mkdirSync(path3.dirname(expiryFile), { recursive: true, mode: 448 });
1228
+ fs2.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1229
+ } else {
1230
+ fs2.rmSync(expiryFile, { force: true });
1231
+ }
1052
1232
  } catch {
1053
1233
  }
1054
1234
  }
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;
1235
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1236
+ function readTokenExpiry(tokenFilePath) {
1129
1237
  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" };
1238
+ const recorded = Date.parse(fs2.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1239
+ if (Number.isFinite(recorded))
1240
+ return recorded;
1241
+ } catch {
1137
1242
  }
1138
- if (response.status === 401)
1139
- return { kind: "rejected", httpStatus: 401 };
1140
- if (!response.ok)
1141
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1142
- let body;
1143
1243
  try {
1144
- body = await response.json();
1244
+ return fs2.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1145
1245
  } catch {
1146
- return { kind: "failed", reason: "the reply was not readable" };
1246
+ return void 0;
1147
1247
  }
1148
- if (!Array.isArray(body))
1149
- return { kind: "failed", reason: "the reply was not a list" };
1150
- return { kind: "ok", initiatives: body };
1151
1248
  }
1152
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1153
- let response;
1249
+ function listPersistedToolInstallationIds(toolType) {
1250
+ const prefix = `${sanitizeFilePart(toolType)}_`;
1251
+ const dir = path3.join(ascendaHome(), "tokens");
1252
+ let names;
1154
1253
  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" };
1254
+ names = fs2.readdirSync(dir);
1255
+ } catch {
1256
+ return [];
1162
1257
  }
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;
1258
+ const ids = [];
1259
+ for (const name of names.sort()) {
1260
+ if (!name.startsWith(prefix) || name.length === prefix.length)
1261
+ continue;
1262
+ const file = path3.join(dir, name);
1263
+ try {
1264
+ if (!fs2.statSync(file).isFile())
1265
+ continue;
1266
+ } catch {
1267
+ continue;
1268
+ }
1269
+ if (readTokenFile(file) === void 0)
1270
+ continue;
1271
+ ids.push(`${toolType}:${name.slice(prefix.length)}`);
1272
+ }
1273
+ return ids;
1274
+ }
1275
+ function readTokenFile(tokenFilePath) {
1170
1276
  try {
1171
- body = await response.json();
1277
+ if (!fs2.existsSync(tokenFilePath))
1278
+ return void 0;
1279
+ const value = fs2.readFileSync(tokenFilePath, "utf8").trim();
1280
+ return value || void 0;
1172
1281
  } 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);
1229
- } catch {
1230
- return { duplicates: 0 };
1231
- }
1232
- if (!parsed || typeof parsed !== "object")
1233
- return { duplicates: 0 };
1234
- const single = parsed.status;
1235
- if (isDeliveredStatus(single))
1236
- return { duplicates: single === "duplicate" ? 1 : 0 };
1237
- const raw = parsed.results;
1238
- if (!Array.isArray(raw))
1239
- return { duplicates: 0 };
1240
- const results = [];
1241
- for (const item of raw) {
1242
- if (!item || typeof item !== "object")
1243
- continue;
1244
- const { index, status, reason } = item;
1245
- if (typeof index !== "number" || typeof status !== "string")
1246
- continue;
1247
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
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
- };
1274
- }
1275
- }
1276
- async function parseIngestResponse(response) {
1277
- if (response.ok) {
1278
- const outcome = { result: "accepted", httpStatus: response.status };
1279
- let read = { duplicates: 0 };
1280
- try {
1281
- read = readSuccessBody(await response.text());
1282
- } catch {
1283
- read = { duplicates: 0 };
1284
- }
1285
- return {
1286
- ...outcome,
1287
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1288
- ...read.results !== void 0 ? { results: read.results } : {}
1289
- };
1290
- }
1291
- const body = await response.text();
1292
- let errorCode;
1293
- try {
1294
- errorCode = JSON.parse(body).error;
1295
- } catch {
1296
- errorCode = void 0;
1297
- }
1298
- const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1299
- if (response.status === 401)
1300
- return { ...base, result: "auth_failed" };
1301
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1302
- return { ...base, result: "consent_missing" };
1303
- if (response.status === 400 || response.status === 422)
1304
- return { ...base, result: "validation_failed" };
1305
- return { ...base, result: "transport_error" };
1306
- }
1307
- }
1308
- });
1309
-
1310
- // ../packages/tool-kit/out/tokenStore.js
1311
- var require_tokenStore = __commonJS({
1312
- "../packages/tool-kit/out/tokenStore.js"(exports) {
1313
- "use strict";
1314
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1315
- if (k2 === void 0) k2 = k;
1316
- var desc = Object.getOwnPropertyDescriptor(m, k);
1317
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1318
- desc = { enumerable: true, get: function() {
1319
- return m[k];
1320
- } };
1321
- }
1322
- Object.defineProperty(o, k2, desc);
1323
- } : function(o, m, k, k2) {
1324
- if (k2 === void 0) k2 = k;
1325
- o[k2] = m[k];
1326
- });
1327
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1328
- Object.defineProperty(o, "default", { enumerable: true, value: v });
1329
- } : function(o, v) {
1330
- o["default"] = v;
1331
- });
1332
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1333
- var ownKeys = function(o) {
1334
- ownKeys = Object.getOwnPropertyNames || function(o2) {
1335
- var ar = [];
1336
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1337
- return ar;
1338
- };
1339
- return ownKeys(o);
1340
- };
1341
- return function(mod) {
1342
- if (mod && mod.__esModule) return mod;
1343
- var result = {};
1344
- if (mod != null) {
1345
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1346
- }
1347
- __setModuleDefault(result, mod);
1348
- return result;
1349
- };
1350
- }();
1351
- Object.defineProperty(exports, "__esModule", { value: true });
1352
- exports.EVENT_TOKEN_TTL_MS = void 0;
1353
- exports.ascendaHome = ascendaHome;
1354
- exports.defaultTokenFilePath = defaultTokenFilePath;
1355
- exports.tokenExpiryFilePath = tokenExpiryFilePath;
1356
- exports.persistEventWriteToken = persistEventWriteToken;
1357
- exports.readTokenExpiry = readTokenExpiry;
1358
- exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1359
- exports.readTokenFile = readTokenFile;
1360
- exports.sanitizeFilePart = sanitizeFilePart;
1361
- var fs = __importStar(__require("fs"));
1362
- var os2 = __importStar(__require("os"));
1363
- var path2 = __importStar(__require("path"));
1364
- function ascendaHome(home = os2.homedir()) {
1365
- return process.env.ASCENDA_HOME ?? path2.join(home, ".ascenda");
1366
- }
1367
- function defaultTokenFilePath(toolInstallationId) {
1368
- return path2.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1369
- }
1370
- function tokenExpiryFilePath(tokenFilePath) {
1371
- return path2.join(path2.dirname(tokenFilePath), "expiry", path2.basename(tokenFilePath));
1372
- }
1373
- function persistEventWriteToken(tokenFilePath, token, expiresAt) {
1374
- const dir = path2.dirname(tokenFilePath);
1375
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1376
- fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1377
- if (process.platform !== "win32") {
1378
- fs.chmodSync(dir, 448);
1379
- fs.chmodSync(tokenFilePath, 384);
1380
- }
1381
- const expiryFile = tokenExpiryFilePath(tokenFilePath);
1382
- try {
1383
- if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1384
- fs.mkdirSync(path2.dirname(expiryFile), { recursive: true, mode: 448 });
1385
- fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1386
- } else {
1387
- fs.rmSync(expiryFile, { force: true });
1388
- }
1389
- } catch {
1390
- }
1391
- }
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
- }
1400
- 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 = path2.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 = path2.join(dir, name);
1420
- try {
1421
- if (!fs.statSync(file).isFile())
1422
- continue;
1423
- } catch {
1424
- continue;
1425
- }
1426
- if (readTokenFile(file) === void 0)
1427
- continue;
1428
- ids.push(`${toolType}:${name.slice(prefix.length)}`);
1429
- }
1430
- return ids;
1431
- }
1432
- function readTokenFile(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;
1282
+ return void 0;
1440
1283
  }
1441
1284
  }
1442
1285
  function sanitizeFilePart(value) {
@@ -1495,13 +1338,13 @@ var require_stateStore = __commonJS({
1495
1338
  exports.recordOutboxDiscard = recordOutboxDiscard;
1496
1339
  exports.shouldAnnounceFailure = shouldAnnounceFailure;
1497
1340
  exports.markFailureNotified = markFailureNotified;
1498
- var fs = __importStar(__require("fs"));
1499
- var path2 = __importStar(__require("path"));
1341
+ var fs2 = __importStar(__require("fs"));
1342
+ var path3 = __importStar(__require("path"));
1500
1343
  var tokenStore_1 = require_tokenStore();
1501
1344
  function defaultStateFilePath(toolInstallationId) {
1502
1345
  const dir = process.env.ASCENDA_STATE_DIR?.trim();
1503
- const base = dir ? dir : path2.join((0, tokenStore_1.ascendaHome)(), "state");
1504
- return path2.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1346
+ const base = dir ? dir : path3.join((0, tokenStore_1.ascendaHome)(), "state");
1347
+ return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1505
1348
  }
1506
1349
  function unresolvedToolInstallationId(toolType) {
1507
1350
  return `${toolType}:unresolved`;
@@ -1511,9 +1354,9 @@ var require_stateStore = __commonJS({
1511
1354
  }
1512
1355
  function readCollectorState(stateFilePath) {
1513
1356
  try {
1514
- if (!fs.existsSync(stateFilePath))
1357
+ if (!fs2.existsSync(stateFilePath))
1515
1358
  return void 0;
1516
- const raw = fs.readFileSync(stateFilePath, "utf8").trim();
1359
+ const raw = fs2.readFileSync(stateFilePath, "utf8").trim();
1517
1360
  if (!raw)
1518
1361
  return void 0;
1519
1362
  const parsed = JSON.parse(raw);
@@ -1580,17 +1423,17 @@ var require_stateStore = __commonJS({
1580
1423
  function writeStateFile(stateFilePath, state) {
1581
1424
  const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1582
1425
  try {
1583
- const dir = path2.dirname(stateFilePath);
1584
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1585
- fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1426
+ const dir = path3.dirname(stateFilePath);
1427
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1428
+ fs2.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1586
1429
  `, { encoding: "utf8", mode: 384 });
1587
- fs.renameSync(temporaryPath, stateFilePath);
1430
+ fs2.renameSync(temporaryPath, stateFilePath);
1588
1431
  if (process.platform !== "win32")
1589
- fs.chmodSync(stateFilePath, 384);
1432
+ fs2.chmodSync(stateFilePath, 384);
1590
1433
  } catch {
1591
1434
  try {
1592
- if (fs.existsSync(temporaryPath))
1593
- fs.unlinkSync(temporaryPath);
1435
+ if (fs2.existsSync(temporaryPath))
1436
+ fs2.unlinkSync(temporaryPath);
1594
1437
  } catch {
1595
1438
  }
1596
1439
  }
@@ -1651,8 +1494,8 @@ var require_outbox = __commonJS({
1651
1494
  exports.readOutboxSummary = readOutboxSummary;
1652
1495
  exports.claimOutbox = claimOutbox;
1653
1496
  exports.enforceOutboxBounds = enforceOutboxBounds;
1654
- var fs = __importStar(__require("fs"));
1655
- var path2 = __importStar(__require("path"));
1497
+ var fs2 = __importStar(__require("fs"));
1498
+ var path3 = __importStar(__require("path"));
1656
1499
  var stateStore_1 = require_stateStore();
1657
1500
  var tokenStore_1 = require_tokenStore();
1658
1501
  exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
@@ -1668,25 +1511,25 @@ var require_outbox = __commonJS({
1668
1511
  return !(value === "0" || value === "false" || value === "no" || value === "off");
1669
1512
  }
1670
1513
  function defaultOutboxFilePath(toolInstallationId) {
1671
- const dir = path2.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1672
- return path2.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1514
+ const dir = path3.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1515
+ return path3.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1673
1516
  }
1674
1517
  function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1675
1518
  try {
1676
- const dir = path2.dirname(outboxFilePath);
1677
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1519
+ const dir = path3.dirname(outboxFilePath);
1520
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1678
1521
  const entry = { queuedAt: now.toISOString(), payload };
1679
- fs.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1522
+ fs2.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1680
1523
  `, { encoding: "utf8", mode: 384 });
1681
1524
  if (process.platform !== "win32")
1682
- fs.chmodSync(outboxFilePath, 384);
1525
+ fs2.chmodSync(outboxFilePath, 384);
1683
1526
  return true;
1684
1527
  } catch {
1685
1528
  return false;
1686
1529
  }
1687
1530
  }
1688
1531
  function readOutboxSummary(outboxFilePath) {
1689
- const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs.existsSync(file));
1532
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs2.existsSync(file));
1690
1533
  if (files.length === 0)
1691
1534
  return void 0;
1692
1535
  let depth = 0;
@@ -1701,125 +1544,950 @@ var require_outbox = __commonJS({
1701
1544
  oldestQueuedAt = entry.queuedAt;
1702
1545
  }
1703
1546
  }
1704
- return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1547
+ return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1548
+ }
1549
+ function claimOutbox(outboxFilePath, now = Date.now()) {
1550
+ const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1551
+ const claimed = [];
1552
+ try {
1553
+ fs2.renameSync(outboxFilePath, claimPath);
1554
+ claimed.push(claimPath);
1555
+ } catch {
1556
+ }
1557
+ let orphanIndex = 0;
1558
+ for (const orphan of listClaimFiles(outboxFilePath)) {
1559
+ if (claimed.includes(orphan))
1560
+ continue;
1561
+ try {
1562
+ if (now - fs2.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1563
+ continue;
1564
+ const mine = `${claimPath}.${orphanIndex++}`;
1565
+ fs2.renameSync(orphan, mine);
1566
+ claimed.push(mine);
1567
+ } catch {
1568
+ }
1569
+ }
1570
+ if (claimed.length === 0)
1571
+ return void 0;
1572
+ const entries = [];
1573
+ let unreadable = 0;
1574
+ for (const file of claimed) {
1575
+ const read = readEntries(file);
1576
+ entries.push(...read.entries);
1577
+ unreadable += read.unreadable;
1578
+ }
1579
+ entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1580
+ let released = false;
1581
+ return {
1582
+ entries,
1583
+ unreadable,
1584
+ release(remainder) {
1585
+ if (released)
1586
+ return;
1587
+ released = true;
1588
+ if (remainder.length > 0) {
1589
+ try {
1590
+ fs2.mkdirSync(path3.dirname(outboxFilePath), { recursive: true, mode: 448 });
1591
+ fs2.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1592
+ `).join(""), { encoding: "utf8", mode: 384 });
1593
+ if (process.platform !== "win32")
1594
+ fs2.chmodSync(outboxFilePath, 384);
1595
+ } catch {
1596
+ return;
1597
+ }
1598
+ }
1599
+ for (const file of claimed) {
1600
+ try {
1601
+ fs2.unlinkSync(file);
1602
+ } catch {
1603
+ }
1604
+ }
1605
+ }
1606
+ };
1607
+ }
1608
+ function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1609
+ const reasons = {};
1610
+ let oldestQueuedAt;
1611
+ const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1612
+ const fresh = [];
1613
+ for (const entry of entries) {
1614
+ if (entry.queuedAt < cutoff) {
1615
+ reasons.age = (reasons.age ?? 0) + 1;
1616
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1617
+ oldestQueuedAt = entry.queuedAt;
1618
+ } else {
1619
+ fresh.push(entry);
1620
+ }
1621
+ }
1622
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1623
+ if (excess > 0) {
1624
+ reasons.count = excess;
1625
+ const first = fresh[0]?.queuedAt;
1626
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1627
+ oldestQueuedAt = first;
1628
+ }
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 = path3.dirname(outboxFilePath);
1635
+ const prefix = `${path3.basename(outboxFilePath)}.`;
1636
+ try {
1637
+ return fs2.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path3.join(dir, name)).sort();
1638
+ } catch {
1639
+ return [];
1640
+ }
1641
+ }
1642
+ function readEntries(file) {
1643
+ let raw;
1644
+ try {
1645
+ raw = fs2.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 fs2 = __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 - fs2.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1734
+ } catch {
1735
+ return false;
1736
+ }
1737
+ }
1738
+ function touchLock(lockPath) {
1739
+ try {
1740
+ fs2.writeFileSync(lockPath, `${process.pid}
1741
+ `, { encoding: "utf8", mode: 384 });
1742
+ } catch {
1743
+ }
1744
+ }
1745
+ function removeLock(lockPath) {
1746
+ try {
1747
+ fs2.unlinkSync(lockPath);
1748
+ } catch {
1749
+ }
1750
+ }
1751
+ function outboxHasEntries(outboxFilePath) {
1752
+ try {
1753
+ return fs2.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 fs2 = __importStar(__require("fs"));
2026
+ var path3 = __importStar(__require("path"));
2027
+ var tokenStore_1 = require_tokenStore();
2028
+ function credentialsFilePath() {
2029
+ return path3.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2030
+ }
2031
+ function readMachineCredentials() {
2032
+ try {
2033
+ const raw = fs2.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
+ fs2.mkdirSync(path3.dirname(file), { recursive: true, mode: 448 });
2047
+ fs2.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2048
+ `, { encoding: "utf8", mode: 384 });
2049
+ if (process.platform !== "win32") {
2050
+ fs2.chmodSync(path3.dirname(file), 448);
2051
+ fs2.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 fs2 = __importStar(__require("fs"));
2159
+ var os2 = __importStar(__require("os"));
2160
+ var path3 = __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 os2.homedir();
2173
+ if (value.startsWith("~/"))
2174
+ return path3.join(os2.homedir(), value.slice(2));
2175
+ return path3.resolve(value);
2176
+ }
2177
+ function defaultEventLogPath() {
2178
+ return path3.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 = path3.dirname(logFilePath);
2223
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
2224
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
2225
+ fs2.appendFileSync(logFilePath, `${JSON.stringify(line)}
2226
+ `, { encoding: "utf8", mode: 384 });
2227
+ if (process.platform !== "win32")
2228
+ fs2.chmodSync(logFilePath, 384);
2229
+ } catch {
2230
+ }
2231
+ }
2232
+ function rotateIfLarge(logFilePath) {
2233
+ try {
2234
+ if (fs2.statSync(logFilePath).size < MAX_BYTES)
2235
+ return;
2236
+ fs2.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 };
2363
+ }
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) {
2373
+ try {
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;
2380
+ } catch {
2381
+ return false;
2382
+ }
1705
2383
  }
1706
- function claimOutbox(outboxFilePath, now = Date.now()) {
1707
- const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1708
- const claimed = [];
2384
+ async function apiError(response) {
2385
+ const body = await response.text();
2386
+ let errorCode;
1709
2387
  try {
1710
- fs.renameSync(outboxFilePath, claimPath);
1711
- claimed.push(claimPath);
2388
+ const parsed = JSON.parse(body);
2389
+ errorCode = parsed.code ?? parsed.error;
1712
2390
  } catch {
2391
+ errorCode = void 0;
1713
2392
  }
1714
- let orphanIndex = 0;
1715
- for (const orphan of listClaimFiles(outboxFilePath)) {
1716
- if (claimed.includes(orphan))
1717
- continue;
1718
- try {
1719
- if (now - fs.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1720
- continue;
1721
- const mine = `${claimPath}.${orphanIndex++}`;
1722
- fs.renameSync(orphan, mine);
1723
- claimed.push(mine);
1724
- } catch {
1725
- }
1726
- }
1727
- if (claimed.length === 0)
1728
- return void 0;
1729
- const entries = [];
1730
- let unreadable = 0;
1731
- for (const file of claimed) {
1732
- const read = readEntries(file);
1733
- entries.push(...read.entries);
1734
- unreadable += read.unreadable;
1735
- }
1736
- entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1737
- let released = false;
1738
- return {
1739
- entries,
1740
- unreadable,
1741
- release(remainder) {
1742
- if (released)
1743
- return;
1744
- released = true;
1745
- if (remainder.length > 0) {
1746
- try {
1747
- fs.mkdirSync(path2.dirname(outboxFilePath), { recursive: true, mode: 448 });
1748
- fs.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1749
- `).join(""), { encoding: "utf8", mode: 384 });
1750
- if (process.platform !== "win32")
1751
- fs.chmodSync(outboxFilePath, 384);
1752
- } catch {
1753
- return;
1754
- }
1755
- }
1756
- for (const file of claimed) {
1757
- try {
1758
- fs.unlinkSync(file);
1759
- } catch {
1760
- }
1761
- }
1762
- }
1763
- };
2393
+ return new AscendaApiError(response.status, errorCode, body);
1764
2394
  }
1765
- function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1766
- const reasons = {};
1767
- let oldestQueuedAt;
1768
- const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1769
- const fresh = [];
1770
- for (const entry of entries) {
1771
- if (entry.queuedAt < cutoff) {
1772
- reasons.age = (reasons.age ?? 0) + 1;
1773
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1774
- oldestQueuedAt = entry.queuedAt;
1775
- } else {
1776
- fresh.push(entry);
1777
- }
1778
- }
1779
- const excess = Math.max(0, fresh.length - bounds.maxEntries);
1780
- if (excess > 0) {
1781
- reasons.count = excess;
1782
- const first = fresh[0]?.queuedAt;
1783
- if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1784
- oldestQueuedAt = first;
1785
- }
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 } : {} } };
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();
1789
2406
  }
1790
- function listClaimFiles(outboxFilePath) {
1791
- const dir = path2.dirname(outboxFilePath);
1792
- const prefix = `${path2.basename(outboxFilePath)}.`;
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;
1793
2412
  try {
1794
- return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path2.join(dir, name)).sort();
2413
+ parsed = JSON.parse(body);
1795
2414
  } catch {
1796
- return [];
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")
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 } : {} });
1797
2433
  }
2434
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1798
2435
  }
1799
- function readEntries(file) {
1800
- let raw;
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) {
1801
2446
  try {
1802
- raw = fs.readFileSync(file, "utf8");
1803
- } catch {
1804
- return { entries: [], unreadable: 0 };
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
+ };
1805
2459
  }
1806
- const entries = [];
1807
- let unreadable = 0;
1808
- for (const line of raw.split("\n")) {
1809
- if (!line.trim())
1810
- continue;
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 base = { httpStatus: response.status, errorCode, detail: body || void 0 };
2484
+ if (response.status === 401)
2485
+ return { ...base, result: "auth_failed" };
2486
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
2487
+ return { ...base, result: "consent_missing" };
2488
+ if (response.status === 400 || response.status === 422)
2489
+ return { ...base, result: "validation_failed" };
2490
+ return { ...base, 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
@@ -2065,11 +2735,34 @@ var require_eventSender = __commonJS({
2065
2735
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
2066
2736
  }
2067
2737
  if (this.isRetryable(outcome)) {
2068
- await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
2738
+ await new Promise((resolve3) => setTimeout(resolve3, RETRY_DELAY_MS));
2069
2739
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
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));
@@ -2328,16 +3021,16 @@ var require_contextRegistry = __commonJS({
2328
3021
  exports.readWorkContextRegistry = readWorkContextRegistry;
2329
3022
  exports.recordWorkContext = recordWorkContext;
2330
3023
  exports.recordWorkContextAlias = recordWorkContextAlias;
2331
- var fs = __importStar(__require("fs"));
3024
+ var fs2 = __importStar(__require("fs"));
2332
3025
  var os2 = __importStar(__require("os"));
2333
- var path2 = __importStar(__require("path"));
3026
+ var path3 = __importStar(__require("path"));
2334
3027
  var MAX_PATHS_PER_ENTRY = 8;
2335
3028
  function workContextRegistryFilePath() {
2336
- return path2.join(os2.homedir(), ".ascenda", "work-contexts.json");
3029
+ return path3.join(os2.homedir(), ".ascenda", "work-contexts.json");
2337
3030
  }
2338
3031
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
2339
3032
  try {
2340
- const parsed = JSON.parse(fs.readFileSync(registryFilePath, "utf8"));
3033
+ const parsed = JSON.parse(fs2.readFileSync(registryFilePath, "utf8"));
2341
3034
  if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
2342
3035
  return parsed;
2343
3036
  }
@@ -2399,147 +3092,30 @@ var require_contextRegistry = __commonJS({
2399
3092
  if (dayOf(existing.lastSeenAt) !== dayOf(nowIso)) {
2400
3093
  existing.lastSeenAt = nowIso;
2401
3094
  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 = path2.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]);
3095
+ }
2465
3096
  }
2466
- __setModuleDefault(result, mod);
2467
- return result;
2468
- };
2469
- }();
2470
- Object.defineProperty(exports, "__esModule", { value: true });
2471
- exports.credentialsFilePath = credentialsFilePath;
2472
- exports.readMachineCredentials = readMachineCredentials;
2473
- exports.writeMachineCredentials = writeMachineCredentials;
2474
- exports.writeTopLevelCredentials = writeTopLevelCredentials;
2475
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2476
- exports.readHostCredentials = readHostCredentials;
2477
- exports.writeHostCredentials = writeHostCredentials;
2478
- exports.removeHostCredentials = removeHostCredentials;
2479
- var fs = __importStar(__require("fs"));
2480
- var path2 = __importStar(__require("path"));
2481
- var tokenStore_1 = require_tokenStore();
2482
- function credentialsFilePath() {
2483
- return path2.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2484
- }
2485
- function readMachineCredentials() {
2486
- try {
2487
- const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
2488
- if (!raw)
2489
- return void 0;
2490
- const parsed = JSON.parse(raw);
2491
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2492
- return void 0;
2493
- return parsed;
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(path2.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 = path3.dirname(registryFilePath);
3110
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
3111
+ const tmp = `${registryFilePath}.${process.pid}.tmp`;
3112
+ fs2.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2502
3113
  `, { encoding: "utf8", mode: 384 });
3114
+ fs2.renameSync(tmp, registryFilePath);
2503
3115
  if (process.platform !== "win32") {
2504
- fs.chmodSync(path2.dirname(file), 448);
2505
- fs.chmodSync(file, 384);
3116
+ fs2.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,12 +3162,14 @@ var require_forgeProject = __commonJS({
2586
3162
  }();
2587
3163
  Object.defineProperty(exports, "__esModule", { value: true });
2588
3164
  exports.forgeProjectHash = forgeProjectHash;
3165
+ exports.forgeRepoKey = forgeRepoKey;
3166
+ exports.forgeBranchKey = forgeBranchKey;
2589
3167
  exports.parseForgeFullName = parseForgeFullName;
2590
3168
  exports.readForgeFullName = readForgeFullName;
2591
3169
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
2592
3170
  exports.recordForgeProjectAlias = recordForgeProjectAlias;
2593
- var fs = __importStar(__require("fs"));
2594
- var path2 = __importStar(__require("path"));
3171
+ var fs2 = __importStar(__require("fs"));
3172
+ var path3 = __importStar(__require("path"));
2595
3173
  var contextRegistry_1 = require_contextRegistry();
2596
3174
  function forgeProjectHash(value) {
2597
3175
  let h = 2166136261;
@@ -2601,6 +3179,19 @@ var require_forgeProject = __commonJS({
2601
3179
  }
2602
3180
  return h.toString(16).padStart(8, "0");
2603
3181
  }
3182
+ function forgeRepoKey(fullName) {
3183
+ return forgeProjectHash(fullName.toLowerCase());
3184
+ }
3185
+ function forgeBranchKey(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;
@@ -2637,7 +3228,7 @@ var require_forgeProject = __commonJS({
2637
3228
  return null;
2638
3229
  let config;
2639
3230
  try {
2640
- config = fs.readFileSync(path2.join(repositoryRoot, ".git", "config"), "utf8");
3231
+ config = fs2.readFileSync(path3.join(repositoryRoot, ".git", "config"), "utf8");
2641
3232
  } catch {
2642
3233
  return null;
2643
3234
  }
@@ -2744,31 +3335,31 @@ var require_salt = __commonJS({
2744
3335
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
2745
3336
  exports.hashWithMachineSalt = hashWithMachineSalt;
2746
3337
  var crypto = __importStar(__require("crypto"));
2747
- var fs = __importStar(__require("fs"));
2748
- var path2 = __importStar(__require("path"));
3338
+ var fs2 = __importStar(__require("fs"));
3339
+ var path3 = __importStar(__require("path"));
2749
3340
  var tokenStore_1 = require_tokenStore();
2750
3341
  function machineSaltFilePath() {
2751
- return path2.join((0, tokenStore_1.ascendaHome)(), "salt");
3342
+ return path3.join((0, tokenStore_1.ascendaHome)(), "salt");
2752
3343
  }
2753
3344
  var cache = /* @__PURE__ */ new Map();
2754
3345
  function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
2755
3346
  const hit = cache.get(saltFilePath);
2756
3347
  if (hit)
2757
3348
  return hit;
2758
- const dir = path2.dirname(saltFilePath);
2759
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
3349
+ const dir = path3.dirname(saltFilePath);
3350
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
2760
3351
  let salt;
2761
3352
  try {
2762
3353
  salt = crypto.randomBytes(32).toString("hex");
2763
- fs.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
3354
+ fs2.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2764
3355
  } catch (error) {
2765
3356
  if (error.code !== "EEXIST")
2766
3357
  throw error;
2767
- salt = fs.readFileSync(saltFilePath, "utf8").trim();
3358
+ salt = fs2.readFileSync(saltFilePath, "utf8").trim();
2768
3359
  }
2769
3360
  if (process.platform !== "win32") {
2770
- fs.chmodSync(dir, 448);
2771
- fs.chmodSync(saltFilePath, 384);
3361
+ fs2.chmodSync(dir, 448);
3362
+ fs2.chmodSync(saltFilePath, 384);
2772
3363
  }
2773
3364
  cache.set(saltFilePath, salt);
2774
3365
  return salt;
@@ -2828,8 +3419,8 @@ var require_workContext = __commonJS({
2828
3419
  exports.deriveBranchHash = deriveBranchHash;
2829
3420
  exports.readBranchName = readBranchName;
2830
3421
  exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
2831
- var fs = __importStar(__require("fs"));
2832
- var path2 = __importStar(__require("path"));
3422
+ var fs2 = __importStar(__require("fs"));
3423
+ var path3 = __importStar(__require("path"));
2833
3424
  var salt_1 = require_salt();
2834
3425
  var MAX_WALK_DEPTH = 64;
2835
3426
  function deriveWorkContext(cwd, saltFilePath) {
@@ -2860,14 +3451,14 @@ var require_workContext = __commonJS({
2860
3451
  };
2861
3452
  }
2862
3453
  function resolveRepositoryRoots(startDir) {
2863
- if (!fs.existsSync(startDir))
3454
+ if (!fs2.existsSync(startDir))
2864
3455
  return null;
2865
3456
  let dir = startDir;
2866
3457
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
2867
- const dotGit = path2.join(dir, ".git");
3458
+ const dotGit = path3.join(dir, ".git");
2868
3459
  let stat = null;
2869
3460
  try {
2870
- stat = fs.statSync(dotGit);
3461
+ stat = fs2.statSync(dotGit);
2871
3462
  } catch {
2872
3463
  stat = null;
2873
3464
  }
@@ -2878,7 +3469,7 @@ var require_workContext = __commonJS({
2878
3469
  const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
2879
3470
  return { checkoutRoot: dir, canonicalRoot, gitDir };
2880
3471
  }
2881
- const parent = path2.dirname(dir);
3472
+ const parent = path3.dirname(dir);
2882
3473
  if (parent === dir)
2883
3474
  return null;
2884
3475
  dir = parent;
@@ -2887,16 +3478,16 @@ var require_workContext = __commonJS({
2887
3478
  }
2888
3479
  function readGitdirPointer(dotGitFile, containingDir) {
2889
3480
  try {
2890
- const match = /^gitdir:\s*(.+)\s*$/m.exec(fs.readFileSync(dotGitFile, "utf8"));
3481
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(fs2.readFileSync(dotGitFile, "utf8"));
2891
3482
  if (!match)
2892
3483
  return null;
2893
- return path2.resolve(containingDir, match[1].trim());
3484
+ return path3.resolve(containingDir, match[1].trim());
2894
3485
  } catch {
2895
3486
  return null;
2896
3487
  }
2897
3488
  }
2898
3489
  function worktreeParentRoot(resolvedGitDir) {
2899
- const marker = `${path2.sep}.git${path2.sep}worktrees${path2.sep}`;
3490
+ const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
2900
3491
  const idx = resolvedGitDir.indexOf(marker);
2901
3492
  if (idx === -1)
2902
3493
  return null;
@@ -2906,12 +3497,12 @@ var require_workContext = __commonJS({
2906
3497
  const sep = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
2907
3498
  const leading = /^[\\/]/.test(startPath) ? sep : "";
2908
3499
  const segments = startPath.split(/[\\/]/).filter(Boolean);
2909
- const join2 = (count) => leading + segments.slice(0, count).join(sep);
3500
+ const join3 = (count) => leading + segments.slice(0, count).join(sep);
2910
3501
  for (let i = 0; i + 2 < segments.length; i++) {
2911
3502
  if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
2912
3503
  if (i === 0)
2913
3504
  return null;
2914
- return { checkoutRoot: join2(i + 3), canonicalRoot: join2(i), gitDir: null };
3505
+ return { checkoutRoot: join3(i + 3), canonicalRoot: join3(i), gitDir: null };
2915
3506
  }
2916
3507
  }
2917
3508
  for (let i = 0; i + 1 < segments.length; i++) {
@@ -2921,7 +3512,7 @@ var require_workContext = __commonJS({
2921
3512
  continue;
2922
3513
  const repoName = folder.slice(0, -suffix.length);
2923
3514
  const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep);
2924
- return { checkoutRoot: join2(i + 2), canonicalRoot, gitDir: null };
3515
+ return { checkoutRoot: join3(i + 2), canonicalRoot, gitDir: null };
2925
3516
  }
2926
3517
  return null;
2927
3518
  }
@@ -2969,7 +3560,7 @@ var require_workContext = __commonJS({
2969
3560
  return null;
2970
3561
  let head;
2971
3562
  try {
2972
- head = fs.readFileSync(path2.join(gitDir, "HEAD"), "utf8").trim();
3563
+ head = fs2.readFileSync(path3.join(gitDir, "HEAD"), "utf8").trim();
2973
3564
  } catch {
2974
3565
  return null;
2975
3566
  }
@@ -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 = repoKeysEnabled;
3625
+ exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd;
3626
+ var fs2 = __importStar(__require("fs"));
3627
+ var path3 = __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 repoKeysEnabled() {
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 = fs2.readFileSync(path3.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 || !repoKeysEnabled())
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 = deliverHookEvents2;
3682
+ exports.flushHookOutbox = flushHookOutbox2;
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 deliverHookEvents2(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 flushHookOutbox2(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}: ` : "";
@@ -3305,7 +4051,7 @@ var require_studyJoin = __commonJS({
3305
4051
  const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3306
4052
  const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3307
4053
  while (Date.now() < deadline) {
3308
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
4054
+ await new Promise((resolve3) => setTimeout(resolve3, pollIntervalMs));
3309
4055
  let poll;
3310
4056
  try {
3311
4057
  poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
@@ -3368,7 +4114,7 @@ var require_studyJoin = __commonJS({
3368
4114
  return true;
3369
4115
  }
3370
4116
  function askChoice(stdin, stdout) {
3371
- return new Promise((resolve) => {
4117
+ return new Promise((resolve3) => {
3372
4118
  const rl = readline.createInterface({ input: stdin, output: stdout });
3373
4119
  let settled = false;
3374
4120
  const finish = (value) => {
@@ -3376,7 +4122,7 @@ var require_studyJoin = __commonJS({
3376
4122
  return;
3377
4123
  settled = true;
3378
4124
  rl.close();
3379
- resolve(value.trim());
4125
+ resolve3(value.trim());
3380
4126
  };
3381
4127
  rl.question("Choice [Not now]: ", finish);
3382
4128
  rl.once("close", () => finish(""));
@@ -3594,79 +4340,33 @@ var require_initiatives = __commonJS({
3594
4340
  result: asResult(o.result)
3595
4341
  };
3596
4342
  }
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");
3669
- }
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);
4369
+ }
3670
4370
  }
3671
4371
  });
3672
4372
 
@@ -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 = stampLastHook2;
3722
4424
  exports.readLastHook = readLastHook;
@@ -3724,12 +4426,13 @@ var require_hookRunner = __commonJS({
3724
4426
  exports.resolveHookNode = resolveHookNode;
3725
4427
  exports.tidyHomePath = tidyHomePath;
3726
4428
  var child_process_1 = __require("child_process");
3727
- var fs = __importStar(__require("fs"));
3728
- var path2 = __importStar(__require("path"));
4429
+ var fs2 = __importStar(__require("fs"));
4430
+ var path3 = __importStar(__require("path"));
4431
+ var collectorVersion_1 = require_collectorVersion();
3729
4432
  var tokenStore_1 = require_tokenStore();
3730
4433
  function hookRunnerPaths(binaryName) {
3731
- const launcher = path2.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3732
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
4434
+ const launcher = path3.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
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,62 +4526,98 @@ 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 fs2.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
- const source = path2.resolve(options.source ?? process.argv[1]);
3831
- fs.mkdirSync(path2.dirname(paths.launcher), { recursive: true });
4555
+ const source = path3.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 && fs2.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4560
+ options.onKeptNewer?.(installed, incoming);
4561
+ if (process.platform !== "win32" && !fs2.existsSync(paths.launcher))
4562
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4563
+ return paths.launcher;
4564
+ }
4565
+ fs2.mkdirSync(path3.dirname(paths.launcher), { recursive: true });
3832
4566
  if (process.platform === "win32") {
3833
- if (source !== path2.resolve(paths.launcher))
3834
- fs.copyFileSync(source, paths.launcher);
4567
+ if (source !== path3.resolve(paths.launcher))
4568
+ fs2.copyFileSync(source, paths.launcher);
4569
+ writeAtomically(paths.version, `${incoming}
4570
+ `, 420);
3835
4571
  return paths.launcher;
3836
4572
  }
3837
- if (source !== path2.resolve(paths.bundle))
3838
- writeAtomically(paths.bundle, fs.readFileSync(source), 493);
4573
+ if (source !== path3.resolve(paths.bundle))
4574
+ writeAtomically(paths.bundle, fs2.readFileSync(source), 493);
3839
4575
  writeAtomically(paths.launcher, hookLauncherScript(options), 493);
3840
4576
  writeAtomically(paths.record, `${process.execPath}
3841
4577
  `, 420);
3842
- fs.rmSync(paths.noNode, { force: true });
4578
+ if (source !== path3.resolve(paths.bundle))
4579
+ writeAtomically(paths.version, `${incoming}
4580
+ `, 420);
4581
+ fs2.rmSync(paths.noNode, { force: true });
3843
4582
  return paths.launcher;
3844
4583
  }
3845
4584
  function removeHookRunner(binaryName) {
3846
4585
  const removed = [];
3847
4586
  for (const file of Object.values(hookRunnerPaths(binaryName))) {
3848
- if (!fs.existsSync(file))
4587
+ if (!fs2.existsSync(file))
3849
4588
  continue;
3850
- fs.rmSync(file, { force: true });
4589
+ fs2.rmSync(file, { force: true });
3851
4590
  removed.push(file);
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`;
3860
- fs.writeFileSync(tmp, contents, { mode });
3861
- fs.chmodSync(tmp, mode);
3862
- fs.renameSync(tmp, target);
4599
+ fs2.writeFileSync(tmp, contents, { mode });
4600
+ fs2.chmodSync(tmp, mode);
4601
+ fs2.renameSync(tmp, target);
3863
4602
  }
3864
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path2.join((0, tokenStore_1.ascendaHome)(), "state");
4603
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join((0, tokenStore_1.ascendaHome)(), "state");
3865
4604
  function lastHookPath(tool) {
3866
- return path2.join(stateDir(), `${tool}-last-hook.json`);
4605
+ return path3.join(stateDir(), `${tool}-last-hook.json`);
3867
4606
  }
3868
4607
  function stampLastHook2(tool, event, now = /* @__PURE__ */ new Date()) {
3869
4608
  try {
3870
- fs.mkdirSync(stateDir(), { recursive: true });
4609
+ fs2.mkdirSync(stateDir(), { recursive: true });
3871
4610
  const file = lastHookPath(tool);
3872
4611
  const tmp = `${file}.${process.pid}.tmp`;
3873
- fs.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
4612
+ fs2.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
3874
4613
  `, { mode: 384 });
3875
- fs.renameSync(tmp, file);
4614
+ fs2.renameSync(tmp, file);
3876
4615
  } catch {
3877
4616
  }
3878
4617
  }
3879
4618
  function readLastHook(tool) {
3880
4619
  try {
3881
- const parsed = JSON.parse(fs.readFileSync(lastHookPath(tool), "utf8"));
4620
+ const parsed = JSON.parse(fs2.readFileSync(lastHookPath(tool), "utf8"));
3882
4621
  if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
3883
4622
  return void 0;
3884
4623
  return { event: parsed.event, at: parsed.at };
@@ -3901,7 +4640,7 @@ var require_hookRunner = __commonJS({
3901
4640
  return `${Math.round(hours / 24)} days ago`;
3902
4641
  }
3903
4642
  function resolveHookNode(launcher) {
3904
- if (!fs.existsSync(launcher))
4643
+ if (!fs2.existsSync(launcher))
3905
4644
  return { problem: "the hook launcher is not installed" };
3906
4645
  const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
3907
4646
  encoding: "utf8",
@@ -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 fs2 = __importStar(__require("fs"));
4709
+ var path3 = __importStar(__require("path"));
4710
+ var hookRunner_1 = require_hookRunner();
4711
+ function replaceSettingsFile(settingsFile, contents) {
4712
+ const exists = fs2.existsSync(settingsFile);
4713
+ const target = exists ? fs2.realpathSync(settingsFile) : settingsFile;
4714
+ if (exists) {
4715
+ const backup = `${settingsFile}.ascenda-backup`;
4716
+ if (!fs2.existsSync(backup))
4717
+ fs2.copyFileSync(target, backup);
4718
+ }
4719
+ fs2.mkdirSync(path3.dirname(target), { recursive: true });
4720
+ const mode = exists ? fs2.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) {
@@ -3974,22 +4822,22 @@ var require_saverHandoff = __commonJS({
3974
4822
  exports.heldForSaver = heldForSaver;
3975
4823
  exports.readSaverStatuses = readSaverStatuses;
3976
4824
  exports.probeSocket = probeSocket;
3977
- var fs = __importStar(__require("fs"));
4825
+ var fs2 = __importStar(__require("fs"));
3978
4826
  var net = __importStar(__require("net"));
3979
4827
  var os2 = __importStar(__require("os"));
3980
- var path2 = __importStar(__require("path"));
4828
+ var path3 = __importStar(__require("path"));
3981
4829
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3982
4830
  function saverContainerDir() {
3983
- return process.env.ASCENDA_SAVER_CONTAINER ?? path2.join(os2.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
4831
+ return process.env.ASCENDA_SAVER_CONTAINER ?? path3.join(os2.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
3984
4832
  }
3985
4833
  function saverSupportDir() {
3986
- return path2.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
4834
+ return path3.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
3987
4835
  }
3988
4836
  function saverReplayPath() {
3989
- return path2.join(saverContainerDir(), "l.replay.json");
4837
+ return path3.join(saverContainerDir(), "l.replay.json");
3990
4838
  }
3991
4839
  function saverStatusDir() {
3992
- return path2.join(saverSupportDir(), "status");
4840
+ return path3.join(saverSupportDir(), "status");
3993
4841
  }
3994
4842
  exports.SAVER_REPLAY_WINDOW_MS = 30 * 60 * 1e3;
3995
4843
  var SAVER_REPLAY_MAX = 32;
@@ -3998,7 +4846,7 @@ var require_saverHandoff = __commonJS({
3998
4846
  try {
3999
4847
  if (process.env.ASCENDA_LIVE_BUS_SOCKET && !process.env.ASCENDA_SAVER_CONTAINER)
4000
4848
  return;
4001
- if (!fs.existsSync(saverSupportDir()))
4849
+ if (!fs2.existsSync(saverSupportDir()))
4002
4850
  return;
4003
4851
  const wire = signal;
4004
4852
  const tool = wire.tool;
@@ -4012,15 +4860,15 @@ var require_saverHandoff = __commonJS({
4012
4860
  kept.sort((a, b) => a.at - b.at);
4013
4861
  const body = JSON.stringify({ schema: exports.SAVER_REPLAY_SCHEMA, signals: kept.slice(-SAVER_REPLAY_MAX) });
4014
4862
  const tmp = `${file}.${process.pid}.tmp`;
4015
- fs.writeFileSync(tmp, `${body}
4863
+ fs2.writeFileSync(tmp, `${body}
4016
4864
  `, { mode: 384 });
4017
- fs.renameSync(tmp, file);
4865
+ fs2.renameSync(tmp, file);
4018
4866
  } catch {
4019
4867
  }
4020
4868
  }
4021
4869
  function readHeld(file) {
4022
4870
  try {
4023
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
4871
+ const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
4024
4872
  if (parsed.schema !== exports.SAVER_REPLAY_SCHEMA || !Array.isArray(parsed.signals))
4025
4873
  return [];
4026
4874
  return parsed.signals.filter((held) => typeof held === "object" && held !== null && typeof held.tool === "string" && typeof held.session === "string" && typeof held.event === "string" && typeof held.at === "number");
@@ -4037,14 +4885,14 @@ var require_saverHandoff = __commonJS({
4037
4885
  function readSaverStatuses(now = Date.now()) {
4038
4886
  let names;
4039
4887
  try {
4040
- names = fs.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
4888
+ names = fs2.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
4041
4889
  } catch {
4042
4890
  return [];
4043
4891
  }
4044
4892
  const readings = [];
4045
4893
  for (const name of names) {
4046
4894
  try {
4047
- const status = JSON.parse(fs.readFileSync(path2.join(saverStatusDir(), name), "utf8"));
4895
+ const status = JSON.parse(fs2.readFileSync(path3.join(saverStatusDir(), name), "utf8"));
4048
4896
  if (typeof status.pid !== "number" || typeof status.updatedAt !== "string")
4049
4897
  continue;
4050
4898
  readings.push({ ...status, alive: processAlive(status.pid), ageMs: now - Date.parse(status.updatedAt) });
@@ -4062,14 +4910,14 @@ var require_saverHandoff = __commonJS({
4062
4910
  }
4063
4911
  }
4064
4912
  function probeSocket(socketPath, timeoutMs = 300) {
4065
- return new Promise((resolve) => {
4913
+ return new Promise((resolve3) => {
4066
4914
  try {
4067
- if (!fs.statSync(socketPath).isSocket()) {
4068
- resolve("absent");
4915
+ if (!fs2.statSync(socketPath).isSocket()) {
4916
+ resolve3("absent");
4069
4917
  return;
4070
4918
  }
4071
4919
  } catch {
4072
- resolve("absent");
4920
+ resolve3("absent");
4073
4921
  return;
4074
4922
  }
4075
4923
  let settled = false;
@@ -4079,7 +4927,7 @@ var require_saverHandoff = __commonJS({
4079
4927
  settled = true;
4080
4928
  clearTimeout(timer);
4081
4929
  socket.destroy();
4082
- resolve(state);
4930
+ resolve3(state);
4083
4931
  };
4084
4932
  const socket = net.createConnection(socketPath);
4085
4933
  const timer = setTimeout(() => finish("unreachable"), timeoutMs);
@@ -4139,10 +4987,10 @@ var require_liveBus = __commonJS({
4139
4987
  exports.bucketPromptSize = bucketPromptSize2;
4140
4988
  exports.emitLiveSignal = emitLiveSignal2;
4141
4989
  exports.deliverLine = deliverLine;
4142
- var fs = __importStar(__require("fs"));
4990
+ var fs2 = __importStar(__require("fs"));
4143
4991
  var net = __importStar(__require("net"));
4144
4992
  var os2 = __importStar(__require("os"));
4145
- var path2 = __importStar(__require("path"));
4993
+ var path3 = __importStar(__require("path"));
4146
4994
  var hookSet_1 = require_hookSet();
4147
4995
  var saverHandoff_1 = require_saverHandoff();
4148
4996
  var WRITE_TIMEOUT_MS = 50;
@@ -4155,9 +5003,9 @@ var require_liveBus = __commonJS({
4155
5003
  return [override];
4156
5004
  const home = os2.homedir();
4157
5005
  return [
4158
- path2.join(home, ".ascenda", "live.sock"),
4159
- path2.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4160
- path2.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
5006
+ path3.join(home, ".ascenda", "live.sock"),
5007
+ path3.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
5008
+ path3.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4161
5009
  ];
4162
5010
  }
4163
5011
  function existingSocketCandidates() {
@@ -4166,7 +5014,7 @@ var require_liveBus = __commonJS({
4166
5014
  return candidates;
4167
5015
  return candidates.filter((candidate) => {
4168
5016
  try {
4169
- return fs.statSync(candidate).isSocket();
5017
+ return fs2.statSync(candidate).isSocket();
4170
5018
  } catch {
4171
5019
  return false;
4172
5020
  }
@@ -4203,10 +5051,10 @@ var require_liveBus = __commonJS({
4203
5051
  });
4204
5052
  }
4205
5053
  function deliverLine(line) {
4206
- return new Promise((resolve) => {
5054
+ return new Promise((resolve3) => {
4207
5055
  const candidates = existingSocketCandidates();
4208
5056
  if (candidates.length === 0) {
4209
- resolve(void 0);
5057
+ resolve3(void 0);
4210
5058
  return;
4211
5059
  }
4212
5060
  let settled = false;
@@ -4225,7 +5073,7 @@ var require_liveBus = __commonJS({
4225
5073
  settled = true;
4226
5074
  clearTimeout(timer);
4227
5075
  drop();
4228
- resolve(accepted);
5076
+ resolve3(accepted);
4229
5077
  };
4230
5078
  const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4231
5079
  const tryFrom = (index) => {
@@ -4425,7 +5273,7 @@ var require_liveSignalDoctor = __commonJS({
4425
5273
  if (accepted !== saverSocket)
4426
5274
  return { tone: "ok", text: `the desktop app took it (${accepted})` };
4427
5275
  for (let waited = 0; waited < 2e3; waited += 100) {
4428
- await new Promise((resolve) => setTimeout(resolve, 100));
5276
+ await new Promise((resolve3) => setTimeout(resolve3, 100));
4429
5277
  const answered = (0, saverHandoff_1.readSaverStatuses)().find((status) => status.lastPingSession === session);
4430
5278
  if (answered)
4431
5279
  return { tone: "ok", text: `OK. The screen saver (pid ${answered.pid}) received it` };
@@ -4688,18 +5536,22 @@ var require_cliAgentSetup = __commonJS({
4688
5536
  exports.runCliAgentSetup = runCliAgentSetup2;
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"));
4694
- var fs = __importStar(__require("fs"));
5544
+ var fs2 = __importStar(__require("fs"));
4695
5545
  var os2 = __importStar(__require("os"));
4696
- var path2 = __importStar(__require("path"));
5546
+ var path3 = __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)(), os2.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, os2.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, os2.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.");
@@ -4854,7 +5723,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4854
5723
  return 0;
4855
5724
  }
4856
5725
  function isHomeProject(options) {
4857
- return options.scope === "project" && path2.resolve(options.projectDir) === path2.resolve(os2.homedir());
5726
+ return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os2.homedir());
4858
5727
  }
4859
5728
  function parseArgs(argv, spec) {
4860
5729
  const options = {
@@ -4909,11 +5778,23 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4909
5778
  break;
4910
5779
  }
4911
5780
  case "--project-dir":
4912
- options.projectDir = path2.resolve(next());
5781
+ options.projectDir = path3.resolve(next());
4913
5782
  break;
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
@@ -5037,19 +5918,24 @@ Pairing ${status.status}. Run setup again.`);
5037
5918
  console.log(" Waiting...");
5038
5919
  announced = true;
5039
5920
  }
5040
- await new Promise((resolve) => setTimeout(resolve, 2e3));
5921
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
5041
5922
  }
5042
5923
  console.error("\nPairing timed out. 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 ?? {} };
5050
- const exists = fs.existsSync(settingsFile);
5936
+ const exists = fs2.existsSync(settingsFile);
5051
5937
  if (exists) {
5052
- const raw = fs.readFileSync(settingsFile, "utf8").trim();
5938
+ const raw = fs2.readFileSync(settingsFile, "utf8").trim();
5053
5939
  if (raw) {
5054
5940
  try {
5055
5941
  settings = JSON.parse(raw);
@@ -5063,13 +5949,12 @@ ${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)}
5071
5956
  `;
5072
- if (exists && fs.readFileSync(settingsFile, "utf8") === serialised)
5957
+ if (exists && fs2.readFileSync(settingsFile, "utf8") === serialised)
5073
5958
  return false;
5074
5959
  if (dryRun) {
5075
5960
  console.log(`
@@ -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(path2.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,35 +5972,137 @@ ${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, os2.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];
5118
6102
  }
5119
6103
  function readSettings(settingsFile) {
5120
6104
  try {
5121
- return JSON.parse(fs.readFileSync(settingsFile, "utf8"));
6105
+ return JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
5122
6106
  } catch {
5123
6107
  return {};
5124
6108
  }
@@ -5136,7 +6120,8 @@ ${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"}`);
5139
- console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
6123
+ console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
6124
+ console.log(`hook binary ${fs2.existsSync(binary) ? binary : "\u2014 not installed"}`);
5140
6125
  const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5141
6126
  if (node) {
5142
6127
  console.log(node.problem ? `node \u2014 ${node.problem}. Install Node 20 or newer, then run setup again` : `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
@@ -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 && fs2.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
5179
6172
  return healthy ? 0 : 1;
5180
6173
  }
5181
6174
  function countRegistered(settings, spec) {
@@ -5196,7 +6189,7 @@ ${serialised}`);
5196
6189
  file: (0, hookRunner_1.tidyHomePath)(file, home),
5197
6190
  registered,
5198
6191
  scope,
5199
- homeProject: scope === "project" && path2.resolve(projectDir) === path2.resolve(home)
6192
+ homeProject: scope === "project" && path3.resolve(projectDir) === path3.resolve(home)
5200
6193
  });
5201
6194
  }
5202
6195
  return found;
@@ -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, os2.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
  }
@@ -5249,13 +6269,13 @@ ${serialised}`);
5249
6269
  ];
5250
6270
  }
5251
6271
  function removeOurHookEntries(settingsFile, spec) {
5252
- if (!fs.existsSync(settingsFile))
6272
+ if (!fs2.existsSync(settingsFile))
5253
6273
  return true;
5254
6274
  try {
5255
- const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
6275
+ const settings = JSON.parse(fs2.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;
@@ -5274,7 +6293,7 @@ ${serialised}`);
5274
6293
  }
5275
6294
  function uninstall(options, spec) {
5276
6295
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
5277
- if (fs.existsSync(settingsFile)) {
6296
+ if (fs2.existsSync(settingsFile)) {
5278
6297
  if (!removeOurHookEntries(settingsFile, spec)) {
5279
6298
  console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
5280
6299
  return 1;
@@ -5289,7 +6308,7 @@ ${serialised}`);
5289
6308
  (0, credentials_1.removeHostCredentials)(spec.host);
5290
6309
  console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
5291
6310
  }
5292
- console.log(`tokens left in ${path2.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
6311
+ console.log(`tokens left in ${path3.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
5293
6312
  return 0;
5294
6313
  }
5295
6314
  }
@@ -5338,24 +6357,39 @@ var require_turnState = __commonJS({
5338
6357
  }();
5339
6358
  Object.defineProperty(exports, "__esModule", { value: true });
5340
6359
  exports.recordTurnStart = recordTurnStart2;
6360
+ exports.readTurnPromptId = readTurnPromptId2;
5341
6361
  exports.consumeTurnDurationMs = consumeTurnDurationMs2;
5342
- var fs = __importStar(__require("fs"));
5343
- var path2 = __importStar(__require("path"));
6362
+ var crypto_1 = __require("crypto");
6363
+ var fs2 = __importStar(__require("fs"));
6364
+ var path3 = __importStar(__require("path"));
5344
6365
  var tokenStore_1 = require_tokenStore();
5345
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path2.join((0, tokenStore_1.ascendaHome)(), "state");
6366
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join((0, tokenStore_1.ascendaHome)(), "state");
5346
6367
  function turnFile(agent, sessionId) {
5347
- return path2.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
6368
+ return path3.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
5348
6369
  }
5349
6370
  function sanitize(value) {
5350
6371
  return value.replace(/[^a-zA-Z0-9._-]/g, "_");
5351
6372
  }
5352
6373
  function recordTurnStart2(agent, sessionId, now = Date.now()) {
5353
6374
  if (!sessionId)
5354
- return;
6375
+ return void 0;
6376
+ try {
6377
+ const promptId = (0, crypto_1.randomUUID)();
6378
+ fs2.mkdirSync(stateDir(), { recursive: true });
6379
+ fs2.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
6380
+ return promptId;
6381
+ } catch {
6382
+ return void 0;
6383
+ }
6384
+ }
6385
+ function readTurnPromptId2(agent, sessionId) {
6386
+ if (!sessionId)
6387
+ return void 0;
5355
6388
  try {
5356
- fs.mkdirSync(stateDir(), { recursive: true });
5357
- fs.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
6389
+ const id = fs2.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
6390
+ return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
5358
6391
  } catch {
6392
+ return void 0;
5359
6393
  }
5360
6394
  }
5361
6395
  function consumeTurnDurationMs2(agent, sessionId, now = Date.now()) {
@@ -5363,8 +6397,8 @@ 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());
5367
- fs.rmSync(file, { force: true });
6400
+ const started = Number(fs2.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
6401
+ fs2.rmSync(file, { force: true });
5368
6402
  if (!Number.isFinite(started) || started <= 0 || started > now)
5369
6403
  return void 0;
5370
6404
  return now - started;
@@ -5423,14 +6457,14 @@ var require_agentProcess = __commonJS({
5423
6457
  exports.findAgentPid = findAgentPid2;
5424
6458
  exports.livePidFields = livePidFields;
5425
6459
  var child_process_1 = __require("child_process");
5426
- var path2 = __importStar(__require("path"));
6460
+ var path3 = __importStar(__require("path"));
5427
6461
  exports.AGENT_PROCESS = {
5428
6462
  claude_code: {
5429
- executable: (command) => path2.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
6463
+ executable: (command) => path3.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
5430
6464
  scriptMarkers: ["@anthropic-ai/claude-code"]
5431
6465
  },
5432
6466
  codex: {
5433
- executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path2.basename(command)),
6467
+ executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path3.basename(command)),
5434
6468
  args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
5435
6469
  },
5436
6470
  gemini_cli: {
@@ -5484,7 +6518,7 @@ var require_agentProcess = __commonJS({
5484
6518
  if (rule.executable(info.command)) {
5485
6519
  return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
5486
6520
  }
5487
- if (markers.length > 0 && SCRIPT_RUNTIME.test(path2.basename(info.command))) {
6521
+ if (markers.length > 0 && SCRIPT_RUNTIME.test(path3.basename(info.command))) {
5488
6522
  const args = argsLookup(pid);
5489
6523
  const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
5490
6524
  if (marker !== 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,10 +7226,10 @@ 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
 
6095
7231
  // src/mapCodexEvent.ts
6096
- var import_tool_kit = __toESM(require_out2(), 1);
7232
+ var import_tool_kit = __toESM(require_out3(), 1);
6097
7233
 
6098
7234
  // src/types.ts
6099
7235
  var ASCENDA_TOOL_TYPE = "cli_agent";
@@ -6139,6 +7275,12 @@ function mapEvent(hookName, input, turnDurationMs) {
6139
7275
  // the count is that a gate was reached, when, and in which session.
6140
7276
  case "PermissionRequest":
6141
7277
  return [{ eventType: "supervision_interruption", severity: "low", metadata: withHost({ interruptionKind: "permission_request" }) }];
7278
+ // Codex 0.146 and later. The session is over, whatever the `reason`: Codex
7279
+ // sends "other" for every ending today, so it is carried only as the
7280
+ // catalog's own word and never branched on. Same row as Claude Code's
7281
+ // `SessionEnd`, so the two sum.
7282
+ case "SessionEnd":
7283
+ return mapSessionEnd(input);
6142
7284
  // The subagent lifecycle is still deliberately unmapped: it is not an
6143
7285
  // interruption of the person, and it is out of scope here.
6144
7286
  case "SubagentStart":
@@ -6153,6 +7295,17 @@ function mapSessionStart(input) {
6153
7295
  if (source && source !== "startup" && source !== "resume") return [];
6154
7296
  return [{ eventType: "create_focus_session", severity: "low", metadata: withHost({ activity: "session_started", ...autonomyModeMetadata(input) }) }];
6155
7297
  }
7298
+ function mapSessionEnd(input) {
7299
+ const raw = input["reason"];
7300
+ return [{
7301
+ eventType: "recovery_offline_period",
7302
+ severity: "low",
7303
+ metadata: withHost({
7304
+ activity: "session_ended",
7305
+ ...raw === void 0 || raw === null ? {} : { sessionEndReason: classifySessionEndReason(raw) }
7306
+ })
7307
+ }];
7308
+ }
6156
7309
  function mapUserPromptSubmit(input) {
6157
7310
  const prompt = (0, import_tool_kit.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit.getNestedString)(input, [["payload", "prompt"]]);
6158
7311
  const autonomy = autonomyModeMetadata(input);
@@ -6166,10 +7319,10 @@ function mapPostToolUse(input) {
6166
7319
  const toolName = getToolName(input);
6167
7320
  const safeToolName = sanitiseToolName(toolName);
6168
7321
  const outcome = (0, import_tool_kit.inferOutcome)(input);
6169
- const command = (0, import_tool_kit.getString)(input, ["command"]) ?? (0, import_tool_kit.getNestedString)(input, [["tool_input", "command"], ["input", "command"]]);
7322
+ const command = getCommand(input);
6170
7323
  const commandClass = (0, import_tool_kit.classifyCommand)(command);
6171
7324
  const lowered = toolName?.toLowerCase();
6172
- const isShell = lowered === "bash" || lowered === "shell" || lowered === "local_shell";
7325
+ const isShell = lowered === "bash" || lowered === "shell" || lowered === "local_shell" || lowered === "exec_command" || lowered === "shell_command";
6173
7326
  const autonomy = autonomyModeMetadata(input);
6174
7327
  if (outcome === "failure") {
6175
7328
  if (isShell && (0, import_tool_kit.isVerificationCommand)(commandClass)) {
@@ -6183,7 +7336,8 @@ function mapPostToolUse(input) {
6183
7336
  if (isShell && (0, import_tool_kit.isVerificationCommand)(commandClass)) {
6184
7337
  return [{ eventType: "editor_verification_activity", severity: "low", metadata: withHost({ toolName: safeToolName, commandClass, outcome, activity: "ai_test_or_build_run", ...autonomy }) }];
6185
7338
  }
6186
- return [{ eventType: "ai_tool_call_completed", severity: "low", metadata: withHost({ toolName: safeToolName, commandClass, outcome, ...autonomy }) }];
7339
+ const facts = isShell && outcome === "success" ? (0, import_tool_kit.shellCommandFacts)(command) : {};
7340
+ return [{ eventType: "ai_tool_call_completed", severity: "low", metadata: withHost({ toolName: safeToolName, commandClass, outcome, ...facts, ...autonomy }) }];
6187
7341
  }
6188
7342
  function mapPreCompact(input) {
6189
7343
  const trigger = (0, import_tool_kit.getString)(input, ["trigger", "reason"]);
@@ -6226,8 +7380,32 @@ var AUTONOMY_BY_PERMISSION_MODE = {
6226
7380
  dontask: "dont_ask",
6227
7381
  bypasspermissions: "bypass_permissions"
6228
7382
  };
7383
+ var SESSION_END_REASONS = ["clear", "resume", "logout", "prompt_input_exit", "other"];
7384
+ function classifySessionEndReason(raw) {
7385
+ if (typeof raw !== "string") return "unknown";
7386
+ const value = raw.trim().toLowerCase();
7387
+ return SESSION_END_REASONS.includes(value) ? value : "unknown";
7388
+ }
6229
7389
  function getToolName(input) {
6230
- return (0, import_tool_kit.getString)(input, ["tool_name", "toolName", "name"]);
7390
+ return (0, import_tool_kit.getString)(input, ["tool_name", "toolName", "name"])?.replace(/^functions\./i, "");
7391
+ }
7392
+ function getCommand(input) {
7393
+ const direct = (0, import_tool_kit.getString)(input, ["command"]);
7394
+ if (direct !== void 0) return unwrapShell(direct);
7395
+ const toolInput = (0, import_tool_kit.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit.getNested)(input, ["input"]);
7396
+ if (!toolInput || typeof toolInput !== "object") return void 0;
7397
+ const raw = toolInput["command"] ?? toolInput["cmd"];
7398
+ if (typeof raw === "string") return unwrapShell(raw);
7399
+ if (Array.isArray(raw) && raw.every((word) => typeof word === "string")) {
7400
+ const argv = raw;
7401
+ const script = argv.length >= 3 && /^-[a-z]*c$/i.test(argv[1]) ? argv[argv.length - 1] : argv.join(" ");
7402
+ return unwrapShell(script);
7403
+ }
7404
+ return void 0;
7405
+ }
7406
+ function unwrapShell(command) {
7407
+ const wrapped = /^\s*(?:\S*\/)?(?:ba|z|da)?sh\s+-[a-z]*c\s+(["'])([\s\S]*)\1\s*$/i.exec(command);
7408
+ return wrapped ? wrapped[2] : command;
6231
7409
  }
6232
7410
  function sanitiseToolName(toolName) {
6233
7411
  if (!toolName) return "unknown";
@@ -6238,7 +7416,7 @@ function withHost(metadata) {
6238
7416
  }
6239
7417
 
6240
7418
  // src/liveSignal.ts
6241
- var import_tool_kit2 = __toESM(require_out2(), 1);
7419
+ var import_tool_kit2 = __toESM(require_out3(), 1);
6242
7420
  function liveSignalFor(hookName, input) {
6243
7421
  switch (hookName) {
6244
7422
  case "UserPromptSubmit": {
@@ -6255,6 +7433,11 @@ function liveSignalFor(hookName, input) {
6255
7433
  return { event: "stop" };
6256
7434
  case "PermissionRequest":
6257
7435
  return { event: "awaiting" };
7436
+ // Closing Codex mid-turn runs no `Stop`, so without this the session held
7437
+ // its level until it went stale. A `halted` never creates a session and is
7438
+ // ignored for one that already stopped.
7439
+ case "SessionEnd":
7440
+ return { event: "halted" };
6258
7441
  default:
6259
7442
  return void 0;
6260
7443
  }
@@ -6262,7 +7445,66 @@ function liveSignalFor(hookName, input) {
6262
7445
 
6263
7446
  // src/setup.ts
6264
7447
  import * as os from "os";
7448
+ import * as path2 from "path";
7449
+
7450
+ // src/hookTrust.ts
7451
+ import * as fs from "fs";
6265
7452
  import * as path from "path";
7453
+ var HEADER = /^\s*\[\s*hooks\s*\.\s*state\s*\.\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*\]/;
7454
+ function parseApprovalKeys(toml) {
7455
+ const keys = [];
7456
+ for (const line of toml.split(/\r?\n/)) {
7457
+ const match = HEADER.exec(line);
7458
+ if (!match) continue;
7459
+ const quoted = match[1];
7460
+ const key = quoted.startsWith("'") ? quoted.slice(1, -1) : unescapeBasicString(quoted.slice(1, -1));
7461
+ const parts = /^(.*):([^:]+):(\d+):(\d+)$/.exec(key);
7462
+ if (!parts) continue;
7463
+ keys.push({ file: parts[1], event: parts[2], group: Number(parts[3]), handler: Number(parts[4]) });
7464
+ }
7465
+ return keys;
7466
+ }
7467
+ function unescapeBasicString(value) {
7468
+ return value.replace(/\\(["\\])/g, "$1");
7469
+ }
7470
+ var eventId = (event) => event.toLowerCase().replace(/[^a-z]/g, "");
7471
+ var fileId = (file) => {
7472
+ const slashed = file.replace(/\\/g, "/");
7473
+ return process.platform === "win32" || /^[A-Za-z]:\//.test(slashed) ? slashed.toLowerCase() : slashed;
7474
+ };
7475
+ function checkCodexHookTrust(settingsFile, ours) {
7476
+ const approvalsFile = path.join(path.dirname(settingsFile), "config.toml");
7477
+ let toml = "";
7478
+ try {
7479
+ toml = fs.readFileSync(approvalsFile, "utf8");
7480
+ } catch (error) {
7481
+ if (error.code !== "ENOENT") return { approvalsFile, untrusted: [], stale: [], unreadable: true };
7482
+ }
7483
+ const here = fileId(path.resolve(settingsFile));
7484
+ const keys = parseApprovalKeys(toml).filter((key) => fileId(key.file) === here);
7485
+ const approved = (position) => keys.some((key) => eventId(key.event) === eventId(position.event) && key.group === position.group && key.handler === position.handler);
7486
+ const untrusted = ours.filter((position) => !approved(position));
7487
+ const ourEvents = new Set(ours.map((position) => eventId(position.event)));
7488
+ const stale = [];
7489
+ for (const key of keys) {
7490
+ if (!ourEvents.has(eventId(key.event))) continue;
7491
+ if (ours.some((position) => eventId(position.event) === eventId(key.event) && position.group === key.group && position.handler === key.handler)) continue;
7492
+ stale.push(`An approval for ${key.event} (group ${key.group}, handler ${key.handler}) points at a hook that has moved or gone.`);
7493
+ }
7494
+ if (untrusted.length === 0 && stale.length === 0 && changedAfterApproval(settingsFile, approvalsFile)) {
7495
+ stale.push("The hooks file was changed after the last approval was recorded, so a changed command may be waiting for re-approval.");
7496
+ }
7497
+ return { approvalsFile, untrusted, stale };
7498
+ }
7499
+ function changedAfterApproval(hooksFile, approvalsFile) {
7500
+ try {
7501
+ return fs.statSync(hooksFile).mtimeMs > fs.statSync(approvalsFile).mtimeMs;
7502
+ } catch {
7503
+ return false;
7504
+ }
7505
+ }
7506
+
7507
+ // src/setup.ts
6266
7508
  var HOOK_EVENTS = [
6267
7509
  "SessionStart",
6268
7510
  "UserPromptSubmit",
@@ -6271,9 +7513,17 @@ var HOOK_EVENTS = [
6271
7513
  "PreCompact",
6272
7514
  "PostCompact",
6273
7515
  "Stop",
6274
- "PermissionRequest"
7516
+ "PermissionRequest",
7517
+ // Codex 0.146 and later; an older Codex ignores an event it doesn't know.
7518
+ "SessionEnd"
6275
7519
  ];
6276
7520
  var HOOK_TIMEOUT_SECONDS = 10;
7521
+ function codexHome() {
7522
+ const configured = process.env.CODEX_HOME?.trim();
7523
+ return configured ? path2.resolve(configured) : path2.join(os.homedir(), ".codex");
7524
+ }
7525
+ var SESSION_END_TIMEOUT_SECONDS = 3;
7526
+ var hookTimeoutSeconds = (event) => event === "SessionEnd" ? SESSION_END_TIMEOUT_SECONDS : HOOK_TIMEOUT_SECONDS;
6277
7527
  var SETUP = {
6278
7528
  host: CODEX_HOST,
6279
7529
  displayName: "Codex CLI",
@@ -6282,25 +7532,30 @@ var SETUP = {
6282
7532
  binaryName: "ascenda-codex-hook",
6283
7533
  hookEvents: HOOK_EVENTS,
6284
7534
  restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not run them.",
6285
- // Codex reports the posture it was working under and its approval gate; it
6286
- // sends no model, no git action and no per-file change size.
6287
- sends: ["posture", "waiting"],
7535
+ // Codex reports the posture it was working under, its approval gate, and
7536
+ // the git action or milestone a shell command reached. It sends no model and
7537
+ // no per-file change size.
7538
+ sends: ["posture", "waiting", "git", "turns", "forge"],
7539
+ trust: {
7540
+ check: checkCodexHookTrust,
7541
+ fix: "Restart Codex and open /hooks, then approve the Ascenda hooks. A hook whose command changed needs approving again."
7542
+ },
6288
7543
  settings: {
6289
- settingsPath: (scope, projectDir) => scope === "user" ? path.join(os.homedir(), ".codex", "hooks.json") : path.join(projectDir, ".codex", "hooks.json"),
7544
+ settingsPath: (scope, projectDir) => scope === "user" ? path2.join(codexHome(), "hooks.json") : path2.join(projectDir, ".codex", "hooks.json"),
6290
7545
  // Codex nests as Gemini does — each event maps to an array of
6291
7546
  // { hooks: [{ type, command }] } — but reads the event from argv rather
6292
7547
  // than stdin, so unlike Gemini the name has to be on the command line.
6293
- entry: (command, event) => ({ hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }),
6294
- commandOf: (entry) => {
6295
- const group = entry;
6296
- const command = group?.hooks?.find((hook) => typeof hook?.command === "string")?.command;
6297
- return typeof command === "string" ? command : void 0;
6298
- }
7548
+ entry: (command, event) => ({ hooks: [{ type: "command", command: `${command} ${event}`, timeout: hookTimeoutSeconds(event) }] }),
7549
+ grouped: true
6299
7550
  }
6300
7551
  };
6301
7552
 
6302
7553
  // src/cli.ts
6303
7554
  async function main() {
7555
+ if (process.argv[2] === import_tool_kit3.OUTBOX_FLUSH_COMMAND) {
7556
+ await (0, import_tool_kit3.flushHookOutbox)({ toolType: ASCENDA_TOOL_TYPE, host: CODEX_HOST, source: "cli_agent" });
7557
+ return;
7558
+ }
6304
7559
  const command = process.argv[2];
6305
7560
  if ((0, import_tool_kit3.isCliAgentManagementCommand)(command)) {
6306
7561
  managementExitCode = await (0, import_tool_kit3.runCliAgentSetup)(process.argv.slice(2), SETUP);
@@ -6315,8 +7570,10 @@ async function main() {
6315
7570
  const sessionId = typeof input.session_id === "string" ? input.session_id : void 0;
6316
7571
  let turnDurationMs;
6317
7572
  (0, import_tool_kit3.stampLastHook)(CODEX_HOST, hookName);
6318
- if (hookName === "UserPromptSubmit") (0, import_tool_kit3.recordTurnStart)(CODEX_HOST, sessionId);
7573
+ const promptId = hookName === "UserPromptSubmit" ? (0, import_tool_kit3.recordTurnStart)(CODEX_HOST, sessionId) : (0, import_tool_kit3.readTurnPromptId)(CODEX_HOST, sessionId);
6319
7574
  if (hookName === "Stop") turnDurationMs = (0, import_tool_kit3.consumeTurnDurationMs)(CODEX_HOST, sessionId);
7575
+ const workDir = typeof input.cwd === "string" ? input.cwd : void 0;
7576
+ if (hookName === "SessionEnd") process.env.ASCENDA_HTTP_TIMEOUT_MS ??= "1500";
6320
7577
  await emitLive(hookName, input, sessionId);
6321
7578
  await (0, import_tool_kit3.deliverHookEvents)(mapCodexEvent(hookName, input, turnDurationMs), {
6322
7579
  toolType: ASCENDA_TOOL_TYPE,
@@ -6324,6 +7581,9 @@ async function main() {
6324
7581
  setupCommand: `npx ${SETUP.packageName} setup`,
6325
7582
  source: "cli_agent",
6326
7583
  sessionId,
7584
+ promptId,
7585
+ cwd: workDir,
7586
+ forgeKeys: true,
6327
7587
  onNotice: emitSystemMessage
6328
7588
  });
6329
7589
  }