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

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.37" ? "0.1.37" : 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
- }
2089
- }
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;
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;
2096
2389
  }
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 } : {} } };
2100
2390
  }
2101
- function listClaimFiles(outboxFilePath) {
2102
- const dir = path4.dirname(outboxFilePath);
2103
- const prefix = `${path4.basename(outboxFilePath)}.`;
2391
+ async function apiError(response) {
2392
+ const body = await response.text();
2393
+ let errorCode;
2104
2394
  try {
2105
- return fs5.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path4.join(dir, name)).sort();
2395
+ const parsed = JSON.parse(body);
2396
+ errorCode = parsed.code ?? parsed.error;
2106
2397
  } catch {
2107
- return [];
2398
+ errorCode = void 0;
2108
2399
  }
2400
+ return new AscendaApiError2(response.status, errorCode, body);
2109
2401
  }
2110
- function readEntries(file) {
2111
- let raw;
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;
2112
2419
  try {
2113
- raw = fs5.readFileSync(file, "utf8");
2420
+ parsed = JSON.parse(body);
2114
2421
  } catch {
2115
- return { entries: [], unreadable: 0 };
2422
+ return { duplicates: 0 };
2116
2423
  }
2117
- const entries = [];
2118
- let unreadable = 0;
2119
- for (const line of raw.split("\n")) {
2120
- if (!line.trim())
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")
2121
2435
  continue;
2122
- 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 });
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 } : {} });
2440
+ }
2441
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
2442
+ }
2443
+ function isRetryableStatus(status) {
2444
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
2445
+ }
2446
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
2447
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
2448
+ }
2449
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
2450
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
2451
+ }
2452
+ async function sendIngest(url, eventWriteToken, body, signal) {
2453
+ try {
2454
+ const response = await fetch(url, {
2455
+ method: "POST",
2456
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2457
+ body,
2458
+ signal
2459
+ });
2460
+ return parseIngestResponse(response);
2461
+ } catch (error) {
2462
+ return {
2463
+ result: "transport_error",
2464
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
2465
+ };
2466
+ }
2467
+ }
2468
+ async function parseIngestResponse(response) {
2469
+ if (response.ok) {
2470
+ const outcome = { result: "accepted", httpStatus: response.status };
2471
+ let read = { duplicates: 0 };
2472
+ try {
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(""));
@@ -3827,52 +4377,6 @@ var require_initiatives = __commonJS({
3827
4377
  }
3828
4378
  });
3829
4379
 
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
- }
3873
- }
3874
- });
3875
-
3876
4380
  // ../packages/tool-kit/out/hookRunner.js
3877
4381
  var require_hookRunner = __commonJS({
3878
4382
  "../packages/tool-kit/out/hookRunner.js"(exports) {
@@ -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`;
@@ -4120,8 +4663,117 @@ var require_hookRunner = __commonJS({
4120
4663
  return { node, how, problem: `${node} did not run` };
4121
4664
  return { node, how, version: version.stdout.trim() };
4122
4665
  }
4123
- function tidyHomePath(file, home = process.env.HOME ?? "") {
4124
- return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
4666
+ function tidyHomePath(file, home = process.env.HOME ?? "") {
4667
+ return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
4668
+ }
4669
+ }
4670
+ });
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");
4125
4777
  }
4126
4778
  }
4127
4779
  });
@@ -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;
@@ -5599,6 +6416,100 @@ var require_turnState = __commonJS({
5599
6416
  }
5600
6417
  });
5601
6418
 
6419
+ // ../packages/tool-kit/out/pluginBundle.js
6420
+ var require_pluginBundle = __commonJS({
6421
+ "../packages/tool-kit/out/pluginBundle.js"(exports) {
6422
+ "use strict";
6423
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
6424
+ if (k2 === void 0) k2 = k;
6425
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6426
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6427
+ desc = { enumerable: true, get: function() {
6428
+ return m[k];
6429
+ } };
6430
+ }
6431
+ Object.defineProperty(o, k2, desc);
6432
+ } : function(o, m, k, k2) {
6433
+ if (k2 === void 0) k2 = k;
6434
+ o[k2] = m[k];
6435
+ });
6436
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
6437
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
6438
+ } : function(o, v) {
6439
+ o["default"] = v;
6440
+ });
6441
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
6442
+ var ownKeys = function(o) {
6443
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
6444
+ var ar = [];
6445
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
6446
+ return ar;
6447
+ };
6448
+ return ownKeys(o);
6449
+ };
6450
+ return function(mod) {
6451
+ if (mod && mod.__esModule) return mod;
6452
+ var result = {};
6453
+ if (mod != null) {
6454
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
6455
+ }
6456
+ __setModuleDefault(result, mod);
6457
+ return result;
6458
+ };
6459
+ }();
6460
+ Object.defineProperty(exports, "__esModule", { value: true });
6461
+ exports.pluginBundlePaths = pluginBundlePaths2;
6462
+ exports.installPluginBundle = installPluginBundle2;
6463
+ exports.describePluginBundleOutcome = describePluginBundleOutcome2;
6464
+ var fs5 = __importStar(__require("fs"));
6465
+ var path4 = __importStar(__require("path"));
6466
+ var collectorVersion_1 = require_collectorVersion();
6467
+ var hookRunner_1 = require_hookRunner();
6468
+ var tokenStore_1 = require_tokenStore();
6469
+ function pluginBundlePaths2(name) {
6470
+ const base = path4.join((0, tokenStore_1.ascendaHome)(), "plugin", name);
6471
+ return { bundle: `${base}.mjs`, version: `${base}.version`, checked: `${base}.checked` };
6472
+ }
6473
+ function installPluginBundle2(options) {
6474
+ const paths = pluginBundlePaths2(options.name);
6475
+ const source = path4.resolve(options.source ?? process.argv[1]);
6476
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
6477
+ const installed = readVersion(paths.version);
6478
+ const present = fs5.existsSync(paths.bundle);
6479
+ if (source === path4.resolve(paths.bundle))
6480
+ return { kind: "current", version: installed ?? incoming };
6481
+ if (present && installed && (0, hookRunner_1.isDowngrade)(installed, incoming))
6482
+ return { kind: "kept-newer", installed, incoming };
6483
+ const contents = fs5.readFileSync(source);
6484
+ if (present && installed === incoming && contents.equals(fs5.readFileSync(paths.bundle))) {
6485
+ return { kind: "current", version: incoming };
6486
+ }
6487
+ fs5.mkdirSync(path4.dirname(paths.bundle), { recursive: true });
6488
+ (0, hookRunner_1.writeAtomically)(paths.bundle, contents, 420);
6489
+ (0, hookRunner_1.writeAtomically)(paths.version, `${incoming}
6490
+ `, 420);
6491
+ return present && installed ? { kind: "installed", version: incoming, replaced: installed } : { kind: "installed", version: incoming };
6492
+ }
6493
+ function describePluginBundleOutcome2(outcome, bundle) {
6494
+ switch (outcome.kind) {
6495
+ case "installed":
6496
+ return outcome.replaced && outcome.replaced !== outcome.version ? `Updated the plugin's bundle from ${outcome.replaced} to ${outcome.version}: ${bundle}` : `Installed the plugin's bundle (${outcome.version}): ${bundle}`;
6497
+ case "current":
6498
+ return `The plugin's bundle is already ${outcome.version}: ${bundle}`;
6499
+ case "kept-newer":
6500
+ return `Kept the plugin's bundle at ${outcome.installed}. This copy is the older ${outcome.incoming}.`;
6501
+ }
6502
+ }
6503
+ function readVersion(file) {
6504
+ try {
6505
+ return fs5.readFileSync(file, "utf8").trim() || void 0;
6506
+ } catch {
6507
+ return void 0;
6508
+ }
6509
+ }
6510
+ }
6511
+ });
6512
+
5602
6513
  // ../packages/tool-kit/out/agentProcess.js
5603
6514
  var require_agentProcess = __commonJS({
5604
6515
  "../packages/tool-kit/out/agentProcess.js"(exports) {
@@ -5743,10 +6654,11 @@ var require_out3 = __commonJS({
5743
6654
  "../packages/tool-kit/out/index.js"(exports) {
5744
6655
  "use strict";
5745
6656
  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;
6657
+ 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;
6658
+ 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;
6659
+ 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;
6660
+ 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.pluginBundlePaths = exports.installPluginBundle = exports.describePluginBundleOutcome = 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;
6661
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = void 0;
5750
6662
  var commandClassifier_1 = require_commandClassifier();
5751
6663
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5752
6664
  return commandClassifier_1.classifyCommand;
@@ -5765,9 +6677,16 @@ var require_out3 = __commonJS({
5765
6677
  Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
5766
6678
  return workMilestoneClassifier_1.classifyWorkMilestone;
5767
6679
  } });
6680
+ Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
6681
+ return workMilestoneClassifier_1.classifyMcpWorkMilestone;
6682
+ } });
5768
6683
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
5769
6684
  return workMilestoneClassifier_1.invitesDebrief;
5770
6685
  } });
6686
+ var shellFacts_1 = require_shellFacts();
6687
+ Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
6688
+ return shellFacts_1.shellCommandFacts;
6689
+ } });
5771
6690
  var autonomyBand_1 = require_autonomyBand();
5772
6691
  Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
5773
6692
  return autonomyBand_1.autonomyBand;
@@ -5837,6 +6756,28 @@ var require_out3 = __commonJS({
5837
6756
  Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
5838
6757
  return collectorVersion_1.describeCollectorVersion;
5839
6758
  } });
6759
+ var backgroundDelivery_1 = require_backgroundDelivery();
6760
+ Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
6761
+ return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
6762
+ } });
6763
+ Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
6764
+ return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
6765
+ } });
6766
+ Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
6767
+ return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
6768
+ } });
6769
+ Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
6770
+ return backgroundDelivery_1.flushLockPath;
6771
+ } });
6772
+ Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
6773
+ return backgroundDelivery_1.hookDeliveryInline;
6774
+ } });
6775
+ Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
6776
+ return backgroundDelivery_1.runOutboxFlush;
6777
+ } });
6778
+ Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
6779
+ return backgroundDelivery_1.startBackgroundFlush;
6780
+ } });
5840
6781
  var eventSender_1 = require_eventSender();
5841
6782
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
5842
6783
  return eventSender_1.AscendaEventSender;
@@ -5895,9 +6836,18 @@ var require_out3 = __commonJS({
5895
6836
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
5896
6837
  return hookAdapter_1.deliverHookEvents;
5897
6838
  } });
6839
+ Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
6840
+ return hookAdapter_1.flushHookOutbox;
6841
+ } });
5898
6842
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
5899
6843
  return hookAdapter_1.loadCliAgentConfig;
5900
6844
  } });
6845
+ Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
6846
+ return hookAdapter_1.withForgeKeys;
6847
+ } });
6848
+ Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
6849
+ return hookAdapter_1.withPromptId;
6850
+ } });
5901
6851
  Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
5902
6852
  return hookAdapter_1.resolveCliAgentInstallationId;
5903
6853
  } });
@@ -5914,12 +6864,18 @@ var require_out3 = __commonJS({
5914
6864
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
5915
6865
  return cliAgentSetup_1.isCliAgentManagementCommand;
5916
6866
  } });
6867
+ Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
6868
+ return cliAgentSetup_1.ourHookPositions;
6869
+ } });
5917
6870
  Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5918
6871
  return cliAgentSetup_1.registeredHookSets;
5919
6872
  } });
5920
6873
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
5921
6874
  return cliAgentSetup_1.runCliAgentSetup;
5922
6875
  } });
6876
+ Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
6877
+ return cliAgentSetup_1.trustProblemLines;
6878
+ } });
5923
6879
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
5924
6880
  return cliAgentSetup_1.writeHookSettings;
5925
6881
  } });
@@ -5961,6 +6917,9 @@ var require_out3 = __commonJS({
5961
6917
  Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
5962
6918
  return credentials_1.writeEventLogSetting;
5963
6919
  } });
6920
+ Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
6921
+ return credentials_1.writeRepoKeysSetting;
6922
+ } });
5964
6923
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5965
6924
  return credentials_1.writeMachineCredentials;
5966
6925
  } });
@@ -5971,6 +6930,9 @@ var require_out3 = __commonJS({
5971
6930
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
5972
6931
  return turnState_1.consumeTurnDurationMs;
5973
6932
  } });
6933
+ Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
6934
+ return turnState_1.readTurnPromptId;
6935
+ } });
5974
6936
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
5975
6937
  return turnState_1.recordTurnStart;
5976
6938
  } });
@@ -6105,6 +7067,12 @@ var require_out3 = __commonJS({
6105
7067
  Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
6106
7068
  return forgeProject_1.forgeProjectHash;
6107
7069
  } });
7070
+ Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
7071
+ return forgeProject_1.forgeRepoKey;
7072
+ } });
7073
+ Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
7074
+ return forgeProject_1.forgeBranchKey;
7075
+ } });
6108
7076
  Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
6109
7077
  return forgeProject_1.parseForgeFullName;
6110
7078
  } });
@@ -6117,6 +7085,16 @@ var require_out3 = __commonJS({
6117
7085
  Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
6118
7086
  return forgeProject_1.recordForgeProjectAlias;
6119
7087
  } });
7088
+ var forgeKeys_1 = require_forgeKeys();
7089
+ Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
7090
+ return forgeKeys_1.REPO_KEYS_ENV_VAR;
7091
+ } });
7092
+ Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
7093
+ return forgeKeys_1.deriveForgeKeysForCwd;
7094
+ } });
7095
+ Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
7096
+ return forgeKeys_1.repoKeysEnabled;
7097
+ } });
6120
7098
  var liveBus_1 = require_liveBus();
6121
7099
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
6122
7100
  return liveBus_1.emitLiveSignal;
@@ -6187,6 +7165,9 @@ var require_out3 = __commonJS({
6187
7165
  Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
6188
7166
  return hookRunner_1.installHookRunner;
6189
7167
  } });
7168
+ Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
7169
+ return hookRunner_1.isDowngrade;
7170
+ } });
6190
7171
  Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
6191
7172
  return hookRunner_1.lastHookPath;
6192
7173
  } });
@@ -6205,6 +7186,23 @@ var require_out3 = __commonJS({
6205
7186
  Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
6206
7187
  return hookRunner_1.tidyHomePath;
6207
7188
  } });
7189
+ Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
7190
+ return hookRunner_1.writeAtomically;
7191
+ } });
7192
+ var settingsFile_1 = require_settingsFile();
7193
+ Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
7194
+ return settingsFile_1.replaceSettingsFile;
7195
+ } });
7196
+ var pluginBundle_1 = require_pluginBundle();
7197
+ Object.defineProperty(exports, "describePluginBundleOutcome", { enumerable: true, get: function() {
7198
+ return pluginBundle_1.describePluginBundleOutcome;
7199
+ } });
7200
+ Object.defineProperty(exports, "installPluginBundle", { enumerable: true, get: function() {
7201
+ return pluginBundle_1.installPluginBundle;
7202
+ } });
7203
+ Object.defineProperty(exports, "pluginBundlePaths", { enumerable: true, get: function() {
7204
+ return pluginBundle_1.pluginBundlePaths;
7205
+ } });
6208
7206
  var liveSignalDoctor_1 = require_liveSignalDoctor();
6209
7207
  Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
6210
7208
  return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
@@ -6364,7 +7362,9 @@ var init_types = __esm({
6364
7362
  "Notification",
6365
7363
  "SessionEnd",
6366
7364
  "SubagentStart",
6367
- "SubagentStop"
7365
+ "SubagentStop",
7366
+ "PermissionRequest",
7367
+ "PermissionDenied"
6368
7368
  ];
6369
7369
  ASCENDA_TOOL_TYPE = "claude_code";
6370
7370
  CLAUDE_HOST = "claude_code";
@@ -6372,20 +7372,24 @@ var init_types = __esm({
6372
7372
  });
6373
7373
 
6374
7374
  // src/paths.ts
6375
- import * as fs2 from "fs";
6376
- import * as os2 from "os";
6377
- import * as path2 from "path";
7375
+ import * as fs from "fs";
7376
+ import * as os from "os";
7377
+ import * as path from "path";
7378
+ function claudeConfigDir() {
7379
+ const configured = process.env.CLAUDE_CONFIG_DIR?.trim();
7380
+ return configured ? path.resolve(configured) : path.join(os.homedir(), ".claude");
7381
+ }
6378
7382
  function hookBinPath() {
6379
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook");
7383
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook");
6380
7384
  }
6381
7385
  function hookBundlePath() {
6382
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.mjs");
7386
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.mjs");
6383
7387
  }
6384
7388
  function hookNodeRecordPath() {
6385
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.node");
7389
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.node");
6386
7390
  }
6387
7391
  function hookNoNodePath() {
6388
- return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.no-node");
7392
+ return path.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook.no-node");
6389
7393
  }
6390
7394
  function readCredentials() {
6391
7395
  const credentials = (0, import_tool_kit5.readMachineCredentials)();
@@ -6403,11 +7407,11 @@ function removeCredentials() {
6403
7407
  (0, import_tool_kit5.writeMachineCredentials)({ tools: credentials.tools });
6404
7408
  return;
6405
7409
  }
6406
- fs2.rmSync((0, import_tool_kit5.credentialsFilePath)(), { force: true });
7410
+ fs.rmSync((0, import_tool_kit5.credentialsFilePath)(), { force: true });
6407
7411
  }
6408
7412
  function selfCommand() {
6409
7413
  if (process.platform === "win32") return "npx @ascenda-one/claude-code-hooks";
6410
- const home = os2.homedir();
7414
+ const home = os.homedir();
6411
7415
  const bin = hookBinPath();
6412
7416
  return bin.startsWith(`${home}/`) ? `~${bin.slice(home.length)}` : bin;
6413
7417
  }
@@ -6560,7 +7564,7 @@ __export(setup_exports, {
6560
7564
  });
6561
7565
  import * as crypto from "crypto";
6562
7566
  import * as fs3 from "fs";
6563
- import * as os3 from "os";
7567
+ import * as os2 from "os";
6564
7568
  import * as path3 from "path";
6565
7569
  async function runSetup(argv) {
6566
7570
  let options;
@@ -6603,6 +7607,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6603
7607
  ...unpaired ? { localOnly: true, installedAt: now } : { pairedAt: now }
6604
7608
  });
6605
7609
  if (options.eventLog !== void 0) (0, import_tool_kit11.writeEventLogSetting)(options.eventLog);
7610
+ if (options.repoKeys !== void 0) (0, import_tool_kit11.writeRepoKeysSetting)(options.repoKeys);
6606
7611
  }
6607
7612
  if (isHomeProject(options)) {
6608
7613
  detail("scope", "user (a project install in the home folder only loads when Claude Code starts there)");
@@ -6620,7 +7625,7 @@ ${(0, import_tool_kit11.renderSetupDisclosure)({ sends: SENDS, displayName: "Cla
6620
7625
  settingsPath({ ...options, scope: options.scope === "user" ? "project" : "user" }),
6621
7626
  // The home folder's project file, where a project-scope setup run from
6622
7627
  // `~` used to put them.
6623
- path3.join(os3.homedir(), ".claude", "settings.local.json")
7628
+ homeProjectSettingsPath()
6624
7629
  ]);
6625
7630
  otherFiles.delete(settingsFile);
6626
7631
  for (const otherFile of otherFiles) {
@@ -6734,6 +7739,12 @@ function parseArgs(argv) {
6734
7739
  i += consumed;
6735
7740
  break;
6736
7741
  }
7742
+ case "--repo-keys":
7743
+ options.repoKeys = true;
7744
+ break;
7745
+ case "--no-repo-keys":
7746
+ options.repoKeys = false;
7747
+ break;
6737
7748
  case "--no-pair":
6738
7749
  // `--no-pairing` is the spelling the CLI agents' setup landed under
6739
7750
  // first, and the one their README still showed for a day. Both parse
@@ -6758,7 +7769,7 @@ ${USAGE}`);
6758
7769
  return options;
6759
7770
  }
6760
7771
  function isHomeProject(options) {
6761
- return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os3.homedir());
7772
+ return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os2.homedir());
6762
7773
  }
6763
7774
  async function resolveIdentity(apiBaseUrl, options) {
6764
7775
  const existingId = options.toolInstallationId ?? readCredentials()?.toolInstallationId;
@@ -6778,7 +7789,7 @@ async function resolveIdentity(apiBaseUrl, options) {
6778
7789
  }
6779
7790
  let session;
6780
7791
  try {
6781
- session = await (0, import_tool_kit11.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os3.hostname()}`);
7792
+ session = await (0, import_tool_kit11.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os2.hostname()}`);
6782
7793
  } catch (error) {
6783
7794
  return {
6784
7795
  toolInstallationId,
@@ -6805,7 +7816,7 @@ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
6805
7816
  if (++failures >= POLL_ERROR_TOLERANCE) {
6806
7817
  return { reason: `lost contact while waiting (${error instanceof Error ? error.message : String(error)})` };
6807
7818
  }
6808
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
7819
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
6809
7820
  continue;
6810
7821
  }
6811
7822
  if (status.status === "paired" && status.eventWriteToken) return { token: status.eventWriteToken };
@@ -6816,22 +7827,29 @@ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
6816
7827
  console.log(" Waiting...");
6817
7828
  announced = true;
6818
7829
  }
6819
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
7830
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
6820
7831
  }
6821
7832
  return { reason: "no confirmation within 5 minutes" };
6822
7833
  }
6823
7834
  function tidyHome(file) {
6824
- const home = os3.homedir();
7835
+ const home = os2.homedir();
6825
7836
  return file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
6826
7837
  }
6827
7838
  function restartLine(options) {
6828
7839
  return options.scope === "user" ? "Restart Claude Code to load the hooks." : "Restart Claude Code in this project to load the hooks.";
6829
7840
  }
6830
7841
  function installBinary(dryRun) {
6831
- return (0, import_tool_kit11.installHookRunner)({ ...LAUNCHER_OPTIONS, dryRun });
7842
+ return (0, import_tool_kit11.installHookRunner)({
7843
+ ...LAUNCHER_OPTIONS,
7844
+ dryRun,
7845
+ 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.`)
7846
+ });
6832
7847
  }
6833
7848
  function settingsPath(options) {
6834
- return options.scope === "user" ? path3.join(os3.homedir(), ".claude", "settings.json") : path3.join(options.projectDir, ".claude", "settings.local.json");
7849
+ return options.scope === "user" ? path3.join(claudeConfigDir(), "settings.json") : path3.join(options.projectDir, ".claude", "settings.local.json");
7850
+ }
7851
+ function homeProjectSettingsPath() {
7852
+ return path3.join(os2.homedir(), ".claude", "settings.local.json");
6835
7853
  }
6836
7854
  function writeSettings(settingsFile, binary, dryRun) {
6837
7855
  let settings = {};
@@ -6851,8 +7869,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
6851
7869
  const command = hookCommand(binary);
6852
7870
  const hooks = { ...settings.hooks ?? {} };
6853
7871
  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 }] }];
7872
+ hooks[event] = placeOurEntry(hooks[event] ?? [], { type: "command", command: `${command} ${event}${(0, import_tool_kit11.hookSetArgument)(HOOK_SET)}`, timeout: HOOK_TIMEOUT_SECONDS });
6856
7873
  }
6857
7874
  const updated = { ...settings, hooks };
6858
7875
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -6864,9 +7881,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
6864
7881
  ${serialised}`);
6865
7882
  return true;
6866
7883
  }
6867
- if (exists) fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
6868
- fs3.mkdirSync(path3.dirname(settingsFile), { recursive: true });
6869
- fs3.writeFileSync(settingsFile, serialised, "utf8");
7884
+ (0, import_tool_kit11.replaceSettingsFile)(settingsFile, serialised);
6870
7885
  return true;
6871
7886
  }
6872
7887
  function hookCommand(binary) {
@@ -6877,22 +7892,57 @@ function removeOurHooks(settingsFile) {
6877
7892
  const settings = JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
6878
7893
  const hooks = { ...settings.hooks ?? {} };
6879
7894
  for (const event of Object.keys(hooks)) {
6880
- const kept = hooks[event].filter((group) => !isOurs(group));
7895
+ const kept = withoutOurEntries(hooks[event]);
6881
7896
  if (kept.length) hooks[event] = kept;
6882
7897
  else delete hooks[event];
6883
7898
  }
6884
7899
  const updated = { ...settings, hooks };
6885
7900
  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");
7901
+ (0, import_tool_kit11.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
7902
+ `);
6889
7903
  return true;
6890
7904
  } catch {
6891
7905
  return false;
6892
7906
  }
6893
7907
  }
7908
+ function isOurEntry(entry) {
7909
+ return typeof entry?.command === "string" && entry.command.includes(HOOK_MARKER);
7910
+ }
6894
7911
  function isOurs(group) {
6895
- return (group.hooks ?? []).some((entry) => typeof entry.command === "string" && entry.command.includes(HOOK_MARKER));
7912
+ return (group.hooks ?? []).some(isOurEntry);
7913
+ }
7914
+ function withoutOurEntries(groups) {
7915
+ const kept = [];
7916
+ for (const group of groups) {
7917
+ if (!isOurs(group)) {
7918
+ kept.push(group);
7919
+ continue;
7920
+ }
7921
+ const others = (group.hooks ?? []).filter((entry) => !isOurEntry(entry));
7922
+ if (others.length) kept.push({ ...group, hooks: others });
7923
+ }
7924
+ return kept;
7925
+ }
7926
+ function placeOurEntry(groups, wanted) {
7927
+ let placed = false;
7928
+ const result = [];
7929
+ for (const group of groups) {
7930
+ if (!isOurs(group)) {
7931
+ result.push(group);
7932
+ continue;
7933
+ }
7934
+ const matchesAll = group.matcher === void 0 || group.matcher === "";
7935
+ const next = [];
7936
+ for (const entry of group.hooks ?? []) {
7937
+ if (!isOurEntry(entry)) next.push(entry);
7938
+ else if (!placed && matchesAll) {
7939
+ next.push(wanted);
7940
+ placed = true;
7941
+ }
7942
+ }
7943
+ if (next.length) result.push({ ...group, hooks: next });
7944
+ }
7945
+ return placed ? result : [...result, { hooks: [wanted] }];
6896
7946
  }
6897
7947
  function findStaleHookCommands(settings, binary) {
6898
7948
  const stale = /* @__PURE__ */ new Set();
@@ -6919,9 +7969,8 @@ function ourHookSets(settings) {
6919
7969
  const sets = /* @__PURE__ */ new Map();
6920
7970
  for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
6921
7971
  for (const group of groups ?? []) {
6922
- if (!isOurs(group)) continue;
6923
7972
  for (const entry of group.hooks ?? []) {
6924
- if (typeof entry?.command !== "string") continue;
7973
+ if (!isOurEntry(entry)) continue;
6925
7974
  const set = (0, import_tool_kit11.hookSetOfCommand)(entry.command);
6926
7975
  sets.set(event, Math.min(set, sets.get(event) ?? set));
6927
7976
  }
@@ -6938,13 +7987,13 @@ function registrationSummary(projectDir) {
6938
7987
  const files = /* @__PURE__ */ new Map([
6939
7988
  [settingsPath({ scope: "user", projectDir }), "user"],
6940
7989
  [settingsPath({ scope: "project", projectDir }), "project"],
6941
- [path3.join(os3.homedir(), ".claude", "settings.local.json"), "project"]
7990
+ [homeProjectSettingsPath(), "project"]
6942
7991
  ]);
6943
7992
  const found = [];
6944
7993
  for (const [file, scope] of files) {
6945
7994
  const { registered } = countRegistered(file, binary);
6946
7995
  if (registered === 0) continue;
6947
- found.push({ file, scope, registered, homeProject: path3.resolve(file) === path3.resolve(os3.homedir(), ".claude", "settings.local.json") });
7996
+ found.push({ file, scope, registered, homeProject: path3.resolve(file) === path3.resolve(homeProjectSettingsPath()) });
6948
7997
  }
6949
7998
  return found;
6950
7999
  }
@@ -7025,7 +8074,7 @@ function uninstall(options) {
7025
8074
  }
7026
8075
  console.log(`hooks removed from ${settingsFile}`);
7027
8076
  }
7028
- for (const file of [hookBinPath(), hookBundlePath(), hookNodeRecordPath(), hookNoNodePath()]) {
8077
+ for (const file of [hookBinPath(), hookBundlePath(), hookNodeRecordPath(), hookNoNodePath(), `${hookBinPath()}.version`]) {
7029
8078
  if (!fs3.existsSync(file)) continue;
7030
8079
  fs3.rmSync(file);
7031
8080
  if (file === hookBinPath() || file === hookBundlePath()) console.log(`removed ${file}`);
@@ -7048,11 +8097,11 @@ var init_setup = __esm({
7048
8097
  init_launcher();
7049
8098
  init_paths();
7050
8099
  init_types();
7051
- HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop"];
7052
- HOOK_SET = 3;
8100
+ HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop", "PermissionRequest", "PermissionDenied"];
8101
+ HOOK_SET = 4;
7053
8102
  HOOK_TIMEOUT_SECONDS = 5;
7054
8103
  HOOK_MARKER = "ascenda-claude-hook";
7055
- SENDS = ["model", "posture", "git", "edits", "waiting", "subagents"];
8104
+ SENDS = ["model", "posture", "git", "edits", "waiting", "subagents", "forge", "turns"];
7056
8105
  USAGE = `ascenda-claude-hook setup \u2014 wire Claude Code to Ascenda telemetry
7057
8106
 
7058
8107
  npx @ascenda-one/claude-code-hooks setup [options]
@@ -7076,6 +8125,10 @@ Options
7076
8125
  --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
7077
8126
  On by default when not paired; machine-wide, shared by every agent
7078
8127
  (--no-pairing is accepted too)
8128
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
8129
+ repository gets a key and, off its default branch, a branch key, so a pull
8130
+ request can be matched to a session. They are digests anyone who guesses the
8131
+ names can reproduce. Machine-wide. --repo-keys turns them back on
7079
8132
  --scope user|project where hooks are registered (default user: every project)
7080
8133
  --project-dir <path> project root for --scope project (default cwd)
7081
8134
  --dry-run print what would change, write nothing
@@ -7089,6 +8142,7 @@ Options
7089
8142
  // src/cli.ts
7090
8143
  var import_tool_kit14 = __toESM(require_out3(), 1);
7091
8144
  var import_tool_kit15 = __toESM(require_out3(), 1);
8145
+ var import_tool_kit16 = __toESM(require_out3(), 1);
7092
8146
  import { randomUUID as randomUUID2 } from "node:crypto";
7093
8147
  import * as fs4 from "node:fs";
7094
8148
 
@@ -7123,6 +8177,13 @@ var AscendaClient = class {
7123
8177
  queue(mapped) {
7124
8178
  return this.sender.queue(mapped);
7125
8179
  }
8180
+ outboxFilePath() {
8181
+ return this.sender.outboxFilePath();
8182
+ }
8183
+ /** Drains the outbox until it's empty or the door refuses. What the background flusher runs. */
8184
+ async flushOutbox() {
8185
+ await (0, import_tool_kit.runOutboxFlush)(this.sender);
8186
+ }
7126
8187
  async renewEventToken() {
7127
8188
  return this.sender.renewEventToken();
7128
8189
  }
@@ -7139,12 +8200,15 @@ var import_tool_kit3 = __toESM(require_out3(), 1);
7139
8200
  function mapClaudeEvent(hookName, input) {
7140
8201
  const events = mapEvent(hookName, input);
7141
8202
  if (events.length === 0) return events;
7142
- const branchHash = (0, import_tool_kit4.deriveBranchHashForCwd)((0, import_tool_kit3.getString)(input, ["cwd"]) ?? process.cwd());
8203
+ const cwd = (0, import_tool_kit3.getString)(input, ["cwd"]) ?? process.cwd();
8204
+ const branchHash = (0, import_tool_kit4.deriveBranchHashForCwd)(cwd);
8205
+ const { repoKey, branchKey } = (0, import_tool_kit4.deriveForgeKeysForCwd)(cwd);
8206
+ const promptId = readPromptId(input);
7143
8207
  const runtime = claudeRuntime();
7144
8208
  const subagentId = readSubagentId(input);
7145
8209
  return events.map((event) => ({
7146
8210
  ...event,
7147
- metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...subagentId ? { subagentId } : {}, ...event.metadata }
8211
+ metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...repoKey ? { repoKey } : {}, ...branchKey ? { branchKey } : {}, ...promptId ? { promptId } : {}, ...subagentId ? { subagentId } : {}, ...event.metadata }
7148
8212
  }));
7149
8213
  }
7150
8214
  function mapEvent(hookName, input) {
@@ -7180,6 +8244,10 @@ function mapEvent(hookName, input) {
7180
8244
  return mapSubagent("subagent_started", input);
7181
8245
  case "SubagentStop":
7182
8246
  return mapSubagent("subagent_stopped", input);
8247
+ case "PermissionRequest":
8248
+ return mapPermission("permission_requested", input);
8249
+ case "PermissionDenied":
8250
+ return mapPermission("permission_denied", input);
7183
8251
  default:
7184
8252
  return [];
7185
8253
  }
@@ -7191,7 +8259,7 @@ function isNewSessionStart(input) {
7191
8259
  function milestoneInviting(input) {
7192
8260
  if ((0, import_tool_kit3.outcomeForHook)("PostToolUse", input) !== "success") return false;
7193
8261
  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));
8262
+ return (0, import_tool_kit4.invitesDebrief)((0, import_tool_kit4.classifyWorkMilestone)(command) ?? (0, import_tool_kit4.classifyMcpWorkMilestone)(getToolName(input)));
7195
8263
  }
7196
8264
  function mapSessionStart(input) {
7197
8265
  if (!isNewSessionStart(input)) return [];
@@ -7247,14 +8315,27 @@ var BUILT_IN_SUBAGENTS = {
7247
8315
  "statusline-setup": "statusline_setup",
7248
8316
  "claude-code-guide": "claude_code_guide"
7249
8317
  };
8318
+ function readPromptId(input) {
8319
+ const raw = input["prompt_id"];
8320
+ if (typeof raw !== "string") return void 0;
8321
+ const value = raw.trim();
8322
+ return /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : void 0;
8323
+ }
7250
8324
  function readSubagentId(input) {
7251
8325
  const raw = input["agent_id"];
7252
8326
  if (typeof raw !== "string") return void 0;
7253
8327
  const value = raw.trim();
7254
8328
  return /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : void 0;
7255
8329
  }
8330
+ function isTaskNotificationPrompt(prompt) {
8331
+ return prompt !== void 0 && prompt.trimStart().startsWith("<task-notification>");
8332
+ }
8333
+ function isBashModePrompt(prompt) {
8334
+ return prompt !== void 0 && prompt.trimStart().startsWith("<bash-input>");
8335
+ }
7256
8336
  function mapUserPromptSubmit(input) {
7257
8337
  const prompt = (0, import_tool_kit3.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit3.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
8338
+ if (isTaskNotificationPrompt(prompt) || isBashModePrompt(prompt)) return [];
7258
8339
  const autonomy = autonomyModeMetadata(input);
7259
8340
  const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...autonomy } }];
7260
8341
  if ((0, import_tool_kit3.looksLikeCorrection)(prompt)) {
@@ -7271,10 +8352,23 @@ function mapNotification(input) {
7271
8352
  // Low, always. Being asked is overhead to be counted, not a failure to be
7272
8353
  // flagged, and a severity that climbed would make this the input to a score.
7273
8354
  severity: "low",
7274
- metadata: { interruptionKind: notificationKind((0, import_tool_kit3.getString)(input, ["message"])) }
8355
+ metadata: { interruptionKind: notificationKind((0, import_tool_kit3.getString)(input, ["message"]), (0, import_tool_kit3.getString)(input, ["notification_type", "notificationType"])) }
8356
+ }];
8357
+ }
8358
+ function mapPermission(eventType, input) {
8359
+ return [{
8360
+ eventType,
8361
+ severity: "low",
8362
+ metadata: { toolName: sanitiseToolName(getToolName(input)), ...autonomyModeMetadata(input) }
7275
8363
  }];
7276
8364
  }
7277
- function notificationKind(message) {
8365
+ function notificationKind(message, notificationType) {
8366
+ if (notificationType !== void 0) {
8367
+ if (notificationType === "permission_prompt") return "permission_request";
8368
+ if (notificationType === "elicitation_dialog") return "input_request";
8369
+ if (notificationType === "idle_prompt") return "idle_prompt";
8370
+ return "other";
8371
+ }
7278
8372
  const text = message?.toLowerCase() ?? "";
7279
8373
  if (text.includes("permission")) return "permission_request";
7280
8374
  if (text.includes("waiting for your input")) return "idle_prompt";
@@ -7288,7 +8382,7 @@ function mapPostToolUse(hookName, input) {
7288
8382
  const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
7289
8383
  const commandClass = (0, import_tool_kit4.classifyCommand)(command);
7290
8384
  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;
8385
+ const milestoneKind = outcome === "success" ? (0, import_tool_kit4.classifyWorkMilestone)(command) ?? (0, import_tool_kit4.classifyMcpWorkMilestone)(toolName) : void 0;
7292
8386
  const autonomy = autonomyModeMetadata(input);
7293
8387
  if (outcome === "cancelled") {
7294
8388
  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 +8495,8 @@ function getToolName(input) {
7401
8495
  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
8496
  }
7403
8497
  function computeLinesChanged(toolName, input) {
8498
+ const patched = linesFromStructuredPatch((0, import_tool_kit3.getNested)(input, ["tool_response", "structuredPatch"]));
8499
+ if (patched !== void 0) return patched;
7404
8500
  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
8501
  if (!toolInput || typeof toolInput !== "object") return void 0;
7406
8502
  const record = toolInput;
@@ -7430,16 +8526,33 @@ function computeLinesChanged(toolName, input) {
7430
8526
  }
7431
8527
  return sawOne ? total : void 0;
7432
8528
  }
8529
+ case "notebookedit": {
8530
+ if (record["edit_mode"] === "delete") return void 0;
8531
+ const source = record["new_source"];
8532
+ return typeof source === "string" ? countLines(source) : void 0;
8533
+ }
7433
8534
  default:
7434
8535
  return void 0;
7435
8536
  }
7436
8537
  }
8538
+ function linesFromStructuredPatch(patch) {
8539
+ if (!Array.isArray(patch) || patch.length === 0) return void 0;
8540
+ let count = 0;
8541
+ for (const hunk of patch) {
8542
+ const lines = hunk && typeof hunk === "object" ? hunk["lines"] : void 0;
8543
+ if (!Array.isArray(lines)) continue;
8544
+ for (const line of lines) {
8545
+ if (typeof line === "string" && (line.startsWith("+") || line.startsWith("-"))) count += 1;
8546
+ }
8547
+ }
8548
+ return count;
8549
+ }
7437
8550
  function countLines(text) {
7438
8551
  return text.length === 0 ? 0 : text.split("\n").length;
7439
8552
  }
7440
8553
  function isWriteTool(toolName) {
7441
8554
  const value = toolName?.toLowerCase();
7442
- return value === "write" || value === "edit" || value === "multiedit";
8555
+ return value === "write" || value === "edit" || value === "multiedit" || value === "notebookedit";
7443
8556
  }
7444
8557
  function sanitiseToolName(toolName) {
7445
8558
  if (!toolName) return "unknown";
@@ -7487,9 +8600,9 @@ function notificationLiveEvent(input) {
7487
8600
  }
7488
8601
 
7489
8602
  // src/usageLimitReset.ts
7490
- import * as fs from "node:fs";
7491
- import * as os from "node:os";
7492
- import * as path from "node:path";
8603
+ init_paths();
8604
+ import * as fs2 from "node:fs";
8605
+ import * as path2 from "node:path";
7493
8606
  var MAX_RESUME_AHEAD_MS = 6 * 60 * 60 * 1e3;
7494
8607
  var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
7495
8608
  var RESET_CLAUSE = new RegExp(
@@ -7597,11 +8710,10 @@ function managedSettingsPath() {
7597
8710
  return "/etc/claude-code/managed-settings.json";
7598
8711
  }
7599
8712
  function autoContinueEnabled(sources = {}) {
7600
- const home = sources.home ?? os.homedir();
7601
8713
  const files = [
7602
8714
  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")
8715
+ ...sources.projectDir ? [path2.join(sources.projectDir, ".claude", "settings.local.json"), path2.join(sources.projectDir, ".claude", "settings.json")] : [],
8716
+ path2.join(sources.configDir ?? claudeConfigDir(), "settings.json")
7605
8717
  ];
7606
8718
  for (const file of files) {
7607
8719
  const value = readSetting(file, "autoContinueAtUsageLimit");
@@ -7611,7 +8723,7 @@ function autoContinueEnabled(sources = {}) {
7611
8723
  }
7612
8724
  function readSetting(file, key) {
7613
8725
  try {
7614
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
8726
+ const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
7615
8727
  if (parsed && typeof parsed === "object" && key in parsed) return parsed[key];
7616
8728
  } catch {
7617
8729
  }
@@ -7628,7 +8740,7 @@ init_hookHealth();
7628
8740
  var import_tool_kit12 = __toESM(require_out3(), 1);
7629
8741
  init_paths();
7630
8742
  var import_tool_kit13 = __toESM(require_out3(), 1);
7631
- import * as os4 from "os";
8743
+ import * as os3 from "os";
7632
8744
  async function localSignalLines(projectDir = process.cwd()) {
7633
8745
  const { registrationSummary: registrationSummary2, REGISTERED_EVENT_COUNT: REGISTERED_EVENT_COUNT2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
7634
8746
  return (0, import_tool_kit12.liveSignalDoctorLines)({
@@ -7643,7 +8755,7 @@ async function localSignalLines(projectDir = process.cwd()) {
7643
8755
  });
7644
8756
  }
7645
8757
  function tidy(file) {
7646
- const home = os4.homedir();
8758
+ const home = os3.homedir();
7647
8759
  return file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
7648
8760
  }
7649
8761
 
@@ -7679,7 +8791,7 @@ Waiting for confirmation (expires ${session.expiresAt})...
7679
8791
  );
7680
8792
  const deadline = Date.now() + 11 * 60 * 1e3;
7681
8793
  while (Date.now() < deadline) {
7682
- await new Promise((resolve2) => setTimeout(resolve2, 3e3));
8794
+ await new Promise((resolve3) => setTimeout(resolve3, 3e3));
7683
8795
  const status = await (0, import_tool_kit14.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
7684
8796
  if (status.status === "pending") continue;
7685
8797
  if (status.status !== "paired") {
@@ -7752,7 +8864,7 @@ async function main() {
7752
8864
  const command = process.argv[2];
7753
8865
  if (!command) {
7754
8866
  throw new Error(
7755
- "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | join | object | doctor | setup | status | uninstall"
8867
+ "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | join | object | doctor | setup | status | uninstall | plugin-sync"
7756
8868
  );
7757
8869
  }
7758
8870
  if (command === "pair") {
@@ -7771,6 +8883,14 @@ async function main() {
7771
8883
  await runDoctor();
7772
8884
  return;
7773
8885
  }
8886
+ if (command === import_tool_kit15.OUTBOX_FLUSH_COMMAND) {
8887
+ await runFlush();
8888
+ return;
8889
+ }
8890
+ if (command === PLUGIN_SYNC_COMMAND) {
8891
+ setupExitCode = runPluginSync();
8892
+ return;
8893
+ }
7774
8894
  if (MANAGEMENT_COMMANDS.has(command)) {
7775
8895
  const { runSetup: runSetup2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
7776
8896
  setupExitCode = await runSetup2(process.argv.slice(2));
@@ -7833,6 +8953,13 @@ async function main() {
7833
8953
  }
7834
8954
  return;
7835
8955
  }
8956
+ if (!(0, import_tool_kit15.hookDeliveryInline)() && claudeRuntime() !== "cloud") {
8957
+ for (const event of mappedEvents) {
8958
+ if (!client.queue(event)) console.error("Ascenda telemetry not kept: the event could not be written to the outbox.");
8959
+ }
8960
+ (0, import_tool_kit15.startBackgroundFlush)({ outboxFilePath: client.outboxFilePath() });
8961
+ return;
8962
+ }
7836
8963
  for (const event of mappedEvents) {
7837
8964
  const result = await client.send(event);
7838
8965
  if (result === "accepted") continue;
@@ -7840,6 +8967,26 @@ async function main() {
7840
8967
  return;
7841
8968
  }
7842
8969
  }
8970
+ var PLUGIN_SYNC_COMMAND = "plugin-sync";
8971
+ function runPluginSync() {
8972
+ try {
8973
+ const outcome = (0, import_tool_kit16.installPluginBundle)({ name: "claude-code-hooks" });
8974
+ console.log((0, import_tool_kit16.describePluginBundleOutcome)(outcome, (0, import_tool_kit16.pluginBundlePaths)("claude-code-hooks").bundle));
8975
+ return 0;
8976
+ } catch (error) {
8977
+ console.error(`plugin-sync: ${error instanceof Error ? error.message : String(error)}`);
8978
+ return 1;
8979
+ }
8980
+ }
8981
+ async function runFlush() {
8982
+ let config;
8983
+ try {
8984
+ config = loadConfigFromEnv();
8985
+ } catch {
8986
+ return;
8987
+ }
8988
+ await new AscendaClient(config).flushOutbox();
8989
+ }
7843
8990
  function journalSkippedSend(error) {
7844
8991
  (0, import_tool_kit14.recordSendOutcome)(resolveStateFilePath(), (0, import_tool_kit14.unresolvedToolInstallationId)(ASCENDA_TOOL_TYPE), "skipped_no_installation_id", {
7845
8992
  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 +9097,8 @@ function describeOutcome(state) {
7950
9097
  }
7951
9098
  }
7952
9099
  function writeStdout(text) {
7953
- return new Promise((resolve2) => {
7954
- process.stdout.write(text, () => resolve2());
9100
+ return new Promise((resolve3) => {
9101
+ process.stdout.write(text, () => resolve3());
7955
9102
  });
7956
9103
  }
7957
9104
  async function runDoctor() {
@@ -8084,6 +9231,7 @@ function outboxLines(toolInstallationId, state) {
8084
9231
  lines.push(` Outbox unreadable ${summary.unreadableLines} line(s) did not parse \u2014 discarded and journaled on the next hook`);
8085
9232
  }
8086
9233
  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}`);
9234
+ 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
9235
  const discarded = state?.outboxDiscarded;
8088
9236
  if (discarded) {
8089
9237
  const reasons = Object.entries(discarded.lastReasons).map(([reason, count]) => `${count} ${reason}`).join(", ");