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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -156,25 +156,66 @@ var require_gitActionClassifier = __commonJS({
156
156
  if (!/\bgit\b/.test(value))
157
157
  return void 0;
158
158
  const heads = (0, commandHeads_1.commandHeads)(value);
159
- if (heads.some((h) => /^git\s+commit\b/.test(h) && /\s--amend\b/.test(h)))
159
+ const commands = heads.map(parseGitCommand).filter((c) => c !== void 0);
160
+ if (commands.some((c) => c.verb === "commit" && c.args.includes("--amend")))
160
161
  return "amend";
161
- if (heads.some((h) => /^git\s+revert\b/.test(h)))
162
+ if (commands.some((c) => c.verb === "revert"))
162
163
  return "revert";
163
- if (heads.some((h) => /^git\s+reset\b/.test(h) && /\s--hard\b/.test(h)))
164
+ if (commands.some((c) => c.verb === "reset" && c.args.includes("--hard")))
164
165
  return "reset_hard";
165
- if (heads.some((h) => /^git\s+restore\b/.test(h) && !/\s--staged\b/.test(h)))
166
+ if (commands.some(discardsWork))
166
167
  return "restore";
167
- if (heads.some((h) => /^git\s+checkout\b.*\s--\s/.test(h)))
168
- return "restore";
169
- if (heads.some((h) => /^git\s+push\b/.test(h)))
168
+ if (commands.some((c) => c.verb === "push"))
170
169
  return "push";
171
- if (heads.some((h) => /^git\s+commit\b/.test(h)))
170
+ if (commands.some((c) => c.verb === "commit"))
172
171
  return "commit";
173
172
  return void 0;
174
173
  }
175
174
  function isReworkGitAction2(action) {
176
175
  return action === "revert" || action === "reset_hard" || action === "restore";
177
176
  }
177
+ var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path"]);
178
+ function parseGitCommand(head) {
179
+ const words = head.split(/\s+/);
180
+ if (words[0] !== "git")
181
+ return void 0;
182
+ let i = 1;
183
+ while (i < words.length && words[i].startsWith("-")) {
184
+ i += GLOBAL_OPTIONS_WITH_VALUE.has(words[i]) ? 2 : 1;
185
+ }
186
+ if (i >= words.length)
187
+ return void 0;
188
+ return { verb: words[i], args: words.slice(i + 1) };
189
+ }
190
+ function discardsWork({ verb, args }) {
191
+ switch (verb) {
192
+ case "restore":
193
+ return !args.includes("--staged");
194
+ case "switch":
195
+ return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
196
+ case "clean": {
197
+ const flags = args.filter((a) => /^-[a-z]+$/.test(a)).join("");
198
+ const dryRun = args.includes("--dry-run") || flags.includes("n");
199
+ return !dryRun && (args.includes("--force") || flags.includes("f"));
200
+ }
201
+ case "checkout":
202
+ return checkoutDiscards(args);
203
+ default:
204
+ return false;
205
+ }
206
+ }
207
+ function checkoutDiscards(args) {
208
+ if (args.includes("--"))
209
+ return true;
210
+ if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
211
+ return false;
212
+ const words = args.filter((a) => !a.startsWith("-"));
213
+ if (words.length >= 2)
214
+ return true;
215
+ if (words.length === 1)
216
+ return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
217
+ return false;
218
+ }
178
219
  }
179
220
  });
180
221
 
@@ -185,6 +226,7 @@ var require_workMilestoneClassifier = __commonJS({
185
226
  Object.defineProperty(exports, "__esModule", { value: true });
186
227
  exports.classifyWorkMilestone = classifyWorkMilestone2;
187
228
  exports.invitesDebrief = invitesDebrief2;
229
+ exports.classifyMcpWorkMilestone = classifyMcpWorkMilestone2;
188
230
  var commandHeads_1 = require_commandHeads();
189
231
  function classifyWorkMilestone2(command) {
190
232
  if (!command)
@@ -204,6 +246,41 @@ var require_workMilestoneClassifier = __commonJS({
204
246
  function invitesDebrief2(kind) {
205
247
  return kind === "pr_merged" || kind === "issue_closed";
206
248
  }
249
+ function classifyMcpWorkMilestone2(toolName) {
250
+ if (!toolName)
251
+ return void 0;
252
+ const parts = toolName.toLowerCase().split("__");
253
+ if (parts[0] !== "mcp" || parts.length < 3)
254
+ return void 0;
255
+ const tool = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
256
+ if (/^(merge|accept)(pullrequest|mergerequest)$/.test(tool))
257
+ return "pr_merged";
258
+ if (/^closeissue$/.test(tool))
259
+ return "issue_closed";
260
+ if (/^(create|open)(pullrequest|mergerequest)$/.test(tool))
261
+ return "pr_opened";
262
+ return void 0;
263
+ }
264
+ }
265
+ });
266
+
267
+ // ../packages/tool-kit/out/shellFacts.js
268
+ var require_shellFacts = __commonJS({
269
+ "../packages/tool-kit/out/shellFacts.js"(exports) {
270
+ "use strict";
271
+ Object.defineProperty(exports, "__esModule", { value: true });
272
+ exports.shellCommandFacts = shellCommandFacts;
273
+ var gitActionClassifier_1 = require_gitActionClassifier();
274
+ var workMilestoneClassifier_1 = require_workMilestoneClassifier();
275
+ function shellCommandFacts(command) {
276
+ const gitAction = (0, gitActionClassifier_1.classifyGitAction)(command);
277
+ const milestoneKind = (0, workMilestoneClassifier_1.classifyWorkMilestone)(command);
278
+ return {
279
+ ...gitAction !== void 0 ? { gitAction } : {},
280
+ ...(0, gitActionClassifier_1.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
281
+ ...milestoneKind !== void 0 ? { milestoneKind } : {}
282
+ };
283
+ }
207
284
  }
208
285
  });
209
286
 
@@ -597,6 +674,61 @@ var require_metricKeys = __commonJS({
597
674
  subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
598
675
  subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
599
676
  subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
677
+ advisorMessageCount: {
678
+ family: "counts",
679
+ readBy: ["diagnostic"],
680
+ note: "Claude Code only: advisor calls (a second model consulted inside one API message). Their tokens and models are already folded into the session totals and model mix, and this is the receipt for how much of that they are."
681
+ },
682
+ advisorTokensTotal: {
683
+ family: "context",
684
+ readBy: ["diagnostic"],
685
+ unit: "tokens",
686
+ note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
687
+ },
688
+ cacheCreationTokens: {
689
+ family: "context",
690
+ readBy: ["diagnostic"],
691
+ unit: "tokens",
692
+ note: "Prompt-cache writes, summed once per API message. Absent where the store never wrote the figure, which is not the same as none written."
693
+ },
694
+ cacheCreation5mTokens: {
695
+ family: "context",
696
+ readBy: ["diagnostic"],
697
+ unit: "tokens",
698
+ note: "The part of cacheCreationTokens written with the 5-minute lifetime. Absent on transcripts that only record the total."
699
+ },
700
+ cacheCreation1hTokens: {
701
+ family: "context",
702
+ readBy: ["diagnostic"],
703
+ unit: "tokens",
704
+ note: "The part of cacheCreationTokens written with the 1-hour lifetime. Absent on transcripts that only record the total."
705
+ },
706
+ headlessPromptLines: {
707
+ family: "reading",
708
+ readBy: ["diagnostic"],
709
+ unit: "lines",
710
+ note: "Claude Code only: user lines written by the Agent SDK or a headless run (entrypoint sdk-*). Nobody typed them, so promptCount leaves them out. Counted once per line across the store."
711
+ },
712
+ tokensNotCollected: {
713
+ family: "context",
714
+ readBy: ["diagnostic"],
715
+ note: "True when the store recorded no token figures for this session (Cursor builds that write a zero tokenCount, Codex rollouts from before token_count events). The token keys are then left off the event instead of being sent as 0, so absent and zero stay apart. Metrics are flat scalars with no null, so a flag beside the missing keys is the marker the contract allows."
716
+ },
717
+ unattributedSubagentTranscripts: {
718
+ family: "reading",
719
+ readBy: ["diagnostic"],
720
+ note: "Claude Code only: flat subagent transcripts whose lines name no parent session, so they could not be folded anywhere."
721
+ },
722
+ duplicateChatSessions: {
723
+ family: "reading",
724
+ readBy: ["diagnostic"],
725
+ note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
726
+ },
727
+ sessionsStartedFromBubble: {
728
+ family: "reading",
729
+ readBy: ["diagnostic"],
730
+ note: "Cursor only: sessions whose start is the earliest message rather than the header's createdAt, which can sit months before anyone typed."
731
+ },
600
732
  toolName: {
601
733
  family: "tools",
602
734
  readBy: ["backend"],
@@ -704,7 +836,9 @@ var require_out = __commonJS({
704
836
  exports.COLLABORATION_EVENT_TYPES = [
705
837
  "review_requested_of_me",
706
838
  "review_given",
707
- "pull_request_opened"
839
+ "pull_request_opened",
840
+ "pull_request_closed",
841
+ "pull_request_merged"
708
842
  ];
709
843
  exports.EVENT_METADATA_DISCLOSURE = {
710
844
  language: "edits",
@@ -716,6 +850,13 @@ var require_out = __commonJS({
716
850
  gitAction: "git",
717
851
  milestoneKind: "git",
718
852
  branchHash: "repo",
853
+ repoKey: "forge",
854
+ headRepoKey: "forge",
855
+ prCreatedAt: "git",
856
+ prClosedAt: "git",
857
+ prMergedAt: "git",
858
+ branchKey: "forge",
859
+ promptId: "turns",
719
860
  autonomyMode: "posture",
720
861
  modelClass: "model",
721
862
  modelId: "model",
@@ -765,6 +906,13 @@ var require_out = __commonJS({
765
906
  "gitAction",
766
907
  "milestoneKind",
767
908
  "branchHash",
909
+ "repoKey",
910
+ "headRepoKey",
911
+ "prCreatedAt",
912
+ "prClosedAt",
913
+ "prMergedAt",
914
+ "branchKey",
915
+ "promptId",
768
916
  "autonomyMode",
769
917
  "modelClass",
770
918
  "modelId",
@@ -834,6 +982,10 @@ var require_out = __commonJS({
834
982
  review_requested_of_me: "supervision",
835
983
  review_given: "supervision",
836
984
  pull_request_opened: "creation",
985
+ // Where a pull request of yours ended up. A boundary like a turn ending, not
986
+ // work in itself, so neutral: it must not weigh on any workload leg.
987
+ pull_request_closed: "neutral",
988
+ pull_request_merged: "neutral",
837
989
  context_pressure_high: "risk",
838
990
  agent_loop_long: "risk",
839
991
  after_hours_ai_session: "risk",
@@ -864,6 +1016,16 @@ var require_out = __commonJS({
864
1016
  // step toward an interruption count becoming a score, a streak, or something
865
1017
  // that fires on a miss. It must never become any of those.
866
1018
  supervision_interruption: "supervision",
1019
+ // The agent asked to run a tool, and the auto-mode classifier refused one.
1020
+ // Claude Code's `PermissionRequest` and `PermissionDenied` hooks. Neutral,
1021
+ // because the Notification for the same prompt is already counted above as
1022
+ // `supervision_interruption`, and counting both would weigh one prompt
1023
+ // twice. These rows exist for the public event stream: which tool asked, and
1024
+ // under which posture. `permission_requested` fires before the person
1025
+ // answers and no hook reports their answer, so neither event says whether
1026
+ // the request was granted.
1027
+ permission_requested: "neutral",
1028
+ permission_denied: "neutral",
867
1029
  // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
868
1030
  approach_churn_detected: "risk",
869
1031
  goal_drift_detected: "risk",
@@ -988,122 +1150,13 @@ var require_collectorVersion = __commonJS({
988
1150
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
989
1151
  exports.describeCollectorVersion = describeCollectorVersion2;
990
1152
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
991
- exports.COLLECTOR_VERSION = "0.1.35" ? "0.1.35" : exports.UNRELEASED_COLLECTOR_VERSION;
1153
+ exports.COLLECTOR_VERSION = "0.1.36" ? "0.1.36" : exports.UNRELEASED_COLLECTOR_VERSION;
992
1154
  function describeCollectorVersion2(version = exports.COLLECTOR_VERSION) {
993
1155
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
994
1156
  }
995
1157
  }
996
1158
  });
997
1159
 
998
- // ../packages/agent-events/out/index.js
999
- var require_out2 = __commonJS({
1000
- "../packages/agent-events/out/index.js"(exports) {
1001
- "use strict";
1002
- Object.defineProperty(exports, "__esModule", { value: true });
1003
- exports.KNOWN_AGENTS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1004
- exports.isAgentEventV0 = isAgentEventV0;
1005
- exports.parseEventLogLine = parseEventLogLine;
1006
- exports.normaliseKind = normaliseKind;
1007
- exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1008
- exports.AGENT_EVENT_KINDS = [
1009
- "session.started",
1010
- "session.ended",
1011
- "prompt.submitted",
1012
- "tool.started",
1013
- "tool.completed",
1014
- "tool.failed",
1015
- "turn.completed",
1016
- "agent.waiting",
1017
- "context.compacted",
1018
- "subagent.started",
1019
- "subagent.stopped",
1020
- "other"
1021
- ];
1022
- exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1023
- function isAgentEventV0(value) {
1024
- if (!value || typeof value !== "object")
1025
- return false;
1026
- const e = value;
1027
- 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";
1028
- }
1029
- function parseEventLogLine(line) {
1030
- if (!line.trim())
1031
- return void 0;
1032
- try {
1033
- const parsed = JSON.parse(line);
1034
- return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1035
- } catch {
1036
- return void 0;
1037
- }
1038
- }
1039
- function normaliseKind(kind) {
1040
- return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1041
- }
1042
- }
1043
- });
1044
-
1045
- // ../packages/tool-kit/out/agentEvent.js
1046
- var require_agentEvent = __commonJS({
1047
- "../packages/tool-kit/out/agentEvent.js"(exports) {
1048
- "use strict";
1049
- Object.defineProperty(exports, "__esModule", { value: true });
1050
- exports.toAgentEvent = toAgentEvent;
1051
- var agent_events_1 = require_out2();
1052
- var KIND_BY_TYPE = {
1053
- create_focus_session: "session.started",
1054
- recovery_offline_period: "session.ended",
1055
- ai_prompt_submitted: "prompt.submitted",
1056
- ai_tool_call_started: "tool.started",
1057
- ai_tool_call_completed: "tool.completed",
1058
- ai_file_write: "tool.completed",
1059
- ai_file_edit: "tool.completed",
1060
- editor_verification_activity: "tool.completed",
1061
- ai_tool_call_failed: "tool.failed",
1062
- compile_error: "tool.failed",
1063
- tool_failure: "tool.failed",
1064
- ai_turn_completed: "turn.completed",
1065
- supervision_interruption: "agent.waiting",
1066
- context_compression_manual: "context.compacted",
1067
- context_compression_auto: "context.compacted",
1068
- subagent_started: "subagent.started",
1069
- subagent_stopped: "subagent.stopped"
1070
- };
1071
- function agentOf(payload) {
1072
- const host = stringField(payload.metadata?.host);
1073
- if (host)
1074
- return host;
1075
- return payload.source === "vscode_extension" ? "vscode" : payload.source;
1076
- }
1077
- function stringField(value) {
1078
- return typeof value === "string" && value.length > 0 ? value : void 0;
1079
- }
1080
- function toAgentEvent(payload) {
1081
- const metadata = payload.metadata ?? {};
1082
- const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1083
- const tool = kind.startsWith("tool.") ? stringField(metadata.toolName) : void 0;
1084
- const outcome = stringField(metadata.outcome);
1085
- return {
1086
- schema: agent_events_1.AGENT_EVENT_SCHEMA,
1087
- id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1088
- time: payload.occurredAt,
1089
- // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1090
- // writes anyway; without it the event in memory and the one on disk differ.
1091
- ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1092
- agent: agentOf(payload),
1093
- kind,
1094
- ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1095
- ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1096
- ...tool ? { tool } : {},
1097
- ...outcome && outcome !== "unknown" ? { outcome } : {},
1098
- ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1099
- ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1100
- ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1101
- sourceType: payload.eventType
1102
- };
1103
- }
1104
- }
1105
- });
1106
-
1107
1160
  // ../packages/tool-kit/out/tokenStore.js
1108
1161
  var require_tokenStore = __commonJS({
1109
1162
  "../packages/tool-kit/out/tokenStore.js"(exports) {
@@ -1156,9 +1209,9 @@ var require_tokenStore = __commonJS({
1156
1209
  exports.readTokenFile = readTokenFile3;
1157
1210
  exports.sanitizeFilePart = sanitizeFilePart;
1158
1211
  var fs5 = __importStar(__require("fs"));
1159
- var os5 = __importStar(__require("os"));
1212
+ var os4 = __importStar(__require("os"));
1160
1213
  var path4 = __importStar(__require("path"));
1161
- function ascendaHome3(home = os5.homedir()) {
1214
+ function ascendaHome3(home = os4.homedir()) {
1162
1215
  return process.env.ASCENDA_HOME ?? path4.join(home, ".ascenda");
1163
1216
  }
1164
1217
  function defaultTokenFilePath4(toolInstallationId) {
@@ -1242,9 +1295,9 @@ var require_tokenStore = __commonJS({
1242
1295
  }
1243
1296
  });
1244
1297
 
1245
- // ../packages/tool-kit/out/credentials.js
1246
- var require_credentials = __commonJS({
1247
- "../packages/tool-kit/out/credentials.js"(exports) {
1298
+ // ../packages/tool-kit/out/stateStore.js
1299
+ var require_stateStore = __commonJS({
1300
+ "../packages/tool-kit/out/stateStore.js"(exports) {
1248
1301
  "use strict";
1249
1302
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1250
1303
  if (k2 === void 0) k2 = k;
@@ -1284,94 +1337,124 @@ var require_credentials = __commonJS({
1284
1337
  };
1285
1338
  }();
1286
1339
  Object.defineProperty(exports, "__esModule", { value: true });
1287
- exports.credentialsFilePath = credentialsFilePath2;
1288
- exports.readMachineCredentials = readMachineCredentials2;
1289
- exports.writeMachineCredentials = writeMachineCredentials2;
1290
- exports.writeTopLevelCredentials = writeTopLevelCredentials2;
1291
- exports.writeEventLogSetting = writeEventLogSetting2;
1292
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
1293
- exports.readHostCredentials = readHostCredentials;
1294
- exports.writeHostCredentials = writeHostCredentials;
1295
- exports.removeHostCredentials = removeHostCredentials;
1340
+ exports.defaultStateFilePath = defaultStateFilePath2;
1341
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId2;
1342
+ exports.unresolvedStateFilePath = unresolvedStateFilePath2;
1343
+ exports.readCollectorState = readCollectorState2;
1344
+ exports.recordSendOutcome = recordSendOutcome2;
1345
+ exports.recordOutboxDiscard = recordOutboxDiscard;
1346
+ exports.shouldAnnounceFailure = shouldAnnounceFailure2;
1347
+ exports.markFailureNotified = markFailureNotified2;
1296
1348
  var fs5 = __importStar(__require("fs"));
1297
1349
  var path4 = __importStar(__require("path"));
1298
1350
  var tokenStore_1 = require_tokenStore();
1299
- function credentialsFilePath2() {
1300
- return path4.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1351
+ function defaultStateFilePath2(toolInstallationId) {
1352
+ const dir = process.env.ASCENDA_STATE_DIR?.trim();
1353
+ const base = dir ? dir : path4.join((0, tokenStore_1.ascendaHome)(), "state");
1354
+ return path4.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1301
1355
  }
1302
- function readMachineCredentials2() {
1356
+ function unresolvedToolInstallationId2(toolType) {
1357
+ return `${toolType}:unresolved`;
1358
+ }
1359
+ function unresolvedStateFilePath2(toolType) {
1360
+ return defaultStateFilePath2(unresolvedToolInstallationId2(toolType));
1361
+ }
1362
+ function readCollectorState2(stateFilePath) {
1303
1363
  try {
1304
- const raw = fs5.readFileSync(credentialsFilePath2(), "utf8").trim();
1364
+ if (!fs5.existsSync(stateFilePath))
1365
+ return void 0;
1366
+ const raw = fs5.readFileSync(stateFilePath, "utf8").trim();
1305
1367
  if (!raw)
1306
1368
  return void 0;
1307
1369
  const parsed = JSON.parse(raw);
1308
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1370
+ if (!parsed || typeof parsed !== "object")
1309
1371
  return void 0;
1310
1372
  return parsed;
1311
1373
  } catch {
1312
1374
  return void 0;
1313
1375
  }
1314
1376
  }
1315
- function writeMachineCredentials2(credentials) {
1316
- const file = credentialsFilePath2();
1317
- fs5.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
1318
- fs5.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
1319
- `, { encoding: "utf8", mode: 384 });
1320
- if (process.platform !== "win32") {
1321
- fs5.chmodSync(path4.dirname(file), 448);
1322
- fs5.chmodSync(file, 384);
1323
- }
1324
- }
1325
- function writeTopLevelCredentials2(credentials) {
1326
- const existing = readMachineCredentials2();
1327
- const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
1328
- writeMachineCredentials2({
1329
- ...credentials,
1330
- ...eventLogPath ? { eventLogPath } : {},
1331
- ...existing?.tools ? { tools: existing.tools } : {}
1332
- });
1377
+ function recordSendOutcome2(stateFilePath, toolInstallationId, outcome, detail = {}) {
1378
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1379
+ const previous = readCollectorState2(stateFilePath);
1380
+ const accepted = outcome === "accepted";
1381
+ const next = {
1382
+ toolInstallationId,
1383
+ lastAttemptAt: now,
1384
+ lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1385
+ lastOutcome: outcome,
1386
+ consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1387
+ ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1388
+ ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1389
+ ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1390
+ // A success closes the episode; a failure either opens one or continues
1391
+ // the one already open. Carrying `notifiedFailingSince` across a
1392
+ // continuing episode is what keeps the notice to once per outage.
1393
+ ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1394
+ ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1395
+ // Cumulative by design: a send outcome, success included, never erases
1396
+ // the record of what the outbox had to throw away.
1397
+ ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1398
+ };
1399
+ writeStateFile(stateFilePath, next);
1400
+ return next;
1333
1401
  }
1334
- function writeEventLogSetting2(value) {
1335
- const existing = readMachineCredentials2() ?? {};
1336
- writeMachineCredentials2({ ...existing, eventLogPath: value });
1402
+ function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1403
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1404
+ const previous = readCollectorState2(stateFilePath);
1405
+ const next = {
1406
+ ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1407
+ toolInstallationId,
1408
+ lastOutcome: "outbox_discarded",
1409
+ outboxDiscarded: {
1410
+ total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1411
+ lastAt: now,
1412
+ lastCount: discard.count,
1413
+ lastReasons: discard.reasons,
1414
+ ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1415
+ }
1416
+ };
1417
+ writeStateFile(stateFilePath, next);
1418
+ return next;
1337
1419
  }
1338
- function isLocalOnlyHostInstall(host, hasToken) {
1339
- const credentials = readHostCredentials(host);
1340
- if (!credentials?.localOnly)
1341
- return false;
1342
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
1420
+ function shouldAnnounceFailure2(state) {
1421
+ if (!state || state.consecutiveFailures === 0 || !state.failingSince)
1343
1422
  return false;
1344
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1423
+ return state.notifiedFailingSince !== state.failingSince;
1345
1424
  }
1346
- function readHostCredentials(host) {
1347
- const entry = readMachineCredentials2()?.tools?.[host];
1348
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
1349
- return void 0;
1350
- return entry;
1425
+ function markFailureNotified2(stateFilePath, state) {
1426
+ if (!state.failingSince)
1427
+ return;
1428
+ writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
1351
1429
  }
1352
- function writeHostCredentials(host, credentials) {
1353
- const existing = readMachineCredentials2() ?? {};
1354
- writeMachineCredentials2({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1430
+ function writeStateFile(stateFilePath, state) {
1431
+ const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1432
+ try {
1433
+ const dir = path4.dirname(stateFilePath);
1434
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1435
+ fs5.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1436
+ `, { encoding: "utf8", mode: 384 });
1437
+ fs5.renameSync(temporaryPath, stateFilePath);
1438
+ if (process.platform !== "win32")
1439
+ fs5.chmodSync(stateFilePath, 384);
1440
+ } catch {
1441
+ try {
1442
+ if (fs5.existsSync(temporaryPath))
1443
+ fs5.unlinkSync(temporaryPath);
1444
+ } catch {
1445
+ }
1446
+ }
1355
1447
  }
1356
- function removeHostCredentials(host) {
1357
- const existing = readMachineCredentials2();
1358
- if (!existing?.tools || !(host in existing.tools))
1359
- return;
1360
- const tools = { ...existing.tools };
1361
- delete tools[host];
1362
- const next = { ...existing };
1363
- if (Object.keys(tools).length)
1364
- next.tools = tools;
1365
- else
1366
- delete next.tools;
1367
- writeMachineCredentials2(next);
1448
+ function truncate(value) {
1449
+ const collapsed = value.replace(/\s+/g, " ").trim();
1450
+ return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
1368
1451
  }
1369
1452
  }
1370
1453
  });
1371
1454
 
1372
- // ../packages/tool-kit/out/eventLog.js
1373
- var require_eventLog = __commonJS({
1374
- "../packages/tool-kit/out/eventLog.js"(exports) {
1455
+ // ../packages/tool-kit/out/outbox.js
1456
+ var require_outbox = __commonJS({
1457
+ "../packages/tool-kit/out/outbox.js"(exports) {
1375
1458
  "use strict";
1376
1459
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1377
1460
  if (k2 === void 0) k2 = k;
@@ -1411,354 +1494,492 @@ var require_eventLog = __commonJS({
1411
1494
  };
1412
1495
  }();
1413
1496
  Object.defineProperty(exports, "__esModule", { value: true });
1414
- exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
1415
- exports.expandUserPath = expandUserPath;
1416
- exports.defaultEventLogPath = defaultEventLogPath;
1417
- exports.resolveEventLog = resolveEventLog3;
1418
- exports.resolveEventLogPath = resolveEventLogPath2;
1419
- exports.describeEventLog = describeEventLog3;
1420
- exports.parseEventLogFlag = parseEventLogFlag2;
1421
- exports.appendEventLog = appendEventLog2;
1497
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1498
+ exports.outboxDrainEnabled = outboxDrainEnabled2;
1499
+ exports.defaultOutboxFilePath = defaultOutboxFilePath2;
1500
+ exports.appendToOutbox = appendToOutbox;
1501
+ exports.readOutboxSummary = readOutboxSummary2;
1502
+ exports.claimOutbox = claimOutbox;
1503
+ exports.enforceOutboxBounds = enforceOutboxBounds;
1422
1504
  var fs5 = __importStar(__require("fs"));
1423
- var os5 = __importStar(__require("os"));
1424
1505
  var path4 = __importStar(__require("path"));
1425
- var agentEvent_1 = require_agentEvent();
1426
- var credentials_1 = require_credentials();
1506
+ var stateStore_1 = require_stateStore();
1427
1507
  var tokenStore_1 = require_tokenStore();
1428
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1429
- exports.EVENT_LOG_OFF = "off";
1430
- var MAX_BYTES = 5 * 1024 * 1024;
1431
- function expandUserPath(configured) {
1432
- const value = configured?.trim();
1433
- if (!value)
1434
- return void 0;
1435
- if (value === "~")
1436
- return os5.homedir();
1437
- if (value.startsWith("~/"))
1438
- return path4.join(os5.homedir(), value.slice(2));
1439
- return path4.resolve(value);
1440
- }
1441
- function defaultEventLogPath() {
1442
- return path4.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1443
- }
1444
- function resolveEventLog3(options = {}) {
1445
- for (const [source, raw] of [
1446
- ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
1447
- ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
1448
- ]) {
1449
- const value = raw?.trim();
1450
- if (!value)
1451
- continue;
1452
- if (value.toLowerCase() === exports.EVENT_LOG_OFF)
1453
- return { path: void 0, source: "disabled" };
1454
- return { path: expandUserPath(value), source };
1455
- }
1456
- if (options.localOnly)
1457
- return { path: defaultEventLogPath(), source: "unpaired-default" };
1458
- return { path: void 0, source: "off" };
1459
- }
1460
- function resolveEventLogPath2(options = {}) {
1461
- return resolveEventLog3(options).path;
1462
- }
1463
- function describeEventLog3(setting, command) {
1464
- switch (setting.source) {
1465
- case "env":
1466
- return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
1467
- case "credentials":
1468
- return `${setting.path} (set by ${command} --event-log)`;
1469
- case "unpaired-default":
1470
- return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
1471
- case "disabled":
1472
- return `off (turned off; ${command} --event-log to turn it on)`;
1473
- case "off":
1474
- return `off (${command} --event-log to keep a local copy of every event)`;
1475
- }
1508
+ exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1509
+ exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1510
+ exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1511
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1512
+ var ORPHANED_CLAIM_AGE_MS = 6e4;
1513
+ var CLAIM_SUFFIX = ".draining";
1514
+ function outboxDrainEnabled2(env = process.env) {
1515
+ const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1516
+ if (value === void 0 || value === "")
1517
+ return true;
1518
+ return !(value === "0" || value === "false" || value === "no" || value === "off");
1476
1519
  }
1477
- function parseEventLogFlag2(argv, index) {
1478
- const peek = argv[index + 1];
1479
- if (peek !== void 0 && !peek.startsWith("-"))
1480
- return { value: peek, consumed: 1 };
1481
- return { value: defaultEventLogPath(), consumed: 0 };
1520
+ function defaultOutboxFilePath2(toolInstallationId) {
1521
+ const dir = path4.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1522
+ return path4.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1482
1523
  }
1483
- function appendEventLog2(logFilePath, entry) {
1524
+ function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1484
1525
  try {
1485
- rotateIfLarge(logFilePath);
1486
- const dir = path4.dirname(logFilePath);
1526
+ const dir = path4.dirname(outboxFilePath);
1487
1527
  fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1488
- const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
1489
- fs5.appendFileSync(logFilePath, `${JSON.stringify(line)}
1528
+ const entry = { queuedAt: now.toISOString(), payload };
1529
+ fs5.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1490
1530
  `, { encoding: "utf8", mode: 384 });
1491
1531
  if (process.platform !== "win32")
1492
- fs5.chmodSync(logFilePath, 384);
1532
+ fs5.chmodSync(outboxFilePath, 384);
1533
+ return true;
1493
1534
  } catch {
1535
+ return false;
1494
1536
  }
1495
1537
  }
1496
- function rotateIfLarge(logFilePath) {
1538
+ function readOutboxSummary2(outboxFilePath) {
1539
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs5.existsSync(file));
1540
+ if (files.length === 0)
1541
+ return void 0;
1542
+ let depth = 0;
1543
+ let unreadableLines = 0;
1544
+ let oldestQueuedAt;
1545
+ for (const file of files) {
1546
+ const { entries, unreadable } = readEntries(file);
1547
+ depth += entries.length;
1548
+ unreadableLines += unreadable;
1549
+ for (const entry of entries) {
1550
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1551
+ oldestQueuedAt = entry.queuedAt;
1552
+ }
1553
+ }
1554
+ return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1555
+ }
1556
+ function claimOutbox(outboxFilePath, now = Date.now()) {
1557
+ const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1558
+ const claimed = [];
1497
1559
  try {
1498
- if (fs5.statSync(logFilePath).size < MAX_BYTES)
1499
- return;
1500
- fs5.renameSync(logFilePath, `${logFilePath}.1`);
1560
+ fs5.renameSync(outboxFilePath, claimPath);
1561
+ claimed.push(claimPath);
1501
1562
  } catch {
1502
1563
  }
1503
- }
1504
- }
1505
- });
1506
-
1507
- // ../packages/tool-kit/out/http.js
1508
- var require_http = __commonJS({
1509
- "../packages/tool-kit/out/http.js"(exports) {
1510
- "use strict";
1511
- Object.defineProperty(exports, "__esModule", { value: true });
1512
- exports.AscendaApiError = void 0;
1513
- exports.createPairingSession = createPairingSession3;
1514
- exports.getPairingStatus = getPairingStatus3;
1515
- exports.startStudyJoin = startStudyJoin;
1516
- exports.getStudyJoinStatus = getStudyJoinStatus;
1517
- exports.readInitiatives = readInitiatives;
1518
- exports.readStudyNotices = readStudyNotices;
1519
- exports.setStudyObjection = setStudyObjection;
1520
- exports.markStudyNoticeShown = markStudyNoticeShown;
1521
- exports.renewToolToken = renewToolToken;
1522
- exports.isRetryableStatus = isRetryableStatus;
1523
- exports.postToolEvent = postToolEvent;
1524
- exports.postToolEventsBatch = postToolEventsBatch;
1525
- exports.parseIngestResponse = parseIngestResponse;
1526
- var tool_contract_1 = require_out();
1527
- var AscendaApiError2 = class extends Error {
1528
- status;
1529
- errorCode;
1530
- constructor(status, errorCode, body) {
1531
- super(body ?? `Ascenda API error ${status}`);
1532
- this.status = status;
1533
- this.errorCode = errorCode;
1534
- this.name = "AscendaApiError";
1564
+ let orphanIndex = 0;
1565
+ for (const orphan of listClaimFiles(outboxFilePath)) {
1566
+ if (claimed.includes(orphan))
1567
+ continue;
1568
+ try {
1569
+ if (now - fs5.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1570
+ continue;
1571
+ const mine = `${claimPath}.${orphanIndex++}`;
1572
+ fs5.renameSync(orphan, mine);
1573
+ claimed.push(mine);
1574
+ } catch {
1575
+ }
1535
1576
  }
1536
- };
1537
- exports.AscendaApiError = AscendaApiError2;
1538
- async function createPairingSession3(apiBaseUrl, toolInstallationId, toolType, displayName) {
1539
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1540
- method: "POST",
1541
- headers: { "Content-Type": "application/json" },
1542
- body: JSON.stringify({ toolInstallationId, toolType, displayName })
1543
- });
1544
- if (!response.ok)
1545
- throw new AscendaApiError2(response.status, void 0, await response.text());
1546
- return await response.json();
1547
- }
1548
- async function getPairingStatus3(apiBaseUrl, pairingSessionId) {
1549
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1550
- method: "GET",
1551
- headers: { Accept: "application/json" }
1552
- });
1553
- if (!response.ok)
1554
- throw new AscendaApiError2(response.status, void 0, await response.text());
1555
- return await response.json();
1577
+ if (claimed.length === 0)
1578
+ return void 0;
1579
+ const entries = [];
1580
+ let unreadable = 0;
1581
+ for (const file of claimed) {
1582
+ const read = readEntries(file);
1583
+ entries.push(...read.entries);
1584
+ unreadable += read.unreadable;
1585
+ }
1586
+ entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1587
+ let released = false;
1588
+ return {
1589
+ entries,
1590
+ unreadable,
1591
+ release(remainder) {
1592
+ if (released)
1593
+ return;
1594
+ released = true;
1595
+ if (remainder.length > 0) {
1596
+ try {
1597
+ fs5.mkdirSync(path4.dirname(outboxFilePath), { recursive: true, mode: 448 });
1598
+ fs5.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1599
+ `).join(""), { encoding: "utf8", mode: 384 });
1600
+ if (process.platform !== "win32")
1601
+ fs5.chmodSync(outboxFilePath, 384);
1602
+ } catch {
1603
+ return;
1604
+ }
1605
+ }
1606
+ for (const file of claimed) {
1607
+ try {
1608
+ fs5.unlinkSync(file);
1609
+ } catch {
1610
+ }
1611
+ }
1612
+ }
1613
+ };
1556
1614
  }
1557
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1558
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1559
- method: "POST",
1560
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1561
- body: JSON.stringify({ joinCode, mode })
1562
- });
1563
- if (!response.ok)
1564
- throw await apiError(response);
1565
- return await response.json();
1615
+ function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1616
+ const reasons = {};
1617
+ let oldestQueuedAt;
1618
+ const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1619
+ const fresh = [];
1620
+ for (const entry of entries) {
1621
+ if (entry.queuedAt < cutoff) {
1622
+ reasons.age = (reasons.age ?? 0) + 1;
1623
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1624
+ oldestQueuedAt = entry.queuedAt;
1625
+ } else {
1626
+ fresh.push(entry);
1627
+ }
1628
+ }
1629
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1630
+ if (excess > 0) {
1631
+ reasons.count = excess;
1632
+ const first = fresh[0]?.queuedAt;
1633
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1634
+ oldestQueuedAt = first;
1635
+ }
1636
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1637
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1638
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1566
1639
  }
1567
- async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1568
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1569
- method: "GET",
1570
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1571
- });
1572
- if (!response.ok)
1573
- throw await apiError(response);
1574
- return await response.json();
1640
+ function listClaimFiles(outboxFilePath) {
1641
+ const dir = path4.dirname(outboxFilePath);
1642
+ const prefix = `${path4.basename(outboxFilePath)}.`;
1643
+ try {
1644
+ return fs5.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path4.join(dir, name)).sort();
1645
+ } catch {
1646
+ return [];
1647
+ }
1575
1648
  }
1576
- async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1577
- let response;
1649
+ function readEntries(file) {
1650
+ let raw;
1578
1651
  try {
1579
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1580
- method: "GET",
1581
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1582
- signal
1583
- });
1584
- } catch (error) {
1585
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1652
+ raw = fs5.readFileSync(file, "utf8");
1653
+ } catch {
1654
+ return { entries: [], unreadable: 0 };
1586
1655
  }
1587
- if (response.status === 401)
1588
- return { kind: "rejected", httpStatus: 401 };
1589
- if (!response.ok)
1590
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1591
- let body;
1656
+ const entries = [];
1657
+ let unreadable = 0;
1658
+ for (const line of raw.split("\n")) {
1659
+ if (!line.trim())
1660
+ continue;
1661
+ try {
1662
+ const parsed = JSON.parse(line);
1663
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1664
+ unreadable += 1;
1665
+ continue;
1666
+ }
1667
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1668
+ } catch {
1669
+ unreadable += 1;
1670
+ }
1671
+ }
1672
+ return { entries, unreadable };
1673
+ }
1674
+ }
1675
+ });
1676
+
1677
+ // ../packages/tool-kit/out/backgroundDelivery.js
1678
+ var require_backgroundDelivery = __commonJS({
1679
+ "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
1680
+ "use strict";
1681
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1682
+ if (k2 === void 0) k2 = k;
1683
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1684
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1685
+ desc = { enumerable: true, get: function() {
1686
+ return m[k];
1687
+ } };
1688
+ }
1689
+ Object.defineProperty(o, k2, desc);
1690
+ } : function(o, m, k, k2) {
1691
+ if (k2 === void 0) k2 = k;
1692
+ o[k2] = m[k];
1693
+ });
1694
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1695
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1696
+ } : function(o, v) {
1697
+ o["default"] = v;
1698
+ });
1699
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1700
+ var ownKeys = function(o) {
1701
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1702
+ var ar = [];
1703
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1704
+ return ar;
1705
+ };
1706
+ return ownKeys(o);
1707
+ };
1708
+ return function(mod) {
1709
+ if (mod && mod.__esModule) return mod;
1710
+ var result = {};
1711
+ if (mod != null) {
1712
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1713
+ }
1714
+ __setModuleDefault(result, mod);
1715
+ return result;
1716
+ };
1717
+ }();
1718
+ Object.defineProperty(exports, "__esModule", { value: true });
1719
+ exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
1720
+ exports.hookDeliveryInline = hookDeliveryInline2;
1721
+ exports.flushLockPath = flushLockPath;
1722
+ exports.startBackgroundFlush = startBackgroundFlush2;
1723
+ exports.runOutboxFlush = runOutboxFlush3;
1724
+ var fs5 = __importStar(__require("fs"));
1725
+ var child_process_1 = __require("child_process");
1726
+ var outbox_1 = require_outbox();
1727
+ exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
1728
+ exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
1729
+ exports.FLUSH_LOCK_FRESH_MS = 2e4;
1730
+ var FLUSH_MAX_PASSES = 20;
1731
+ var FLUSH_MAX_RUN_MS = 6e4;
1732
+ function hookDeliveryInline2(env = process.env) {
1733
+ return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
1734
+ }
1735
+ function flushLockPath(outboxFilePath) {
1736
+ return `${outboxFilePath}.flushing`;
1737
+ }
1738
+ function lockIsFresh(lockPath, now) {
1592
1739
  try {
1593
- body = await response.json();
1740
+ return now - fs5.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1594
1741
  } catch {
1595
- return { kind: "failed", reason: "the reply was not readable" };
1742
+ return false;
1596
1743
  }
1597
- if (!Array.isArray(body))
1598
- return { kind: "failed", reason: "the reply was not a list" };
1599
- return { kind: "ok", initiatives: body };
1600
1744
  }
1601
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1602
- let response;
1745
+ function touchLock(lockPath) {
1603
1746
  try {
1604
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1605
- method: "GET",
1606
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1607
- signal
1608
- });
1609
- } catch (error) {
1610
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1747
+ fs5.writeFileSync(lockPath, `${process.pid}
1748
+ `, { encoding: "utf8", mode: 384 });
1749
+ } catch {
1611
1750
  }
1612
- if (response.status === 404)
1613
- return { kind: "absent" };
1614
- if (response.status === 401)
1615
- return { kind: "rejected", httpStatus: 401 };
1616
- if (!response.ok)
1617
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1618
- let body;
1751
+ }
1752
+ function removeLock(lockPath) {
1619
1753
  try {
1620
- body = await response.json();
1754
+ fs5.unlinkSync(lockPath);
1621
1755
  } catch {
1622
- return { kind: "absent" };
1623
1756
  }
1624
- if (!Array.isArray(body))
1625
- return { kind: "absent" };
1626
- return { kind: "ok", notices: body };
1627
1757
  }
1628
- async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1629
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1630
- method: objected ? "POST" : "DELETE",
1631
- headers: { Authorization: `Bearer ${eventWriteToken}` }
1632
- });
1633
- if (!response.ok)
1634
- throw await apiError(response);
1758
+ function outboxHasEntries(outboxFilePath) {
1759
+ try {
1760
+ return fs5.statSync(outboxFilePath).size > 0;
1761
+ } catch {
1762
+ return false;
1763
+ }
1635
1764
  }
1636
- async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1765
+ function startBackgroundFlush2(options) {
1766
+ const lockPath = flushLockPath(options.outboxFilePath);
1767
+ const now = options.now ?? Date.now();
1768
+ if (lockIsFresh(lockPath, now))
1769
+ return false;
1770
+ const script = options.script ?? process.argv[1];
1771
+ if (!script)
1772
+ return false;
1637
1773
  try {
1638
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1639
- method: "POST",
1640
- headers: { Authorization: `Bearer ${eventWriteToken}` },
1641
- signal
1774
+ touchLock(lockPath);
1775
+ const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
1776
+ detached: true,
1777
+ stdio: "ignore",
1778
+ windowsHide: true,
1779
+ env: process.env
1642
1780
  });
1643
- return response.ok;
1781
+ child.on("error", () => removeLock(lockPath));
1782
+ child.unref();
1783
+ return true;
1644
1784
  } catch {
1785
+ removeLock(lockPath);
1645
1786
  return false;
1646
1787
  }
1647
1788
  }
1648
- async function apiError(response) {
1649
- const body = await response.text();
1650
- let errorCode;
1789
+ async function runOutboxFlush3(sender, now = Date.now) {
1790
+ const outboxFilePath = sender.outboxFilePath();
1791
+ const lockPath = flushLockPath(outboxFilePath);
1792
+ const started = now();
1793
+ let last;
1794
+ let passes = 0;
1795
+ const drain = async () => {
1796
+ while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
1797
+ passes += 1;
1798
+ touchLock(lockPath);
1799
+ last = await sender.flushOutbox();
1800
+ if (!last || last.found === 0 || last.halted || !last.sendEnabled)
1801
+ return;
1802
+ if (last.delivered === 0 && last.discarded === 0)
1803
+ return;
1804
+ }
1805
+ };
1651
1806
  try {
1652
- const parsed = JSON.parse(body);
1653
- errorCode = parsed.code ?? parsed.error;
1807
+ await drain();
1808
+ removeLock(lockPath);
1809
+ if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
1810
+ touchLock(lockPath);
1811
+ await drain();
1812
+ removeLock(lockPath);
1813
+ }
1654
1814
  } catch {
1655
- errorCode = void 0;
1815
+ removeLock(lockPath);
1656
1816
  }
1657
- return new AscendaApiError2(response.status, errorCode, body);
1658
- }
1659
- async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1660
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1661
- method: "POST",
1662
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1663
- signal
1664
- });
1665
- if (response.status === 401)
1666
- return null;
1667
- if (!response.ok)
1668
- throw new AscendaApiError2(response.status, void 0, await response.text());
1669
- return await response.json();
1670
- }
1671
- function isDeliveredStatus(value) {
1672
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1817
+ return last;
1673
1818
  }
1674
- function readSuccessBody(body) {
1675
- let parsed;
1819
+ }
1820
+ });
1821
+
1822
+ // ../packages/agent-events/out/index.js
1823
+ var require_out2 = __commonJS({
1824
+ "../packages/agent-events/out/index.js"(exports) {
1825
+ "use strict";
1826
+ Object.defineProperty(exports, "__esModule", { value: true });
1827
+ exports.KNOWN_AGENTS = exports.WAIT_REASONS = exports.VCS_ACTIONS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1828
+ exports.isAgentEventV0 = isAgentEventV0;
1829
+ exports.parseEventLogLine = parseEventLogLine;
1830
+ exports.normaliseKind = normaliseKind;
1831
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1832
+ exports.AGENT_EVENT_KINDS = [
1833
+ "session.started",
1834
+ "session.ended",
1835
+ "prompt.submitted",
1836
+ "tool.started",
1837
+ "tool.completed",
1838
+ "tool.failed",
1839
+ "turn.completed",
1840
+ "agent.waiting",
1841
+ "permission.requested",
1842
+ "permission.denied",
1843
+ "context.compacted",
1844
+ "subagent.started",
1845
+ "subagent.stopped",
1846
+ "pull_request.opened",
1847
+ "pull_request.closed",
1848
+ "pull_request.merged",
1849
+ "other"
1850
+ ];
1851
+ exports.VCS_ACTIONS = ["commit", "push", "pr_created", "pr_merged"];
1852
+ exports.WAIT_REASONS = ["permission", "idle", "input", "other"];
1853
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1854
+ function isAgentEventV0(value) {
1855
+ if (!value || typeof value !== "object")
1856
+ return false;
1857
+ const e = value;
1858
+ return e.schema === exports.AGENT_EVENT_SCHEMA && typeof e.id === "string" && e.id.length > 0 && typeof e.time === "string" && !Number.isNaN(Date.parse(e.time)) && typeof e.agent === "string" && e.agent.length > 0 && typeof e.kind === "string";
1859
+ }
1860
+ function parseEventLogLine(line) {
1861
+ if (!line.trim())
1862
+ return void 0;
1676
1863
  try {
1677
- parsed = JSON.parse(body);
1864
+ const parsed = JSON.parse(line);
1865
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1678
1866
  } catch {
1679
- return { duplicates: 0 };
1680
- }
1681
- if (!parsed || typeof parsed !== "object")
1682
- return { duplicates: 0 };
1683
- const single = parsed.status;
1684
- if (isDeliveredStatus(single))
1685
- return { duplicates: single === "duplicate" ? 1 : 0 };
1686
- const raw = parsed.results;
1687
- if (!Array.isArray(raw))
1688
- return { duplicates: 0 };
1689
- const results = [];
1690
- for (const item of raw) {
1691
- if (!item || typeof item !== "object")
1692
- continue;
1693
- const { index, status, reason } = item;
1694
- if (typeof index !== "number" || typeof status !== "string")
1695
- continue;
1696
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1867
+ return void 0;
1697
1868
  }
1698
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1699
- }
1700
- function isRetryableStatus(status) {
1701
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1702
1869
  }
1703
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1704
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1870
+ function normaliseKind(kind) {
1871
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1705
1872
  }
1706
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1707
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1873
+ }
1874
+ });
1875
+
1876
+ // ../packages/tool-kit/out/agentEvent.js
1877
+ var require_agentEvent = __commonJS({
1878
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1879
+ "use strict";
1880
+ Object.defineProperty(exports, "__esModule", { value: true });
1881
+ exports.toAgentEvent = toAgentEvent;
1882
+ var agent_events_1 = require_out2();
1883
+ var KIND_BY_TYPE = {
1884
+ create_focus_session: "session.started",
1885
+ recovery_offline_period: "session.ended",
1886
+ ai_prompt_submitted: "prompt.submitted",
1887
+ ai_tool_call_started: "tool.started",
1888
+ ai_tool_call_completed: "tool.completed",
1889
+ ai_file_write: "tool.completed",
1890
+ ai_file_edit: "tool.completed",
1891
+ editor_verification_activity: "tool.completed",
1892
+ ai_tool_call_failed: "tool.failed",
1893
+ compile_error: "tool.failed",
1894
+ tool_failure: "tool.failed",
1895
+ ai_turn_completed: "turn.completed",
1896
+ supervision_interruption: "agent.waiting",
1897
+ permission_requested: "permission.requested",
1898
+ permission_denied: "permission.denied",
1899
+ context_compression_manual: "context.compacted",
1900
+ context_compression_auto: "context.compacted",
1901
+ subagent_started: "subagent.started",
1902
+ subagent_stopped: "subagent.stopped",
1903
+ pull_request_opened: "pull_request.opened",
1904
+ pull_request_closed: "pull_request.closed",
1905
+ pull_request_merged: "pull_request.merged"
1906
+ };
1907
+ function agentOf(payload) {
1908
+ const host = stringField(payload.metadata?.host);
1909
+ if (host)
1910
+ return host;
1911
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1708
1912
  }
1709
- async function sendIngest(url, eventWriteToken, body, signal) {
1710
- try {
1711
- const response = await fetch(url, {
1712
- method: "POST",
1713
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1714
- body,
1715
- signal
1716
- });
1717
- return parseIngestResponse(response);
1718
- } catch (error) {
1719
- return {
1720
- result: "transport_error",
1721
- detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1722
- };
1913
+ function vcsActionOf(metadata) {
1914
+ const milestone = stringField(metadata.milestoneKind);
1915
+ if (milestone === "pr_opened")
1916
+ return "pr_created";
1917
+ if (milestone === "pr_merged")
1918
+ return "pr_merged";
1919
+ const git = stringField(metadata.gitAction);
1920
+ return git === "commit" || git === "push" ? git : void 0;
1921
+ }
1922
+ function waitReasonOf(metadata) {
1923
+ switch (stringField(metadata.interruptionKind)) {
1924
+ case "permission_request":
1925
+ return "permission";
1926
+ case "input_request":
1927
+ return "input";
1928
+ case "idle_prompt":
1929
+ return "idle";
1930
+ case void 0:
1931
+ return void 0;
1932
+ default:
1933
+ return "other";
1723
1934
  }
1724
1935
  }
1725
- async function parseIngestResponse(response) {
1726
- if (response.ok) {
1727
- const outcome = { result: "accepted", httpStatus: response.status };
1728
- let read = { duplicates: 0 };
1729
- try {
1730
- read = readSuccessBody(await response.text());
1731
- } catch {
1732
- read = { duplicates: 0 };
1733
- }
1734
- return {
1735
- ...outcome,
1736
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1737
- ...read.results !== void 0 ? { results: read.results } : {}
1738
- };
1739
- }
1740
- const body = await response.text();
1741
- let errorCode;
1742
- try {
1743
- errorCode = JSON.parse(body).error;
1744
- } catch {
1745
- errorCode = void 0;
1746
- }
1747
- const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1748
- if (response.status === 401)
1749
- return { ...base, result: "auth_failed" };
1750
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1751
- return { ...base, result: "consent_missing" };
1752
- if (response.status === 400 || response.status === 422)
1753
- return { ...base, result: "validation_failed" };
1754
- return { ...base, result: "transport_error" };
1936
+ function stringField(value) {
1937
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1938
+ }
1939
+ function toAgentEvent(payload) {
1940
+ const metadata = payload.metadata ?? {};
1941
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1942
+ const tool = kind.startsWith("tool.") || kind.startsWith("permission.") ? stringField(metadata.toolName) : void 0;
1943
+ const outcome = stringField(metadata.outcome);
1944
+ const vcsAction = kind === "tool.completed" ? vcsActionOf(metadata) : void 0;
1945
+ const reason = kind === "agent.waiting" ? waitReasonOf(metadata) : void 0;
1946
+ const model = kind === "session.started" ? stringField(metadata.modelId) : void 0;
1947
+ return {
1948
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1949
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1950
+ time: payload.occurredAt,
1951
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1952
+ // writes anyway; without it the event in memory and the one on disk differ.
1953
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1954
+ agent: agentOf(payload),
1955
+ kind,
1956
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1957
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1958
+ ...tool ? { tool } : {},
1959
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1960
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1961
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1962
+ ...stringField(metadata.repoKey) ? { repoKey: metadata.repoKey } : {},
1963
+ ...stringField(metadata.branchKey) ? { branchKey: metadata.branchKey } : {},
1964
+ ...stringField(metadata.autonomyMode) ? { permissionMode: metadata.autonomyMode } : {},
1965
+ ...stringField(metadata.headRepoKey) ? { headRepoKey: metadata.headRepoKey } : {},
1966
+ ...stringField(metadata.prCreatedAt) ? { prCreatedAt: metadata.prCreatedAt } : {},
1967
+ ...stringField(metadata.prClosedAt) ? { prClosedAt: metadata.prClosedAt } : {},
1968
+ ...stringField(metadata.prMergedAt) ? { prMergedAt: metadata.prMergedAt } : {},
1969
+ ...stringField(metadata.promptId) ? { promptId: metadata.promptId } : {},
1970
+ ...vcsAction ? { vcsAction } : {},
1971
+ ...reason ? { reason } : {},
1972
+ ...model ? { model } : {},
1973
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1974
+ sourceType: payload.eventType
1975
+ };
1755
1976
  }
1756
1977
  }
1757
1978
  });
1758
1979
 
1759
- // ../packages/tool-kit/out/stateStore.js
1760
- var require_stateStore = __commonJS({
1761
- "../packages/tool-kit/out/stateStore.js"(exports) {
1980
+ // ../packages/tool-kit/out/credentials.js
1981
+ var require_credentials = __commonJS({
1982
+ "../packages/tool-kit/out/credentials.js"(exports) {
1762
1983
  "use strict";
1763
1984
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1764
1985
  if (k2 === void 0) k2 = k;
@@ -1798,124 +2019,102 @@ var require_stateStore = __commonJS({
1798
2019
  };
1799
2020
  }();
1800
2021
  Object.defineProperty(exports, "__esModule", { value: true });
1801
- exports.defaultStateFilePath = defaultStateFilePath2;
1802
- exports.unresolvedToolInstallationId = unresolvedToolInstallationId2;
1803
- exports.unresolvedStateFilePath = unresolvedStateFilePath2;
1804
- exports.readCollectorState = readCollectorState2;
1805
- exports.recordSendOutcome = recordSendOutcome2;
1806
- exports.recordOutboxDiscard = recordOutboxDiscard;
1807
- exports.shouldAnnounceFailure = shouldAnnounceFailure2;
1808
- exports.markFailureNotified = markFailureNotified2;
2022
+ exports.credentialsFilePath = credentialsFilePath2;
2023
+ exports.readMachineCredentials = readMachineCredentials2;
2024
+ exports.writeMachineCredentials = writeMachineCredentials2;
2025
+ exports.writeTopLevelCredentials = writeTopLevelCredentials2;
2026
+ exports.writeRepoKeysSetting = writeRepoKeysSetting2;
2027
+ exports.writeEventLogSetting = writeEventLogSetting2;
2028
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2029
+ exports.readHostCredentials = readHostCredentials;
2030
+ exports.writeHostCredentials = writeHostCredentials;
2031
+ exports.removeHostCredentials = removeHostCredentials;
1809
2032
  var fs5 = __importStar(__require("fs"));
1810
2033
  var path4 = __importStar(__require("path"));
1811
2034
  var tokenStore_1 = require_tokenStore();
1812
- function defaultStateFilePath2(toolInstallationId) {
1813
- const dir = process.env.ASCENDA_STATE_DIR?.trim();
1814
- const base = dir ? dir : path4.join((0, tokenStore_1.ascendaHome)(), "state");
1815
- return path4.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1816
- }
1817
- function unresolvedToolInstallationId2(toolType) {
1818
- return `${toolType}:unresolved`;
1819
- }
1820
- function unresolvedStateFilePath2(toolType) {
1821
- return defaultStateFilePath2(unresolvedToolInstallationId2(toolType));
2035
+ function credentialsFilePath2() {
2036
+ return path4.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1822
2037
  }
1823
- function readCollectorState2(stateFilePath) {
2038
+ function readMachineCredentials2() {
1824
2039
  try {
1825
- if (!fs5.existsSync(stateFilePath))
1826
- return void 0;
1827
- const raw = fs5.readFileSync(stateFilePath, "utf8").trim();
2040
+ const raw = fs5.readFileSync(credentialsFilePath2(), "utf8").trim();
1828
2041
  if (!raw)
1829
2042
  return void 0;
1830
2043
  const parsed = JSON.parse(raw);
1831
- if (!parsed || typeof parsed !== "object")
2044
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1832
2045
  return void 0;
1833
2046
  return parsed;
1834
2047
  } catch {
1835
2048
  return void 0;
1836
2049
  }
1837
2050
  }
1838
- function recordSendOutcome2(stateFilePath, toolInstallationId, outcome, detail = {}) {
1839
- const now = (/* @__PURE__ */ new Date()).toISOString();
1840
- const previous = readCollectorState2(stateFilePath);
1841
- const accepted = outcome === "accepted";
1842
- const next = {
1843
- toolInstallationId,
1844
- lastAttemptAt: now,
1845
- lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1846
- lastOutcome: outcome,
1847
- consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1848
- ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1849
- ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1850
- ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1851
- // A success closes the episode; a failure either opens one or continues
1852
- // the one already open. Carrying `notifiedFailingSince` across a
1853
- // continuing episode is what keeps the notice to once per outage.
1854
- ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1855
- ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1856
- // Cumulative by design: a send outcome, success included, never erases
1857
- // the record of what the outbox had to throw away.
1858
- ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1859
- };
1860
- writeStateFile(stateFilePath, next);
1861
- return next;
2051
+ function writeMachineCredentials2(credentials) {
2052
+ const file = credentialsFilePath2();
2053
+ fs5.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
2054
+ fs5.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2055
+ `, { encoding: "utf8", mode: 384 });
2056
+ if (process.platform !== "win32") {
2057
+ fs5.chmodSync(path4.dirname(file), 448);
2058
+ fs5.chmodSync(file, 384);
2059
+ }
1862
2060
  }
1863
- function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1864
- const now = (/* @__PURE__ */ new Date()).toISOString();
1865
- const previous = readCollectorState2(stateFilePath);
1866
- const next = {
1867
- ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1868
- toolInstallationId,
1869
- lastOutcome: "outbox_discarded",
1870
- outboxDiscarded: {
1871
- total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1872
- lastAt: now,
1873
- lastCount: discard.count,
1874
- lastReasons: discard.reasons,
1875
- ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1876
- }
1877
- };
1878
- writeStateFile(stateFilePath, next);
1879
- return next;
2061
+ function writeTopLevelCredentials2(credentials) {
2062
+ const existing = readMachineCredentials2();
2063
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
2064
+ const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
2065
+ writeMachineCredentials2({
2066
+ ...credentials,
2067
+ ...eventLogPath ? { eventLogPath } : {},
2068
+ ...repoKeys === false ? { repoKeys } : {},
2069
+ ...existing?.tools ? { tools: existing.tools } : {}
2070
+ });
1880
2071
  }
1881
- function shouldAnnounceFailure2(state) {
1882
- if (!state || state.consecutiveFailures === 0 || !state.failingSince)
2072
+ function writeRepoKeysSetting2(on) {
2073
+ const existing = readMachineCredentials2() ?? {};
2074
+ const { repoKeys: _dropped, ...rest } = existing;
2075
+ writeMachineCredentials2(on ? rest : { ...rest, repoKeys: false });
2076
+ }
2077
+ function writeEventLogSetting2(value) {
2078
+ const existing = readMachineCredentials2() ?? {};
2079
+ writeMachineCredentials2({ ...existing, eventLogPath: value });
2080
+ }
2081
+ function isLocalOnlyHostInstall(host, hasToken) {
2082
+ const credentials = readHostCredentials(host);
2083
+ if (!credentials?.localOnly)
1883
2084
  return false;
1884
- return state.notifiedFailingSince !== state.failingSince;
2085
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2086
+ return false;
2087
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1885
2088
  }
1886
- function markFailureNotified2(stateFilePath, state) {
1887
- if (!state.failingSince)
1888
- return;
1889
- writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
2089
+ function readHostCredentials(host) {
2090
+ const entry = readMachineCredentials2()?.tools?.[host];
2091
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
2092
+ return void 0;
2093
+ return entry;
1890
2094
  }
1891
- function writeStateFile(stateFilePath, state) {
1892
- const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1893
- try {
1894
- const dir = path4.dirname(stateFilePath);
1895
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1896
- fs5.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1897
- `, { encoding: "utf8", mode: 384 });
1898
- fs5.renameSync(temporaryPath, stateFilePath);
1899
- if (process.platform !== "win32")
1900
- fs5.chmodSync(stateFilePath, 384);
1901
- } catch {
1902
- try {
1903
- if (fs5.existsSync(temporaryPath))
1904
- fs5.unlinkSync(temporaryPath);
1905
- } catch {
1906
- }
1907
- }
2095
+ function writeHostCredentials(host, credentials) {
2096
+ const existing = readMachineCredentials2() ?? {};
2097
+ writeMachineCredentials2({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1908
2098
  }
1909
- function truncate(value) {
1910
- const collapsed = value.replace(/\s+/g, " ").trim();
1911
- return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
2099
+ function removeHostCredentials(host) {
2100
+ const existing = readMachineCredentials2();
2101
+ if (!existing?.tools || !(host in existing.tools))
2102
+ return;
2103
+ const tools = { ...existing.tools };
2104
+ delete tools[host];
2105
+ const next = { ...existing };
2106
+ if (Object.keys(tools).length)
2107
+ next.tools = tools;
2108
+ else
2109
+ delete next.tools;
2110
+ writeMachineCredentials2(next);
1912
2111
  }
1913
2112
  }
1914
2113
  });
1915
2114
 
1916
- // ../packages/tool-kit/out/outbox.js
1917
- var require_outbox = __commonJS({
1918
- "../packages/tool-kit/out/outbox.js"(exports) {
2115
+ // ../packages/tool-kit/out/eventLog.js
2116
+ var require_eventLog = __commonJS({
2117
+ "../packages/tool-kit/out/eventLog.js"(exports) {
1919
2118
  "use strict";
1920
2119
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1921
2120
  if (k2 === void 0) k2 = k;
@@ -1955,182 +2154,347 @@ var require_outbox = __commonJS({
1955
2154
  };
1956
2155
  }();
1957
2156
  Object.defineProperty(exports, "__esModule", { value: true });
1958
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1959
- exports.outboxDrainEnabled = outboxDrainEnabled2;
1960
- exports.defaultOutboxFilePath = defaultOutboxFilePath2;
1961
- exports.appendToOutbox = appendToOutbox;
1962
- exports.readOutboxSummary = readOutboxSummary2;
1963
- exports.claimOutbox = claimOutbox;
1964
- exports.enforceOutboxBounds = enforceOutboxBounds;
2157
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
2158
+ exports.expandUserPath = expandUserPath;
2159
+ exports.defaultEventLogPath = defaultEventLogPath;
2160
+ exports.resolveEventLog = resolveEventLog3;
2161
+ exports.resolveEventLogPath = resolveEventLogPath2;
2162
+ exports.describeEventLog = describeEventLog3;
2163
+ exports.parseEventLogFlag = parseEventLogFlag2;
2164
+ exports.appendEventLog = appendEventLog2;
1965
2165
  var fs5 = __importStar(__require("fs"));
2166
+ var os4 = __importStar(__require("os"));
1966
2167
  var path4 = __importStar(__require("path"));
1967
- var stateStore_1 = require_stateStore();
2168
+ var agentEvent_1 = require_agentEvent();
2169
+ var credentials_1 = require_credentials();
1968
2170
  var tokenStore_1 = require_tokenStore();
1969
- exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1970
- exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1971
- exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1972
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1973
- var ORPHANED_CLAIM_AGE_MS = 6e4;
1974
- var CLAIM_SUFFIX = ".draining";
1975
- function outboxDrainEnabled2(env = process.env) {
1976
- const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1977
- if (value === void 0 || value === "")
1978
- return true;
1979
- return !(value === "0" || value === "false" || value === "no" || value === "off");
2171
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
2172
+ exports.EVENT_LOG_OFF = "off";
2173
+ var MAX_BYTES = 5 * 1024 * 1024;
2174
+ function expandUserPath(configured) {
2175
+ const value = configured?.trim();
2176
+ if (!value)
2177
+ return void 0;
2178
+ if (value === "~")
2179
+ return os4.homedir();
2180
+ if (value.startsWith("~/"))
2181
+ return path4.join(os4.homedir(), value.slice(2));
2182
+ return path4.resolve(value);
1980
2183
  }
1981
- function defaultOutboxFilePath2(toolInstallationId) {
1982
- const dir = path4.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1983
- return path4.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
2184
+ function defaultEventLogPath() {
2185
+ return path4.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1984
2186
  }
1985
- function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
2187
+ function resolveEventLog3(options = {}) {
2188
+ for (const [source, raw] of [
2189
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
2190
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
2191
+ ]) {
2192
+ const value = raw?.trim();
2193
+ if (!value)
2194
+ continue;
2195
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
2196
+ return { path: void 0, source: "disabled" };
2197
+ return { path: expandUserPath(value), source };
2198
+ }
2199
+ if (options.localOnly)
2200
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
2201
+ return { path: void 0, source: "off" };
2202
+ }
2203
+ function resolveEventLogPath2(options = {}) {
2204
+ return resolveEventLog3(options).path;
2205
+ }
2206
+ function describeEventLog3(setting, command) {
2207
+ switch (setting.source) {
2208
+ case "env":
2209
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
2210
+ case "credentials":
2211
+ return `${setting.path} (set by ${command} --event-log)`;
2212
+ case "unpaired-default":
2213
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
2214
+ case "disabled":
2215
+ return `off (turned off; ${command} --event-log to turn it on)`;
2216
+ case "off":
2217
+ return `off (${command} --event-log to keep a local copy of every event)`;
2218
+ }
2219
+ }
2220
+ function parseEventLogFlag2(argv, index) {
2221
+ const peek = argv[index + 1];
2222
+ if (peek !== void 0 && !peek.startsWith("-"))
2223
+ return { value: peek, consumed: 1 };
2224
+ return { value: defaultEventLogPath(), consumed: 0 };
2225
+ }
2226
+ function appendEventLog2(logFilePath, entry) {
1986
2227
  try {
1987
- const dir = path4.dirname(outboxFilePath);
2228
+ rotateIfLarge(logFilePath);
2229
+ const dir = path4.dirname(logFilePath);
1988
2230
  fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1989
- const entry = { queuedAt: now.toISOString(), payload };
1990
- fs5.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
2231
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
2232
+ fs5.appendFileSync(logFilePath, `${JSON.stringify(line)}
1991
2233
  `, { encoding: "utf8", mode: 384 });
1992
2234
  if (process.platform !== "win32")
1993
- fs5.chmodSync(outboxFilePath, 384);
1994
- return true;
2235
+ fs5.chmodSync(logFilePath, 384);
1995
2236
  } catch {
1996
- return false;
1997
2237
  }
1998
2238
  }
1999
- function readOutboxSummary2(outboxFilePath) {
2000
- const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs5.existsSync(file));
2001
- if (files.length === 0)
2002
- return void 0;
2003
- let depth = 0;
2004
- let unreadableLines = 0;
2005
- let oldestQueuedAt;
2006
- for (const file of files) {
2007
- const { entries, unreadable } = readEntries(file);
2008
- depth += entries.length;
2009
- unreadableLines += unreadable;
2010
- for (const entry of entries) {
2011
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
2012
- oldestQueuedAt = entry.queuedAt;
2013
- }
2239
+ function rotateIfLarge(logFilePath) {
2240
+ try {
2241
+ if (fs5.statSync(logFilePath).size < MAX_BYTES)
2242
+ return;
2243
+ fs5.renameSync(logFilePath, `${logFilePath}.1`);
2244
+ } catch {
2014
2245
  }
2015
- return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
2016
2246
  }
2017
- function claimOutbox(outboxFilePath, now = Date.now()) {
2018
- const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
2019
- const claimed = [];
2247
+ }
2248
+ });
2249
+
2250
+ // ../packages/tool-kit/out/http.js
2251
+ var require_http = __commonJS({
2252
+ "../packages/tool-kit/out/http.js"(exports) {
2253
+ "use strict";
2254
+ Object.defineProperty(exports, "__esModule", { value: true });
2255
+ exports.AscendaApiError = void 0;
2256
+ exports.createPairingSession = createPairingSession3;
2257
+ exports.getPairingStatus = getPairingStatus3;
2258
+ exports.startStudyJoin = startStudyJoin;
2259
+ exports.getStudyJoinStatus = getStudyJoinStatus;
2260
+ exports.readInitiatives = readInitiatives;
2261
+ exports.readStudyNotices = readStudyNotices;
2262
+ exports.setStudyObjection = setStudyObjection;
2263
+ exports.markStudyNoticeShown = markStudyNoticeShown;
2264
+ exports.renewToolToken = renewToolToken;
2265
+ exports.isRetryableStatus = isRetryableStatus;
2266
+ exports.postToolEvent = postToolEvent;
2267
+ exports.postToolEventsBatch = postToolEventsBatch;
2268
+ exports.parseIngestResponse = parseIngestResponse;
2269
+ var tool_contract_1 = require_out();
2270
+ var AscendaApiError2 = class extends Error {
2271
+ status;
2272
+ errorCode;
2273
+ constructor(status, errorCode, body) {
2274
+ super(body ?? `Ascenda API error ${status}`);
2275
+ this.status = status;
2276
+ this.errorCode = errorCode;
2277
+ this.name = "AscendaApiError";
2278
+ }
2279
+ };
2280
+ exports.AscendaApiError = AscendaApiError2;
2281
+ async function createPairingSession3(apiBaseUrl, toolInstallationId, toolType, displayName) {
2282
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
2283
+ method: "POST",
2284
+ headers: { "Content-Type": "application/json" },
2285
+ body: JSON.stringify({ toolInstallationId, toolType, displayName })
2286
+ });
2287
+ if (!response.ok)
2288
+ throw new AscendaApiError2(response.status, void 0, await response.text());
2289
+ return await response.json();
2290
+ }
2291
+ async function getPairingStatus3(apiBaseUrl, pairingSessionId) {
2292
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
2293
+ method: "GET",
2294
+ headers: { Accept: "application/json" }
2295
+ });
2296
+ if (!response.ok)
2297
+ throw new AscendaApiError2(response.status, void 0, await response.text());
2298
+ return await response.json();
2299
+ }
2300
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
2301
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2302
+ method: "POST",
2303
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2304
+ body: JSON.stringify({ joinCode, mode })
2305
+ });
2306
+ if (!response.ok)
2307
+ throw await apiError(response);
2308
+ return await response.json();
2309
+ }
2310
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
2311
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
2312
+ method: "GET",
2313
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
2314
+ });
2315
+ if (!response.ok)
2316
+ throw await apiError(response);
2317
+ return await response.json();
2318
+ }
2319
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
2320
+ let response;
2020
2321
  try {
2021
- fs5.renameSync(outboxFilePath, claimPath);
2022
- claimed.push(claimPath);
2322
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
2323
+ method: "GET",
2324
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2325
+ signal
2326
+ });
2327
+ } catch (error) {
2328
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2329
+ }
2330
+ if (response.status === 401)
2331
+ return { kind: "rejected", httpStatus: 401 };
2332
+ if (!response.ok)
2333
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2334
+ let body;
2335
+ try {
2336
+ body = await response.json();
2023
2337
  } catch {
2338
+ return { kind: "failed", reason: "the reply was not readable" };
2024
2339
  }
2025
- let orphanIndex = 0;
2026
- for (const orphan of listClaimFiles(outboxFilePath)) {
2027
- if (claimed.includes(orphan))
2028
- continue;
2029
- try {
2030
- if (now - fs5.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
2031
- continue;
2032
- const mine = `${claimPath}.${orphanIndex++}`;
2033
- fs5.renameSync(orphan, mine);
2034
- claimed.push(mine);
2035
- } catch {
2036
- }
2340
+ if (!Array.isArray(body))
2341
+ return { kind: "failed", reason: "the reply was not a list" };
2342
+ return { kind: "ok", initiatives: body };
2343
+ }
2344
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
2345
+ let response;
2346
+ try {
2347
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
2348
+ method: "GET",
2349
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2350
+ signal
2351
+ });
2352
+ } catch (error) {
2353
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2037
2354
  }
2038
- if (claimed.length === 0)
2039
- return void 0;
2040
- const entries = [];
2041
- let unreadable = 0;
2042
- for (const file of claimed) {
2043
- const read = readEntries(file);
2044
- entries.push(...read.entries);
2045
- unreadable += read.unreadable;
2355
+ if (response.status === 404)
2356
+ return { kind: "absent" };
2357
+ if (response.status === 401)
2358
+ return { kind: "rejected", httpStatus: 401 };
2359
+ if (!response.ok)
2360
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2361
+ let body;
2362
+ try {
2363
+ body = await response.json();
2364
+ } catch {
2365
+ return { kind: "absent" };
2046
2366
  }
2047
- entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
2048
- let released = false;
2049
- return {
2050
- entries,
2051
- unreadable,
2052
- release(remainder) {
2053
- if (released)
2054
- return;
2055
- released = true;
2056
- if (remainder.length > 0) {
2057
- try {
2058
- fs5.mkdirSync(path4.dirname(outboxFilePath), { recursive: true, mode: 448 });
2059
- fs5.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
2060
- `).join(""), { encoding: "utf8", mode: 384 });
2061
- if (process.platform !== "win32")
2062
- fs5.chmodSync(outboxFilePath, 384);
2063
- } catch {
2064
- return;
2065
- }
2066
- }
2067
- for (const file of claimed) {
2068
- try {
2069
- fs5.unlinkSync(file);
2070
- } catch {
2071
- }
2072
- }
2073
- }
2074
- };
2367
+ if (!Array.isArray(body))
2368
+ return { kind: "absent" };
2369
+ return { kind: "ok", notices: body };
2075
2370
  }
2076
- function enforceOutboxBounds(entries, bounds, now = Date.now()) {
2077
- const reasons = {};
2078
- let oldestQueuedAt;
2079
- const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
2080
- const fresh = [];
2081
- for (const entry of entries) {
2082
- if (entry.queuedAt < cutoff) {
2083
- reasons.age = (reasons.age ?? 0) + 1;
2084
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
2085
- oldestQueuedAt = entry.queuedAt;
2086
- } else {
2087
- fresh.push(entry);
2088
- }
2371
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
2372
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
2373
+ method: objected ? "POST" : "DELETE",
2374
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
2375
+ });
2376
+ if (!response.ok)
2377
+ throw await apiError(response);
2378
+ }
2379
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
2380
+ try {
2381
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
2382
+ method: "POST",
2383
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
2384
+ signal
2385
+ });
2386
+ return response.ok;
2387
+ } catch {
2388
+ return false;
2089
2389
  }
2090
- const excess = Math.max(0, fresh.length - bounds.maxEntries);
2091
- if (excess > 0) {
2092
- reasons.count = excess;
2093
- const first = fresh[0]?.queuedAt;
2094
- if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
2095
- oldestQueuedAt = first;
2390
+ }
2391
+ async function apiError(response) {
2392
+ const body = await response.text();
2393
+ let errorCode;
2394
+ try {
2395
+ const parsed = JSON.parse(body);
2396
+ errorCode = parsed.code ?? parsed.error;
2397
+ } catch {
2398
+ errorCode = void 0;
2096
2399
  }
2097
- const kept = excess > 0 ? fresh.slice(excess) : fresh;
2098
- const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
2099
- return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
2400
+ return new AscendaApiError2(response.status, errorCode, body);
2100
2401
  }
2101
- function listClaimFiles(outboxFilePath) {
2102
- const dir = path4.dirname(outboxFilePath);
2103
- const prefix = `${path4.basename(outboxFilePath)}.`;
2402
+ async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
2403
+ const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
2404
+ method: "POST",
2405
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2406
+ signal
2407
+ });
2408
+ if (response.status === 401)
2409
+ return null;
2410
+ if (!response.ok)
2411
+ throw new AscendaApiError2(response.status, void 0, await response.text());
2412
+ return await response.json();
2413
+ }
2414
+ function isDeliveredStatus(value) {
2415
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
2416
+ }
2417
+ function readSuccessBody(body) {
2418
+ let parsed;
2104
2419
  try {
2105
- return fs5.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path4.join(dir, name)).sort();
2420
+ parsed = JSON.parse(body);
2106
2421
  } catch {
2107
- return [];
2422
+ return { duplicates: 0 };
2423
+ }
2424
+ if (!parsed || typeof parsed !== "object")
2425
+ return { duplicates: 0 };
2426
+ const single = parsed.status;
2427
+ if (isDeliveredStatus(single))
2428
+ return { duplicates: single === "duplicate" ? 1 : 0 };
2429
+ const raw = parsed.results;
2430
+ if (!Array.isArray(raw))
2431
+ return { duplicates: 0 };
2432
+ const results = [];
2433
+ for (const item of raw) {
2434
+ if (!item || typeof item !== "object")
2435
+ continue;
2436
+ const { index, status, reason } = item;
2437
+ if (typeof index !== "number" || typeof status !== "string")
2438
+ continue;
2439
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
2108
2440
  }
2441
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
2109
2442
  }
2110
- function readEntries(file) {
2111
- let raw;
2443
+ function isRetryableStatus(status) {
2444
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
2445
+ }
2446
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
2447
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
2448
+ }
2449
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
2450
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
2451
+ }
2452
+ async function sendIngest(url, eventWriteToken, body, signal) {
2112
2453
  try {
2113
- raw = fs5.readFileSync(file, "utf8");
2114
- } catch {
2115
- return { entries: [], unreadable: 0 };
2454
+ const response = await fetch(url, {
2455
+ method: "POST",
2456
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2457
+ body,
2458
+ signal
2459
+ });
2460
+ return parseIngestResponse(response);
2461
+ } catch (error) {
2462
+ return {
2463
+ result: "transport_error",
2464
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
2465
+ };
2116
2466
  }
2117
- const entries = [];
2118
- let unreadable = 0;
2119
- for (const line of raw.split("\n")) {
2120
- if (!line.trim())
2121
- continue;
2467
+ }
2468
+ async function parseIngestResponse(response) {
2469
+ if (response.ok) {
2470
+ const outcome = { result: "accepted", httpStatus: response.status };
2471
+ let read = { duplicates: 0 };
2122
2472
  try {
2123
- const parsed = JSON.parse(line);
2124
- if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
2125
- unreadable += 1;
2126
- continue;
2127
- }
2128
- entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
2473
+ read = readSuccessBody(await response.text());
2129
2474
  } catch {
2130
- unreadable += 1;
2475
+ read = { duplicates: 0 };
2131
2476
  }
2477
+ return {
2478
+ ...outcome,
2479
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
2480
+ ...read.results !== void 0 ? { results: read.results } : {}
2481
+ };
2132
2482
  }
2133
- return { entries, unreadable };
2483
+ const body = await response.text();
2484
+ let errorCode;
2485
+ try {
2486
+ errorCode = JSON.parse(body).error;
2487
+ } catch {
2488
+ errorCode = void 0;
2489
+ }
2490
+ const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
2491
+ if (response.status === 401)
2492
+ return { ...base, result: "auth_failed" };
2493
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
2494
+ return { ...base, result: "consent_missing" };
2495
+ if (response.status === 400 || response.status === 422)
2496
+ return { ...base, result: "validation_failed" };
2497
+ return { ...base, result: "transport_error" };
2134
2498
  }
2135
2499
  }
2136
2500
  });
@@ -2378,11 +2742,34 @@ var require_eventSender = __commonJS({
2378
2742
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
2379
2743
  }
2380
2744
  if (this.isRetryable(outcome)) {
2381
- await new Promise((resolve2) => setTimeout(resolve2, RETRY_DELAY_MS));
2745
+ await new Promise((resolve3) => setTimeout(resolve3, RETRY_DELAY_MS));
2382
2746
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
2383
2747
  }
2384
2748
  return outcome;
2385
2749
  }
2750
+ /**
2751
+ * One outbox pass with nothing live to send: what a background flusher runs,
2752
+ * once per batch. Unlike the pass {@link post} makes, it may run more than
2753
+ * once per sender, because a flusher isn't on anyone's critical path.
2754
+ *
2755
+ * A halted pass is journaled here. Inside {@link post} the live send that
2756
+ * follows journals it, and a flusher has no live send, so without this an
2757
+ * outage would never reach the journal `doctor` and the notices read.
2758
+ */
2759
+ async flushOutbox() {
2760
+ await this.renewIfExpiring();
2761
+ this.outboxServiced = false;
2762
+ this.lastDrain = void 0;
2763
+ const halted = await this.serviceOutbox();
2764
+ if (halted) {
2765
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, halted.result, {
2766
+ httpStatus: halted.httpStatus,
2767
+ errorCode: halted.errorCode,
2768
+ detail: withNote(halted.detail, "kept in outbox")
2769
+ });
2770
+ }
2771
+ return this.lastDrain;
2772
+ }
2386
2773
  /** A failure that never reached a verdict. Replaying can change the answer. */
2387
2774
  isRetryable(outcome) {
2388
2775
  return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
@@ -2642,11 +3029,11 @@ var require_contextRegistry = __commonJS({
2642
3029
  exports.recordWorkContext = recordWorkContext2;
2643
3030
  exports.recordWorkContextAlias = recordWorkContextAlias;
2644
3031
  var fs5 = __importStar(__require("fs"));
2645
- var os5 = __importStar(__require("os"));
3032
+ var os4 = __importStar(__require("os"));
2646
3033
  var path4 = __importStar(__require("path"));
2647
3034
  var MAX_PATHS_PER_ENTRY = 8;
2648
3035
  function workContextRegistryFilePath() {
2649
- return path4.join(os5.homedir(), ".ascenda", "work-contexts.json");
3036
+ return path4.join(os4.homedir(), ".ascenda", "work-contexts.json");
2650
3037
  }
2651
3038
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
2652
3039
  try {
@@ -2782,6 +3169,8 @@ var require_forgeProject = __commonJS({
2782
3169
  }();
2783
3170
  Object.defineProperty(exports, "__esModule", { value: true });
2784
3171
  exports.forgeProjectHash = forgeProjectHash;
3172
+ exports.forgeRepoKey = forgeRepoKey;
3173
+ exports.forgeBranchKey = forgeBranchKey;
2785
3174
  exports.parseForgeFullName = parseForgeFullName;
2786
3175
  exports.readForgeFullName = readForgeFullName;
2787
3176
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
@@ -2797,6 +3186,19 @@ var require_forgeProject = __commonJS({
2797
3186
  }
2798
3187
  return h.toString(16).padStart(8, "0");
2799
3188
  }
3189
+ function forgeRepoKey(fullName) {
3190
+ return forgeProjectHash(fullName.toLowerCase());
3191
+ }
3192
+ function forgeBranchKey(fullName, branch) {
3193
+ const input = `${fullName.toLowerCase()}
3194
+ ${branch}`;
3195
+ let h = 0xcbf29ce484222325n;
3196
+ for (const byte of Buffer.from(input, "utf8")) {
3197
+ h ^= BigInt(byte);
3198
+ h = BigInt.asUintN(64, h * 0x100000001b3n);
3199
+ }
3200
+ return h.toString(16).padStart(16, "0");
3201
+ }
2800
3202
  function parseForgeFullName(remoteUrl) {
2801
3203
  if (!remoteUrl)
2802
3204
  return null;
@@ -3183,6 +3585,95 @@ var require_workContext = __commonJS({
3183
3585
  }
3184
3586
  });
3185
3587
 
3588
+ // ../packages/tool-kit/out/forgeKeys.js
3589
+ var require_forgeKeys = __commonJS({
3590
+ "../packages/tool-kit/out/forgeKeys.js"(exports) {
3591
+ "use strict";
3592
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3593
+ if (k2 === void 0) k2 = k;
3594
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3595
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3596
+ desc = { enumerable: true, get: function() {
3597
+ return m[k];
3598
+ } };
3599
+ }
3600
+ Object.defineProperty(o, k2, desc);
3601
+ } : function(o, m, k, k2) {
3602
+ if (k2 === void 0) k2 = k;
3603
+ o[k2] = m[k];
3604
+ });
3605
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3606
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3607
+ } : function(o, v) {
3608
+ o["default"] = v;
3609
+ });
3610
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3611
+ var ownKeys = function(o) {
3612
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3613
+ var ar = [];
3614
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3615
+ return ar;
3616
+ };
3617
+ return ownKeys(o);
3618
+ };
3619
+ return function(mod) {
3620
+ if (mod && mod.__esModule) return mod;
3621
+ var result = {};
3622
+ if (mod != null) {
3623
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3624
+ }
3625
+ __setModuleDefault(result, mod);
3626
+ return result;
3627
+ };
3628
+ }();
3629
+ Object.defineProperty(exports, "__esModule", { value: true });
3630
+ exports.REPO_KEYS_ENV_VAR = void 0;
3631
+ exports.repoKeysEnabled = repoKeysEnabled;
3632
+ exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd2;
3633
+ var fs5 = __importStar(__require("fs"));
3634
+ var path4 = __importStar(__require("path"));
3635
+ var credentials_1 = require_credentials();
3636
+ var forgeProject_1 = require_forgeProject();
3637
+ var workContext_1 = require_workContext();
3638
+ exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
3639
+ function repoKeysEnabled() {
3640
+ const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
3641
+ if (env === "off" || env === "0" || env === "false")
3642
+ return false;
3643
+ if (env === "on" || env === "1" || env === "true")
3644
+ return true;
3645
+ return (0, credentials_1.readMachineCredentials)()?.repoKeys !== false;
3646
+ }
3647
+ function readDefaultBranch(repositoryRoot) {
3648
+ try {
3649
+ const head = fs5.readFileSync(path4.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
3650
+ const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
3651
+ return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
3652
+ } catch {
3653
+ return null;
3654
+ }
3655
+ }
3656
+ function deriveForgeKeysForCwd2(cwd) {
3657
+ try {
3658
+ if (!cwd || !repoKeysEnabled())
3659
+ return {};
3660
+ const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
3661
+ const fullName = (0, forgeProject_1.readForgeFullName)(root);
3662
+ if (!root || !fullName)
3663
+ return {};
3664
+ const branch = (0, workContext_1.readBranchName)(cwd);
3665
+ const onDefault = branch !== null && branch === readDefaultBranch(root);
3666
+ return {
3667
+ repoKey: (0, forgeProject_1.forgeRepoKey)(fullName),
3668
+ ...branch && !onDefault ? { branchKey: (0, forgeProject_1.forgeBranchKey)(fullName, branch) } : {}
3669
+ };
3670
+ } catch {
3671
+ return {};
3672
+ }
3673
+ }
3674
+ }
3675
+ });
3676
+
3186
3677
  // ../packages/tool-kit/out/hookAdapter.js
3187
3678
  var require_hookAdapter = __commonJS({
3188
3679
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
@@ -3192,13 +3683,18 @@ var require_hookAdapter = __commonJS({
3192
3683
  exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
3193
3684
  exports.resolveContextHashes = resolveContextHashes;
3194
3685
  exports.loadCliAgentConfig = loadCliAgentConfig;
3686
+ exports.withForgeKeys = withForgeKeys;
3687
+ exports.withPromptId = withPromptId;
3195
3688
  exports.deliverHookEvents = deliverHookEvents;
3689
+ exports.flushHookOutbox = flushHookOutbox;
3196
3690
  var contextRegistry_1 = require_contextRegistry();
3197
3691
  var credentials_1 = require_credentials();
3198
3692
  var forgeProject_1 = require_forgeProject();
3199
3693
  var eventLog_1 = require_eventLog();
3694
+ var forgeKeys_1 = require_forgeKeys();
3200
3695
  var eventSender_1 = require_eventSender();
3201
3696
  var stateStore_1 = require_stateStore();
3697
+ var backgroundDelivery_1 = require_backgroundDelivery();
3202
3698
  var tokenStore_1 = require_tokenStore();
3203
3699
  var workContext_1 = require_workContext();
3204
3700
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -3251,6 +3747,19 @@ var require_hookAdapter = __commonJS({
3251
3747
  };
3252
3748
  }
3253
3749
  function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
3750
+ const pairing = loadCliAgentPairing(toolType, identity);
3751
+ const contextHashes = resolveContextHashes(cwd);
3752
+ return {
3753
+ ...pairing,
3754
+ // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3755
+ // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3756
+ // an empty string, grouping unrelated rows under a value naming no session.
3757
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3758
+ workspaceHash: contextHashes.workspaceHash,
3759
+ projectHash: contextHashes.projectHash
3760
+ };
3761
+ }
3762
+ function loadCliAgentPairing(toolType, identity) {
3254
3763
  const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
3255
3764
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3256
3765
  const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
@@ -3261,26 +3770,33 @@ var require_hookAdapter = __commonJS({
3261
3770
  throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
3262
3771
  if (!fileToken)
3263
3772
  (0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3264
- const contextHashes = resolveContextHashes(cwd);
3265
3773
  return {
3266
3774
  apiBaseUrl,
3267
3775
  toolInstallationId,
3268
3776
  eventWriteToken,
3269
3777
  tokenFilePath,
3270
- // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3271
- // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3272
- // an empty string, grouping unrelated rows under a value naming no session.
3273
- sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3274
- workspaceHash: contextHashes.workspaceHash,
3275
- projectHash: contextHashes.projectHash,
3276
3778
  // Agents await command hooks; fail fast rather than stall the user's turn.
3277
3779
  timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
3278
3780
  };
3279
3781
  }
3782
+ function withForgeKeys(events, cwd) {
3783
+ const keys = (0, forgeKeys_1.deriveForgeKeysForCwd)(cwd ?? process.cwd());
3784
+ if (!keys.repoKey)
3785
+ return events;
3786
+ return events.map((event) => ({ ...event, metadata: { ...keys, ...event.metadata } }));
3787
+ }
3788
+ function withPromptId(events, promptId) {
3789
+ if (!promptId)
3790
+ return events;
3791
+ return events.map((event) => ({ ...event, metadata: { promptId, ...event.metadata } }));
3792
+ }
3280
3793
  async function deliverHookEvents(events, options) {
3281
3794
  if (events.length === 0)
3282
3795
  return;
3283
- const notice = options.onNotice ?? ((message) => console.error(message));
3796
+ events = withPromptId(events, options.promptId);
3797
+ if (options.forgeKeys)
3798
+ events = withForgeKeys(events, options.cwd);
3799
+ const notice = options.onNotice ?? ((message2) => console.error(message2));
3284
3800
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3285
3801
  if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3286
3802
  const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
@@ -3311,21 +3827,55 @@ var require_hookAdapter = __commonJS({
3311
3827
  projectHash: config.projectHash,
3312
3828
  timeoutMs: config.timeoutMs
3313
3829
  });
3314
- for (const event of events) {
3315
- const result = await sender.send(event);
3316
- if (result === "accepted")
3317
- continue;
3318
- if (result === "consent_missing") {
3319
- notice("Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.");
3320
- } else if (result === "auth_failed") {
3321
- notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
3322
- } else if (result === "transport_error") {
3323
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
3324
- } else {
3325
- notice(`Ascenda telemetry rejected: ${result}`);
3830
+ if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
3831
+ for (const event of events) {
3832
+ const result = await sender.send(event);
3833
+ if (result === "accepted")
3834
+ continue;
3835
+ const message2 = noticeFor(result);
3836
+ if (message2)
3837
+ notice(message2);
3838
+ return;
3326
3839
  }
3327
3840
  return;
3328
3841
  }
3842
+ for (const event of events)
3843
+ sender.queue(event);
3844
+ (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
3845
+ const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
3846
+ const message = last ? noticeFor(last) : void 0;
3847
+ if (message)
3848
+ notice(message);
3849
+ }
3850
+ function noticeFor(result) {
3851
+ if (result === "accepted" || result === "duplicate")
3852
+ return void 0;
3853
+ if (result === "consent_missing")
3854
+ return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
3855
+ if (result === "auth_failed")
3856
+ return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
3857
+ if (result === "transport_error")
3858
+ return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
3859
+ if (result === "outbox_discarded")
3860
+ return void 0;
3861
+ return `Ascenda telemetry rejected: ${result}`;
3862
+ }
3863
+ async function flushHookOutbox(options) {
3864
+ let config;
3865
+ try {
3866
+ config = loadCliAgentPairing(options.toolType, options);
3867
+ } catch {
3868
+ return;
3869
+ }
3870
+ const sender = new eventSender_1.AscendaEventSender({
3871
+ apiBaseUrl: config.apiBaseUrl,
3872
+ toolInstallationId: config.toolInstallationId,
3873
+ source: options.source,
3874
+ eventWriteToken: config.eventWriteToken,
3875
+ tokenFilePath: config.tokenFilePath,
3876
+ timeoutMs: config.timeoutMs
3877
+ });
3878
+ await (0, backgroundDelivery_1.runOutboxFlush)(sender);
3329
3879
  }
3330
3880
  function logUnsent2(logFile, events, options) {
3331
3881
  const contextHashes = resolveContextHashes(options.cwd);
@@ -3508,7 +4058,7 @@ var require_studyJoin = __commonJS({
3508
4058
  const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3509
4059
  const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3510
4060
  while (Date.now() < deadline) {
3511
- await new Promise((resolve2) => setTimeout(resolve2, pollIntervalMs));
4061
+ await new Promise((resolve3) => setTimeout(resolve3, pollIntervalMs));
3512
4062
  let poll;
3513
4063
  try {
3514
4064
  poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
@@ -3571,7 +4121,7 @@ var require_studyJoin = __commonJS({
3571
4121
  return true;
3572
4122
  }
3573
4123
  function askChoice(stdin, stdout) {
3574
- return new Promise((resolve2) => {
4124
+ return new Promise((resolve3) => {
3575
4125
  const rl = readline.createInterface({ input: stdin, output: stdout });
3576
4126
  let settled = false;
3577
4127
  const finish = (value) => {
@@ -3579,7 +4129,7 @@ var require_studyJoin = __commonJS({
3579
4129
  return;
3580
4130
  settled = true;
3581
4131
  rl.close();
3582
- resolve2(value.trim());
4132
+ resolve3(value.trim());
3583
4133
  };
3584
4134
  rl.question("Choice [Not now]: ", finish);
3585
4135
  rl.once("close", () => finish(""));
@@ -3818,58 +4368,12 @@ var require_initiatives = __commonJS({
3818
4368
  return "not given";
3819
4369
  return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3820
4370
  }
3821
- function formatDay(iso) {
3822
- const date = new Date(iso);
3823
- if (Number.isNaN(date.getTime()))
3824
- return iso;
3825
- return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
3826
- }
3827
- }
3828
- });
3829
-
3830
- // ../packages/tool-kit/out/setupDisclosure.js
3831
- var require_setupDisclosure = __commonJS({
3832
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3833
- "use strict";
3834
- Object.defineProperty(exports, "__esModule", { value: true });
3835
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3836
- exports.renderSetupDisclosure = renderSetupDisclosure3;
3837
- exports.FAMILY_SENTENCES = {
3838
- 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",
3839
- 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",
3840
- tools: "the name of each tool your agent calls",
3841
- outcome: "whether a call succeeded, failed, or was interrupted",
3842
- clock: "your machine's offset from UTC, so an evening is read as an evening",
3843
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3844
- model: "which model served the session, by name and by tier",
3845
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3846
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
3847
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3848
- context: "how full the context window got",
3849
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3850
- 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",
3851
- 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"
3852
- };
3853
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3854
- exports.REFUSALS = [
3855
- "Never your prompts, your agent's replies, or anything inside a file.",
3856
- "Never a file path, a command line, or a repository or branch name.",
3857
- "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."
3858
- ];
3859
- exports.FREE_TEXT_KEYS = ["message"];
3860
- function renderSetupDisclosure3({ sends, displayName }) {
3861
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3862
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3863
- const lines = [
3864
- `What this sends from ${displayName}, once paired:`,
3865
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3866
- "",
3867
- ...exports.REFUSALS.map((line) => ` ${line}`),
3868
- "",
3869
- " Turn it off by revoking this tool in the Ascenda app."
3870
- ];
3871
- return lines.join("\n");
3872
- }
4371
+ function formatDay(iso) {
4372
+ const date = new Date(iso);
4373
+ if (Number.isNaN(date.getTime()))
4374
+ return iso;
4375
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
4376
+ }
3873
4377
  }
3874
4378
  });
3875
4379
 
@@ -3917,9 +4421,11 @@ var require_hookRunner = __commonJS({
3917
4421
  Object.defineProperty(exports, "__esModule", { value: true });
3918
4422
  exports.hookRunnerPaths = hookRunnerPaths;
3919
4423
  exports.hookLauncherScript = hookLauncherScript2;
4424
+ exports.isDowngrade = isDowngrade;
3920
4425
  exports.installHookRunner = installHookRunner2;
3921
4426
  exports.removeHookRunner = removeHookRunner;
3922
4427
  exports.hookRunnerCommand = hookRunnerCommand2;
4428
+ exports.writeAtomically = writeAtomically;
3923
4429
  exports.lastHookPath = lastHookPath;
3924
4430
  exports.stampLastHook = stampLastHook2;
3925
4431
  exports.readLastHook = readLastHook2;
@@ -3929,10 +4435,11 @@ var require_hookRunner = __commonJS({
3929
4435
  var child_process_1 = __require("child_process");
3930
4436
  var fs5 = __importStar(__require("fs"));
3931
4437
  var path4 = __importStar(__require("path"));
4438
+ var collectorVersion_1 = require_collectorVersion();
3932
4439
  var tokenStore_1 = require_tokenStore();
3933
4440
  function hookRunnerPaths(binaryName) {
3934
4441
  const launcher = path4.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3935
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
4442
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
3936
4443
  }
3937
4444
  var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3938
4445
  function hookLauncherScript2(options) {
@@ -4026,21 +4533,57 @@ var require_hookRunner = __commonJS({
4026
4533
  ""
4027
4534
  ].join("\n");
4028
4535
  }
4536
+ function releaseOf(version) {
4537
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version ?? "").trim());
4538
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
4539
+ }
4540
+ function isDowngrade(installed, incoming) {
4541
+ const have = releaseOf(installed);
4542
+ const want = releaseOf(incoming);
4543
+ if (!have || !want)
4544
+ return false;
4545
+ for (let i = 0; i < 3; i++) {
4546
+ if (have[i] !== want[i])
4547
+ return have[i] > want[i];
4548
+ }
4549
+ return false;
4550
+ }
4551
+ function readInstalledVersion(file) {
4552
+ try {
4553
+ return fs5.readFileSync(file, "utf8").trim() || void 0;
4554
+ } catch {
4555
+ return void 0;
4556
+ }
4557
+ }
4029
4558
  function installHookRunner2(options) {
4030
4559
  const paths = hookRunnerPaths(options.binaryName);
4031
4560
  if (options.dryRun)
4032
4561
  return paths.launcher;
4033
4562
  const source = path4.resolve(options.source ?? process.argv[1]);
4563
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
4564
+ const installed = readInstalledVersion(paths.version);
4565
+ const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
4566
+ if (installed && fs5.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4567
+ options.onKeptNewer?.(installed, incoming);
4568
+ if (process.platform !== "win32" && !fs5.existsSync(paths.launcher))
4569
+ writeAtomically(paths.launcher, hookLauncherScript2(options), 493);
4570
+ return paths.launcher;
4571
+ }
4034
4572
  fs5.mkdirSync(path4.dirname(paths.launcher), { recursive: true });
4035
4573
  if (process.platform === "win32") {
4036
4574
  if (source !== path4.resolve(paths.launcher))
4037
4575
  fs5.copyFileSync(source, paths.launcher);
4576
+ writeAtomically(paths.version, `${incoming}
4577
+ `, 420);
4038
4578
  return paths.launcher;
4039
4579
  }
4040
4580
  if (source !== path4.resolve(paths.bundle))
4041
4581
  writeAtomically(paths.bundle, fs5.readFileSync(source), 493);
4042
4582
  writeAtomically(paths.launcher, hookLauncherScript2(options), 493);
4043
4583
  writeAtomically(paths.record, `${process.execPath}
4584
+ `, 420);
4585
+ if (source !== path4.resolve(paths.bundle))
4586
+ writeAtomically(paths.version, `${incoming}
4044
4587
  `, 420);
4045
4588
  fs5.rmSync(paths.noNode, { force: true });
4046
4589
  return paths.launcher;
@@ -4055,8 +4598,8 @@ var require_hookRunner = __commonJS({
4055
4598
  }
4056
4599
  return removed;
4057
4600
  }
4058
- function hookRunnerCommand2(launcher) {
4059
- return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4601
+ function hookRunnerCommand2(launcher, platform = process.platform) {
4602
+ return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4060
4603
  }
4061
4604
  function writeAtomically(target, contents, mode) {
4062
4605
  const tmp = `${target}.${process.pid}.tmp`;
@@ -4126,6 +4669,115 @@ var require_hookRunner = __commonJS({
4126
4669
  }
4127
4670
  });
4128
4671
 
4672
+ // ../packages/tool-kit/out/settingsFile.js
4673
+ var require_settingsFile = __commonJS({
4674
+ "../packages/tool-kit/out/settingsFile.js"(exports) {
4675
+ "use strict";
4676
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4677
+ if (k2 === void 0) k2 = k;
4678
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4679
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4680
+ desc = { enumerable: true, get: function() {
4681
+ return m[k];
4682
+ } };
4683
+ }
4684
+ Object.defineProperty(o, k2, desc);
4685
+ } : function(o, m, k, k2) {
4686
+ if (k2 === void 0) k2 = k;
4687
+ o[k2] = m[k];
4688
+ });
4689
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4690
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4691
+ } : function(o, v) {
4692
+ o["default"] = v;
4693
+ });
4694
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4695
+ var ownKeys = function(o) {
4696
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4697
+ var ar = [];
4698
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4699
+ return ar;
4700
+ };
4701
+ return ownKeys(o);
4702
+ };
4703
+ return function(mod) {
4704
+ if (mod && mod.__esModule) return mod;
4705
+ var result = {};
4706
+ if (mod != null) {
4707
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4708
+ }
4709
+ __setModuleDefault(result, mod);
4710
+ return result;
4711
+ };
4712
+ }();
4713
+ Object.defineProperty(exports, "__esModule", { value: true });
4714
+ exports.replaceSettingsFile = replaceSettingsFile2;
4715
+ var fs5 = __importStar(__require("fs"));
4716
+ var path4 = __importStar(__require("path"));
4717
+ var hookRunner_1 = require_hookRunner();
4718
+ function replaceSettingsFile2(settingsFile, contents) {
4719
+ const exists = fs5.existsSync(settingsFile);
4720
+ const target = exists ? fs5.realpathSync(settingsFile) : settingsFile;
4721
+ if (exists) {
4722
+ const backup = `${settingsFile}.ascenda-backup`;
4723
+ if (!fs5.existsSync(backup))
4724
+ fs5.copyFileSync(target, backup);
4725
+ }
4726
+ fs5.mkdirSync(path4.dirname(target), { recursive: true });
4727
+ const mode = exists ? fs5.statSync(target).mode & 511 : 420;
4728
+ (0, hookRunner_1.writeAtomically)(target, contents, mode);
4729
+ }
4730
+ }
4731
+ });
4732
+
4733
+ // ../packages/tool-kit/out/setupDisclosure.js
4734
+ var require_setupDisclosure = __commonJS({
4735
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
4736
+ "use strict";
4737
+ Object.defineProperty(exports, "__esModule", { value: true });
4738
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
4739
+ exports.renderSetupDisclosure = renderSetupDisclosure3;
4740
+ exports.FAMILY_SENTENCES = {
4741
+ session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
4742
+ counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
4743
+ tools: "the name of each tool your agent calls",
4744
+ outcome: "whether a call succeeded, failed, or was interrupted",
4745
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
4746
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
4747
+ model: "which model served the session, by name and by tier",
4748
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
4749
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
4750
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
4751
+ context: "how full the context window got",
4752
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, input_request, idle_prompt, or other, and that it asked permission for a tool or had one refused in auto mode, with the tool's name",
4753
+ subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
4754
+ forge: "for a GitHub repository, one digest of owner/repo and one of the branch, which anyone who guesses the names can reproduce, so a pull request can be matched to your session (turn off with setup --no-repo-keys)",
4755
+ turns: "an opaque id your agent gives each prompt, so one turn's events group together",
4756
+ reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
4757
+ };
4758
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
4759
+ exports.REFUSALS = [
4760
+ "Never your prompts, your agent's replies, or anything inside a file.",
4761
+ "Never a file path, a command line, or a repository or branch name.",
4762
+ "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
4763
+ ];
4764
+ exports.FREE_TEXT_KEYS = ["message"];
4765
+ function renderSetupDisclosure3({ sends, displayName }) {
4766
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
4767
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
4768
+ const lines = [
4769
+ `What this sends from ${displayName}, once paired:`,
4770
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
4771
+ "",
4772
+ ...exports.REFUSALS.map((line) => ` ${line}`),
4773
+ "",
4774
+ " Turn it off by revoking this tool in the Ascenda app."
4775
+ ];
4776
+ return lines.join("\n");
4777
+ }
4778
+ }
4779
+ });
4780
+
4129
4781
  // ../packages/tool-kit/out/saverHandoff.js
4130
4782
  var require_saverHandoff = __commonJS({
4131
4783
  "../packages/tool-kit/out/saverHandoff.js"(exports) {
@@ -4179,11 +4831,11 @@ var require_saverHandoff = __commonJS({
4179
4831
  exports.probeSocket = probeSocket;
4180
4832
  var fs5 = __importStar(__require("fs"));
4181
4833
  var net = __importStar(__require("net"));
4182
- var os5 = __importStar(__require("os"));
4834
+ var os4 = __importStar(__require("os"));
4183
4835
  var path4 = __importStar(__require("path"));
4184
4836
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
4185
4837
  function saverContainerDir() {
4186
- return process.env.ASCENDA_SAVER_CONTAINER ?? path4.join(os5.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
4838
+ return process.env.ASCENDA_SAVER_CONTAINER ?? path4.join(os4.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
4187
4839
  }
4188
4840
  function saverSupportDir() {
4189
4841
  return path4.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
@@ -4265,14 +4917,14 @@ var require_saverHandoff = __commonJS({
4265
4917
  }
4266
4918
  }
4267
4919
  function probeSocket(socketPath, timeoutMs = 300) {
4268
- return new Promise((resolve2) => {
4920
+ return new Promise((resolve3) => {
4269
4921
  try {
4270
4922
  if (!fs5.statSync(socketPath).isSocket()) {
4271
- resolve2("absent");
4923
+ resolve3("absent");
4272
4924
  return;
4273
4925
  }
4274
4926
  } catch {
4275
- resolve2("absent");
4927
+ resolve3("absent");
4276
4928
  return;
4277
4929
  }
4278
4930
  let settled = false;
@@ -4282,7 +4934,7 @@ var require_saverHandoff = __commonJS({
4282
4934
  settled = true;
4283
4935
  clearTimeout(timer);
4284
4936
  socket.destroy();
4285
- resolve2(state);
4937
+ resolve3(state);
4286
4938
  };
4287
4939
  const socket = net.createConnection(socketPath);
4288
4940
  const timer = setTimeout(() => finish("unreachable"), timeoutMs);
@@ -4344,7 +4996,7 @@ var require_liveBus = __commonJS({
4344
4996
  exports.deliverLine = deliverLine;
4345
4997
  var fs5 = __importStar(__require("fs"));
4346
4998
  var net = __importStar(__require("net"));
4347
- var os5 = __importStar(__require("os"));
4999
+ var os4 = __importStar(__require("os"));
4348
5000
  var path4 = __importStar(__require("path"));
4349
5001
  var hookSet_1 = require_hookSet();
4350
5002
  var saverHandoff_1 = require_saverHandoff();
@@ -4356,7 +5008,7 @@ var require_liveBus = __commonJS({
4356
5008
  const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
4357
5009
  if (override)
4358
5010
  return [override];
4359
- const home = os5.homedir();
5011
+ const home = os4.homedir();
4360
5012
  return [
4361
5013
  path4.join(home, ".ascenda", "live.sock"),
4362
5014
  path4.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
@@ -4406,10 +5058,10 @@ var require_liveBus = __commonJS({
4406
5058
  });
4407
5059
  }
4408
5060
  function deliverLine(line) {
4409
- return new Promise((resolve2) => {
5061
+ return new Promise((resolve3) => {
4410
5062
  const candidates = existingSocketCandidates();
4411
5063
  if (candidates.length === 0) {
4412
- resolve2(void 0);
5064
+ resolve3(void 0);
4413
5065
  return;
4414
5066
  }
4415
5067
  let settled = false;
@@ -4428,7 +5080,7 @@ var require_liveBus = __commonJS({
4428
5080
  settled = true;
4429
5081
  clearTimeout(timer);
4430
5082
  drop();
4431
- resolve2(accepted);
5083
+ resolve3(accepted);
4432
5084
  };
4433
5085
  const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4434
5086
  const tryFrom = (index) => {
@@ -4628,7 +5280,7 @@ var require_liveSignalDoctor = __commonJS({
4628
5280
  if (accepted !== saverSocket)
4629
5281
  return { tone: "ok", text: `the desktop app took it (${accepted})` };
4630
5282
  for (let waited = 0; waited < 2e3; waited += 100) {
4631
- await new Promise((resolve2) => setTimeout(resolve2, 100));
5283
+ await new Promise((resolve3) => setTimeout(resolve3, 100));
4632
5284
  const answered = (0, saverHandoff_1.readSaverStatuses)().find((status) => status.lastPingSession === session);
4633
5285
  if (answered)
4634
5286
  return { tone: "ok", text: `OK. The screen saver (pid ${answered.pid}) received it` };
@@ -4891,11 +5543,13 @@ var require_cliAgentSetup = __commonJS({
4891
5543
  exports.runCliAgentSetup = runCliAgentSetup;
4892
5544
  exports.writeHookSettings = writeHookSettings;
4893
5545
  exports.registeredHookSets = registeredHookSets;
5546
+ exports.ourHookPositions = ourHookPositions;
5547
+ exports.trustProblemLines = trustProblemLines;
4894
5548
  exports.findStaleHookCommands = findStaleHookCommands2;
4895
5549
  exports.cliAgentRegistrations = cliAgentRegistrations;
4896
5550
  var crypto2 = __importStar(__require("crypto"));
4897
5551
  var fs5 = __importStar(__require("fs"));
4898
- var os5 = __importStar(__require("os"));
5552
+ var os4 = __importStar(__require("os"));
4899
5553
  var path4 = __importStar(__require("path"));
4900
5554
  var collectorVersion_1 = require_collectorVersion();
4901
5555
  var credentials_1 = require_credentials();
@@ -4904,6 +5558,7 @@ var require_cliAgentSetup = __commonJS({
4904
5558
  var http_1 = require_http();
4905
5559
  var hookSet_1 = require_hookSet();
4906
5560
  var initiatives_1 = require_initiatives();
5561
+ var settingsFile_1 = require_settingsFile();
4907
5562
  var setupDisclosure_1 = require_setupDisclosure();
4908
5563
  var hookRunner_1 = require_hookRunner();
4909
5564
  var liveSignalDoctor_1 = require_liveSignalDoctor();
@@ -4920,7 +5575,7 @@ var require_cliAgentSetup = __commonJS({
4920
5575
  return (0, hookRunner_1.hookRunnerPaths)(binaryName).launcher;
4921
5576
  }
4922
5577
  function cliAgentSelfCommand(spec) {
4923
- return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName), os5.homedir());
5578
+ return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName), os4.homedir());
4924
5579
  }
4925
5580
  function usage(spec) {
4926
5581
  return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
@@ -4940,6 +5595,10 @@ Options
4940
5595
  --no-pair install without pairing: local features on, nothing sent
4941
5596
  --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
4942
5597
  On by default when not paired; machine-wide, shared by every agent
5598
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
5599
+ repository gets a key and, off its default branch, a branch key, so a pull
5600
+ request can be matched to a session. They are digests anyone who guesses the
5601
+ names can reproduce. Machine-wide. --repo-keys turns them back on
4943
5602
  --scope user|project where hooks are registered (default user: every project)
4944
5603
  --project-dir <path> project root for --scope project (default cwd)
4945
5604
  --dry-run print what would change, write nothing
@@ -4983,9 +5642,9 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4983
5642
  const binary = installBinary2(spec, options.dryRun);
4984
5643
  const node = options.dryRun || process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
4985
5644
  if (node?.problem)
4986
- row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os5.homedir())}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
5645
+ row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os4.homedir())}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
4987
5646
  else
4988
- row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os5.homedir())}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
5647
+ row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os4.homedir())}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
4989
5648
  if (!options.dryRun) {
4990
5649
  const now = (/* @__PURE__ */ new Date()).toISOString();
4991
5650
  const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
@@ -4996,6 +5655,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4996
5655
  });
4997
5656
  if (options.eventLog !== void 0)
4998
5657
  (0, credentials_1.writeEventLogSetting)(options.eventLog);
5658
+ if (options.repoKeys !== void 0)
5659
+ (0, credentials_1.writeRepoKeysSetting)(options.repoKeys);
4999
5660
  }
5000
5661
  if (isHomeProject2(options)) {
5001
5662
  detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
@@ -5007,18 +5668,18 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5007
5668
  if (written === null)
5008
5669
  return 1;
5009
5670
  const reach = options.scope === "user" ? "every project" : "this project only";
5010
- row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile, os5.homedir())} ${ui.dim(`(${spec.hookEvents.length} events, ${reach}${written ? "" : ", already current"})`)}`);
5671
+ row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile, os4.homedir())} ${ui.dim(`(${spec.hookEvents.length} events, ${reach}${written ? "" : ", already current"})`)}`);
5011
5672
  const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
5012
5673
  if (changes)
5013
5674
  detail("", changes);
5014
5675
  const otherFile = spec.settings.settingsPath(options.scope === "user" ? "project" : "user", options.projectDir);
5015
5676
  if (otherFile !== settingsFile && registeredHookSets(readSettings(otherFile), spec).size > 0) {
5016
5677
  if (options.dryRun) {
5017
- row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os5.homedir())}, so each event runs once`);
5678
+ row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())}, so each event runs once`);
5018
5679
  } else if (removeOurHookEntries(otherFile, spec)) {
5019
- row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os5.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
5680
+ row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
5020
5681
  } else {
5021
- row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os5.homedir())} registers these hooks too, so each event runs twice.`);
5682
+ row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os4.homedir())} registers these hooks too, so each event runs twice.`);
5022
5683
  detail("", `Remove the ${spec.binaryName} entries from one of the two files.`);
5023
5684
  }
5024
5685
  }
@@ -5029,10 +5690,10 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5029
5690
  row("info", "pairing", `none, as asked ${ui.dim("(--no-pair)")}`);
5030
5691
  else
5031
5692
  row("warn", "pairing", "not paired: pairing did not finish");
5032
- detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os5.homedir())} (tools.${spec.host})`);
5693
+ detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os4.homedir())} (tools.${spec.host})`);
5033
5694
  const eventLog = (0, eventLog_1.resolveEventLog)({ localOnly: !identity });
5034
5695
  if (eventLog.path)
5035
- row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path, os5.homedir())} ${ui.dim("(on this machine only)")}`);
5696
+ row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path, os4.homedir())} ${ui.dim("(on this machine only)")}`);
5036
5697
  else if (options.eventLog !== void 0)
5037
5698
  row("info", "events", "off");
5038
5699
  if (options.dryRun) {
@@ -5046,7 +5707,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5046
5707
  console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
5047
5708
  console.log(" They run on this machine and need no account or pairing.");
5048
5709
  if (eventLog.path)
5049
- console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os5.homedir())}, for you or any tool to read.`);
5710
+ console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os4.homedir())}, for you or any tool to read.`);
5050
5711
  } else if (!identity) {
5051
5712
  console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
5052
5713
  console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
@@ -5069,7 +5730,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5069
5730
  return 0;
5070
5731
  }
5071
5732
  function isHomeProject2(options) {
5072
- return options.scope === "project" && path4.resolve(options.projectDir) === path4.resolve(os5.homedir());
5733
+ return options.scope === "project" && path4.resolve(options.projectDir) === path4.resolve(os4.homedir());
5073
5734
  }
5074
5735
  function parseArgs2(argv, spec) {
5075
5736
  const options = {
@@ -5135,6 +5796,12 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5135
5796
  i += consumed;
5136
5797
  break;
5137
5798
  }
5799
+ case "--repo-keys":
5800
+ options.repoKeys = true;
5801
+ break;
5802
+ case "--no-repo-keys":
5803
+ options.repoKeys = false;
5804
+ break;
5138
5805
  case "--no-pair":
5139
5806
  // `--no-pairing` is the spelling this landed under first. Both appeared
5140
5807
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -5215,7 +5882,7 @@ ${usage(spec)}`);
5215
5882
  const toolInstallationId = existingId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
5216
5883
  let session;
5217
5884
  try {
5218
- session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os5.hostname()}`);
5885
+ session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os4.hostname()}`);
5219
5886
  } catch (error) {
5220
5887
  console.error(`
5221
5888
  Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
@@ -5258,13 +5925,18 @@ Pairing ${status.status}. Run setup again.`);
5258
5925
  console.log(" Waiting...");
5259
5926
  announced = true;
5260
5927
  }
5261
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
5928
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
5262
5929
  }
5263
5930
  console.error("\nPairing timed out. Run setup again.");
5264
5931
  return void 0;
5265
5932
  }
5266
5933
  function installBinary2(spec, dryRun) {
5267
- return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
5934
+ return (0, hookRunner_1.installHookRunner)({
5935
+ binaryName: spec.binaryName,
5936
+ setupCommand: `npx ${spec.packageName} setup`,
5937
+ dryRun,
5938
+ onKeptNewer: (installed, incoming) => console.log(` Kept the installed hook bundle (${installed}) rather than replace it with this older ${incoming}. Run setup from the newer version to change it.`)
5939
+ });
5268
5940
  }
5269
5941
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
5270
5942
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -5284,8 +5956,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5284
5956
  const command = hookCommand2(binary, spec);
5285
5957
  const hooks = { ...settings.hooks ?? {} };
5286
5958
  for (const event of spec.hookEvents) {
5287
- const kept = (hooks[event] ?? []).filter((entry) => !isOurs2(entry, spec));
5288
- hooks[event] = [...kept, spec.settings.entry(command, event)];
5959
+ hooks[event] = placeOurEntry2(hooks[event] ?? [], spec.settings.entry(command, event), spec);
5289
5960
  }
5290
5961
  const updated = { ...settings, hooks };
5291
5962
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -5298,10 +5969,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5298
5969
  ${serialised}`);
5299
5970
  return true;
5300
5971
  }
5301
- if (exists)
5302
- fs5.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5303
- fs5.mkdirSync(path4.dirname(settingsFile), { recursive: true });
5304
- fs5.writeFileSync(settingsFile, serialised, "utf8");
5972
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
5305
5973
  return true;
5306
5974
  }
5307
5975
  function hookCommand2(binary, spec) {
@@ -5311,28 +5979,130 @@ ${serialised}`);
5311
5979
  const sets = /* @__PURE__ */ new Map();
5312
5980
  for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
5313
5981
  for (const entry of entries ?? []) {
5314
- if (!isOurs2(entry, spec))
5315
- continue;
5316
- const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
5317
- sets.set(event, Math.min(set, sets.get(event) ?? set));
5982
+ for (const command of commandsOf(entry, spec)) {
5983
+ if (!isOurCommand(command, spec))
5984
+ continue;
5985
+ const set = (0, hookSet_1.hookSetOfCommand)(command);
5986
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5987
+ }
5318
5988
  }
5319
5989
  }
5320
5990
  return sets;
5321
5991
  }
5322
- function isOurs2(entry, spec) {
5992
+ function ourHookPositions(settings, spec) {
5993
+ const found = [];
5994
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5995
+ (groups ?? []).forEach((group, groupIndex) => {
5996
+ const handlers = group?.hooks;
5997
+ if (Array.isArray(handlers)) {
5998
+ handlers.forEach((handler, handlerIndex) => {
5999
+ if (isOurs2({ hooks: [handler] }, spec))
6000
+ found.push({ event, group: groupIndex, handler: handlerIndex });
6001
+ });
6002
+ } else if (isOurs2(group, spec)) {
6003
+ found.push({ event, group: groupIndex, handler: 0 });
6004
+ }
6005
+ });
6006
+ }
6007
+ return found;
6008
+ }
6009
+ function trustProblemLines(spec, settingsFile, settings, indent) {
6010
+ if (!spec.trust)
6011
+ return [];
6012
+ const ours = ourHookPositions(settings, spec);
6013
+ if (ours.length === 0)
6014
+ return [];
6015
+ const report = spec.trust.check(settingsFile, ours);
6016
+ const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os4.homedir());
6017
+ const lines = [];
6018
+ if (report.unreadable) {
6019
+ lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
6020
+ }
6021
+ if (report.untrusted.length) {
6022
+ const names = [...new Set(report.untrusted.map((position) => position.event))].join(", ");
6023
+ lines.push(`${report.untrusted.length} of ${ours.length} hooks are not approved in ${where} (${names}). ${spec.displayName} skips them without a message, so nothing is sent for those events.`);
6024
+ }
6025
+ for (const entry of report.stale)
6026
+ lines.push(entry);
6027
+ if (lines.length)
6028
+ lines.push(spec.trust.fix);
6029
+ return lines.map((line) => `${indent}${line}`);
6030
+ }
6031
+ function commandsOf(entry, spec) {
6032
+ if (spec.settings.grouped) {
6033
+ return innerHooks(entry).map(commandOfHook).filter((command2) => typeof command2 === "string");
6034
+ }
5323
6035
  const command = spec.settings.commandOf(entry);
5324
- return typeof command === "string" && command.includes(spec.binaryName);
6036
+ return typeof command === "string" ? [command] : [];
6037
+ }
6038
+ function innerHooks(entry) {
6039
+ const hooks = entry && typeof entry === "object" ? entry.hooks : void 0;
6040
+ return Array.isArray(hooks) ? hooks : [];
6041
+ }
6042
+ function commandOfHook(hook) {
6043
+ return hook && typeof hook === "object" ? hook.command : void 0;
6044
+ }
6045
+ function isOurCommand(command, spec) {
6046
+ return command.includes(spec.binaryName);
6047
+ }
6048
+ function isOurs2(entry, spec) {
6049
+ return commandsOf(entry, spec).some((command) => isOurCommand(command, spec));
6050
+ }
6051
+ function isOurInnerHook(hook, spec) {
6052
+ const command = commandOfHook(hook);
6053
+ return typeof command === "string" && isOurCommand(command, spec);
6054
+ }
6055
+ function withoutOurEntries2(entries, spec) {
6056
+ if (!spec.settings.grouped)
6057
+ return entries.filter((entry) => !isOurs2(entry, spec));
6058
+ const kept = [];
6059
+ for (const entry of entries) {
6060
+ if (!isOurs2(entry, spec)) {
6061
+ kept.push(entry);
6062
+ continue;
6063
+ }
6064
+ const others = innerHooks(entry).filter((hook) => !isOurInnerHook(hook, spec));
6065
+ if (others.length)
6066
+ kept.push({ ...entry, hooks: others });
6067
+ }
6068
+ return kept;
6069
+ }
6070
+ function placeOurEntry2(entries, wanted, spec) {
6071
+ if (!spec.settings.grouped)
6072
+ return [...withoutOurEntries2(entries, spec), wanted];
6073
+ const replacements = innerHooks(wanted);
6074
+ let placed = false;
6075
+ const result = [];
6076
+ for (const entry of entries) {
6077
+ if (!isOurs2(entry, spec)) {
6078
+ result.push(entry);
6079
+ continue;
6080
+ }
6081
+ const matcher = entry.matcher;
6082
+ const matchesAll = matcher === void 0 || matcher === "";
6083
+ const next = [];
6084
+ for (const hook of innerHooks(entry)) {
6085
+ if (!isOurInnerHook(hook, spec))
6086
+ next.push(hook);
6087
+ else if (!placed && matchesAll) {
6088
+ next.push(...replacements);
6089
+ placed = true;
6090
+ }
6091
+ }
6092
+ if (next.length)
6093
+ result.push({ ...entry, hooks: next });
6094
+ }
6095
+ return placed ? result : [...result, wanted];
5325
6096
  }
5326
6097
  function findStaleHookCommands2(settings, binary, spec) {
5327
6098
  const stale = /* @__PURE__ */ new Set();
5328
6099
  for (const entries of Object.values(settings.hooks ?? {})) {
5329
6100
  for (const entry of entries ?? []) {
5330
- const command = spec.settings.commandOf(entry);
5331
- if (typeof command !== "string")
5332
- continue;
5333
- if (!/ascenda/i.test(command) || command.includes(binary))
5334
- continue;
5335
- stale.add(command);
6101
+ for (const command of commandsOf(entry, spec)) {
6102
+ if (!/ascenda/i.test(command) || command.includes(binary))
6103
+ continue;
6104
+ stale.add(command);
6105
+ }
5336
6106
  }
5337
6107
  }
5338
6108
  return [...stale];
@@ -5376,6 +6146,14 @@ ${serialised}`);
5376
6146
  const oldest = Math.min(...sets);
5377
6147
  console.log(oldest < spec.hookSet ? `hook set ${oldest}, this version registers ${spec.hookSet}. Upgrade: npx ${spec.packageName} setup${options.scope === "user" ? " --scope user" : ""}` : `hook set ${spec.hookSet} (current)`);
5378
6148
  }
6149
+ const trustLines = trustProblemLines(spec, settingsFile, settings, "");
6150
+ if (trustLines.length) {
6151
+ console.log(`not trusted ${trustLines[0]}`);
6152
+ for (const line of trustLines.slice(1))
6153
+ console.log(` ${line}`);
6154
+ } else if (spec.trust && registered > 0) {
6155
+ console.log("trust every registered hook is approved");
6156
+ }
5379
6157
  if (stale.length) {
5380
6158
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
5381
6159
  for (const command of stale)
@@ -5397,14 +6175,14 @@ ${serialised}`);
5397
6175
  await notices.markShown();
5398
6176
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
5399
6177
  const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5400
- const healthy = paired && wired && fs5.existsSync(binary) && !stale.length && !node?.problem;
6178
+ const healthy = paired && wired && fs5.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
5401
6179
  return healthy ? 0 : 1;
5402
6180
  }
5403
6181
  function countRegistered2(settings, spec) {
5404
6182
  return spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs2(entry, spec))).length;
5405
6183
  }
5406
6184
  function cliAgentRegistrations(spec, projectDir = process.cwd()) {
5407
- const home = os5.homedir();
6185
+ const home = os4.homedir();
5408
6186
  const userFile = spec.settings.settingsPath("user", projectDir);
5409
6187
  const projectFile = spec.settings.settingsPath("project", projectDir);
5410
6188
  const found = [];
@@ -5440,12 +6218,37 @@ ${serialised}`);
5440
6218
  } catch (error) {
5441
6219
  lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
5442
6220
  }
6221
+ if (spec.trust) {
6222
+ const found = trustDoctorLines(spec, options.projectDir, ui);
6223
+ if (found.length)
6224
+ lines.push("", ...found);
6225
+ }
5443
6226
  lines.push("", ...accountLines(ui, spec));
5444
6227
  const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
5445
6228
  lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5446
6229
  console.log(lines.join("\n"));
5447
6230
  return 0;
5448
6231
  }
6232
+ function trustDoctorLines(spec, projectDir, ui) {
6233
+ const userFile = spec.settings.settingsPath("user", projectDir);
6234
+ const projectFile = spec.settings.settingsPath("project", projectDir);
6235
+ const files = userFile === projectFile ? [userFile] : [userFile, projectFile];
6236
+ const out = [];
6237
+ for (const file of files) {
6238
+ const settings = readSettings(file);
6239
+ if (ourHookPositions(settings, spec).length === 0)
6240
+ continue;
6241
+ const problems = trustProblemLines(spec, file, settings, "");
6242
+ if (problems.length === 0) {
6243
+ out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os4.homedir())} is approved`);
6244
+ continue;
6245
+ }
6246
+ out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
6247
+ for (const line of problems.slice(1))
6248
+ out.push(`${" ".repeat(25)}${line}`);
6249
+ }
6250
+ return out;
6251
+ }
5449
6252
  function accountLines(ui, spec) {
5450
6253
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5451
6254
  const id = credentials?.toolInstallationId;
@@ -5479,7 +6282,7 @@ ${serialised}`);
5479
6282
  const settings = JSON.parse(fs5.readFileSync(settingsFile, "utf8"));
5480
6283
  const hooks = { ...settings.hooks ?? {} };
5481
6284
  for (const event of Object.keys(hooks)) {
5482
- const kept = hooks[event].filter((entry) => !isOurs2(entry, spec));
6285
+ const kept = withoutOurEntries2(hooks[event], spec);
5483
6286
  if (kept.length)
5484
6287
  hooks[event] = kept;
5485
6288
  else
@@ -5488,9 +6291,8 @@ ${serialised}`);
5488
6291
  const updated = { ...settings, hooks };
5489
6292
  if (!Object.keys(hooks).length)
5490
6293
  delete updated.hooks;
5491
- fs5.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5492
- fs5.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5493
- `, "utf8");
6294
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
6295
+ `);
5494
6296
  return true;
5495
6297
  } catch {
5496
6298
  return false;
@@ -5562,7 +6364,9 @@ var require_turnState = __commonJS({
5562
6364
  }();
5563
6365
  Object.defineProperty(exports, "__esModule", { value: true });
5564
6366
  exports.recordTurnStart = recordTurnStart;
6367
+ exports.readTurnPromptId = readTurnPromptId;
5565
6368
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
6369
+ var crypto_1 = __require("crypto");
5566
6370
  var fs5 = __importStar(__require("fs"));
5567
6371
  var path4 = __importStar(__require("path"));
5568
6372
  var tokenStore_1 = require_tokenStore();
@@ -5575,11 +6379,24 @@ var require_turnState = __commonJS({
5575
6379
  }
5576
6380
  function recordTurnStart(agent, sessionId, now = Date.now()) {
5577
6381
  if (!sessionId)
5578
- return;
6382
+ return void 0;
5579
6383
  try {
6384
+ const promptId = (0, crypto_1.randomUUID)();
5580
6385
  fs5.mkdirSync(stateDir(), { recursive: true });
5581
- fs5.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
6386
+ fs5.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
6387
+ return promptId;
6388
+ } catch {
6389
+ return void 0;
6390
+ }
6391
+ }
6392
+ function readTurnPromptId(agent, sessionId) {
6393
+ if (!sessionId)
6394
+ return void 0;
6395
+ try {
6396
+ const id = fs5.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
6397
+ return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
5582
6398
  } catch {
6399
+ return void 0;
5583
6400
  }
5584
6401
  }
5585
6402
  function consumeTurnDurationMs(agent, sessionId, now = Date.now()) {
@@ -5587,7 +6404,7 @@ var require_turnState = __commonJS({
5587
6404
  return void 0;
5588
6405
  const file = turnFile(agent, sessionId);
5589
6406
  try {
5590
- const started = Number(fs5.readFileSync(file, "utf8").trim());
6407
+ const started = Number(fs5.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
5591
6408
  fs5.rmSync(file, { force: true });
5592
6409
  if (!Number.isFinite(started) || started <= 0 || started > now)
5593
6410
  return void 0;
@@ -5743,10 +6560,11 @@ var require_out3 = __commonJS({
5743
6560
  "../packages/tool-kit/out/index.js"(exports) {
5744
6561
  "use strict";
5745
6562
  Object.defineProperty(exports, "__esModule", { value: true });
5746
- exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.resolveEventLog = exports.parseEventLogFlag = exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
5747
- exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = exports.isCliAgentManagementCommand = void 0;
5748
- exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = void 0;
5749
- exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = void 0;
6563
+ exports.resolveEventLog = exports.parseEventLogFlag = exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.startBackgroundFlush = exports.runOutboxFlush = exports.hookDeliveryInline = exports.flushLockPath = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = exports.FLUSH_LOCK_FRESH_MS = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.shellCommandFacts = exports.invitesDebrief = exports.classifyMcpWorkMilestone = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
6564
+ exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.readTurnPromptId = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeRepoKeysSetting = exports.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.trustProblemLines = exports.runCliAgentSetup = exports.registeredHookSets = exports.ourHookPositions = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.withPromptId = exports.withForgeKeys = exports.loadCliAgentConfig = exports.flushHookOutbox = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = void 0;
6565
+ exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.repoKeysEnabled = exports.deriveForgeKeysForCwd = exports.REPO_KEYS_ENV_VAR = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeBranchKey = exports.forgeRepoKey = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = void 0;
6566
+ exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.replaceSettingsFile = exports.writeAtomically = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.isDowngrade = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = void 0;
6567
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = void 0;
5750
6568
  var commandClassifier_1 = require_commandClassifier();
5751
6569
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5752
6570
  return commandClassifier_1.classifyCommand;
@@ -5765,9 +6583,16 @@ var require_out3 = __commonJS({
5765
6583
  Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
5766
6584
  return workMilestoneClassifier_1.classifyWorkMilestone;
5767
6585
  } });
6586
+ Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
6587
+ return workMilestoneClassifier_1.classifyMcpWorkMilestone;
6588
+ } });
5768
6589
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
5769
6590
  return workMilestoneClassifier_1.invitesDebrief;
5770
6591
  } });
6592
+ var shellFacts_1 = require_shellFacts();
6593
+ Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
6594
+ return shellFacts_1.shellCommandFacts;
6595
+ } });
5771
6596
  var autonomyBand_1 = require_autonomyBand();
5772
6597
  Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
5773
6598
  return autonomyBand_1.autonomyBand;
@@ -5837,6 +6662,28 @@ var require_out3 = __commonJS({
5837
6662
  Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
5838
6663
  return collectorVersion_1.describeCollectorVersion;
5839
6664
  } });
6665
+ var backgroundDelivery_1 = require_backgroundDelivery();
6666
+ Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
6667
+ return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
6668
+ } });
6669
+ Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
6670
+ return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
6671
+ } });
6672
+ Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
6673
+ return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
6674
+ } });
6675
+ Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
6676
+ return backgroundDelivery_1.flushLockPath;
6677
+ } });
6678
+ Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
6679
+ return backgroundDelivery_1.hookDeliveryInline;
6680
+ } });
6681
+ Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
6682
+ return backgroundDelivery_1.runOutboxFlush;
6683
+ } });
6684
+ Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
6685
+ return backgroundDelivery_1.startBackgroundFlush;
6686
+ } });
5840
6687
  var eventSender_1 = require_eventSender();
5841
6688
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
5842
6689
  return eventSender_1.AscendaEventSender;
@@ -5895,9 +6742,18 @@ var require_out3 = __commonJS({
5895
6742
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
5896
6743
  return hookAdapter_1.deliverHookEvents;
5897
6744
  } });
6745
+ Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
6746
+ return hookAdapter_1.flushHookOutbox;
6747
+ } });
5898
6748
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
5899
6749
  return hookAdapter_1.loadCliAgentConfig;
5900
6750
  } });
6751
+ Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
6752
+ return hookAdapter_1.withForgeKeys;
6753
+ } });
6754
+ Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
6755
+ return hookAdapter_1.withPromptId;
6756
+ } });
5901
6757
  Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
5902
6758
  return hookAdapter_1.resolveCliAgentInstallationId;
5903
6759
  } });
@@ -5914,12 +6770,18 @@ var require_out3 = __commonJS({
5914
6770
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
5915
6771
  return cliAgentSetup_1.isCliAgentManagementCommand;
5916
6772
  } });
6773
+ Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
6774
+ return cliAgentSetup_1.ourHookPositions;
6775
+ } });
5917
6776
  Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5918
6777
  return cliAgentSetup_1.registeredHookSets;
5919
6778
  } });
5920
6779
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
5921
6780
  return cliAgentSetup_1.runCliAgentSetup;
5922
6781
  } });
6782
+ Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
6783
+ return cliAgentSetup_1.trustProblemLines;
6784
+ } });
5923
6785
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
5924
6786
  return cliAgentSetup_1.writeHookSettings;
5925
6787
  } });
@@ -5961,6 +6823,9 @@ var require_out3 = __commonJS({
5961
6823
  Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
5962
6824
  return credentials_1.writeEventLogSetting;
5963
6825
  } });
6826
+ Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
6827
+ return credentials_1.writeRepoKeysSetting;
6828
+ } });
5964
6829
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5965
6830
  return credentials_1.writeMachineCredentials;
5966
6831
  } });
@@ -5971,6 +6836,9 @@ var require_out3 = __commonJS({
5971
6836
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
5972
6837
  return turnState_1.consumeTurnDurationMs;
5973
6838
  } });
6839
+ Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
6840
+ return turnState_1.readTurnPromptId;
6841
+ } });
5974
6842
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
5975
6843
  return turnState_1.recordTurnStart;
5976
6844
  } });
@@ -6105,6 +6973,12 @@ var require_out3 = __commonJS({
6105
6973
  Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
6106
6974
  return forgeProject_1.forgeProjectHash;
6107
6975
  } });
6976
+ Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
6977
+ return forgeProject_1.forgeRepoKey;
6978
+ } });
6979
+ Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
6980
+ return forgeProject_1.forgeBranchKey;
6981
+ } });
6108
6982
  Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
6109
6983
  return forgeProject_1.parseForgeFullName;
6110
6984
  } });
@@ -6117,6 +6991,16 @@ var require_out3 = __commonJS({
6117
6991
  Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
6118
6992
  return forgeProject_1.recordForgeProjectAlias;
6119
6993
  } });
6994
+ var forgeKeys_1 = require_forgeKeys();
6995
+ Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
6996
+ return forgeKeys_1.REPO_KEYS_ENV_VAR;
6997
+ } });
6998
+ Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
6999
+ return forgeKeys_1.deriveForgeKeysForCwd;
7000
+ } });
7001
+ Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
7002
+ return forgeKeys_1.repoKeysEnabled;
7003
+ } });
6120
7004
  var liveBus_1 = require_liveBus();
6121
7005
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
6122
7006
  return liveBus_1.emitLiveSignal;
@@ -6187,6 +7071,9 @@ var require_out3 = __commonJS({
6187
7071
  Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
6188
7072
  return hookRunner_1.installHookRunner;
6189
7073
  } });
7074
+ Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
7075
+ return hookRunner_1.isDowngrade;
7076
+ } });
6190
7077
  Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
6191
7078
  return hookRunner_1.lastHookPath;
6192
7079
  } });
@@ -6205,6 +7092,13 @@ var require_out3 = __commonJS({
6205
7092
  Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
6206
7093
  return hookRunner_1.tidyHomePath;
6207
7094
  } });
7095
+ Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
7096
+ return hookRunner_1.writeAtomically;
7097
+ } });
7098
+ var settingsFile_1 = require_settingsFile();
7099
+ Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
7100
+ return settingsFile_1.replaceSettingsFile;
7101
+ } });
6208
7102
  var liveSignalDoctor_1 = require_liveSignalDoctor();
6209
7103
  Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
6210
7104
  return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
@@ -6364,7 +7258,9 @@ var init_types = __esm({
6364
7258
  "Notification",
6365
7259
  "SessionEnd",
6366
7260
  "SubagentStart",
6367
- "SubagentStop"
7261
+ "SubagentStop",
7262
+ "PermissionRequest",
7263
+ "PermissionDenied"
6368
7264
  ];
6369
7265
  ASCENDA_TOOL_TYPE = "claude_code";
6370
7266
  CLAUDE_HOST = "claude_code";
@@ -6372,20 +7268,24 @@ var init_types = __esm({
6372
7268
  });
6373
7269
 
6374
7270
  // src/paths.ts
6375
- import * as fs2 from "fs";
6376
- import * as os2 from "os";
6377
- import * as path2 from "path";
7271
+ import * as fs from "fs";
7272
+ import * as os from "os";
7273
+ import * as path from "path";
7274
+ function claudeConfigDir() {
7275
+ const configured = process.env.CLAUDE_CONFIG_DIR?.trim();
7276
+ return configured ? path.resolve(configured) : path.join(os.homedir(), ".claude");
7277
+ }
6378
7278
  function hookBinPath() {
6379
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook");
7279
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook");
6380
7280
  }
6381
7281
  function hookBundlePath() {
6382
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.mjs");
7282
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.mjs");
6383
7283
  }
6384
7284
  function hookNodeRecordPath() {
6385
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.node");
7285
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.node");
6386
7286
  }
6387
7287
  function hookNoNodePath() {
6388
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.no-node");
7288
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.no-node");
6389
7289
  }
6390
7290
  function readCredentials() {
6391
7291
  const credentials = (0, import_tool_kit5.readMachineCredentials)();
@@ -6403,11 +7303,11 @@ function removeCredentials() {
6403
7303
  (0, import_tool_kit5.writeMachineCredentials)({ tools: credentials.tools });
6404
7304
  return;
6405
7305
  }
6406
- fs2.rmSync((0, import_tool_kit5.credentialsFilePath)(), { force: true });
7306
+ fs.rmSync((0, import_tool_kit5.credentialsFilePath)(), { force: true });
6407
7307
  }
6408
7308
  function selfCommand() {
6409
7309
  if (process.platform === "win32") return "npx @ascenda-one/claude-code-hooks";
6410
- const home = os2.homedir();
7310
+ const home = os.homedir();
6411
7311
  const bin = hookBinPath();
6412
7312
  return bin.startsWith(`${home}/`) ? `~${bin.slice(home.length)}` : bin;
6413
7313
  }
@@ -6560,7 +7460,7 @@ __export(setup_exports, {
6560
7460
  });
6561
7461
  import * as crypto from "crypto";
6562
7462
  import * as fs3 from "fs";
6563
- import * as os3 from "os";
7463
+ import * as os2 from "os";
6564
7464
  import * as path3 from "path";
6565
7465
  async function runSetup(argv) {
6566
7466
  let options;
@@ -6603,6 +7503,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6603
7503
  ...unpaired ? { localOnly: true, installedAt: now } : { pairedAt: now }
6604
7504
  });
6605
7505
  if (options.eventLog !== void 0) (0, import_tool_kit11.writeEventLogSetting)(options.eventLog);
7506
+ if (options.repoKeys !== void 0) (0, import_tool_kit11.writeRepoKeysSetting)(options.repoKeys);
6606
7507
  }
6607
7508
  if (isHomeProject(options)) {
6608
7509
  detail("scope", "user (a project install in the home folder only loads when Claude Code starts there)");
@@ -6620,7 +7521,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6620
7521
  settingsPath({ ...options, scope: options.scope === "user" ? "project" : "user" }),
6621
7522
  // The home folder's project file, where a project-scope setup run from
6622
7523
  // `~` used to put them.
6623
- path3.join(os3.homedir(), ".claude", "settings.local.json")
7524
+ homeProjectSettingsPath()
6624
7525
  ]);
6625
7526
  otherFiles.delete(settingsFile);
6626
7527
  for (const otherFile of otherFiles) {
@@ -6734,6 +7635,12 @@ function parseArgs(argv) {
6734
7635
  i += consumed;
6735
7636
  break;
6736
7637
  }
7638
+ case "--repo-keys":
7639
+ options.repoKeys = true;
7640
+ break;
7641
+ case "--no-repo-keys":
7642
+ options.repoKeys = false;
7643
+ break;
6737
7644
  case "--no-pair":
6738
7645
  // `--no-pairing` is the spelling the CLI agents' setup landed under
6739
7646
  // first, and the one their README still showed for a day. Both parse
@@ -6758,7 +7665,7 @@ ${USAGE}`);
6758
7665
  return options;
6759
7666
  }
6760
7667
  function isHomeProject(options) {
6761
- return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os3.homedir());
7668
+ return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os2.homedir());
6762
7669
  }
6763
7670
  async function resolveIdentity(apiBaseUrl, options) {
6764
7671
  const existingId = options.toolInstallationId ?? readCredentials()?.toolInstallationId;
@@ -6778,7 +7685,7 @@ async function resolveIdentity(apiBaseUrl, options) {
6778
7685
  }
6779
7686
  let session;
6780
7687
  try {
6781
- session = await (0, import_tool_kit11.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os3.hostname()}`);
7688
+ session = await (0, import_tool_kit11.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os2.hostname()}`);
6782
7689
  } catch (error) {
6783
7690
  return {
6784
7691
  toolInstallationId,
@@ -6805,7 +7712,7 @@ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
6805
7712
  if (++failures >= POLL_ERROR_TOLERANCE) {
6806
7713
  return { reason: `lost contact while waiting (${error instanceof Error ? error.message : String(error)})` };
6807
7714
  }
6808
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
7715
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
6809
7716
  continue;
6810
7717
  }
6811
7718
  if (status.status === "paired" && status.eventWriteToken) return { token: status.eventWriteToken };
@@ -6816,22 +7723,29 @@ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
6816
7723
  console.log(" Waiting...");
6817
7724
  announced = true;
6818
7725
  }
6819
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
7726
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
6820
7727
  }
6821
7728
  return { reason: "no confirmation within 5 minutes" };
6822
7729
  }
6823
7730
  function tidyHome(file) {
6824
- const home = os3.homedir();
7731
+ const home = os2.homedir();
6825
7732
  return file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
6826
7733
  }
6827
7734
  function restartLine(options) {
6828
7735
  return options.scope === "user" ? "Restart Claude Code to load the hooks." : "Restart Claude Code in this project to load the hooks.";
6829
7736
  }
6830
7737
  function installBinary(dryRun) {
6831
- return (0, import_tool_kit11.installHookRunner)({ ...LAUNCHER_OPTIONS, dryRun });
7738
+ return (0, import_tool_kit11.installHookRunner)({
7739
+ ...LAUNCHER_OPTIONS,
7740
+ dryRun,
7741
+ onKeptNewer: (installed, incoming) => console.log(`Kept the installed hook bundle (${installed}) rather than replace it with this older ${incoming}. Run setup from the newer version to change it.`)
7742
+ });
6832
7743
  }
6833
7744
  function settingsPath(options) {
6834
- return options.scope === "user" ? path3.join(os3.homedir(), ".claude", "settings.json") : path3.join(options.projectDir, ".claude", "settings.local.json");
7745
+ return options.scope === "user" ? path3.join(claudeConfigDir(), "settings.json") : path3.join(options.projectDir, ".claude", "settings.local.json");
7746
+ }
7747
+ function homeProjectSettingsPath() {
7748
+ return path3.join(os2.homedir(), ".claude", "settings.local.json");
6835
7749
  }
6836
7750
  function writeSettings(settingsFile, binary, dryRun) {
6837
7751
  let settings = {};
@@ -6851,8 +7765,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
6851
7765
  const command = hookCommand(binary);
6852
7766
  const hooks = { ...settings.hooks ?? {} };
6853
7767
  for (const event of HOOK_EVENTS) {
6854
- const kept = (hooks[event] ?? []).filter((group) => !isOurs(group));
6855
- hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}${(0, import_tool_kit11.hookSetArgument)(HOOK_SET)}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
7768
+ hooks[event] = placeOurEntry(hooks[event] ?? [], { type: "command", command: `${command} ${event}${(0, import_tool_kit11.hookSetArgument)(HOOK_SET)}`, timeout: HOOK_TIMEOUT_SECONDS });
6856
7769
  }
6857
7770
  const updated = { ...settings, hooks };
6858
7771
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -6864,9 +7777,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
6864
7777
  ${serialised}`);
6865
7778
  return true;
6866
7779
  }
6867
- if (exists) fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
6868
- fs3.mkdirSync(path3.dirname(settingsFile), { recursive: true });
6869
- fs3.writeFileSync(settingsFile, serialised, "utf8");
7780
+ (0, import_tool_kit11.replaceSettingsFile)(settingsFile, serialised);
6870
7781
  return true;
6871
7782
  }
6872
7783
  function hookCommand(binary) {
@@ -6877,22 +7788,57 @@ function removeOurHooks(settingsFile) {
6877
7788
  const settings = JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
6878
7789
  const hooks = { ...settings.hooks ?? {} };
6879
7790
  for (const event of Object.keys(hooks)) {
6880
- const kept = hooks[event].filter((group) => !isOurs(group));
7791
+ const kept = withoutOurEntries(hooks[event]);
6881
7792
  if (kept.length) hooks[event] = kept;
6882
7793
  else delete hooks[event];
6883
7794
  }
6884
7795
  const updated = { ...settings, hooks };
6885
7796
  if (!Object.keys(hooks).length) delete updated.hooks;
6886
- fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
6887
- fs3.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
6888
- `, "utf8");
7797
+ (0, import_tool_kit11.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
7798
+ `);
6889
7799
  return true;
6890
7800
  } catch {
6891
7801
  return false;
6892
7802
  }
6893
7803
  }
7804
+ function isOurEntry(entry) {
7805
+ return typeof entry?.command === "string" && entry.command.includes(HOOK_MARKER);
7806
+ }
6894
7807
  function isOurs(group) {
6895
- return (group.hooks ?? []).some((entry) => typeof entry.command === "string" && entry.command.includes(HOOK_MARKER));
7808
+ return (group.hooks ?? []).some(isOurEntry);
7809
+ }
7810
+ function withoutOurEntries(groups) {
7811
+ const kept = [];
7812
+ for (const group of groups) {
7813
+ if (!isOurs(group)) {
7814
+ kept.push(group);
7815
+ continue;
7816
+ }
7817
+ const others = (group.hooks ?? []).filter((entry) => !isOurEntry(entry));
7818
+ if (others.length) kept.push({ ...group, hooks: others });
7819
+ }
7820
+ return kept;
7821
+ }
7822
+ function placeOurEntry(groups, wanted) {
7823
+ let placed = false;
7824
+ const result = [];
7825
+ for (const group of groups) {
7826
+ if (!isOurs(group)) {
7827
+ result.push(group);
7828
+ continue;
7829
+ }
7830
+ const matchesAll = group.matcher === void 0 || group.matcher === "";
7831
+ const next = [];
7832
+ for (const entry of group.hooks ?? []) {
7833
+ if (!isOurEntry(entry)) next.push(entry);
7834
+ else if (!placed && matchesAll) {
7835
+ next.push(wanted);
7836
+ placed = true;
7837
+ }
7838
+ }
7839
+ if (next.length) result.push({ ...group, hooks: next });
7840
+ }
7841
+ return placed ? result : [...result, { hooks: [wanted] }];
6896
7842
  }
6897
7843
  function findStaleHookCommands(settings, binary) {
6898
7844
  const stale = /* @__PURE__ */ new Set();
@@ -6919,9 +7865,8 @@ function ourHookSets(settings) {
6919
7865
  const sets = /* @__PURE__ */ new Map();
6920
7866
  for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
6921
7867
  for (const group of groups ?? []) {
6922
- if (!isOurs(group)) continue;
6923
7868
  for (const entry of group.hooks ?? []) {
6924
- if (typeof entry?.command !== "string") continue;
7869
+ if (!isOurEntry(entry)) continue;
6925
7870
  const set = (0, import_tool_kit11.hookSetOfCommand)(entry.command);
6926
7871
  sets.set(event, Math.min(set, sets.get(event) ?? set));
6927
7872
  }
@@ -6938,13 +7883,13 @@ function registrationSummary(projectDir) {
6938
7883
  const files = /* @__PURE__ */ new Map([
6939
7884
  [settingsPath({ scope: "user", projectDir }), "user"],
6940
7885
  [settingsPath({ scope: "project", projectDir }), "project"],
6941
- [path3.join(os3.homedir(), ".claude", "settings.local.json"), "project"]
7886
+ [homeProjectSettingsPath(), "project"]
6942
7887
  ]);
6943
7888
  const found = [];
6944
7889
  for (const [file, scope] of files) {
6945
7890
  const { registered } = countRegistered(file, binary);
6946
7891
  if (registered === 0) continue;
6947
- found.push({ file, scope, registered, homeProject: path3.resolve(file) === path3.resolve(os3.homedir(), ".claude", "settings.local.json") });
7892
+ found.push({ file, scope, registered, homeProject: path3.resolve(file) === path3.resolve(homeProjectSettingsPath()) });
6948
7893
  }
6949
7894
  return found;
6950
7895
  }
@@ -7025,7 +7970,7 @@ function uninstall(options) {
7025
7970
  }
7026
7971
  console.log(`hooks removed from ${settingsFile}`);
7027
7972
  }
7028
- for (const file of [hookBinPath(), hookBundlePath(), hookNodeRecordPath(), hookNoNodePath()]) {
7973
+ for (const file of [hookBinPath(), hookBundlePath(), hookNodeRecordPath(), hookNoNodePath(), `${hookBinPath()}.version`]) {
7029
7974
  if (!fs3.existsSync(file)) continue;
7030
7975
  fs3.rmSync(file);
7031
7976
  if (file === hookBinPath() || file === hookBundlePath()) console.log(`removed ${file}`);
@@ -7048,11 +7993,11 @@ var init_setup = __esm({
7048
7993
  init_launcher();
7049
7994
  init_paths();
7050
7995
  init_types();
7051
- HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop"];
7052
- HOOK_SET = 3;
7996
+ HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop", "PermissionRequest", "PermissionDenied"];
7997
+ HOOK_SET = 4;
7053
7998
  HOOK_TIMEOUT_SECONDS = 5;
7054
7999
  HOOK_MARKER = "ascenda-claude-hook";
7055
- SENDS = ["model", "posture", "git", "edits", "waiting", "subagents"];
8000
+ SENDS = ["model", "posture", "git", "edits", "waiting", "subagents", "forge", "turns"];
7056
8001
  USAGE = `ascenda-claude-hook setup \u2014 wire Claude Code to Ascenda telemetry
7057
8002
 
7058
8003
  npx @ascenda-one/claude-code-hooks setup [options]
@@ -7076,6 +8021,10 @@ Options
7076
8021
  --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
7077
8022
  On by default when not paired; machine-wide, shared by every agent
7078
8023
  (--no-pairing is accepted too)
8024
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
8025
+ repository gets a key and, off its default branch, a branch key, so a pull
8026
+ request can be matched to a session. They are digests anyone who guesses the
8027
+ names can reproduce. Machine-wide. --repo-keys turns them back on
7079
8028
  --scope user|project where hooks are registered (default user: every project)
7080
8029
  --project-dir <path> project root for --scope project (default cwd)
7081
8030
  --dry-run print what would change, write nothing
@@ -7123,6 +8072,13 @@ var AscendaClient = class {
7123
8072
  queue(mapped) {
7124
8073
  return this.sender.queue(mapped);
7125
8074
  }
8075
+ outboxFilePath() {
8076
+ return this.sender.outboxFilePath();
8077
+ }
8078
+ /** Drains the outbox until it's empty or the door refuses. What the background flusher runs. */
8079
+ async flushOutbox() {
8080
+ await (0, import_tool_kit.runOutboxFlush)(this.sender);
8081
+ }
7126
8082
  async renewEventToken() {
7127
8083
  return this.sender.renewEventToken();
7128
8084
  }
@@ -7139,12 +8095,15 @@ var import_tool_kit3 = __toESM(require_out3(), 1);
7139
8095
  function mapClaudeEvent(hookName, input) {
7140
8096
  const events = mapEvent(hookName, input);
7141
8097
  if (events.length === 0) return events;
7142
- const branchHash = (0, import_tool_kit4.deriveBranchHashForCwd)((0, import_tool_kit3.getString)(input, ["cwd"]) ?? process.cwd());
8098
+ const cwd = (0, import_tool_kit3.getString)(input, ["cwd"]) ?? process.cwd();
8099
+ const branchHash = (0, import_tool_kit4.deriveBranchHashForCwd)(cwd);
8100
+ const { repoKey, branchKey } = (0, import_tool_kit4.deriveForgeKeysForCwd)(cwd);
8101
+ const promptId = readPromptId(input);
7143
8102
  const runtime = claudeRuntime();
7144
8103
  const subagentId = readSubagentId(input);
7145
8104
  return events.map((event) => ({
7146
8105
  ...event,
7147
- metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...subagentId ? { subagentId } : {}, ...event.metadata }
8106
+ metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...repoKey ? { repoKey } : {}, ...branchKey ? { branchKey } : {}, ...promptId ? { promptId } : {}, ...subagentId ? { subagentId } : {}, ...event.metadata }
7148
8107
  }));
7149
8108
  }
7150
8109
  function mapEvent(hookName, input) {
@@ -7180,6 +8139,10 @@ function mapEvent(hookName, input) {
7180
8139
  return mapSubagent("subagent_started", input);
7181
8140
  case "SubagentStop":
7182
8141
  return mapSubagent("subagent_stopped", input);
8142
+ case "PermissionRequest":
8143
+ return mapPermission("permission_requested", input);
8144
+ case "PermissionDenied":
8145
+ return mapPermission("permission_denied", input);
7183
8146
  default:
7184
8147
  return [];
7185
8148
  }
@@ -7191,7 +8154,7 @@ function isNewSessionStart(input) {
7191
8154
  function milestoneInviting(input) {
7192
8155
  if ((0, import_tool_kit3.outcomeForHook)("PostToolUse", input) !== "success") return false;
7193
8156
  const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
7194
- return (0, import_tool_kit4.invitesDebrief)((0, import_tool_kit4.classifyWorkMilestone)(command));
8157
+ return (0, import_tool_kit4.invitesDebrief)((0, import_tool_kit4.classifyWorkMilestone)(command) ?? (0, import_tool_kit4.classifyMcpWorkMilestone)(getToolName(input)));
7195
8158
  }
7196
8159
  function mapSessionStart(input) {
7197
8160
  if (!isNewSessionStart(input)) return [];
@@ -7247,14 +8210,27 @@ var BUILT_IN_SUBAGENTS = {
7247
8210
  "statusline-setup": "statusline_setup",
7248
8211
  "claude-code-guide": "claude_code_guide"
7249
8212
  };
8213
+ function readPromptId(input) {
8214
+ const raw = input["prompt_id"];
8215
+ if (typeof raw !== "string") return void 0;
8216
+ const value = raw.trim();
8217
+ return /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : void 0;
8218
+ }
7250
8219
  function readSubagentId(input) {
7251
8220
  const raw = input["agent_id"];
7252
8221
  if (typeof raw !== "string") return void 0;
7253
8222
  const value = raw.trim();
7254
8223
  return /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : void 0;
7255
8224
  }
8225
+ function isTaskNotificationPrompt(prompt) {
8226
+ return prompt !== void 0 && prompt.trimStart().startsWith("<task-notification>");
8227
+ }
8228
+ function isBashModePrompt(prompt) {
8229
+ return prompt !== void 0 && prompt.trimStart().startsWith("<bash-input>");
8230
+ }
7256
8231
  function mapUserPromptSubmit(input) {
7257
8232
  const prompt = (0, import_tool_kit3.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit3.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
8233
+ if (isTaskNotificationPrompt(prompt) || isBashModePrompt(prompt)) return [];
7258
8234
  const autonomy = autonomyModeMetadata(input);
7259
8235
  const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...autonomy } }];
7260
8236
  if ((0, import_tool_kit3.looksLikeCorrection)(prompt)) {
@@ -7271,10 +8247,23 @@ function mapNotification(input) {
7271
8247
  // Low, always. Being asked is overhead to be counted, not a failure to be
7272
8248
  // flagged, and a severity that climbed would make this the input to a score.
7273
8249
  severity: "low",
7274
- metadata: { interruptionKind: notificationKind((0, import_tool_kit3.getString)(input, ["message"])) }
8250
+ metadata: { interruptionKind: notificationKind((0, import_tool_kit3.getString)(input, ["message"]), (0, import_tool_kit3.getString)(input, ["notification_type", "notificationType"])) }
8251
+ }];
8252
+ }
8253
+ function mapPermission(eventType, input) {
8254
+ return [{
8255
+ eventType,
8256
+ severity: "low",
8257
+ metadata: { toolName: sanitiseToolName(getToolName(input)), ...autonomyModeMetadata(input) }
7275
8258
  }];
7276
8259
  }
7277
- function notificationKind(message) {
8260
+ function notificationKind(message, notificationType) {
8261
+ if (notificationType !== void 0) {
8262
+ if (notificationType === "permission_prompt") return "permission_request";
8263
+ if (notificationType === "elicitation_dialog") return "input_request";
8264
+ if (notificationType === "idle_prompt") return "idle_prompt";
8265
+ return "other";
8266
+ }
7278
8267
  const text = message?.toLowerCase() ?? "";
7279
8268
  if (text.includes("permission")) return "permission_request";
7280
8269
  if (text.includes("waiting for your input")) return "idle_prompt";
@@ -7288,7 +8277,7 @@ function mapPostToolUse(hookName, input) {
7288
8277
  const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
7289
8278
  const commandClass = (0, import_tool_kit4.classifyCommand)(command);
7290
8279
  const gitAction = outcome === "success" ? (0, import_tool_kit4.classifyGitAction)(command) : void 0;
7291
- const milestoneKind = outcome === "success" ? (0, import_tool_kit4.classifyWorkMilestone)(command) : void 0;
8280
+ const milestoneKind = outcome === "success" ? (0, import_tool_kit4.classifyWorkMilestone)(command) ?? (0, import_tool_kit4.classifyMcpWorkMilestone)(toolName) : void 0;
7292
8281
  const autonomy = autonomyModeMetadata(input);
7293
8282
  if (outcome === "cancelled") {
7294
8283
  return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), reason: "manual_interrupt", ...autonomy } }];
@@ -7401,6 +8390,8 @@ function getToolName(input) {
7401
8390
  return (0, import_tool_kit3.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
7402
8391
  }
7403
8392
  function computeLinesChanged(toolName, input) {
8393
+ const patched = linesFromStructuredPatch((0, import_tool_kit3.getNested)(input, ["tool_response", "structuredPatch"]));
8394
+ if (patched !== void 0) return patched;
7404
8395
  const toolInput = (0, import_tool_kit3.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit3.getNested)(input, ["input"]) ?? (0, import_tool_kit3.getNested)(input, ["parameters"]);
7405
8396
  if (!toolInput || typeof toolInput !== "object") return void 0;
7406
8397
  const record = toolInput;
@@ -7430,16 +8421,33 @@ function computeLinesChanged(toolName, input) {
7430
8421
  }
7431
8422
  return sawOne ? total : void 0;
7432
8423
  }
8424
+ case "notebookedit": {
8425
+ if (record["edit_mode"] === "delete") return void 0;
8426
+ const source = record["new_source"];
8427
+ return typeof source === "string" ? countLines(source) : void 0;
8428
+ }
7433
8429
  default:
7434
8430
  return void 0;
7435
8431
  }
7436
8432
  }
8433
+ function linesFromStructuredPatch(patch) {
8434
+ if (!Array.isArray(patch) || patch.length === 0) return void 0;
8435
+ let count = 0;
8436
+ for (const hunk of patch) {
8437
+ const lines = hunk && typeof hunk === "object" ? hunk["lines"] : void 0;
8438
+ if (!Array.isArray(lines)) continue;
8439
+ for (const line of lines) {
8440
+ if (typeof line === "string" && (line.startsWith("+") || line.startsWith("-"))) count += 1;
8441
+ }
8442
+ }
8443
+ return count;
8444
+ }
7437
8445
  function countLines(text) {
7438
8446
  return text.length === 0 ? 0 : text.split("\n").length;
7439
8447
  }
7440
8448
  function isWriteTool(toolName) {
7441
8449
  const value = toolName?.toLowerCase();
7442
- return value === "write" || value === "edit" || value === "multiedit";
8450
+ return value === "write" || value === "edit" || value === "multiedit" || value === "notebookedit";
7443
8451
  }
7444
8452
  function sanitiseToolName(toolName) {
7445
8453
  if (!toolName) return "unknown";
@@ -7487,9 +8495,9 @@ function notificationLiveEvent(input) {
7487
8495
  }
7488
8496
 
7489
8497
  // src/usageLimitReset.ts
7490
- import * as fs from "node:fs";
7491
- import * as os from "node:os";
7492
- import * as path from "node:path";
8498
+ init_paths();
8499
+ import * as fs2 from "node:fs";
8500
+ import * as path2 from "node:path";
7493
8501
  var MAX_RESUME_AHEAD_MS = 6 * 60 * 60 * 1e3;
7494
8502
  var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
7495
8503
  var RESET_CLAUSE = new RegExp(
@@ -7597,11 +8605,10 @@ function managedSettingsPath() {
7597
8605
  return "/etc/claude-code/managed-settings.json";
7598
8606
  }
7599
8607
  function autoContinueEnabled(sources = {}) {
7600
- const home = sources.home ?? os.homedir();
7601
8608
  const files = [
7602
8609
  sources.managedPath ?? managedSettingsPath(),
7603
- ...sources.projectDir ? [path.join(sources.projectDir, ".claude", "settings.local.json"), path.join(sources.projectDir, ".claude", "settings.json")] : [],
7604
- path.join(home, ".claude", "settings.json")
8610
+ ...sources.projectDir ? [path2.join(sources.projectDir, ".claude", "settings.local.json"), path2.join(sources.projectDir, ".claude", "settings.json")] : [],
8611
+ path2.join(sources.configDir ?? claudeConfigDir(), "settings.json")
7605
8612
  ];
7606
8613
  for (const file of files) {
7607
8614
  const value = readSetting(file, "autoContinueAtUsageLimit");
@@ -7611,7 +8618,7 @@ function autoContinueEnabled(sources = {}) {
7611
8618
  }
7612
8619
  function readSetting(file, key) {
7613
8620
  try {
7614
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
8621
+ const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
7615
8622
  if (parsed && typeof parsed === "object" && key in parsed) return parsed[key];
7616
8623
  } catch {
7617
8624
  }
@@ -7628,7 +8635,7 @@ init_hookHealth();
7628
8635
  var import_tool_kit12 = __toESM(require_out3(), 1);
7629
8636
  init_paths();
7630
8637
  var import_tool_kit13 = __toESM(require_out3(), 1);
7631
- import * as os4 from "os";
8638
+ import * as os3 from "os";
7632
8639
  async function localSignalLines(projectDir = process.cwd()) {
7633
8640
  const { registrationSummary: registrationSummary2, REGISTERED_EVENT_COUNT: REGISTERED_EVENT_COUNT2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
7634
8641
  return (0, import_tool_kit12.liveSignalDoctorLines)({
@@ -7643,7 +8650,7 @@ async function localSignalLines(projectDir = process.cwd()) {
7643
8650
  });
7644
8651
  }
7645
8652
  function tidy(file) {
7646
- const home = os4.homedir();
8653
+ const home = os3.homedir();
7647
8654
  return file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
7648
8655
  }
7649
8656
 
@@ -7679,7 +8686,7 @@ Waiting for confirmation (expires ${session.expiresAt})...
7679
8686
  );
7680
8687
  const deadline = Date.now() + 11 * 60 * 1e3;
7681
8688
  while (Date.now() < deadline) {
7682
- await new Promise((resolve2) => setTimeout(resolve2, 3e3));
8689
+ await new Promise((resolve3) => setTimeout(resolve3, 3e3));
7683
8690
  const status = await (0, import_tool_kit14.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
7684
8691
  if (status.status === "pending") continue;
7685
8692
  if (status.status !== "paired") {
@@ -7771,6 +8778,10 @@ async function main() {
7771
8778
  await runDoctor();
7772
8779
  return;
7773
8780
  }
8781
+ if (command === import_tool_kit15.OUTBOX_FLUSH_COMMAND) {
8782
+ await runFlush();
8783
+ return;
8784
+ }
7774
8785
  if (MANAGEMENT_COMMANDS.has(command)) {
7775
8786
  const { runSetup: runSetup2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
7776
8787
  setupExitCode = await runSetup2(process.argv.slice(2));
@@ -7833,6 +8844,13 @@ async function main() {
7833
8844
  }
7834
8845
  return;
7835
8846
  }
8847
+ if (!(0, import_tool_kit15.hookDeliveryInline)() && claudeRuntime() !== "cloud") {
8848
+ for (const event of mappedEvents) {
8849
+ if (!client.queue(event)) console.error("Ascenda telemetry not kept: the event could not be written to the outbox.");
8850
+ }
8851
+ (0, import_tool_kit15.startBackgroundFlush)({ outboxFilePath: client.outboxFilePath() });
8852
+ return;
8853
+ }
7836
8854
  for (const event of mappedEvents) {
7837
8855
  const result = await client.send(event);
7838
8856
  if (result === "accepted") continue;
@@ -7840,6 +8858,15 @@ async function main() {
7840
8858
  return;
7841
8859
  }
7842
8860
  }
8861
+ async function runFlush() {
8862
+ let config;
8863
+ try {
8864
+ config = loadConfigFromEnv();
8865
+ } catch {
8866
+ return;
8867
+ }
8868
+ await new AscendaClient(config).flushOutbox();
8869
+ }
7843
8870
  function journalSkippedSend(error) {
7844
8871
  (0, import_tool_kit14.recordSendOutcome)(resolveStateFilePath(), (0, import_tool_kit14.unresolvedToolInstallationId)(ASCENDA_TOOL_TYPE), "skipped_no_installation_id", {
7845
8872
  detail: error.candidates.length === 0 ? "no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, no claude_code token file" : `no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, ${error.candidates.length} claude_code token files (${error.candidates.join(", ")})`
@@ -7950,8 +8977,8 @@ function describeOutcome(state) {
7950
8977
  }
7951
8978
  }
7952
8979
  function writeStdout(text) {
7953
- return new Promise((resolve2) => {
7954
- process.stdout.write(text, () => resolve2());
8980
+ return new Promise((resolve3) => {
8981
+ process.stdout.write(text, () => resolve3());
7955
8982
  });
7956
8983
  }
7957
8984
  async function runDoctor() {
@@ -8084,6 +9111,7 @@ function outboxLines(toolInstallationId, state) {
8084
9111
  lines.push(` Outbox unreadable ${summary.unreadableLines} line(s) did not parse \u2014 discarded and journaled on the next hook`);
8085
9112
  }
8086
9113
  lines.push(` Outbox drain ${(0, import_tool_kit14.outboxDrainEnabled)() ? "on (queued events are replayed, oldest first)" : "off \u2014 queued events are kept and bounded, not sent"} \u2014 ${import_tool_kit14.OUTBOX_DRAIN_ENV_VAR}`);
9114
+ lines.push(` Delivery ${claudeRuntime() === "cloud" ? "inline (hosted session)" : (0, import_tool_kit15.hookDeliveryInline)() ? `inline \u2014 ${import_tool_kit15.HOOK_DELIVERY_ENV_VAR} or ${import_tool_kit14.OUTBOX_DRAIN_ENV_VAR}` : "background sender (the hook queues and returns)"}`);
8087
9115
  const discarded = state?.outboxDiscarded;
8088
9116
  if (discarded) {
8089
9117
  const reasons = Object.entries(discarded.lastReasons).map(([reason, count]) => `${count} ${reason}`).join(", ");