@ascenda-one/agent-mcp 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.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/dist/cli.js +1868 -732
  4. package/package.json +3 -2
package/dist/cli.js CHANGED
@@ -153,25 +153,66 @@ var require_gitActionClassifier = __commonJS({
153
153
  if (!/\bgit\b/.test(value))
154
154
  return void 0;
155
155
  const heads = (0, commandHeads_1.commandHeads)(value);
156
- if (heads.some((h) => /^git\s+commit\b/.test(h) && /\s--amend\b/.test(h)))
156
+ const commands = heads.map(parseGitCommand).filter((c) => c !== void 0);
157
+ if (commands.some((c) => c.verb === "commit" && c.args.includes("--amend")))
157
158
  return "amend";
158
- if (heads.some((h) => /^git\s+revert\b/.test(h)))
159
+ if (commands.some((c) => c.verb === "revert"))
159
160
  return "revert";
160
- if (heads.some((h) => /^git\s+reset\b/.test(h) && /\s--hard\b/.test(h)))
161
+ if (commands.some((c) => c.verb === "reset" && c.args.includes("--hard")))
161
162
  return "reset_hard";
162
- if (heads.some((h) => /^git\s+restore\b/.test(h) && !/\s--staged\b/.test(h)))
163
+ if (commands.some(discardsWork))
163
164
  return "restore";
164
- if (heads.some((h) => /^git\s+checkout\b.*\s--\s/.test(h)))
165
- return "restore";
166
- if (heads.some((h) => /^git\s+push\b/.test(h)))
165
+ if (commands.some((c) => c.verb === "push"))
167
166
  return "push";
168
- if (heads.some((h) => /^git\s+commit\b/.test(h)))
167
+ if (commands.some((c) => c.verb === "commit"))
169
168
  return "commit";
170
169
  return void 0;
171
170
  }
172
171
  function isReworkGitAction(action) {
173
172
  return action === "revert" || action === "reset_hard" || action === "restore";
174
173
  }
174
+ var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path"]);
175
+ function parseGitCommand(head) {
176
+ const words = head.split(/\s+/);
177
+ if (words[0] !== "git")
178
+ return void 0;
179
+ let i = 1;
180
+ while (i < words.length && words[i].startsWith("-")) {
181
+ i += GLOBAL_OPTIONS_WITH_VALUE.has(words[i]) ? 2 : 1;
182
+ }
183
+ if (i >= words.length)
184
+ return void 0;
185
+ return { verb: words[i], args: words.slice(i + 1) };
186
+ }
187
+ function discardsWork({ verb, args }) {
188
+ switch (verb) {
189
+ case "restore":
190
+ return !args.includes("--staged");
191
+ case "switch":
192
+ return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
193
+ case "clean": {
194
+ const flags = args.filter((a) => /^-[a-z]+$/.test(a)).join("");
195
+ const dryRun = args.includes("--dry-run") || flags.includes("n");
196
+ return !dryRun && (args.includes("--force") || flags.includes("f"));
197
+ }
198
+ case "checkout":
199
+ return checkoutDiscards(args);
200
+ default:
201
+ return false;
202
+ }
203
+ }
204
+ function checkoutDiscards(args) {
205
+ if (args.includes("--"))
206
+ return true;
207
+ if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
208
+ return false;
209
+ const words = args.filter((a) => !a.startsWith("-"));
210
+ if (words.length >= 2)
211
+ return true;
212
+ if (words.length === 1)
213
+ return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
214
+ return false;
215
+ }
175
216
  }
176
217
  });
177
218
 
@@ -182,6 +223,7 @@ var require_workMilestoneClassifier = __commonJS({
182
223
  Object.defineProperty(exports, "__esModule", { value: true });
183
224
  exports.classifyWorkMilestone = classifyWorkMilestone;
184
225
  exports.invitesDebrief = invitesDebrief;
226
+ exports.classifyMcpWorkMilestone = classifyMcpWorkMilestone;
185
227
  var commandHeads_1 = require_commandHeads();
186
228
  function classifyWorkMilestone(command) {
187
229
  if (!command)
@@ -201,6 +243,41 @@ var require_workMilestoneClassifier = __commonJS({
201
243
  function invitesDebrief(kind) {
202
244
  return kind === "pr_merged" || kind === "issue_closed";
203
245
  }
246
+ function classifyMcpWorkMilestone(toolName) {
247
+ if (!toolName)
248
+ return void 0;
249
+ const parts = toolName.toLowerCase().split("__");
250
+ if (parts[0] !== "mcp" || parts.length < 3)
251
+ return void 0;
252
+ const tool = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
253
+ if (/^(merge|accept)(pullrequest|mergerequest)$/.test(tool))
254
+ return "pr_merged";
255
+ if (/^closeissue$/.test(tool))
256
+ return "issue_closed";
257
+ if (/^(create|open)(pullrequest|mergerequest)$/.test(tool))
258
+ return "pr_opened";
259
+ return void 0;
260
+ }
261
+ }
262
+ });
263
+
264
+ // ../packages/tool-kit/out/shellFacts.js
265
+ var require_shellFacts = __commonJS({
266
+ "../packages/tool-kit/out/shellFacts.js"(exports) {
267
+ "use strict";
268
+ Object.defineProperty(exports, "__esModule", { value: true });
269
+ exports.shellCommandFacts = shellCommandFacts;
270
+ var gitActionClassifier_1 = require_gitActionClassifier();
271
+ var workMilestoneClassifier_1 = require_workMilestoneClassifier();
272
+ function shellCommandFacts(command) {
273
+ const gitAction = (0, gitActionClassifier_1.classifyGitAction)(command);
274
+ const milestoneKind = (0, workMilestoneClassifier_1.classifyWorkMilestone)(command);
275
+ return {
276
+ ...gitAction !== void 0 ? { gitAction } : {},
277
+ ...(0, gitActionClassifier_1.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
278
+ ...milestoneKind !== void 0 ? { milestoneKind } : {}
279
+ };
280
+ }
204
281
  }
205
282
  });
206
283
 
@@ -594,6 +671,61 @@ var require_metricKeys = __commonJS({
594
671
  subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
595
672
  subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
596
673
  subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
674
+ advisorMessageCount: {
675
+ family: "counts",
676
+ readBy: ["diagnostic"],
677
+ 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."
678
+ },
679
+ advisorTokensTotal: {
680
+ family: "context",
681
+ readBy: ["diagnostic"],
682
+ unit: "tokens",
683
+ note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
684
+ },
685
+ cacheCreationTokens: {
686
+ family: "context",
687
+ readBy: ["diagnostic"],
688
+ unit: "tokens",
689
+ 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."
690
+ },
691
+ cacheCreation5mTokens: {
692
+ family: "context",
693
+ readBy: ["diagnostic"],
694
+ unit: "tokens",
695
+ note: "The part of cacheCreationTokens written with the 5-minute lifetime. Absent on transcripts that only record the total."
696
+ },
697
+ cacheCreation1hTokens: {
698
+ family: "context",
699
+ readBy: ["diagnostic"],
700
+ unit: "tokens",
701
+ note: "The part of cacheCreationTokens written with the 1-hour lifetime. Absent on transcripts that only record the total."
702
+ },
703
+ headlessPromptLines: {
704
+ family: "reading",
705
+ readBy: ["diagnostic"],
706
+ unit: "lines",
707
+ 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."
708
+ },
709
+ tokensNotCollected: {
710
+ family: "context",
711
+ readBy: ["diagnostic"],
712
+ 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."
713
+ },
714
+ unattributedSubagentTranscripts: {
715
+ family: "reading",
716
+ readBy: ["diagnostic"],
717
+ note: "Claude Code only: flat subagent transcripts whose lines name no parent session, so they could not be folded anywhere."
718
+ },
719
+ duplicateChatSessions: {
720
+ family: "reading",
721
+ readBy: ["diagnostic"],
722
+ note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
723
+ },
724
+ sessionsStartedFromBubble: {
725
+ family: "reading",
726
+ readBy: ["diagnostic"],
727
+ note: "Cursor only: sessions whose start is the earliest message rather than the header's createdAt, which can sit months before anyone typed."
728
+ },
597
729
  toolName: {
598
730
  family: "tools",
599
731
  readBy: ["backend"],
@@ -633,9 +765,11 @@ var require_out = __commonJS({
633
765
  "../packages/tool-contract/out/index.js"(exports) {
634
766
  "use strict";
635
767
  Object.defineProperty(exports, "__esModule", { value: true });
636
- 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;
768
+ 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;
637
769
  exports.combineDisjointHalves = combineDisjointHalves;
638
770
  exports.requireComparableQuantities = requireComparableQuantities;
771
+ exports.joinEventPayload = joinEventPayload;
772
+ exports.splitEventPayload = splitEventPayload;
639
773
  exports.ASCENDA_TELEMETRY_SOURCES = [
640
774
  "vscode_extension",
641
775
  "cursor_mcp",
@@ -699,7 +833,9 @@ var require_out = __commonJS({
699
833
  exports.COLLABORATION_EVENT_TYPES = [
700
834
  "review_requested_of_me",
701
835
  "review_given",
702
- "pull_request_opened"
836
+ "pull_request_opened",
837
+ "pull_request_closed",
838
+ "pull_request_merged"
703
839
  ];
704
840
  exports.EVENT_METADATA_DISCLOSURE = {
705
841
  language: "edits",
@@ -711,6 +847,13 @@ var require_out = __commonJS({
711
847
  gitAction: "git",
712
848
  milestoneKind: "git",
713
849
  branchHash: "repo",
850
+ repoKey: "forge",
851
+ headRepoKey: "forge",
852
+ prCreatedAt: "git",
853
+ prClosedAt: "git",
854
+ prMergedAt: "git",
855
+ branchKey: "forge",
856
+ promptId: "turns",
714
857
  autonomyMode: "posture",
715
858
  modelClass: "model",
716
859
  modelId: "model",
@@ -760,6 +903,13 @@ var require_out = __commonJS({
760
903
  "gitAction",
761
904
  "milestoneKind",
762
905
  "branchHash",
906
+ "repoKey",
907
+ "headRepoKey",
908
+ "prCreatedAt",
909
+ "prClosedAt",
910
+ "prMergedAt",
911
+ "branchKey",
912
+ "promptId",
763
913
  "autonomyMode",
764
914
  "modelClass",
765
915
  "modelId",
@@ -787,6 +937,24 @@ var require_out = __commonJS({
787
937
  "importSchema",
788
938
  "collectorVersion"
789
939
  ];
940
+ exports.DELIVERY_ENVELOPE_KEYS = ["toolInstallationId", "idempotencyKey"];
941
+ function joinEventPayload(envelope, body) {
942
+ const payload = { toolInstallationId: envelope.toolInstallationId };
943
+ for (const [key, value] of Object.entries(body)) {
944
+ payload[key] = value;
945
+ if (key === "occurredAt" && envelope.idempotencyKey !== void 0) {
946
+ payload.idempotencyKey = envelope.idempotencyKey;
947
+ }
948
+ }
949
+ return payload;
950
+ }
951
+ function splitEventPayload(payload) {
952
+ const { toolInstallationId, idempotencyKey, ...body } = payload;
953
+ const envelope = { toolInstallationId };
954
+ if (idempotencyKey !== void 0)
955
+ envelope.idempotencyKey = idempotencyKey;
956
+ return { envelope, body };
957
+ }
790
958
  exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
791
959
  exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
792
960
  exports.EVENT_WORKLOAD_CATEGORY = {
@@ -811,6 +979,10 @@ var require_out = __commonJS({
811
979
  review_requested_of_me: "supervision",
812
980
  review_given: "supervision",
813
981
  pull_request_opened: "creation",
982
+ // Where a pull request of yours ended up. A boundary like a turn ending, not
983
+ // work in itself, so neutral: it must not weigh on any workload leg.
984
+ pull_request_closed: "neutral",
985
+ pull_request_merged: "neutral",
814
986
  context_pressure_high: "risk",
815
987
  agent_loop_long: "risk",
816
988
  after_hours_ai_session: "risk",
@@ -841,6 +1013,16 @@ var require_out = __commonJS({
841
1013
  // step toward an interruption count becoming a score, a streak, or something
842
1014
  // that fires on a miss. It must never become any of those.
843
1015
  supervision_interruption: "supervision",
1016
+ // The agent asked to run a tool, and the auto-mode classifier refused one.
1017
+ // Claude Code's `PermissionRequest` and `PermissionDenied` hooks. Neutral,
1018
+ // because the Notification for the same prompt is already counted above as
1019
+ // `supervision_interruption`, and counting both would weigh one prompt
1020
+ // twice. These rows exist for the public event stream: which tool asked, and
1021
+ // under which posture. `permission_requested` fires before the person
1022
+ // answers and no hook reports their answer, so neither event says whether
1023
+ // the request was granted.
1024
+ permission_requested: "neutral",
1025
+ permission_denied: "neutral",
844
1026
  // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
845
1027
  approach_churn_detected: "risk",
846
1028
  goal_drift_detected: "risk",
@@ -965,16 +1147,16 @@ var require_collectorVersion = __commonJS({
965
1147
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
966
1148
  exports.describeCollectorVersion = describeCollectorVersion;
967
1149
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
968
- exports.COLLECTOR_VERSION = "0.1.34" ? "0.1.34" : exports.UNRELEASED_COLLECTOR_VERSION;
1150
+ exports.COLLECTOR_VERSION = "0.1.36" ? "0.1.36" : exports.UNRELEASED_COLLECTOR_VERSION;
969
1151
  function describeCollectorVersion(version2 = exports.COLLECTOR_VERSION) {
970
1152
  return version2 === exports.UNRELEASED_COLLECTOR_VERSION ? `${version2} (built from a checkout, not a release)` : version2;
971
1153
  }
972
1154
  }
973
1155
  });
974
1156
 
975
- // ../packages/tool-kit/out/eventLog.js
976
- var require_eventLog = __commonJS({
977
- "../packages/tool-kit/out/eventLog.js"(exports) {
1157
+ // ../packages/tool-kit/out/tokenStore.js
1158
+ var require_tokenStore = __commonJS({
1159
+ "../packages/tool-kit/out/tokenStore.js"(exports) {
978
1160
  "use strict";
979
1161
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
980
1162
  if (k2 === void 0) k2 = k;
@@ -1014,407 +1196,68 @@ var require_eventLog = __commonJS({
1014
1196
  };
1015
1197
  }();
1016
1198
  Object.defineProperty(exports, "__esModule", { value: true });
1017
- exports.EVENT_LOG_ENV_VAR = void 0;
1018
- exports.expandUserPath = expandUserPath;
1019
- exports.resolveEventLogPath = resolveEventLogPath;
1020
- exports.appendEventLog = appendEventLog;
1199
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1200
+ exports.ascendaHome = ascendaHome;
1201
+ exports.defaultTokenFilePath = defaultTokenFilePath2;
1202
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1203
+ exports.persistEventWriteToken = persistEventWriteToken2;
1204
+ exports.readTokenExpiry = readTokenExpiry;
1205
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1206
+ exports.readTokenFile = readTokenFile2;
1207
+ exports.sanitizeFilePart = sanitizeFilePart;
1021
1208
  var fs = __importStar(__require("fs"));
1022
1209
  var os = __importStar(__require("os"));
1023
1210
  var path = __importStar(__require("path"));
1024
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1025
- var MAX_BYTES = 5 * 1024 * 1024;
1026
- function expandUserPath(configured) {
1027
- const value = configured?.trim();
1028
- if (!value)
1029
- return void 0;
1030
- if (value === "~")
1031
- return os.homedir();
1032
- if (value.startsWith("~/"))
1033
- return path.join(os.homedir(), value.slice(2));
1034
- return path.resolve(value);
1211
+ function ascendaHome(home = os.homedir()) {
1212
+ return process.env.ASCENDA_HOME ?? path.join(home, ".ascenda");
1035
1213
  }
1036
- function resolveEventLogPath() {
1037
- return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
1214
+ function defaultTokenFilePath2(toolInstallationId) {
1215
+ return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1038
1216
  }
1039
- function appendEventLog(logFilePath, entry) {
1040
- try {
1041
- rotateIfLarge(logFilePath);
1042
- const dir = path.dirname(logFilePath);
1043
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1044
- fs.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1045
- `, { encoding: "utf8", mode: 384 });
1046
- if (process.platform !== "win32")
1047
- fs.chmodSync(logFilePath, 384);
1048
- } catch {
1049
- }
1217
+ function tokenExpiryFilePath(tokenFilePath) {
1218
+ return path.join(path.dirname(tokenFilePath), "expiry", path.basename(tokenFilePath));
1050
1219
  }
1051
- function rotateIfLarge(logFilePath) {
1220
+ function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
1221
+ const dir = path.dirname(tokenFilePath);
1222
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
1223
+ fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1224
+ if (process.platform !== "win32") {
1225
+ fs.chmodSync(dir, 448);
1226
+ fs.chmodSync(tokenFilePath, 384);
1227
+ }
1228
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1052
1229
  try {
1053
- if (fs.statSync(logFilePath).size < MAX_BYTES)
1054
- return;
1055
- fs.renameSync(logFilePath, `${logFilePath}.1`);
1230
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1231
+ fs.mkdirSync(path.dirname(expiryFile), { recursive: true, mode: 448 });
1232
+ fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1233
+ } else {
1234
+ fs.rmSync(expiryFile, { force: true });
1235
+ }
1056
1236
  } catch {
1057
1237
  }
1058
1238
  }
1059
- }
1060
- });
1061
-
1062
- // ../packages/tool-kit/out/http.js
1063
- var require_http = __commonJS({
1064
- "../packages/tool-kit/out/http.js"(exports) {
1065
- "use strict";
1066
- Object.defineProperty(exports, "__esModule", { value: true });
1067
- exports.AscendaApiError = void 0;
1068
- exports.createPairingSession = createPairingSession;
1069
- exports.getPairingStatus = getPairingStatus;
1070
- exports.startStudyJoin = startStudyJoin;
1071
- exports.getStudyJoinStatus = getStudyJoinStatus;
1072
- exports.readInitiatives = readInitiatives;
1073
- exports.readStudyNotices = readStudyNotices;
1074
- exports.setStudyObjection = setStudyObjection;
1075
- exports.markStudyNoticeShown = markStudyNoticeShown;
1076
- exports.renewToolToken = renewToolToken;
1077
- exports.isRetryableStatus = isRetryableStatus;
1078
- exports.postToolEvent = postToolEvent;
1079
- exports.postToolEventsBatch = postToolEventsBatch;
1080
- exports.parseIngestResponse = parseIngestResponse;
1081
- var tool_contract_1 = require_out();
1082
- var AscendaApiError = class extends Error {
1083
- status;
1084
- errorCode;
1085
- constructor(status, errorCode, body) {
1086
- super(body ?? `Ascenda API error ${status}`);
1087
- this.status = status;
1088
- this.errorCode = errorCode;
1089
- this.name = "AscendaApiError";
1090
- }
1091
- };
1092
- exports.AscendaApiError = AscendaApiError;
1093
- async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
1094
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1095
- method: "POST",
1096
- headers: { "Content-Type": "application/json" },
1097
- body: JSON.stringify({ toolInstallationId, toolType, displayName })
1098
- });
1099
- if (!response.ok)
1100
- throw new AscendaApiError(response.status, void 0, await response.text());
1101
- return await response.json();
1102
- }
1103
- async function getPairingStatus(apiBaseUrl, pairingSessionId) {
1104
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1105
- method: "GET",
1106
- headers: { Accept: "application/json" }
1107
- });
1108
- if (!response.ok)
1109
- throw new AscendaApiError(response.status, void 0, await response.text());
1110
- return await response.json();
1111
- }
1112
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1113
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1114
- method: "POST",
1115
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1116
- body: JSON.stringify({ joinCode, mode })
1117
- });
1118
- if (!response.ok)
1119
- throw await apiError(response);
1120
- return await response.json();
1121
- }
1122
- async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1123
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1124
- method: "GET",
1125
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1126
- });
1127
- if (!response.ok)
1128
- throw await apiError(response);
1129
- return await response.json();
1130
- }
1131
- async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1132
- let response;
1239
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1240
+ function readTokenExpiry(tokenFilePath) {
1133
1241
  try {
1134
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1135
- method: "GET",
1136
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1137
- signal
1138
- });
1139
- } catch (error2) {
1140
- return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1242
+ const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1243
+ if (Number.isFinite(recorded))
1244
+ return recorded;
1245
+ } catch {
1141
1246
  }
1142
- if (response.status === 401)
1143
- return { kind: "rejected", httpStatus: 401 };
1144
- if (!response.ok)
1145
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1146
- let body;
1147
1247
  try {
1148
- body = await response.json();
1248
+ return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1149
1249
  } catch {
1150
- return { kind: "failed", reason: "the reply was not readable" };
1250
+ return void 0;
1151
1251
  }
1152
- if (!Array.isArray(body))
1153
- return { kind: "failed", reason: "the reply was not a list" };
1154
- return { kind: "ok", initiatives: body };
1155
1252
  }
1156
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1157
- let response;
1253
+ function listPersistedToolInstallationIds(toolType) {
1254
+ const prefix = `${sanitizeFilePart(toolType)}_`;
1255
+ const dir = path.join(ascendaHome(), "tokens");
1256
+ let names;
1158
1257
  try {
1159
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1160
- method: "GET",
1161
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1162
- signal
1163
- });
1164
- } catch (error2) {
1165
- return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1166
- }
1167
- if (response.status === 404)
1168
- return { kind: "absent" };
1169
- if (response.status === 401)
1170
- return { kind: "rejected", httpStatus: 401 };
1171
- if (!response.ok)
1172
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1173
- let body;
1174
- try {
1175
- body = await response.json();
1176
- } catch {
1177
- return { kind: "absent" };
1178
- }
1179
- if (!Array.isArray(body))
1180
- return { kind: "absent" };
1181
- return { kind: "ok", notices: body };
1182
- }
1183
- async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1184
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1185
- method: objected ? "POST" : "DELETE",
1186
- headers: { Authorization: `Bearer ${eventWriteToken}` }
1187
- });
1188
- if (!response.ok)
1189
- throw await apiError(response);
1190
- }
1191
- async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1192
- try {
1193
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1194
- method: "POST",
1195
- headers: { Authorization: `Bearer ${eventWriteToken}` },
1196
- signal
1197
- });
1198
- return response.ok;
1199
- } catch {
1200
- return false;
1201
- }
1202
- }
1203
- async function apiError(response) {
1204
- const body = await response.text();
1205
- let errorCode;
1206
- try {
1207
- const parsed = JSON.parse(body);
1208
- errorCode = parsed.code ?? parsed.error;
1209
- } catch {
1210
- errorCode = void 0;
1211
- }
1212
- return new AscendaApiError(response.status, errorCode, body);
1213
- }
1214
- async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1215
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1216
- method: "POST",
1217
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1218
- signal
1219
- });
1220
- if (response.status === 401)
1221
- return null;
1222
- if (!response.ok)
1223
- throw new AscendaApiError(response.status, void 0, await response.text());
1224
- return await response.json();
1225
- }
1226
- function isDeliveredStatus(value) {
1227
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1228
- }
1229
- function readSuccessBody(body) {
1230
- let parsed;
1231
- try {
1232
- parsed = JSON.parse(body);
1233
- } catch {
1234
- return { duplicates: 0 };
1235
- }
1236
- if (!parsed || typeof parsed !== "object")
1237
- return { duplicates: 0 };
1238
- const single = parsed.status;
1239
- if (isDeliveredStatus(single))
1240
- return { duplicates: single === "duplicate" ? 1 : 0 };
1241
- const raw = parsed.results;
1242
- if (!Array.isArray(raw))
1243
- return { duplicates: 0 };
1244
- const results = [];
1245
- for (const item of raw) {
1246
- if (!item || typeof item !== "object")
1247
- continue;
1248
- const { index, status, reason } = item;
1249
- if (typeof index !== "number" || typeof status !== "string")
1250
- continue;
1251
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1252
- }
1253
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1254
- }
1255
- function isRetryableStatus(status) {
1256
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1257
- }
1258
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1259
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1260
- }
1261
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1262
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1263
- }
1264
- async function sendIngest(url, eventWriteToken, body, signal) {
1265
- try {
1266
- const response = await fetch(url, {
1267
- method: "POST",
1268
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1269
- body,
1270
- signal
1271
- });
1272
- return parseIngestResponse(response);
1273
- } catch (error2) {
1274
- return {
1275
- result: "transport_error",
1276
- detail: error2 instanceof Error ? `${error2.name}: ${error2.message}` : String(error2)
1277
- };
1278
- }
1279
- }
1280
- async function parseIngestResponse(response) {
1281
- if (response.ok) {
1282
- const outcome = { result: "accepted", httpStatus: response.status };
1283
- let read = { duplicates: 0 };
1284
- try {
1285
- read = readSuccessBody(await response.text());
1286
- } catch {
1287
- read = { duplicates: 0 };
1288
- }
1289
- return {
1290
- ...outcome,
1291
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1292
- ...read.results !== void 0 ? { results: read.results } : {}
1293
- };
1294
- }
1295
- const body = await response.text();
1296
- let errorCode;
1297
- try {
1298
- errorCode = JSON.parse(body).error;
1299
- } catch {
1300
- errorCode = void 0;
1301
- }
1302
- const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1303
- if (response.status === 401)
1304
- return { ...base, result: "auth_failed" };
1305
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1306
- return { ...base, result: "consent_missing" };
1307
- if (response.status === 400 || response.status === 422)
1308
- return { ...base, result: "validation_failed" };
1309
- return { ...base, result: "transport_error" };
1310
- }
1311
- }
1312
- });
1313
-
1314
- // ../packages/tool-kit/out/tokenStore.js
1315
- var require_tokenStore = __commonJS({
1316
- "../packages/tool-kit/out/tokenStore.js"(exports) {
1317
- "use strict";
1318
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1319
- if (k2 === void 0) k2 = k;
1320
- var desc = Object.getOwnPropertyDescriptor(m, k);
1321
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1322
- desc = { enumerable: true, get: function() {
1323
- return m[k];
1324
- } };
1325
- }
1326
- Object.defineProperty(o, k2, desc);
1327
- } : function(o, m, k, k2) {
1328
- if (k2 === void 0) k2 = k;
1329
- o[k2] = m[k];
1330
- });
1331
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1332
- Object.defineProperty(o, "default", { enumerable: true, value: v });
1333
- } : function(o, v) {
1334
- o["default"] = v;
1335
- });
1336
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1337
- var ownKeys = function(o) {
1338
- ownKeys = Object.getOwnPropertyNames || function(o2) {
1339
- var ar = [];
1340
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1341
- return ar;
1342
- };
1343
- return ownKeys(o);
1344
- };
1345
- return function(mod) {
1346
- if (mod && mod.__esModule) return mod;
1347
- var result = {};
1348
- if (mod != null) {
1349
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1350
- }
1351
- __setModuleDefault(result, mod);
1352
- return result;
1353
- };
1354
- }();
1355
- Object.defineProperty(exports, "__esModule", { value: true });
1356
- exports.EVENT_TOKEN_TTL_MS = void 0;
1357
- exports.ascendaHome = ascendaHome;
1358
- exports.defaultTokenFilePath = defaultTokenFilePath2;
1359
- exports.tokenExpiryFilePath = tokenExpiryFilePath;
1360
- exports.persistEventWriteToken = persistEventWriteToken2;
1361
- exports.readTokenExpiry = readTokenExpiry;
1362
- exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1363
- exports.readTokenFile = readTokenFile2;
1364
- exports.sanitizeFilePart = sanitizeFilePart;
1365
- var fs = __importStar(__require("fs"));
1366
- var os = __importStar(__require("os"));
1367
- var path = __importStar(__require("path"));
1368
- function ascendaHome(home = os.homedir()) {
1369
- return process.env.ASCENDA_HOME ?? path.join(home, ".ascenda");
1370
- }
1371
- function defaultTokenFilePath2(toolInstallationId) {
1372
- return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1373
- }
1374
- function tokenExpiryFilePath(tokenFilePath) {
1375
- return path.join(path.dirname(tokenFilePath), "expiry", path.basename(tokenFilePath));
1376
- }
1377
- function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
1378
- const dir = path.dirname(tokenFilePath);
1379
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1380
- fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1381
- if (process.platform !== "win32") {
1382
- fs.chmodSync(dir, 448);
1383
- fs.chmodSync(tokenFilePath, 384);
1384
- }
1385
- const expiryFile = tokenExpiryFilePath(tokenFilePath);
1386
- try {
1387
- if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1388
- fs.mkdirSync(path.dirname(expiryFile), { recursive: true, mode: 448 });
1389
- fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1390
- } else {
1391
- fs.rmSync(expiryFile, { force: true });
1392
- }
1393
- } catch {
1394
- }
1395
- }
1396
- exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1397
- function readTokenExpiry(tokenFilePath) {
1398
- try {
1399
- const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1400
- if (Number.isFinite(recorded))
1401
- return recorded;
1402
- } catch {
1403
- }
1404
- try {
1405
- return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1406
- } catch {
1407
- return void 0;
1408
- }
1409
- }
1410
- function listPersistedToolInstallationIds(toolType) {
1411
- const prefix = `${sanitizeFilePart(toolType)}_`;
1412
- const dir = path.join(ascendaHome(), "tokens");
1413
- let names;
1414
- try {
1415
- names = fs.readdirSync(dir);
1416
- } catch {
1417
- return [];
1258
+ names = fs.readdirSync(dir);
1259
+ } catch {
1260
+ return [];
1418
1261
  }
1419
1262
  const ids = [];
1420
1263
  for (const name of names.sort()) {
@@ -1780,50 +1623,875 @@ var require_outbox = __commonJS({
1780
1623
  fresh.push(entry);
1781
1624
  }
1782
1625
  }
1783
- const excess = Math.max(0, fresh.length - bounds.maxEntries);
1784
- if (excess > 0) {
1785
- reasons.count = excess;
1786
- const first = fresh[0]?.queuedAt;
1787
- if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1788
- oldestQueuedAt = first;
1626
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1627
+ if (excess > 0) {
1628
+ reasons.count = excess;
1629
+ const first = fresh[0]?.queuedAt;
1630
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1631
+ oldestQueuedAt = first;
1632
+ }
1633
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1634
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1635
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1636
+ }
1637
+ function listClaimFiles(outboxFilePath) {
1638
+ const dir = path.dirname(outboxFilePath);
1639
+ const prefix = `${path.basename(outboxFilePath)}.`;
1640
+ try {
1641
+ return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
1642
+ } catch {
1643
+ return [];
1644
+ }
1645
+ }
1646
+ function readEntries(file) {
1647
+ let raw;
1648
+ try {
1649
+ raw = fs.readFileSync(file, "utf8");
1650
+ } catch {
1651
+ return { entries: [], unreadable: 0 };
1652
+ }
1653
+ const entries = [];
1654
+ let unreadable = 0;
1655
+ for (const line of raw.split("\n")) {
1656
+ if (!line.trim())
1657
+ continue;
1658
+ try {
1659
+ const parsed = JSON.parse(line);
1660
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1661
+ unreadable += 1;
1662
+ continue;
1663
+ }
1664
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1665
+ } catch {
1666
+ unreadable += 1;
1667
+ }
1668
+ }
1669
+ return { entries, unreadable };
1670
+ }
1671
+ }
1672
+ });
1673
+
1674
+ // ../packages/tool-kit/out/backgroundDelivery.js
1675
+ var require_backgroundDelivery = __commonJS({
1676
+ "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
1677
+ "use strict";
1678
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1679
+ if (k2 === void 0) k2 = k;
1680
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1681
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1682
+ desc = { enumerable: true, get: function() {
1683
+ return m[k];
1684
+ } };
1685
+ }
1686
+ Object.defineProperty(o, k2, desc);
1687
+ } : function(o, m, k, k2) {
1688
+ if (k2 === void 0) k2 = k;
1689
+ o[k2] = m[k];
1690
+ });
1691
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1692
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1693
+ } : function(o, v) {
1694
+ o["default"] = v;
1695
+ });
1696
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1697
+ var ownKeys = function(o) {
1698
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1699
+ var ar = [];
1700
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1701
+ return ar;
1702
+ };
1703
+ return ownKeys(o);
1704
+ };
1705
+ return function(mod) {
1706
+ if (mod && mod.__esModule) return mod;
1707
+ var result = {};
1708
+ if (mod != null) {
1709
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1710
+ }
1711
+ __setModuleDefault(result, mod);
1712
+ return result;
1713
+ };
1714
+ }();
1715
+ Object.defineProperty(exports, "__esModule", { value: true });
1716
+ exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
1717
+ exports.hookDeliveryInline = hookDeliveryInline;
1718
+ exports.flushLockPath = flushLockPath;
1719
+ exports.startBackgroundFlush = startBackgroundFlush;
1720
+ exports.runOutboxFlush = runOutboxFlush;
1721
+ var fs = __importStar(__require("fs"));
1722
+ var child_process_1 = __require("child_process");
1723
+ var outbox_1 = require_outbox();
1724
+ exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
1725
+ exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
1726
+ exports.FLUSH_LOCK_FRESH_MS = 2e4;
1727
+ var FLUSH_MAX_PASSES = 20;
1728
+ var FLUSH_MAX_RUN_MS = 6e4;
1729
+ function hookDeliveryInline(env = process.env) {
1730
+ return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
1731
+ }
1732
+ function flushLockPath(outboxFilePath) {
1733
+ return `${outboxFilePath}.flushing`;
1734
+ }
1735
+ function lockIsFresh(lockPath, now) {
1736
+ try {
1737
+ return now - fs.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1738
+ } catch {
1739
+ return false;
1740
+ }
1741
+ }
1742
+ function touchLock(lockPath) {
1743
+ try {
1744
+ fs.writeFileSync(lockPath, `${process.pid}
1745
+ `, { encoding: "utf8", mode: 384 });
1746
+ } catch {
1747
+ }
1748
+ }
1749
+ function removeLock(lockPath) {
1750
+ try {
1751
+ fs.unlinkSync(lockPath);
1752
+ } catch {
1753
+ }
1754
+ }
1755
+ function outboxHasEntries(outboxFilePath) {
1756
+ try {
1757
+ return fs.statSync(outboxFilePath).size > 0;
1758
+ } catch {
1759
+ return false;
1760
+ }
1761
+ }
1762
+ function startBackgroundFlush(options) {
1763
+ const lockPath = flushLockPath(options.outboxFilePath);
1764
+ const now = options.now ?? Date.now();
1765
+ if (lockIsFresh(lockPath, now))
1766
+ return false;
1767
+ const script = options.script ?? process.argv[1];
1768
+ if (!script)
1769
+ return false;
1770
+ try {
1771
+ touchLock(lockPath);
1772
+ const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
1773
+ detached: true,
1774
+ stdio: "ignore",
1775
+ windowsHide: true,
1776
+ env: process.env
1777
+ });
1778
+ child.on("error", () => removeLock(lockPath));
1779
+ child.unref();
1780
+ return true;
1781
+ } catch {
1782
+ removeLock(lockPath);
1783
+ return false;
1784
+ }
1785
+ }
1786
+ async function runOutboxFlush(sender, now = Date.now) {
1787
+ const outboxFilePath = sender.outboxFilePath();
1788
+ const lockPath = flushLockPath(outboxFilePath);
1789
+ const started = now();
1790
+ let last;
1791
+ let passes = 0;
1792
+ const drain = async () => {
1793
+ while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
1794
+ passes += 1;
1795
+ touchLock(lockPath);
1796
+ last = await sender.flushOutbox();
1797
+ if (!last || last.found === 0 || last.halted || !last.sendEnabled)
1798
+ return;
1799
+ if (last.delivered === 0 && last.discarded === 0)
1800
+ return;
1801
+ }
1802
+ };
1803
+ try {
1804
+ await drain();
1805
+ removeLock(lockPath);
1806
+ if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
1807
+ touchLock(lockPath);
1808
+ await drain();
1809
+ removeLock(lockPath);
1810
+ }
1811
+ } catch {
1812
+ removeLock(lockPath);
1813
+ }
1814
+ return last;
1815
+ }
1816
+ }
1817
+ });
1818
+
1819
+ // ../packages/agent-events/out/index.js
1820
+ var require_out2 = __commonJS({
1821
+ "../packages/agent-events/out/index.js"(exports) {
1822
+ "use strict";
1823
+ Object.defineProperty(exports, "__esModule", { value: true });
1824
+ exports.KNOWN_AGENTS = exports.WAIT_REASONS = exports.VCS_ACTIONS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1825
+ exports.isAgentEventV0 = isAgentEventV0;
1826
+ exports.parseEventLogLine = parseEventLogLine;
1827
+ exports.normaliseKind = normaliseKind;
1828
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1829
+ exports.AGENT_EVENT_KINDS = [
1830
+ "session.started",
1831
+ "session.ended",
1832
+ "prompt.submitted",
1833
+ "tool.started",
1834
+ "tool.completed",
1835
+ "tool.failed",
1836
+ "turn.completed",
1837
+ "agent.waiting",
1838
+ "permission.requested",
1839
+ "permission.denied",
1840
+ "context.compacted",
1841
+ "subagent.started",
1842
+ "subagent.stopped",
1843
+ "pull_request.opened",
1844
+ "pull_request.closed",
1845
+ "pull_request.merged",
1846
+ "other"
1847
+ ];
1848
+ exports.VCS_ACTIONS = ["commit", "push", "pr_created", "pr_merged"];
1849
+ exports.WAIT_REASONS = ["permission", "idle", "input", "other"];
1850
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1851
+ function isAgentEventV0(value) {
1852
+ if (!value || typeof value !== "object")
1853
+ return false;
1854
+ const e = value;
1855
+ 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";
1856
+ }
1857
+ function parseEventLogLine(line) {
1858
+ if (!line.trim())
1859
+ return void 0;
1860
+ try {
1861
+ const parsed = JSON.parse(line);
1862
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1863
+ } catch {
1864
+ return void 0;
1865
+ }
1866
+ }
1867
+ function normaliseKind(kind) {
1868
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1869
+ }
1870
+ }
1871
+ });
1872
+
1873
+ // ../packages/tool-kit/out/agentEvent.js
1874
+ var require_agentEvent = __commonJS({
1875
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1876
+ "use strict";
1877
+ Object.defineProperty(exports, "__esModule", { value: true });
1878
+ exports.toAgentEvent = toAgentEvent;
1879
+ var agent_events_1 = require_out2();
1880
+ var KIND_BY_TYPE = {
1881
+ create_focus_session: "session.started",
1882
+ recovery_offline_period: "session.ended",
1883
+ ai_prompt_submitted: "prompt.submitted",
1884
+ ai_tool_call_started: "tool.started",
1885
+ ai_tool_call_completed: "tool.completed",
1886
+ ai_file_write: "tool.completed",
1887
+ ai_file_edit: "tool.completed",
1888
+ editor_verification_activity: "tool.completed",
1889
+ ai_tool_call_failed: "tool.failed",
1890
+ compile_error: "tool.failed",
1891
+ tool_failure: "tool.failed",
1892
+ ai_turn_completed: "turn.completed",
1893
+ supervision_interruption: "agent.waiting",
1894
+ permission_requested: "permission.requested",
1895
+ permission_denied: "permission.denied",
1896
+ context_compression_manual: "context.compacted",
1897
+ context_compression_auto: "context.compacted",
1898
+ subagent_started: "subagent.started",
1899
+ subagent_stopped: "subagent.stopped",
1900
+ pull_request_opened: "pull_request.opened",
1901
+ pull_request_closed: "pull_request.closed",
1902
+ pull_request_merged: "pull_request.merged"
1903
+ };
1904
+ function agentOf(payload) {
1905
+ const host = stringField(payload.metadata?.host);
1906
+ if (host)
1907
+ return host;
1908
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1909
+ }
1910
+ function vcsActionOf(metadata) {
1911
+ const milestone = stringField(metadata.milestoneKind);
1912
+ if (milestone === "pr_opened")
1913
+ return "pr_created";
1914
+ if (milestone === "pr_merged")
1915
+ return "pr_merged";
1916
+ const git = stringField(metadata.gitAction);
1917
+ return git === "commit" || git === "push" ? git : void 0;
1918
+ }
1919
+ function waitReasonOf(metadata) {
1920
+ switch (stringField(metadata.interruptionKind)) {
1921
+ case "permission_request":
1922
+ return "permission";
1923
+ case "input_request":
1924
+ return "input";
1925
+ case "idle_prompt":
1926
+ return "idle";
1927
+ case void 0:
1928
+ return void 0;
1929
+ default:
1930
+ return "other";
1931
+ }
1932
+ }
1933
+ function stringField(value) {
1934
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1935
+ }
1936
+ function toAgentEvent(payload) {
1937
+ const metadata = payload.metadata ?? {};
1938
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1939
+ const tool = kind.startsWith("tool.") || kind.startsWith("permission.") ? stringField(metadata.toolName) : void 0;
1940
+ const outcome = stringField(metadata.outcome);
1941
+ const vcsAction = kind === "tool.completed" ? vcsActionOf(metadata) : void 0;
1942
+ const reason = kind === "agent.waiting" ? waitReasonOf(metadata) : void 0;
1943
+ const model = kind === "session.started" ? stringField(metadata.modelId) : void 0;
1944
+ return {
1945
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1946
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1947
+ time: payload.occurredAt,
1948
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1949
+ // writes anyway; without it the event in memory and the one on disk differ.
1950
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1951
+ agent: agentOf(payload),
1952
+ kind,
1953
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1954
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1955
+ ...tool ? { tool } : {},
1956
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1957
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1958
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1959
+ ...stringField(metadata.repoKey) ? { repoKey: metadata.repoKey } : {},
1960
+ ...stringField(metadata.branchKey) ? { branchKey: metadata.branchKey } : {},
1961
+ ...stringField(metadata.autonomyMode) ? { permissionMode: metadata.autonomyMode } : {},
1962
+ ...stringField(metadata.headRepoKey) ? { headRepoKey: metadata.headRepoKey } : {},
1963
+ ...stringField(metadata.prCreatedAt) ? { prCreatedAt: metadata.prCreatedAt } : {},
1964
+ ...stringField(metadata.prClosedAt) ? { prClosedAt: metadata.prClosedAt } : {},
1965
+ ...stringField(metadata.prMergedAt) ? { prMergedAt: metadata.prMergedAt } : {},
1966
+ ...stringField(metadata.promptId) ? { promptId: metadata.promptId } : {},
1967
+ ...vcsAction ? { vcsAction } : {},
1968
+ ...reason ? { reason } : {},
1969
+ ...model ? { model } : {},
1970
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1971
+ sourceType: payload.eventType
1972
+ };
1973
+ }
1974
+ }
1975
+ });
1976
+
1977
+ // ../packages/tool-kit/out/credentials.js
1978
+ var require_credentials = __commonJS({
1979
+ "../packages/tool-kit/out/credentials.js"(exports) {
1980
+ "use strict";
1981
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1982
+ if (k2 === void 0) k2 = k;
1983
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1984
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1985
+ desc = { enumerable: true, get: function() {
1986
+ return m[k];
1987
+ } };
1988
+ }
1989
+ Object.defineProperty(o, k2, desc);
1990
+ } : function(o, m, k, k2) {
1991
+ if (k2 === void 0) k2 = k;
1992
+ o[k2] = m[k];
1993
+ });
1994
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1995
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1996
+ } : function(o, v) {
1997
+ o["default"] = v;
1998
+ });
1999
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2000
+ var ownKeys = function(o) {
2001
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2002
+ var ar = [];
2003
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2004
+ return ar;
2005
+ };
2006
+ return ownKeys(o);
2007
+ };
2008
+ return function(mod) {
2009
+ if (mod && mod.__esModule) return mod;
2010
+ var result = {};
2011
+ if (mod != null) {
2012
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2013
+ }
2014
+ __setModuleDefault(result, mod);
2015
+ return result;
2016
+ };
2017
+ }();
2018
+ Object.defineProperty(exports, "__esModule", { value: true });
2019
+ exports.credentialsFilePath = credentialsFilePath;
2020
+ exports.readMachineCredentials = readMachineCredentials;
2021
+ exports.writeMachineCredentials = writeMachineCredentials;
2022
+ exports.writeTopLevelCredentials = writeTopLevelCredentials;
2023
+ exports.writeRepoKeysSetting = writeRepoKeysSetting;
2024
+ exports.writeEventLogSetting = writeEventLogSetting;
2025
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2026
+ exports.readHostCredentials = readHostCredentials;
2027
+ exports.writeHostCredentials = writeHostCredentials;
2028
+ exports.removeHostCredentials = removeHostCredentials;
2029
+ var fs = __importStar(__require("fs"));
2030
+ var path = __importStar(__require("path"));
2031
+ var tokenStore_1 = require_tokenStore();
2032
+ function credentialsFilePath() {
2033
+ return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2034
+ }
2035
+ function readMachineCredentials() {
2036
+ try {
2037
+ const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
2038
+ if (!raw)
2039
+ return void 0;
2040
+ const parsed = JSON.parse(raw);
2041
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2042
+ return void 0;
2043
+ return parsed;
2044
+ } catch {
2045
+ return void 0;
2046
+ }
2047
+ }
2048
+ function writeMachineCredentials(credentials) {
2049
+ const file = credentialsFilePath();
2050
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2051
+ fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2052
+ `, { encoding: "utf8", mode: 384 });
2053
+ if (process.platform !== "win32") {
2054
+ fs.chmodSync(path.dirname(file), 448);
2055
+ fs.chmodSync(file, 384);
2056
+ }
2057
+ }
2058
+ function writeTopLevelCredentials(credentials) {
2059
+ const existing = readMachineCredentials();
2060
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
2061
+ const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
2062
+ writeMachineCredentials({
2063
+ ...credentials,
2064
+ ...eventLogPath ? { eventLogPath } : {},
2065
+ ...repoKeys === false ? { repoKeys } : {},
2066
+ ...existing?.tools ? { tools: existing.tools } : {}
2067
+ });
2068
+ }
2069
+ function writeRepoKeysSetting(on) {
2070
+ const existing = readMachineCredentials() ?? {};
2071
+ const { repoKeys: _dropped, ...rest } = existing;
2072
+ writeMachineCredentials(on ? rest : { ...rest, repoKeys: false });
2073
+ }
2074
+ function writeEventLogSetting(value) {
2075
+ const existing = readMachineCredentials() ?? {};
2076
+ writeMachineCredentials({ ...existing, eventLogPath: value });
2077
+ }
2078
+ function isLocalOnlyHostInstall(host, hasToken) {
2079
+ const credentials = readHostCredentials(host);
2080
+ if (!credentials?.localOnly)
2081
+ return false;
2082
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2083
+ return false;
2084
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2085
+ }
2086
+ function readHostCredentials(host) {
2087
+ const entry = readMachineCredentials()?.tools?.[host];
2088
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
2089
+ return void 0;
2090
+ return entry;
2091
+ }
2092
+ function writeHostCredentials(host, credentials) {
2093
+ const existing = readMachineCredentials() ?? {};
2094
+ writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2095
+ }
2096
+ function removeHostCredentials(host) {
2097
+ const existing = readMachineCredentials();
2098
+ if (!existing?.tools || !(host in existing.tools))
2099
+ return;
2100
+ const tools = { ...existing.tools };
2101
+ delete tools[host];
2102
+ const next = { ...existing };
2103
+ if (Object.keys(tools).length)
2104
+ next.tools = tools;
2105
+ else
2106
+ delete next.tools;
2107
+ writeMachineCredentials(next);
2108
+ }
2109
+ }
2110
+ });
2111
+
2112
+ // ../packages/tool-kit/out/eventLog.js
2113
+ var require_eventLog = __commonJS({
2114
+ "../packages/tool-kit/out/eventLog.js"(exports) {
2115
+ "use strict";
2116
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2117
+ if (k2 === void 0) k2 = k;
2118
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2119
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2120
+ desc = { enumerable: true, get: function() {
2121
+ return m[k];
2122
+ } };
2123
+ }
2124
+ Object.defineProperty(o, k2, desc);
2125
+ } : function(o, m, k, k2) {
2126
+ if (k2 === void 0) k2 = k;
2127
+ o[k2] = m[k];
2128
+ });
2129
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2130
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2131
+ } : function(o, v) {
2132
+ o["default"] = v;
2133
+ });
2134
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2135
+ var ownKeys = function(o) {
2136
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2137
+ var ar = [];
2138
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2139
+ return ar;
2140
+ };
2141
+ return ownKeys(o);
2142
+ };
2143
+ return function(mod) {
2144
+ if (mod && mod.__esModule) return mod;
2145
+ var result = {};
2146
+ if (mod != null) {
2147
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2148
+ }
2149
+ __setModuleDefault(result, mod);
2150
+ return result;
2151
+ };
2152
+ }();
2153
+ Object.defineProperty(exports, "__esModule", { value: true });
2154
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
2155
+ exports.expandUserPath = expandUserPath;
2156
+ exports.defaultEventLogPath = defaultEventLogPath;
2157
+ exports.resolveEventLog = resolveEventLog;
2158
+ exports.resolveEventLogPath = resolveEventLogPath;
2159
+ exports.describeEventLog = describeEventLog;
2160
+ exports.parseEventLogFlag = parseEventLogFlag;
2161
+ exports.appendEventLog = appendEventLog;
2162
+ var fs = __importStar(__require("fs"));
2163
+ var os = __importStar(__require("os"));
2164
+ var path = __importStar(__require("path"));
2165
+ var agentEvent_1 = require_agentEvent();
2166
+ var credentials_1 = require_credentials();
2167
+ var tokenStore_1 = require_tokenStore();
2168
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
2169
+ exports.EVENT_LOG_OFF = "off";
2170
+ var MAX_BYTES = 5 * 1024 * 1024;
2171
+ function expandUserPath(configured) {
2172
+ const value = configured?.trim();
2173
+ if (!value)
2174
+ return void 0;
2175
+ if (value === "~")
2176
+ return os.homedir();
2177
+ if (value.startsWith("~/"))
2178
+ return path.join(os.homedir(), value.slice(2));
2179
+ return path.resolve(value);
2180
+ }
2181
+ function defaultEventLogPath() {
2182
+ return path.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
2183
+ }
2184
+ function resolveEventLog(options = {}) {
2185
+ for (const [source, raw] of [
2186
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
2187
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
2188
+ ]) {
2189
+ const value = raw?.trim();
2190
+ if (!value)
2191
+ continue;
2192
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
2193
+ return { path: void 0, source: "disabled" };
2194
+ return { path: expandUserPath(value), source };
2195
+ }
2196
+ if (options.localOnly)
2197
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
2198
+ return { path: void 0, source: "off" };
2199
+ }
2200
+ function resolveEventLogPath(options = {}) {
2201
+ return resolveEventLog(options).path;
2202
+ }
2203
+ function describeEventLog(setting, command) {
2204
+ switch (setting.source) {
2205
+ case "env":
2206
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
2207
+ case "credentials":
2208
+ return `${setting.path} (set by ${command} --event-log)`;
2209
+ case "unpaired-default":
2210
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
2211
+ case "disabled":
2212
+ return `off (turned off; ${command} --event-log to turn it on)`;
2213
+ case "off":
2214
+ return `off (${command} --event-log to keep a local copy of every event)`;
2215
+ }
2216
+ }
2217
+ function parseEventLogFlag(argv, index) {
2218
+ const peek = argv[index + 1];
2219
+ if (peek !== void 0 && !peek.startsWith("-"))
2220
+ return { value: peek, consumed: 1 };
2221
+ return { value: defaultEventLogPath(), consumed: 0 };
2222
+ }
2223
+ function appendEventLog(logFilePath, entry) {
2224
+ try {
2225
+ rotateIfLarge(logFilePath);
2226
+ const dir = path.dirname(logFilePath);
2227
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
2228
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
2229
+ fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
2230
+ `, { encoding: "utf8", mode: 384 });
2231
+ if (process.platform !== "win32")
2232
+ fs.chmodSync(logFilePath, 384);
2233
+ } catch {
2234
+ }
2235
+ }
2236
+ function rotateIfLarge(logFilePath) {
2237
+ try {
2238
+ if (fs.statSync(logFilePath).size < MAX_BYTES)
2239
+ return;
2240
+ fs.renameSync(logFilePath, `${logFilePath}.1`);
2241
+ } catch {
2242
+ }
2243
+ }
2244
+ }
2245
+ });
2246
+
2247
+ // ../packages/tool-kit/out/http.js
2248
+ var require_http = __commonJS({
2249
+ "../packages/tool-kit/out/http.js"(exports) {
2250
+ "use strict";
2251
+ Object.defineProperty(exports, "__esModule", { value: true });
2252
+ exports.AscendaApiError = void 0;
2253
+ exports.createPairingSession = createPairingSession;
2254
+ exports.getPairingStatus = getPairingStatus;
2255
+ exports.startStudyJoin = startStudyJoin;
2256
+ exports.getStudyJoinStatus = getStudyJoinStatus;
2257
+ exports.readInitiatives = readInitiatives;
2258
+ exports.readStudyNotices = readStudyNotices;
2259
+ exports.setStudyObjection = setStudyObjection;
2260
+ exports.markStudyNoticeShown = markStudyNoticeShown;
2261
+ exports.renewToolToken = renewToolToken;
2262
+ exports.isRetryableStatus = isRetryableStatus;
2263
+ exports.postToolEvent = postToolEvent;
2264
+ exports.postToolEventsBatch = postToolEventsBatch;
2265
+ exports.parseIngestResponse = parseIngestResponse;
2266
+ var tool_contract_1 = require_out();
2267
+ var AscendaApiError = class extends Error {
2268
+ status;
2269
+ errorCode;
2270
+ constructor(status, errorCode, body) {
2271
+ super(body ?? `Ascenda API error ${status}`);
2272
+ this.status = status;
2273
+ this.errorCode = errorCode;
2274
+ this.name = "AscendaApiError";
2275
+ }
2276
+ };
2277
+ exports.AscendaApiError = AscendaApiError;
2278
+ async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
2279
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
2280
+ method: "POST",
2281
+ headers: { "Content-Type": "application/json" },
2282
+ body: JSON.stringify({ toolInstallationId, toolType, displayName })
2283
+ });
2284
+ if (!response.ok)
2285
+ throw new AscendaApiError(response.status, void 0, await response.text());
2286
+ return await response.json();
2287
+ }
2288
+ async function getPairingStatus(apiBaseUrl, pairingSessionId) {
2289
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
2290
+ method: "GET",
2291
+ headers: { Accept: "application/json" }
2292
+ });
2293
+ if (!response.ok)
2294
+ throw new AscendaApiError(response.status, void 0, await response.text());
2295
+ return await response.json();
2296
+ }
2297
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
2298
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2299
+ method: "POST",
2300
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2301
+ body: JSON.stringify({ joinCode, mode })
2302
+ });
2303
+ if (!response.ok)
2304
+ throw await apiError(response);
2305
+ return await response.json();
2306
+ }
2307
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
2308
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
2309
+ method: "GET",
2310
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
2311
+ });
2312
+ if (!response.ok)
2313
+ throw await apiError(response);
2314
+ return await response.json();
2315
+ }
2316
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
2317
+ let response;
2318
+ try {
2319
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
2320
+ method: "GET",
2321
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2322
+ signal
2323
+ });
2324
+ } catch (error2) {
2325
+ return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2326
+ }
2327
+ if (response.status === 401)
2328
+ return { kind: "rejected", httpStatus: 401 };
2329
+ if (!response.ok)
2330
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2331
+ let body;
2332
+ try {
2333
+ body = await response.json();
2334
+ } catch {
2335
+ return { kind: "failed", reason: "the reply was not readable" };
2336
+ }
2337
+ if (!Array.isArray(body))
2338
+ return { kind: "failed", reason: "the reply was not a list" };
2339
+ return { kind: "ok", initiatives: body };
2340
+ }
2341
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
2342
+ let response;
2343
+ try {
2344
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
2345
+ method: "GET",
2346
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2347
+ signal
2348
+ });
2349
+ } catch (error2) {
2350
+ return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2351
+ }
2352
+ if (response.status === 404)
2353
+ return { kind: "absent" };
2354
+ if (response.status === 401)
2355
+ return { kind: "rejected", httpStatus: 401 };
2356
+ if (!response.ok)
2357
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2358
+ let body;
2359
+ try {
2360
+ body = await response.json();
2361
+ } catch {
2362
+ return { kind: "absent" };
2363
+ }
2364
+ if (!Array.isArray(body))
2365
+ return { kind: "absent" };
2366
+ return { kind: "ok", notices: body };
2367
+ }
2368
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
2369
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
2370
+ method: objected ? "POST" : "DELETE",
2371
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
2372
+ });
2373
+ if (!response.ok)
2374
+ throw await apiError(response);
2375
+ }
2376
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
2377
+ try {
2378
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
2379
+ method: "POST",
2380
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
2381
+ signal
2382
+ });
2383
+ return response.ok;
2384
+ } catch {
2385
+ return false;
1789
2386
  }
1790
- const kept = excess > 0 ? fresh.slice(excess) : fresh;
1791
- const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1792
- return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1793
2387
  }
1794
- function listClaimFiles(outboxFilePath) {
1795
- const dir = path.dirname(outboxFilePath);
1796
- const prefix = `${path.basename(outboxFilePath)}.`;
2388
+ async function apiError(response) {
2389
+ const body = await response.text();
2390
+ let errorCode;
1797
2391
  try {
1798
- return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
2392
+ const parsed = JSON.parse(body);
2393
+ errorCode = parsed.code ?? parsed.error;
1799
2394
  } catch {
1800
- return [];
2395
+ errorCode = void 0;
1801
2396
  }
2397
+ return new AscendaApiError(response.status, errorCode, body);
1802
2398
  }
1803
- function readEntries(file) {
1804
- let raw;
2399
+ async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
2400
+ const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
2401
+ method: "POST",
2402
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2403
+ signal
2404
+ });
2405
+ if (response.status === 401)
2406
+ return null;
2407
+ if (!response.ok)
2408
+ throw new AscendaApiError(response.status, void 0, await response.text());
2409
+ return await response.json();
2410
+ }
2411
+ function isDeliveredStatus(value) {
2412
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
2413
+ }
2414
+ function readSuccessBody(body) {
2415
+ let parsed;
1805
2416
  try {
1806
- raw = fs.readFileSync(file, "utf8");
2417
+ parsed = JSON.parse(body);
1807
2418
  } catch {
1808
- return { entries: [], unreadable: 0 };
2419
+ return { duplicates: 0 };
1809
2420
  }
1810
- const entries = [];
1811
- let unreadable = 0;
1812
- for (const line of raw.split("\n")) {
1813
- if (!line.trim())
2421
+ if (!parsed || typeof parsed !== "object")
2422
+ return { duplicates: 0 };
2423
+ const single = parsed.status;
2424
+ if (isDeliveredStatus(single))
2425
+ return { duplicates: single === "duplicate" ? 1 : 0 };
2426
+ const raw = parsed.results;
2427
+ if (!Array.isArray(raw))
2428
+ return { duplicates: 0 };
2429
+ const results = [];
2430
+ for (const item of raw) {
2431
+ if (!item || typeof item !== "object")
2432
+ continue;
2433
+ const { index, status, reason } = item;
2434
+ if (typeof index !== "number" || typeof status !== "string")
1814
2435
  continue;
2436
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
2437
+ }
2438
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
2439
+ }
2440
+ function isRetryableStatus(status) {
2441
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
2442
+ }
2443
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
2444
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
2445
+ }
2446
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
2447
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
2448
+ }
2449
+ async function sendIngest(url, eventWriteToken, body, signal) {
2450
+ try {
2451
+ const response = await fetch(url, {
2452
+ method: "POST",
2453
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2454
+ body,
2455
+ signal
2456
+ });
2457
+ return parseIngestResponse(response);
2458
+ } catch (error2) {
2459
+ return {
2460
+ result: "transport_error",
2461
+ detail: error2 instanceof Error ? `${error2.name}: ${error2.message}` : String(error2)
2462
+ };
2463
+ }
2464
+ }
2465
+ async function parseIngestResponse(response) {
2466
+ if (response.ok) {
2467
+ const outcome = { result: "accepted", httpStatus: response.status };
2468
+ let read = { duplicates: 0 };
1815
2469
  try {
1816
- const parsed = JSON.parse(line);
1817
- if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1818
- unreadable += 1;
1819
- continue;
1820
- }
1821
- entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
2470
+ read = readSuccessBody(await response.text());
1822
2471
  } catch {
1823
- unreadable += 1;
2472
+ read = { duplicates: 0 };
1824
2473
  }
2474
+ return {
2475
+ ...outcome,
2476
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
2477
+ ...read.results !== void 0 ? { results: read.results } : {}
2478
+ };
1825
2479
  }
1826
- return { entries, unreadable };
2480
+ const body = await response.text();
2481
+ let errorCode;
2482
+ try {
2483
+ errorCode = JSON.parse(body).error;
2484
+ } catch {
2485
+ errorCode = void 0;
2486
+ }
2487
+ const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
2488
+ if (response.status === 401)
2489
+ return { ...base, result: "auth_failed" };
2490
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
2491
+ return { ...base, result: "consent_missing" };
2492
+ if (response.status === 400 || response.status === 422)
2493
+ return { ...base, result: "validation_failed" };
2494
+ return { ...base, result: "transport_error" };
1827
2495
  }
1828
2496
  }
1829
2497
  });
@@ -1853,6 +2521,7 @@ var require_eventSender = __commonJS({
1853
2521
  "use strict";
1854
2522
  Object.defineProperty(exports, "__esModule", { value: true });
1855
2523
  exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
2524
+ exports.buildEventBody = buildEventBody;
1856
2525
  exports.buildEventPayload = buildEventPayload;
1857
2526
  var afterHours_1 = require_afterHours();
1858
2527
  var tool_contract_1 = require_out();
@@ -1871,12 +2540,10 @@ var require_eventSender = __commonJS({
1871
2540
  }
1872
2541
  };
1873
2542
  exports.AscendaSemanticEventError = AscendaSemanticEventError;
1874
- function buildEventPayload(identity, mapped) {
2543
+ function buildEventBody(identity, mapped) {
1875
2544
  return {
1876
- toolInstallationId: identity.toolInstallationId,
1877
2545
  source: identity.source,
1878
2546
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1879
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1880
2547
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1881
2548
  sessionId: identity.sessionId ?? void 0,
1882
2549
  workspaceHash: identity.workspaceHash ?? void 0,
@@ -1888,6 +2555,9 @@ var require_eventSender = __commonJS({
1888
2555
  metadata: withCollectorVersion(mapped.metadata)
1889
2556
  };
1890
2557
  }
2558
+ function buildEventPayload(identity, mapped) {
2559
+ return (0, tool_contract_1.joinEventPayload)({ toolInstallationId: identity.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() }, buildEventBody(identity, mapped));
2560
+ }
1891
2561
  function withCollectorVersion(metadata) {
1892
2562
  return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION };
1893
2563
  }
@@ -1963,12 +2633,10 @@ var require_eventSender = __commonJS({
1963
2633
  if (!mapped.metadata.skillVersion || !mapped.metadata.skillVersion.trim()) {
1964
2634
  throw new AscendaSemanticEventError(`metadata.skillVersion is required for semantic event "${mapped.eventType}".`);
1965
2635
  }
1966
- const payload = {
1967
- toolInstallationId: this.config.toolInstallationId,
2636
+ const body = {
1968
2637
  source: this.config.source,
1969
2638
  eventType: mapped.eventType,
1970
2639
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1971
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1972
2640
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1973
2641
  severity: "low",
1974
2642
  sessionId: this.config.sessionId ?? void 0,
@@ -1979,7 +2647,7 @@ var require_eventSender = __commonJS({
1979
2647
  privacyMode: "metadata_only",
1980
2648
  metadata: withCollectorVersion(mapped.metadata)
1981
2649
  };
1982
- return this.post(payload);
2650
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
1983
2651
  }
1984
2652
  /**
1985
2653
  * Sends a collaboration event under `workflow_telemetry`.
@@ -1994,12 +2662,10 @@ var require_eventSender = __commonJS({
1994
2662
  if (!tool_contract_1.COLLABORATION_EVENT_TYPES.includes(mapped.eventType)) {
1995
2663
  throw new AscendaSemanticEventError(`"${mapped.eventType}" is not a collaboration event type. Use send() for a deterministic host event.`);
1996
2664
  }
1997
- const payload = {
1998
- toolInstallationId: this.config.toolInstallationId,
2665
+ const body = {
1999
2666
  source: this.config.source,
2000
2667
  eventType: mapped.eventType,
2001
2668
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
2002
- idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
2003
2669
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
2004
2670
  severity: "low",
2005
2671
  sessionId: this.config.sessionId ?? void 0,
@@ -2010,7 +2676,11 @@ var require_eventSender = __commonJS({
2010
2676
  privacyMode: "metadata_only",
2011
2677
  metadata: withCollectorVersion(mapped.metadata)
2012
2678
  };
2013
- return this.post(payload);
2679
+ return this.post((0, tool_contract_1.joinEventPayload)(this.envelope(), body));
2680
+ }
2681
+ /** A fresh envelope per event: the key belongs to the event, so every retry of it reuses this one. */
2682
+ envelope() {
2683
+ return { toolInstallationId: this.config.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() };
2014
2684
  }
2015
2685
  /**
2016
2686
  * The single choke point every event passes through, and therefore the only
@@ -2074,6 +2744,29 @@ var require_eventSender = __commonJS({
2074
2744
  }
2075
2745
  return outcome;
2076
2746
  }
2747
+ /**
2748
+ * One outbox pass with nothing live to send: what a background flusher runs,
2749
+ * once per batch. Unlike the pass {@link post} makes, it may run more than
2750
+ * once per sender, because a flusher isn't on anyone's critical path.
2751
+ *
2752
+ * A halted pass is journaled here. Inside {@link post} the live send that
2753
+ * follows journals it, and a flusher has no live send, so without this an
2754
+ * outage would never reach the journal `doctor` and the notices read.
2755
+ */
2756
+ async flushOutbox() {
2757
+ await this.renewIfExpiring();
2758
+ this.outboxServiced = false;
2759
+ this.lastDrain = void 0;
2760
+ const halted = await this.serviceOutbox();
2761
+ if (halted) {
2762
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, halted.result, {
2763
+ httpStatus: halted.httpStatus,
2764
+ errorCode: halted.errorCode,
2765
+ detail: withNote(halted.detail, "kept in outbox")
2766
+ });
2767
+ }
2768
+ return this.lastDrain;
2769
+ }
2077
2770
  /** A failure that never reached a verdict. Replaying can change the answer. */
2078
2771
  isRetryable(outcome) {
2079
2772
  return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
@@ -2410,140 +3103,23 @@ var require_contextRegistry = __commonJS({
2410
3103
  writeRegistry(registryFilePath, registry2);
2411
3104
  return true;
2412
3105
  } catch {
2413
- return false;
2414
- }
2415
- }
2416
- function dayOf(iso) {
2417
- return iso.slice(0, 10);
2418
- }
2419
- function writeRegistry(registryFilePath, registry2) {
2420
- const dir = path.dirname(registryFilePath);
2421
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
2422
- const tmp = `${registryFilePath}.${process.pid}.tmp`;
2423
- fs.writeFileSync(tmp, `${JSON.stringify(registry2, null, 2)}
2424
- `, { encoding: "utf8", mode: 384 });
2425
- fs.renameSync(tmp, registryFilePath);
2426
- if (process.platform !== "win32") {
2427
- fs.chmodSync(registryFilePath, 384);
2428
- }
2429
- }
2430
- }
2431
- });
2432
-
2433
- // ../packages/tool-kit/out/credentials.js
2434
- var require_credentials = __commonJS({
2435
- "../packages/tool-kit/out/credentials.js"(exports) {
2436
- "use strict";
2437
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2438
- if (k2 === void 0) k2 = k;
2439
- var desc = Object.getOwnPropertyDescriptor(m, k);
2440
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2441
- desc = { enumerable: true, get: function() {
2442
- return m[k];
2443
- } };
2444
- }
2445
- Object.defineProperty(o, k2, desc);
2446
- } : function(o, m, k, k2) {
2447
- if (k2 === void 0) k2 = k;
2448
- o[k2] = m[k];
2449
- });
2450
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2451
- Object.defineProperty(o, "default", { enumerable: true, value: v });
2452
- } : function(o, v) {
2453
- o["default"] = v;
2454
- });
2455
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2456
- var ownKeys = function(o) {
2457
- ownKeys = Object.getOwnPropertyNames || function(o2) {
2458
- var ar = [];
2459
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2460
- return ar;
2461
- };
2462
- return ownKeys(o);
2463
- };
2464
- return function(mod) {
2465
- if (mod && mod.__esModule) return mod;
2466
- var result = {};
2467
- if (mod != null) {
2468
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2469
- }
2470
- __setModuleDefault(result, mod);
2471
- return result;
2472
- };
2473
- }();
2474
- Object.defineProperty(exports, "__esModule", { value: true });
2475
- exports.credentialsFilePath = credentialsFilePath;
2476
- exports.readMachineCredentials = readMachineCredentials;
2477
- exports.writeMachineCredentials = writeMachineCredentials;
2478
- exports.writeTopLevelCredentials = writeTopLevelCredentials;
2479
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2480
- exports.readHostCredentials = readHostCredentials;
2481
- exports.writeHostCredentials = writeHostCredentials;
2482
- exports.removeHostCredentials = removeHostCredentials;
2483
- var fs = __importStar(__require("fs"));
2484
- var path = __importStar(__require("path"));
2485
- var tokenStore_1 = require_tokenStore();
2486
- function credentialsFilePath() {
2487
- return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2488
- }
2489
- function readMachineCredentials() {
2490
- try {
2491
- const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
2492
- if (!raw)
2493
- return void 0;
2494
- const parsed = JSON.parse(raw);
2495
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2496
- return void 0;
2497
- return parsed;
2498
- } catch {
2499
- return void 0;
3106
+ return false;
2500
3107
  }
2501
3108
  }
2502
- function writeMachineCredentials(credentials) {
2503
- const file = credentialsFilePath();
2504
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2505
- fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
3109
+ function dayOf(iso) {
3110
+ return iso.slice(0, 10);
3111
+ }
3112
+ function writeRegistry(registryFilePath, registry2) {
3113
+ const dir = path.dirname(registryFilePath);
3114
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
3115
+ const tmp = `${registryFilePath}.${process.pid}.tmp`;
3116
+ fs.writeFileSync(tmp, `${JSON.stringify(registry2, null, 2)}
2506
3117
  `, { encoding: "utf8", mode: 384 });
3118
+ fs.renameSync(tmp, registryFilePath);
2507
3119
  if (process.platform !== "win32") {
2508
- fs.chmodSync(path.dirname(file), 448);
2509
- fs.chmodSync(file, 384);
3120
+ fs.chmodSync(registryFilePath, 384);
2510
3121
  }
2511
3122
  }
2512
- function writeTopLevelCredentials(credentials) {
2513
- const existing = readMachineCredentials();
2514
- writeMachineCredentials({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2515
- }
2516
- function isLocalOnlyHostInstall(host, hasToken) {
2517
- const credentials = readHostCredentials(host);
2518
- if (!credentials?.localOnly)
2519
- return false;
2520
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2521
- return false;
2522
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2523
- }
2524
- function readHostCredentials(host) {
2525
- const entry = readMachineCredentials()?.tools?.[host];
2526
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
2527
- return void 0;
2528
- return entry;
2529
- }
2530
- function writeHostCredentials(host, credentials) {
2531
- const existing = readMachineCredentials() ?? {};
2532
- writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2533
- }
2534
- function removeHostCredentials(host) {
2535
- const existing = readMachineCredentials();
2536
- if (!existing?.tools || !(host in existing.tools))
2537
- return;
2538
- const tools = { ...existing.tools };
2539
- delete tools[host];
2540
- const next = { ...existing };
2541
- if (Object.keys(tools).length)
2542
- next.tools = tools;
2543
- else
2544
- delete next.tools;
2545
- writeMachineCredentials(next);
2546
- }
2547
3123
  }
2548
3124
  });
2549
3125
 
@@ -2590,6 +3166,8 @@ var require_forgeProject = __commonJS({
2590
3166
  }();
2591
3167
  Object.defineProperty(exports, "__esModule", { value: true });
2592
3168
  exports.forgeProjectHash = forgeProjectHash;
3169
+ exports.forgeRepoKey = forgeRepoKey;
3170
+ exports.forgeBranchKey = forgeBranchKey;
2593
3171
  exports.parseForgeFullName = parseForgeFullName;
2594
3172
  exports.readForgeFullName = readForgeFullName;
2595
3173
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
@@ -2605,6 +3183,19 @@ var require_forgeProject = __commonJS({
2605
3183
  }
2606
3184
  return h.toString(16).padStart(8, "0");
2607
3185
  }
3186
+ function forgeRepoKey(fullName) {
3187
+ return forgeProjectHash(fullName.toLowerCase());
3188
+ }
3189
+ function forgeBranchKey(fullName, branch) {
3190
+ const input = `${fullName.toLowerCase()}
3191
+ ${branch}`;
3192
+ let h = 0xcbf29ce484222325n;
3193
+ for (const byte of Buffer.from(input, "utf8")) {
3194
+ h ^= BigInt(byte);
3195
+ h = BigInt.asUintN(64, h * 0x100000001b3n);
3196
+ }
3197
+ return h.toString(16).padStart(16, "0");
3198
+ }
2608
3199
  function parseForgeFullName(remoteUrl) {
2609
3200
  if (!remoteUrl)
2610
3201
  return null;
@@ -2991,6 +3582,95 @@ var require_workContext = __commonJS({
2991
3582
  }
2992
3583
  });
2993
3584
 
3585
+ // ../packages/tool-kit/out/forgeKeys.js
3586
+ var require_forgeKeys = __commonJS({
3587
+ "../packages/tool-kit/out/forgeKeys.js"(exports) {
3588
+ "use strict";
3589
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3590
+ if (k2 === void 0) k2 = k;
3591
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3592
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3593
+ desc = { enumerable: true, get: function() {
3594
+ return m[k];
3595
+ } };
3596
+ }
3597
+ Object.defineProperty(o, k2, desc);
3598
+ } : function(o, m, k, k2) {
3599
+ if (k2 === void 0) k2 = k;
3600
+ o[k2] = m[k];
3601
+ });
3602
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3603
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3604
+ } : function(o, v) {
3605
+ o["default"] = v;
3606
+ });
3607
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3608
+ var ownKeys = function(o) {
3609
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3610
+ var ar = [];
3611
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3612
+ return ar;
3613
+ };
3614
+ return ownKeys(o);
3615
+ };
3616
+ return function(mod) {
3617
+ if (mod && mod.__esModule) return mod;
3618
+ var result = {};
3619
+ if (mod != null) {
3620
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3621
+ }
3622
+ __setModuleDefault(result, mod);
3623
+ return result;
3624
+ };
3625
+ }();
3626
+ Object.defineProperty(exports, "__esModule", { value: true });
3627
+ exports.REPO_KEYS_ENV_VAR = void 0;
3628
+ exports.repoKeysEnabled = repoKeysEnabled;
3629
+ exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd;
3630
+ var fs = __importStar(__require("fs"));
3631
+ var path = __importStar(__require("path"));
3632
+ var credentials_1 = require_credentials();
3633
+ var forgeProject_1 = require_forgeProject();
3634
+ var workContext_1 = require_workContext();
3635
+ exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
3636
+ function repoKeysEnabled() {
3637
+ const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
3638
+ if (env === "off" || env === "0" || env === "false")
3639
+ return false;
3640
+ if (env === "on" || env === "1" || env === "true")
3641
+ return true;
3642
+ return (0, credentials_1.readMachineCredentials)()?.repoKeys !== false;
3643
+ }
3644
+ function readDefaultBranch(repositoryRoot) {
3645
+ try {
3646
+ const head = fs.readFileSync(path.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
3647
+ const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
3648
+ return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
3649
+ } catch {
3650
+ return null;
3651
+ }
3652
+ }
3653
+ function deriveForgeKeysForCwd(cwd) {
3654
+ try {
3655
+ if (!cwd || !repoKeysEnabled())
3656
+ return {};
3657
+ const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
3658
+ const fullName = (0, forgeProject_1.readForgeFullName)(root);
3659
+ if (!root || !fullName)
3660
+ return {};
3661
+ const branch = (0, workContext_1.readBranchName)(cwd);
3662
+ const onDefault = branch !== null && branch === readDefaultBranch(root);
3663
+ return {
3664
+ repoKey: (0, forgeProject_1.forgeRepoKey)(fullName),
3665
+ ...branch && !onDefault ? { branchKey: (0, forgeProject_1.forgeBranchKey)(fullName, branch) } : {}
3666
+ };
3667
+ } catch {
3668
+ return {};
3669
+ }
3670
+ }
3671
+ }
3672
+ });
3673
+
2994
3674
  // ../packages/tool-kit/out/hookAdapter.js
2995
3675
  var require_hookAdapter = __commonJS({
2996
3676
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
@@ -3000,13 +3680,18 @@ var require_hookAdapter = __commonJS({
3000
3680
  exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
3001
3681
  exports.resolveContextHashes = resolveContextHashes;
3002
3682
  exports.loadCliAgentConfig = loadCliAgentConfig;
3683
+ exports.withForgeKeys = withForgeKeys;
3684
+ exports.withPromptId = withPromptId;
3003
3685
  exports.deliverHookEvents = deliverHookEvents;
3686
+ exports.flushHookOutbox = flushHookOutbox;
3004
3687
  var contextRegistry_1 = require_contextRegistry();
3005
3688
  var credentials_1 = require_credentials();
3006
3689
  var forgeProject_1 = require_forgeProject();
3007
3690
  var eventLog_1 = require_eventLog();
3691
+ var forgeKeys_1 = require_forgeKeys();
3008
3692
  var eventSender_1 = require_eventSender();
3009
3693
  var stateStore_1 = require_stateStore();
3694
+ var backgroundDelivery_1 = require_backgroundDelivery();
3010
3695
  var tokenStore_1 = require_tokenStore();
3011
3696
  var workContext_1 = require_workContext();
3012
3697
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -3059,6 +3744,19 @@ var require_hookAdapter = __commonJS({
3059
3744
  };
3060
3745
  }
3061
3746
  function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
3747
+ const pairing = loadCliAgentPairing(toolType, identity);
3748
+ const contextHashes = resolveContextHashes(cwd);
3749
+ return {
3750
+ ...pairing,
3751
+ // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3752
+ // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3753
+ // an empty string, grouping unrelated rows under a value naming no session.
3754
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3755
+ workspaceHash: contextHashes.workspaceHash,
3756
+ projectHash: contextHashes.projectHash
3757
+ };
3758
+ }
3759
+ function loadCliAgentPairing(toolType, identity) {
3062
3760
  const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
3063
3761
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3064
3762
  const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
@@ -3069,29 +3767,40 @@ var require_hookAdapter = __commonJS({
3069
3767
  throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
3070
3768
  if (!fileToken)
3071
3769
  (0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3072
- const contextHashes = resolveContextHashes(cwd);
3073
3770
  return {
3074
3771
  apiBaseUrl,
3075
3772
  toolInstallationId,
3076
3773
  eventWriteToken,
3077
3774
  tokenFilePath,
3078
- // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3079
- // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3080
- // an empty string, grouping unrelated rows under a value naming no session.
3081
- sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3082
- workspaceHash: contextHashes.workspaceHash,
3083
- projectHash: contextHashes.projectHash,
3084
3775
  // Agents await command hooks; fail fast rather than stall the user's turn.
3085
3776
  timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
3086
3777
  };
3087
3778
  }
3779
+ function withForgeKeys(events, cwd) {
3780
+ const keys = (0, forgeKeys_1.deriveForgeKeysForCwd)(cwd ?? process.cwd());
3781
+ if (!keys.repoKey)
3782
+ return events;
3783
+ return events.map((event) => ({ ...event, metadata: { ...keys, ...event.metadata } }));
3784
+ }
3785
+ function withPromptId(events, promptId) {
3786
+ if (!promptId)
3787
+ return events;
3788
+ return events.map((event) => ({ ...event, metadata: { promptId, ...event.metadata } }));
3789
+ }
3088
3790
  async function deliverHookEvents(events, options) {
3089
3791
  if (events.length === 0)
3090
3792
  return;
3091
- const notice = options.onNotice ?? ((message) => console.error(message));
3793
+ events = withPromptId(events, options.promptId);
3794
+ if (options.forgeKeys)
3795
+ events = withForgeKeys(events, options.cwd);
3796
+ const notice = options.onNotice ?? ((message2) => console.error(message2));
3092
3797
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3093
- if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken))
3798
+ if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3799
+ const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
3800
+ if (logFile)
3801
+ logUnsent(logFile, events, options);
3094
3802
  return;
3803
+ }
3095
3804
  let config2;
3096
3805
  try {
3097
3806
  config2 = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
@@ -3101,20 +3810,7 @@ var require_hookAdapter = __commonJS({
3101
3810
  const logFile = (0, eventLog_1.resolveEventLogPath)();
3102
3811
  if (!logFile)
3103
3812
  throw error2;
3104
- const contextHashes = resolveContextHashes(options.cwd);
3105
- for (const event of events) {
3106
- (0, eventLog_1.appendEventLog)(logFile, {
3107
- loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3108
- delivery: "not_sent",
3109
- payload: (0, eventSender_1.buildEventPayload)({
3110
- toolInstallationId: `${options.toolType}:unpaired`,
3111
- source: options.source,
3112
- sessionId: options.sessionId ?? null,
3113
- workspaceHash: contextHashes.workspaceHash,
3114
- projectHash: contextHashes.projectHash
3115
- }, event)
3116
- });
3117
- }
3813
+ logUnsent(logFile, events, options);
3118
3814
  return;
3119
3815
  }
3120
3816
  const sender = new eventSender_1.AscendaEventSender({
@@ -3128,21 +3824,71 @@ var require_hookAdapter = __commonJS({
3128
3824
  projectHash: config2.projectHash,
3129
3825
  timeoutMs: config2.timeoutMs
3130
3826
  });
3131
- for (const event of events) {
3132
- const result = await sender.send(event);
3133
- if (result === "accepted")
3134
- continue;
3135
- if (result === "consent_missing") {
3136
- notice("Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.");
3137
- } else if (result === "auth_failed") {
3138
- notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
3139
- } else if (result === "transport_error") {
3140
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
3141
- } else {
3142
- notice(`Ascenda telemetry rejected: ${result}`);
3827
+ if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
3828
+ for (const event of events) {
3829
+ const result = await sender.send(event);
3830
+ if (result === "accepted")
3831
+ continue;
3832
+ const message2 = noticeFor(result);
3833
+ if (message2)
3834
+ notice(message2);
3835
+ return;
3143
3836
  }
3144
3837
  return;
3145
3838
  }
3839
+ for (const event of events)
3840
+ sender.queue(event);
3841
+ (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
3842
+ const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
3843
+ const message = last ? noticeFor(last) : void 0;
3844
+ if (message)
3845
+ notice(message);
3846
+ }
3847
+ function noticeFor(result) {
3848
+ if (result === "accepted" || result === "duplicate")
3849
+ return void 0;
3850
+ if (result === "consent_missing")
3851
+ return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
3852
+ if (result === "auth_failed")
3853
+ return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
3854
+ if (result === "transport_error")
3855
+ return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
3856
+ if (result === "outbox_discarded")
3857
+ return void 0;
3858
+ return `Ascenda telemetry rejected: ${result}`;
3859
+ }
3860
+ async function flushHookOutbox(options) {
3861
+ let config2;
3862
+ try {
3863
+ config2 = loadCliAgentPairing(options.toolType, options);
3864
+ } catch {
3865
+ return;
3866
+ }
3867
+ const sender = new eventSender_1.AscendaEventSender({
3868
+ apiBaseUrl: config2.apiBaseUrl,
3869
+ toolInstallationId: config2.toolInstallationId,
3870
+ source: options.source,
3871
+ eventWriteToken: config2.eventWriteToken,
3872
+ tokenFilePath: config2.tokenFilePath,
3873
+ timeoutMs: config2.timeoutMs
3874
+ });
3875
+ await (0, backgroundDelivery_1.runOutboxFlush)(sender);
3876
+ }
3877
+ function logUnsent(logFile, events, options) {
3878
+ const contextHashes = resolveContextHashes(options.cwd);
3879
+ for (const event of events) {
3880
+ (0, eventLog_1.appendEventLog)(logFile, {
3881
+ loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
3882
+ delivery: "not_sent",
3883
+ payload: (0, eventSender_1.buildEventPayload)({
3884
+ toolInstallationId: `${options.toolType}:unpaired`,
3885
+ source: options.source,
3886
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || options.sessionId || null,
3887
+ workspaceHash: contextHashes.workspaceHash,
3888
+ projectHash: contextHashes.projectHash
3889
+ }, event)
3890
+ });
3891
+ }
3146
3892
  }
3147
3893
  function journalSkippedSend(host, error2) {
3148
3894
  const who = host ? `${host}: ` : "";
@@ -3580,96 +4326,50 @@ var require_initiatives = __commonJS({
3580
4326
  }
3581
4327
  function asInitiative(value) {
3582
4328
  if (!value || typeof value !== "object")
3583
- return void 0;
3584
- const o = value;
3585
- if (typeof o.title !== "string" || typeof o.status !== "string")
3586
- return void 0;
3587
- return {
3588
- id: typeof o.id === "string" ? o.id : "",
3589
- organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3590
- title: o.title,
3591
- summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3592
- measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3593
- scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3594
- scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3595
- withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3596
- status: o.status,
3597
- direction: typeof o.direction === "string" ? o.direction : null,
3598
- result: asResult(o.result)
3599
- };
3600
- }
3601
- function asResult(value) {
3602
- if (!value || typeof value !== "object")
3603
- return null;
3604
- const r = value;
3605
- const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
3606
- return {
3607
- scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3608
- value: num(r.value),
3609
- baselineValue: num(r.baselineValue),
3610
- delta: num(r.delta),
3611
- movement: typeof r.movement === "string" ? r.movement : null,
3612
- outcome: typeof r.outcome === "string" ? r.outcome : "",
3613
- withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3614
- basis: typeof r.basis === "string" ? r.basis : null
3615
- };
3616
- }
3617
- function formatWindowOrRaw(startUtc, endUtc) {
3618
- if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3619
- return "not given";
3620
- return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3621
- }
3622
- function formatDay(iso) {
3623
- const date3 = new Date(iso);
3624
- if (Number.isNaN(date3.getTime()))
3625
- return iso;
3626
- return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date3);
3627
- }
3628
- }
3629
- });
3630
-
3631
- // ../packages/tool-kit/out/setupDisclosure.js
3632
- var require_setupDisclosure = __commonJS({
3633
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3634
- "use strict";
3635
- Object.defineProperty(exports, "__esModule", { value: true });
3636
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3637
- exports.renderSetupDisclosure = renderSetupDisclosure;
3638
- exports.FAMILY_SENTENCES = {
3639
- 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",
3640
- 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",
3641
- tools: "the name of each tool your agent calls",
3642
- outcome: "whether a call succeeded, failed, or was interrupted",
3643
- clock: "your machine's offset from UTC, so an evening is read as an evening",
3644
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3645
- model: "which model served the session, by name and by tier",
3646
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3647
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
3648
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3649
- context: "how full the context window got",
3650
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3651
- 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",
3652
- 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"
3653
- };
3654
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3655
- exports.REFUSALS = [
3656
- "Never your prompts, your agent's replies, or anything inside a file.",
3657
- "Never a file path, a command line, or a repository or branch name.",
3658
- "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."
3659
- ];
3660
- exports.FREE_TEXT_KEYS = ["message"];
3661
- function renderSetupDisclosure({ sends, displayName }) {
3662
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3663
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3664
- const lines = [
3665
- `What this sends from ${displayName}, once paired:`,
3666
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3667
- "",
3668
- ...exports.REFUSALS.map((line) => ` ${line}`),
3669
- "",
3670
- " Turn it off by revoking this tool in the Ascenda app."
3671
- ];
3672
- return lines.join("\n");
4329
+ return void 0;
4330
+ const o = value;
4331
+ if (typeof o.title !== "string" || typeof o.status !== "string")
4332
+ return void 0;
4333
+ return {
4334
+ id: typeof o.id === "string" ? o.id : "",
4335
+ organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
4336
+ title: o.title,
4337
+ summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
4338
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
4339
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
4340
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
4341
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
4342
+ status: o.status,
4343
+ direction: typeof o.direction === "string" ? o.direction : null,
4344
+ result: asResult(o.result)
4345
+ };
4346
+ }
4347
+ function asResult(value) {
4348
+ if (!value || typeof value !== "object")
4349
+ return null;
4350
+ const r = value;
4351
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
4352
+ return {
4353
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
4354
+ value: num(r.value),
4355
+ baselineValue: num(r.baselineValue),
4356
+ delta: num(r.delta),
4357
+ movement: typeof r.movement === "string" ? r.movement : null,
4358
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
4359
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
4360
+ basis: typeof r.basis === "string" ? r.basis : null
4361
+ };
4362
+ }
4363
+ function formatWindowOrRaw(startUtc, endUtc) {
4364
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
4365
+ return "not given";
4366
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
4367
+ }
4368
+ function formatDay(iso) {
4369
+ const date3 = new Date(iso);
4370
+ if (Number.isNaN(date3.getTime()))
4371
+ return iso;
4372
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date3);
3673
4373
  }
3674
4374
  }
3675
4375
  });
@@ -3718,9 +4418,11 @@ var require_hookRunner = __commonJS({
3718
4418
  Object.defineProperty(exports, "__esModule", { value: true });
3719
4419
  exports.hookRunnerPaths = hookRunnerPaths;
3720
4420
  exports.hookLauncherScript = hookLauncherScript;
4421
+ exports.isDowngrade = isDowngrade;
3721
4422
  exports.installHookRunner = installHookRunner;
3722
4423
  exports.removeHookRunner = removeHookRunner;
3723
4424
  exports.hookRunnerCommand = hookRunnerCommand;
4425
+ exports.writeAtomically = writeAtomically;
3724
4426
  exports.lastHookPath = lastHookPath;
3725
4427
  exports.stampLastHook = stampLastHook;
3726
4428
  exports.readLastHook = readLastHook;
@@ -3730,10 +4432,11 @@ var require_hookRunner = __commonJS({
3730
4432
  var child_process_1 = __require("child_process");
3731
4433
  var fs = __importStar(__require("fs"));
3732
4434
  var path = __importStar(__require("path"));
4435
+ var collectorVersion_1 = require_collectorVersion();
3733
4436
  var tokenStore_1 = require_tokenStore();
3734
4437
  function hookRunnerPaths(binaryName) {
3735
4438
  const launcher = path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3736
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
4439
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
3737
4440
  }
3738
4441
  var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3739
4442
  function hookLauncherScript(options) {
@@ -3827,21 +4530,57 @@ var require_hookRunner = __commonJS({
3827
4530
  ""
3828
4531
  ].join("\n");
3829
4532
  }
4533
+ function releaseOf(version2) {
4534
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version2 ?? "").trim());
4535
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
4536
+ }
4537
+ function isDowngrade(installed, incoming) {
4538
+ const have = releaseOf(installed);
4539
+ const want = releaseOf(incoming);
4540
+ if (!have || !want)
4541
+ return false;
4542
+ for (let i = 0; i < 3; i++) {
4543
+ if (have[i] !== want[i])
4544
+ return have[i] > want[i];
4545
+ }
4546
+ return false;
4547
+ }
4548
+ function readInstalledVersion(file) {
4549
+ try {
4550
+ return fs.readFileSync(file, "utf8").trim() || void 0;
4551
+ } catch {
4552
+ return void 0;
4553
+ }
4554
+ }
3830
4555
  function installHookRunner(options) {
3831
4556
  const paths = hookRunnerPaths(options.binaryName);
3832
4557
  if (options.dryRun)
3833
4558
  return paths.launcher;
3834
4559
  const source = path.resolve(options.source ?? process.argv[1]);
4560
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
4561
+ const installed = readInstalledVersion(paths.version);
4562
+ const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
4563
+ if (installed && fs.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4564
+ options.onKeptNewer?.(installed, incoming);
4565
+ if (process.platform !== "win32" && !fs.existsSync(paths.launcher))
4566
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4567
+ return paths.launcher;
4568
+ }
3835
4569
  fs.mkdirSync(path.dirname(paths.launcher), { recursive: true });
3836
4570
  if (process.platform === "win32") {
3837
4571
  if (source !== path.resolve(paths.launcher))
3838
4572
  fs.copyFileSync(source, paths.launcher);
4573
+ writeAtomically(paths.version, `${incoming}
4574
+ `, 420);
3839
4575
  return paths.launcher;
3840
4576
  }
3841
4577
  if (source !== path.resolve(paths.bundle))
3842
4578
  writeAtomically(paths.bundle, fs.readFileSync(source), 493);
3843
4579
  writeAtomically(paths.launcher, hookLauncherScript(options), 493);
3844
4580
  writeAtomically(paths.record, `${process.execPath}
4581
+ `, 420);
4582
+ if (source !== path.resolve(paths.bundle))
4583
+ writeAtomically(paths.version, `${incoming}
3845
4584
  `, 420);
3846
4585
  fs.rmSync(paths.noNode, { force: true });
3847
4586
  return paths.launcher;
@@ -3856,8 +4595,8 @@ var require_hookRunner = __commonJS({
3856
4595
  }
3857
4596
  return removed;
3858
4597
  }
3859
- function hookRunnerCommand(launcher) {
3860
- return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4598
+ function hookRunnerCommand(launcher, platform = process.platform) {
4599
+ return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
3861
4600
  }
3862
4601
  function writeAtomically(target, contents, mode) {
3863
4602
  const tmp = `${target}.${process.pid}.tmp`;
@@ -3927,6 +4666,115 @@ var require_hookRunner = __commonJS({
3927
4666
  }
3928
4667
  });
3929
4668
 
4669
+ // ../packages/tool-kit/out/settingsFile.js
4670
+ var require_settingsFile = __commonJS({
4671
+ "../packages/tool-kit/out/settingsFile.js"(exports) {
4672
+ "use strict";
4673
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4674
+ if (k2 === void 0) k2 = k;
4675
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4676
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4677
+ desc = { enumerable: true, get: function() {
4678
+ return m[k];
4679
+ } };
4680
+ }
4681
+ Object.defineProperty(o, k2, desc);
4682
+ } : function(o, m, k, k2) {
4683
+ if (k2 === void 0) k2 = k;
4684
+ o[k2] = m[k];
4685
+ });
4686
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4687
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4688
+ } : function(o, v) {
4689
+ o["default"] = v;
4690
+ });
4691
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4692
+ var ownKeys = function(o) {
4693
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4694
+ var ar = [];
4695
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4696
+ return ar;
4697
+ };
4698
+ return ownKeys(o);
4699
+ };
4700
+ return function(mod) {
4701
+ if (mod && mod.__esModule) return mod;
4702
+ var result = {};
4703
+ if (mod != null) {
4704
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4705
+ }
4706
+ __setModuleDefault(result, mod);
4707
+ return result;
4708
+ };
4709
+ }();
4710
+ Object.defineProperty(exports, "__esModule", { value: true });
4711
+ exports.replaceSettingsFile = replaceSettingsFile;
4712
+ var fs = __importStar(__require("fs"));
4713
+ var path = __importStar(__require("path"));
4714
+ var hookRunner_1 = require_hookRunner();
4715
+ function replaceSettingsFile(settingsFile, contents) {
4716
+ const exists = fs.existsSync(settingsFile);
4717
+ const target = exists ? fs.realpathSync(settingsFile) : settingsFile;
4718
+ if (exists) {
4719
+ const backup = `${settingsFile}.ascenda-backup`;
4720
+ if (!fs.existsSync(backup))
4721
+ fs.copyFileSync(target, backup);
4722
+ }
4723
+ fs.mkdirSync(path.dirname(target), { recursive: true });
4724
+ const mode = exists ? fs.statSync(target).mode & 511 : 420;
4725
+ (0, hookRunner_1.writeAtomically)(target, contents, mode);
4726
+ }
4727
+ }
4728
+ });
4729
+
4730
+ // ../packages/tool-kit/out/setupDisclosure.js
4731
+ var require_setupDisclosure = __commonJS({
4732
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
4733
+ "use strict";
4734
+ Object.defineProperty(exports, "__esModule", { value: true });
4735
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
4736
+ exports.renderSetupDisclosure = renderSetupDisclosure;
4737
+ exports.FAMILY_SENTENCES = {
4738
+ 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",
4739
+ 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",
4740
+ tools: "the name of each tool your agent calls",
4741
+ outcome: "whether a call succeeded, failed, or was interrupted",
4742
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
4743
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
4744
+ model: "which model served the session, by name and by tier",
4745
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
4746
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
4747
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
4748
+ context: "how full the context window got",
4749
+ 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",
4750
+ 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",
4751
+ 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)",
4752
+ turns: "an opaque id your agent gives each prompt, so one turn's events group together",
4753
+ 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"
4754
+ };
4755
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
4756
+ exports.REFUSALS = [
4757
+ "Never your prompts, your agent's replies, or anything inside a file.",
4758
+ "Never a file path, a command line, or a repository or branch name.",
4759
+ "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."
4760
+ ];
4761
+ exports.FREE_TEXT_KEYS = ["message"];
4762
+ function renderSetupDisclosure({ sends, displayName }) {
4763
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
4764
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
4765
+ const lines = [
4766
+ `What this sends from ${displayName}, once paired:`,
4767
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
4768
+ "",
4769
+ ...exports.REFUSALS.map((line) => ` ${line}`),
4770
+ "",
4771
+ " Turn it off by revoking this tool in the Ascenda app."
4772
+ ];
4773
+ return lines.join("\n");
4774
+ }
4775
+ }
4776
+ });
4777
+
3930
4778
  // ../packages/tool-kit/out/saverHandoff.js
3931
4779
  var require_saverHandoff = __commonJS({
3932
4780
  "../packages/tool-kit/out/saverHandoff.js"(exports) {
@@ -4692,6 +5540,8 @@ var require_cliAgentSetup = __commonJS({
4692
5540
  exports.runCliAgentSetup = runCliAgentSetup;
4693
5541
  exports.writeHookSettings = writeHookSettings;
4694
5542
  exports.registeredHookSets = registeredHookSets;
5543
+ exports.ourHookPositions = ourHookPositions;
5544
+ exports.trustProblemLines = trustProblemLines;
4695
5545
  exports.findStaleHookCommands = findStaleHookCommands;
4696
5546
  exports.cliAgentRegistrations = cliAgentRegistrations;
4697
5547
  var crypto = __importStar(__require("crypto"));
@@ -4700,10 +5550,12 @@ var require_cliAgentSetup = __commonJS({
4700
5550
  var path = __importStar(__require("path"));
4701
5551
  var collectorVersion_1 = require_collectorVersion();
4702
5552
  var credentials_1 = require_credentials();
5553
+ var eventLog_1 = require_eventLog();
4703
5554
  var hookAdapter_1 = require_hookAdapter();
4704
5555
  var http_1 = require_http();
4705
5556
  var hookSet_1 = require_hookSet();
4706
5557
  var initiatives_1 = require_initiatives();
5558
+ var settingsFile_1 = require_settingsFile();
4707
5559
  var setupDisclosure_1 = require_setupDisclosure();
4708
5560
  var hookRunner_1 = require_hookRunner();
4709
5561
  var liveSignalDoctor_1 = require_liveSignalDoctor();
@@ -4738,6 +5590,12 @@ Options
4738
5590
  --tool-installation-id <id> reuse an existing pairing instead of creating one
4739
5591
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
4740
5592
  --no-pair install without pairing: local features on, nothing sent
5593
+ --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
5594
+ On by default when not paired; machine-wide, shared by every agent
5595
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
5596
+ repository gets a key and, off its default branch, a branch key, so a pull
5597
+ request can be matched to a session. They are digests anyone who guesses the
5598
+ names can reproduce. Machine-wide. --repo-keys turns them back on
4741
5599
  --scope user|project where hooks are registered (default user: every project)
4742
5600
  --project-dir <path> project root for --scope project (default cwd)
4743
5601
  --dry-run print what would change, write nothing
@@ -4792,6 +5650,10 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4792
5650
  toolInstallationId,
4793
5651
  ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4794
5652
  });
5653
+ if (options.eventLog !== void 0)
5654
+ (0, credentials_1.writeEventLogSetting)(options.eventLog);
5655
+ if (options.repoKeys !== void 0)
5656
+ (0, credentials_1.writeRepoKeysSetting)(options.repoKeys);
4795
5657
  }
4796
5658
  if (isHomeProject(options)) {
4797
5659
  detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
@@ -4826,6 +5688,11 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4826
5688
  else
4827
5689
  row("warn", "pairing", "not paired: pairing did not finish");
4828
5690
  detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os.homedir())} (tools.${spec.host})`);
5691
+ const eventLog = (0, eventLog_1.resolveEventLog)({ localOnly: !identity });
5692
+ if (eventLog.path)
5693
+ row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path, os.homedir())} ${ui.dim("(on this machine only)")}`);
5694
+ else if (options.eventLog !== void 0)
5695
+ row("info", "events", "off");
4829
5696
  if (options.dryRun) {
4830
5697
  console.log("\nDry run. Nothing was written.");
4831
5698
  return 0;
@@ -4836,6 +5703,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4836
5703
  if (chosenLocal) {
4837
5704
  console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
4838
5705
  console.log(" They run on this machine and need no account or pairing.");
5706
+ if (eventLog.path)
5707
+ console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os.homedir())}, for you or any tool to read.`);
4839
5708
  } else if (!identity) {
4840
5709
  console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
4841
5710
  console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
@@ -4918,6 +5787,18 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4918
5787
  case "--dry-run":
4919
5788
  options.dryRun = true;
4920
5789
  break;
5790
+ case "--event-log": {
5791
+ const { value, consumed } = (0, eventLog_1.parseEventLogFlag)(argv, i);
5792
+ options.eventLog = value;
5793
+ i += consumed;
5794
+ break;
5795
+ }
5796
+ case "--repo-keys":
5797
+ options.repoKeys = true;
5798
+ break;
5799
+ case "--no-repo-keys":
5800
+ options.repoKeys = false;
5801
+ break;
4921
5802
  case "--no-pair":
4922
5803
  // `--no-pairing` is the spelling this landed under first. Both appeared
4923
5804
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -5047,7 +5928,12 @@ Pairing ${status.status}. Run setup again.`);
5047
5928
  return void 0;
5048
5929
  }
5049
5930
  function installBinary(spec, dryRun) {
5050
- return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
5931
+ return (0, hookRunner_1.installHookRunner)({
5932
+ binaryName: spec.binaryName,
5933
+ setupCommand: `npx ${spec.packageName} setup`,
5934
+ dryRun,
5935
+ 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.`)
5936
+ });
5051
5937
  }
5052
5938
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
5053
5939
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -5067,8 +5953,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5067
5953
  const command = hookCommand(binary, spec);
5068
5954
  const hooks = { ...settings.hooks ?? {} };
5069
5955
  for (const event of spec.hookEvents) {
5070
- const kept = (hooks[event] ?? []).filter((entry) => !isOurs(entry, spec));
5071
- hooks[event] = [...kept, spec.settings.entry(command, event)];
5956
+ hooks[event] = placeOurEntry(hooks[event] ?? [], spec.settings.entry(command, event), spec);
5072
5957
  }
5073
5958
  const updated = { ...settings, hooks };
5074
5959
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -5081,10 +5966,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5081
5966
  ${serialised}`);
5082
5967
  return true;
5083
5968
  }
5084
- if (exists)
5085
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5086
- fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
5087
- fs.writeFileSync(settingsFile, serialised, "utf8");
5969
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
5088
5970
  return true;
5089
5971
  }
5090
5972
  function hookCommand(binary, spec) {
@@ -5094,28 +5976,130 @@ ${serialised}`);
5094
5976
  const sets = /* @__PURE__ */ new Map();
5095
5977
  for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
5096
5978
  for (const entry of entries ?? []) {
5097
- if (!isOurs(entry, spec))
5098
- continue;
5099
- const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
5100
- sets.set(event, Math.min(set, sets.get(event) ?? set));
5979
+ for (const command of commandsOf(entry, spec)) {
5980
+ if (!isOurCommand(command, spec))
5981
+ continue;
5982
+ const set = (0, hookSet_1.hookSetOfCommand)(command);
5983
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5984
+ }
5101
5985
  }
5102
5986
  }
5103
5987
  return sets;
5104
5988
  }
5105
- function isOurs(entry, spec) {
5989
+ function ourHookPositions(settings, spec) {
5990
+ const found = [];
5991
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5992
+ (groups ?? []).forEach((group, groupIndex) => {
5993
+ const handlers = group?.hooks;
5994
+ if (Array.isArray(handlers)) {
5995
+ handlers.forEach((handler, handlerIndex) => {
5996
+ if (isOurs({ hooks: [handler] }, spec))
5997
+ found.push({ event, group: groupIndex, handler: handlerIndex });
5998
+ });
5999
+ } else if (isOurs(group, spec)) {
6000
+ found.push({ event, group: groupIndex, handler: 0 });
6001
+ }
6002
+ });
6003
+ }
6004
+ return found;
6005
+ }
6006
+ function trustProblemLines(spec, settingsFile, settings, indent) {
6007
+ if (!spec.trust)
6008
+ return [];
6009
+ const ours = ourHookPositions(settings, spec);
6010
+ if (ours.length === 0)
6011
+ return [];
6012
+ const report = spec.trust.check(settingsFile, ours);
6013
+ const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os.homedir());
6014
+ const lines = [];
6015
+ if (report.unreadable) {
6016
+ lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
6017
+ }
6018
+ if (report.untrusted.length) {
6019
+ const names = [...new Set(report.untrusted.map((position) => position.event))].join(", ");
6020
+ 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.`);
6021
+ }
6022
+ for (const entry of report.stale)
6023
+ lines.push(entry);
6024
+ if (lines.length)
6025
+ lines.push(spec.trust.fix);
6026
+ return lines.map((line) => `${indent}${line}`);
6027
+ }
6028
+ function commandsOf(entry, spec) {
6029
+ if (spec.settings.grouped) {
6030
+ return innerHooks(entry).map(commandOfHook).filter((command2) => typeof command2 === "string");
6031
+ }
5106
6032
  const command = spec.settings.commandOf(entry);
5107
- return typeof command === "string" && command.includes(spec.binaryName);
6033
+ return typeof command === "string" ? [command] : [];
6034
+ }
6035
+ function innerHooks(entry) {
6036
+ const hooks = entry && typeof entry === "object" ? entry.hooks : void 0;
6037
+ return Array.isArray(hooks) ? hooks : [];
6038
+ }
6039
+ function commandOfHook(hook) {
6040
+ return hook && typeof hook === "object" ? hook.command : void 0;
6041
+ }
6042
+ function isOurCommand(command, spec) {
6043
+ return command.includes(spec.binaryName);
6044
+ }
6045
+ function isOurs(entry, spec) {
6046
+ return commandsOf(entry, spec).some((command) => isOurCommand(command, spec));
6047
+ }
6048
+ function isOurInnerHook(hook, spec) {
6049
+ const command = commandOfHook(hook);
6050
+ return typeof command === "string" && isOurCommand(command, spec);
6051
+ }
6052
+ function withoutOurEntries(entries, spec) {
6053
+ if (!spec.settings.grouped)
6054
+ return entries.filter((entry) => !isOurs(entry, spec));
6055
+ const kept = [];
6056
+ for (const entry of entries) {
6057
+ if (!isOurs(entry, spec)) {
6058
+ kept.push(entry);
6059
+ continue;
6060
+ }
6061
+ const others = innerHooks(entry).filter((hook) => !isOurInnerHook(hook, spec));
6062
+ if (others.length)
6063
+ kept.push({ ...entry, hooks: others });
6064
+ }
6065
+ return kept;
6066
+ }
6067
+ function placeOurEntry(entries, wanted, spec) {
6068
+ if (!spec.settings.grouped)
6069
+ return [...withoutOurEntries(entries, spec), wanted];
6070
+ const replacements = innerHooks(wanted);
6071
+ let placed = false;
6072
+ const result = [];
6073
+ for (const entry of entries) {
6074
+ if (!isOurs(entry, spec)) {
6075
+ result.push(entry);
6076
+ continue;
6077
+ }
6078
+ const matcher = entry.matcher;
6079
+ const matchesAll = matcher === void 0 || matcher === "";
6080
+ const next = [];
6081
+ for (const hook of innerHooks(entry)) {
6082
+ if (!isOurInnerHook(hook, spec))
6083
+ next.push(hook);
6084
+ else if (!placed && matchesAll) {
6085
+ next.push(...replacements);
6086
+ placed = true;
6087
+ }
6088
+ }
6089
+ if (next.length)
6090
+ result.push({ ...entry, hooks: next });
6091
+ }
6092
+ return placed ? result : [...result, wanted];
5108
6093
  }
5109
6094
  function findStaleHookCommands(settings, binary, spec) {
5110
6095
  const stale = /* @__PURE__ */ new Set();
5111
6096
  for (const entries of Object.values(settings.hooks ?? {})) {
5112
6097
  for (const entry of entries ?? []) {
5113
- const command = spec.settings.commandOf(entry);
5114
- if (typeof command !== "string")
5115
- continue;
5116
- if (!/ascenda/i.test(command) || command.includes(binary))
5117
- continue;
5118
- stale.add(command);
6098
+ for (const command of commandsOf(entry, spec)) {
6099
+ if (!/ascenda/i.test(command) || command.includes(binary))
6100
+ continue;
6101
+ stale.add(command);
6102
+ }
5119
6103
  }
5120
6104
  }
5121
6105
  return [...stale];
@@ -5140,6 +6124,7 @@ ${serialised}`);
5140
6124
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
5141
6125
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
5142
6126
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
6127
+ console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5143
6128
  console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
5144
6129
  const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5145
6130
  if (node) {
@@ -5158,6 +6143,14 @@ ${serialised}`);
5158
6143
  const oldest = Math.min(...sets);
5159
6144
  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)`);
5160
6145
  }
6146
+ const trustLines = trustProblemLines(spec, settingsFile, settings, "");
6147
+ if (trustLines.length) {
6148
+ console.log(`not trusted ${trustLines[0]}`);
6149
+ for (const line of trustLines.slice(1))
6150
+ console.log(` ${line}`);
6151
+ } else if (spec.trust && registered > 0) {
6152
+ console.log("trust every registered hook is approved");
6153
+ }
5161
6154
  if (stale.length) {
5162
6155
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
5163
6156
  for (const command of stale)
@@ -5179,7 +6172,7 @@ ${serialised}`);
5179
6172
  await notices.markShown();
5180
6173
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
5181
6174
  const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5182
- const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
6175
+ const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
5183
6176
  return healthy ? 0 : 1;
5184
6177
  }
5185
6178
  function countRegistered(settings, spec) {
@@ -5222,10 +6215,37 @@ ${serialised}`);
5222
6215
  } catch (error2) {
5223
6216
  lines.push(` Live signal (could not be checked: ${error2 instanceof Error ? error2.message : String(error2)})`);
5224
6217
  }
6218
+ if (spec.trust) {
6219
+ const found = trustDoctorLines(spec, options.projectDir, ui);
6220
+ if (found.length)
6221
+ lines.push("", ...found);
6222
+ }
5225
6223
  lines.push("", ...accountLines(ui, spec));
6224
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
6225
+ lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5226
6226
  console.log(lines.join("\n"));
5227
6227
  return 0;
5228
6228
  }
6229
+ function trustDoctorLines(spec, projectDir, ui) {
6230
+ const userFile = spec.settings.settingsPath("user", projectDir);
6231
+ const projectFile = spec.settings.settingsPath("project", projectDir);
6232
+ const files = userFile === projectFile ? [userFile] : [userFile, projectFile];
6233
+ const out = [];
6234
+ for (const file of files) {
6235
+ const settings = readSettings(file);
6236
+ if (ourHookPositions(settings, spec).length === 0)
6237
+ continue;
6238
+ const problems = trustProblemLines(spec, file, settings, "");
6239
+ if (problems.length === 0) {
6240
+ out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os.homedir())} is approved`);
6241
+ continue;
6242
+ }
6243
+ out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
6244
+ for (const line of problems.slice(1))
6245
+ out.push(`${" ".repeat(25)}${line}`);
6246
+ }
6247
+ return out;
6248
+ }
5229
6249
  function accountLines(ui, spec) {
5230
6250
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5231
6251
  const id = credentials?.toolInstallationId;
@@ -5236,9 +6256,9 @@ ${serialised}`);
5236
6256
  ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}`,
5237
6257
  ...id ? [ui.dim(row("info", "Installation id", id))] : [],
5238
6258
  "",
5239
- " Not paired, which is fine: the screen saver and the live view above work",
5240
- " without it. Nothing leaves this machine and nothing is queued. To send your",
5241
- " sessions to Ascenda's servers, so they appear in the app:",
6259
+ " Not paired, which is fine: the screen saver, the live view and the local",
6260
+ " event log work without it. Nothing leaves this machine and nothing is queued.",
6261
+ " To send your sessions to Ascenda's servers, so they appear in the app:",
5242
6262
  ` ${ui.cyan(`${cliAgentSelfCommand(spec)} setup`)}`
5243
6263
  ];
5244
6264
  }
@@ -5259,7 +6279,7 @@ ${serialised}`);
5259
6279
  const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
5260
6280
  const hooks = { ...settings.hooks ?? {} };
5261
6281
  for (const event of Object.keys(hooks)) {
5262
- const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
6282
+ const kept = withoutOurEntries(hooks[event], spec);
5263
6283
  if (kept.length)
5264
6284
  hooks[event] = kept;
5265
6285
  else
@@ -5268,9 +6288,8 @@ ${serialised}`);
5268
6288
  const updated = { ...settings, hooks };
5269
6289
  if (!Object.keys(hooks).length)
5270
6290
  delete updated.hooks;
5271
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5272
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5273
- `, "utf8");
6291
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
6292
+ `);
5274
6293
  return true;
5275
6294
  } catch {
5276
6295
  return false;
@@ -5342,7 +6361,9 @@ var require_turnState = __commonJS({
5342
6361
  }();
5343
6362
  Object.defineProperty(exports, "__esModule", { value: true });
5344
6363
  exports.recordTurnStart = recordTurnStart;
6364
+ exports.readTurnPromptId = readTurnPromptId;
5345
6365
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
6366
+ var crypto_1 = __require("crypto");
5346
6367
  var fs = __importStar(__require("fs"));
5347
6368
  var path = __importStar(__require("path"));
5348
6369
  var tokenStore_1 = require_tokenStore();
@@ -5355,11 +6376,24 @@ var require_turnState = __commonJS({
5355
6376
  }
5356
6377
  function recordTurnStart(agent, sessionId, now = Date.now()) {
5357
6378
  if (!sessionId)
5358
- return;
6379
+ return void 0;
5359
6380
  try {
6381
+ const promptId = (0, crypto_1.randomUUID)();
5360
6382
  fs.mkdirSync(stateDir(), { recursive: true });
5361
- fs.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
6383
+ fs.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
6384
+ return promptId;
6385
+ } catch {
6386
+ return void 0;
6387
+ }
6388
+ }
6389
+ function readTurnPromptId(agent, sessionId) {
6390
+ if (!sessionId)
6391
+ return void 0;
6392
+ try {
6393
+ const id = fs.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
6394
+ return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
5362
6395
  } catch {
6396
+ return void 0;
5363
6397
  }
5364
6398
  }
5365
6399
  function consumeTurnDurationMs(agent, sessionId, now = Date.now()) {
@@ -5367,7 +6401,7 @@ var require_turnState = __commonJS({
5367
6401
  return void 0;
5368
6402
  const file = turnFile(agent, sessionId);
5369
6403
  try {
5370
- const started = Number(fs.readFileSync(file, "utf8").trim());
6404
+ const started = Number(fs.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
5371
6405
  fs.rmSync(file, { force: true });
5372
6406
  if (!Number.isFinite(started) || started <= 0 || started > now)
5373
6407
  return void 0;
@@ -5519,14 +6553,15 @@ var require_agentProcess = __commonJS({
5519
6553
  });
5520
6554
 
5521
6555
  // ../packages/tool-kit/out/index.js
5522
- var require_out2 = __commonJS({
6556
+ var require_out3 = __commonJS({
5523
6557
  "../packages/tool-kit/out/index.js"(exports) {
5524
6558
  "use strict";
5525
6559
  Object.defineProperty(exports, "__esModule", { value: true });
5526
- 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;
5527
- 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;
5528
- 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;
5529
- 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;
6560
+ 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;
6561
+ 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;
6562
+ 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;
6563
+ 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;
6564
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = void 0;
5530
6565
  var commandClassifier_1 = require_commandClassifier();
5531
6566
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5532
6567
  return commandClassifier_1.classifyCommand;
@@ -5545,9 +6580,16 @@ var require_out2 = __commonJS({
5545
6580
  Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
5546
6581
  return workMilestoneClassifier_1.classifyWorkMilestone;
5547
6582
  } });
6583
+ Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
6584
+ return workMilestoneClassifier_1.classifyMcpWorkMilestone;
6585
+ } });
5548
6586
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
5549
6587
  return workMilestoneClassifier_1.invitesDebrief;
5550
6588
  } });
6589
+ var shellFacts_1 = require_shellFacts();
6590
+ Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
6591
+ return shellFacts_1.shellCommandFacts;
6592
+ } });
5551
6593
  var autonomyBand_1 = require_autonomyBand();
5552
6594
  Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
5553
6595
  return autonomyBand_1.autonomyBand;
@@ -5617,6 +6659,28 @@ var require_out2 = __commonJS({
5617
6659
  Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
5618
6660
  return collectorVersion_1.describeCollectorVersion;
5619
6661
  } });
6662
+ var backgroundDelivery_1 = require_backgroundDelivery();
6663
+ Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
6664
+ return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
6665
+ } });
6666
+ Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
6667
+ return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
6668
+ } });
6669
+ Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
6670
+ return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
6671
+ } });
6672
+ Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
6673
+ return backgroundDelivery_1.flushLockPath;
6674
+ } });
6675
+ Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
6676
+ return backgroundDelivery_1.hookDeliveryInline;
6677
+ } });
6678
+ Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
6679
+ return backgroundDelivery_1.runOutboxFlush;
6680
+ } });
6681
+ Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
6682
+ return backgroundDelivery_1.startBackgroundFlush;
6683
+ } });
5620
6684
  var eventSender_1 = require_eventSender();
5621
6685
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
5622
6686
  return eventSender_1.AscendaEventSender;
@@ -5627,19 +6691,41 @@ var require_out2 = __commonJS({
5627
6691
  Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
5628
6692
  return eventSender_1.TOKEN_RENEW_LEAD_MS;
5629
6693
  } });
6694
+ Object.defineProperty(exports, "buildEventBody", { enumerable: true, get: function() {
6695
+ return eventSender_1.buildEventBody;
6696
+ } });
5630
6697
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
5631
6698
  return eventSender_1.buildEventPayload;
5632
6699
  } });
6700
+ var agentEvent_1 = require_agentEvent();
6701
+ Object.defineProperty(exports, "toAgentEvent", { enumerable: true, get: function() {
6702
+ return agentEvent_1.toAgentEvent;
6703
+ } });
5633
6704
  var eventLog_1 = require_eventLog();
5634
6705
  Object.defineProperty(exports, "EVENT_LOG_ENV_VAR", { enumerable: true, get: function() {
5635
6706
  return eventLog_1.EVENT_LOG_ENV_VAR;
5636
6707
  } });
6708
+ Object.defineProperty(exports, "EVENT_LOG_OFF", { enumerable: true, get: function() {
6709
+ return eventLog_1.EVENT_LOG_OFF;
6710
+ } });
5637
6711
  Object.defineProperty(exports, "appendEventLog", { enumerable: true, get: function() {
5638
6712
  return eventLog_1.appendEventLog;
5639
6713
  } });
6714
+ Object.defineProperty(exports, "defaultEventLogPath", { enumerable: true, get: function() {
6715
+ return eventLog_1.defaultEventLogPath;
6716
+ } });
6717
+ Object.defineProperty(exports, "describeEventLog", { enumerable: true, get: function() {
6718
+ return eventLog_1.describeEventLog;
6719
+ } });
5640
6720
  Object.defineProperty(exports, "expandUserPath", { enumerable: true, get: function() {
5641
6721
  return eventLog_1.expandUserPath;
5642
6722
  } });
6723
+ Object.defineProperty(exports, "parseEventLogFlag", { enumerable: true, get: function() {
6724
+ return eventLog_1.parseEventLogFlag;
6725
+ } });
6726
+ Object.defineProperty(exports, "resolveEventLog", { enumerable: true, get: function() {
6727
+ return eventLog_1.resolveEventLog;
6728
+ } });
5643
6729
  Object.defineProperty(exports, "resolveEventLogPath", { enumerable: true, get: function() {
5644
6730
  return eventLog_1.resolveEventLogPath;
5645
6731
  } });
@@ -5653,9 +6739,18 @@ var require_out2 = __commonJS({
5653
6739
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
5654
6740
  return hookAdapter_1.deliverHookEvents;
5655
6741
  } });
6742
+ Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
6743
+ return hookAdapter_1.flushHookOutbox;
6744
+ } });
5656
6745
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
5657
6746
  return hookAdapter_1.loadCliAgentConfig;
5658
6747
  } });
6748
+ Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
6749
+ return hookAdapter_1.withForgeKeys;
6750
+ } });
6751
+ Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
6752
+ return hookAdapter_1.withPromptId;
6753
+ } });
5659
6754
  Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
5660
6755
  return hookAdapter_1.resolveCliAgentInstallationId;
5661
6756
  } });
@@ -5672,12 +6767,18 @@ var require_out2 = __commonJS({
5672
6767
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
5673
6768
  return cliAgentSetup_1.isCliAgentManagementCommand;
5674
6769
  } });
6770
+ Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
6771
+ return cliAgentSetup_1.ourHookPositions;
6772
+ } });
5675
6773
  Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5676
6774
  return cliAgentSetup_1.registeredHookSets;
5677
6775
  } });
5678
6776
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
5679
6777
  return cliAgentSetup_1.runCliAgentSetup;
5680
6778
  } });
6779
+ Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
6780
+ return cliAgentSetup_1.trustProblemLines;
6781
+ } });
5681
6782
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
5682
6783
  return cliAgentSetup_1.writeHookSettings;
5683
6784
  } });
@@ -5716,6 +6817,12 @@ var require_out2 = __commonJS({
5716
6817
  Object.defineProperty(exports, "writeHostCredentials", { enumerable: true, get: function() {
5717
6818
  return credentials_1.writeHostCredentials;
5718
6819
  } });
6820
+ Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
6821
+ return credentials_1.writeEventLogSetting;
6822
+ } });
6823
+ Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
6824
+ return credentials_1.writeRepoKeysSetting;
6825
+ } });
5719
6826
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5720
6827
  return credentials_1.writeMachineCredentials;
5721
6828
  } });
@@ -5726,6 +6833,9 @@ var require_out2 = __commonJS({
5726
6833
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
5727
6834
  return turnState_1.consumeTurnDurationMs;
5728
6835
  } });
6836
+ Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
6837
+ return turnState_1.readTurnPromptId;
6838
+ } });
5729
6839
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
5730
6840
  return turnState_1.recordTurnStart;
5731
6841
  } });
@@ -5860,6 +6970,12 @@ var require_out2 = __commonJS({
5860
6970
  Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
5861
6971
  return forgeProject_1.forgeProjectHash;
5862
6972
  } });
6973
+ Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
6974
+ return forgeProject_1.forgeRepoKey;
6975
+ } });
6976
+ Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
6977
+ return forgeProject_1.forgeBranchKey;
6978
+ } });
5863
6979
  Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
5864
6980
  return forgeProject_1.parseForgeFullName;
5865
6981
  } });
@@ -5872,6 +6988,16 @@ var require_out2 = __commonJS({
5872
6988
  Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
5873
6989
  return forgeProject_1.recordForgeProjectAlias;
5874
6990
  } });
6991
+ var forgeKeys_1 = require_forgeKeys();
6992
+ Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
6993
+ return forgeKeys_1.REPO_KEYS_ENV_VAR;
6994
+ } });
6995
+ Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
6996
+ return forgeKeys_1.deriveForgeKeysForCwd;
6997
+ } });
6998
+ Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
6999
+ return forgeKeys_1.repoKeysEnabled;
7000
+ } });
5875
7001
  var liveBus_1 = require_liveBus();
5876
7002
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
5877
7003
  return liveBus_1.emitLiveSignal;
@@ -5942,6 +7068,9 @@ var require_out2 = __commonJS({
5942
7068
  Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
5943
7069
  return hookRunner_1.installHookRunner;
5944
7070
  } });
7071
+ Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
7072
+ return hookRunner_1.isDowngrade;
7073
+ } });
5945
7074
  Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
5946
7075
  return hookRunner_1.lastHookPath;
5947
7076
  } });
@@ -5960,6 +7089,13 @@ var require_out2 = __commonJS({
5960
7089
  Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
5961
7090
  return hookRunner_1.tidyHomePath;
5962
7091
  } });
7092
+ Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
7093
+ return hookRunner_1.writeAtomically;
7094
+ } });
7095
+ var settingsFile_1 = require_settingsFile();
7096
+ Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
7097
+ return settingsFile_1.replaceSettingsFile;
7098
+ } });
5963
7099
  var liveSignalDoctor_1 = require_liveSignalDoctor();
5964
7100
  Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
5965
7101
  return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
@@ -19093,7 +20229,7 @@ var StdioServerTransport = class {
19093
20229
  };
19094
20230
 
19095
20231
  // src/config.ts
19096
- var import_tool_kit = __toESM(require_out2(), 1);
20232
+ var import_tool_kit = __toESM(require_out3(), 1);
19097
20233
  import { randomUUID } from "node:crypto";
19098
20234
  function loadConfigFromEnv() {
19099
20235
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
@@ -27222,7 +28358,7 @@ var EMPTY_COMPLETION_RESULT = {
27222
28358
  };
27223
28359
 
27224
28360
  // src/server.ts
27225
- var import_tool_kit2 = __toESM(require_out2(), 1);
28361
+ var import_tool_kit2 = __toESM(require_out3(), 1);
27226
28362
  var import_tool_contract = __toESM(require_out(), 1);
27227
28363
  var RESERVED_METADATA_KEYS = /* @__PURE__ */ new Set([
27228
28364
  "skillVersion",