@ascenda-one/codex-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
@@ -149,25 +149,66 @@ var require_gitActionClassifier = __commonJS({
149
149
  if (!/\bgit\b/.test(value))
150
150
  return void 0;
151
151
  const heads = (0, commandHeads_1.commandHeads)(value);
152
- if (heads.some((h) => /^git\s+commit\b/.test(h) && /\s--amend\b/.test(h)))
152
+ const commands = heads.map(parseGitCommand).filter((c) => c !== void 0);
153
+ if (commands.some((c) => c.verb === "commit" && c.args.includes("--amend")))
153
154
  return "amend";
154
- if (heads.some((h) => /^git\s+revert\b/.test(h)))
155
+ if (commands.some((c) => c.verb === "revert"))
155
156
  return "revert";
156
- if (heads.some((h) => /^git\s+reset\b/.test(h) && /\s--hard\b/.test(h)))
157
+ if (commands.some((c) => c.verb === "reset" && c.args.includes("--hard")))
157
158
  return "reset_hard";
158
- if (heads.some((h) => /^git\s+restore\b/.test(h) && !/\s--staged\b/.test(h)))
159
+ if (commands.some(discardsWork))
159
160
  return "restore";
160
- if (heads.some((h) => /^git\s+checkout\b.*\s--\s/.test(h)))
161
- return "restore";
162
- if (heads.some((h) => /^git\s+push\b/.test(h)))
161
+ if (commands.some((c) => c.verb === "push"))
163
162
  return "push";
164
- if (heads.some((h) => /^git\s+commit\b/.test(h)))
163
+ if (commands.some((c) => c.verb === "commit"))
165
164
  return "commit";
166
165
  return void 0;
167
166
  }
168
167
  function isReworkGitAction(action) {
169
168
  return action === "revert" || action === "reset_hard" || action === "restore";
170
169
  }
170
+ var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path"]);
171
+ function parseGitCommand(head) {
172
+ const words = head.split(/\s+/);
173
+ if (words[0] !== "git")
174
+ return void 0;
175
+ let i = 1;
176
+ while (i < words.length && words[i].startsWith("-")) {
177
+ i += GLOBAL_OPTIONS_WITH_VALUE.has(words[i]) ? 2 : 1;
178
+ }
179
+ if (i >= words.length)
180
+ return void 0;
181
+ return { verb: words[i], args: words.slice(i + 1) };
182
+ }
183
+ function discardsWork({ verb, args }) {
184
+ switch (verb) {
185
+ case "restore":
186
+ return !args.includes("--staged");
187
+ case "switch":
188
+ return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
189
+ case "clean": {
190
+ const flags = args.filter((a) => /^-[a-z]+$/.test(a)).join("");
191
+ const dryRun = args.includes("--dry-run") || flags.includes("n");
192
+ return !dryRun && (args.includes("--force") || flags.includes("f"));
193
+ }
194
+ case "checkout":
195
+ return checkoutDiscards(args);
196
+ default:
197
+ return false;
198
+ }
199
+ }
200
+ function checkoutDiscards(args) {
201
+ if (args.includes("--"))
202
+ return true;
203
+ if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
204
+ return false;
205
+ const words = args.filter((a) => !a.startsWith("-"));
206
+ if (words.length >= 2)
207
+ return true;
208
+ if (words.length === 1)
209
+ return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
210
+ return false;
211
+ }
171
212
  }
172
213
  });
173
214
 
@@ -178,6 +219,7 @@ var require_workMilestoneClassifier = __commonJS({
178
219
  Object.defineProperty(exports, "__esModule", { value: true });
179
220
  exports.classifyWorkMilestone = classifyWorkMilestone;
180
221
  exports.invitesDebrief = invitesDebrief;
222
+ exports.classifyMcpWorkMilestone = classifyMcpWorkMilestone;
181
223
  var commandHeads_1 = require_commandHeads();
182
224
  function classifyWorkMilestone(command) {
183
225
  if (!command)
@@ -197,6 +239,41 @@ var require_workMilestoneClassifier = __commonJS({
197
239
  function invitesDebrief(kind) {
198
240
  return kind === "pr_merged" || kind === "issue_closed";
199
241
  }
242
+ function classifyMcpWorkMilestone(toolName) {
243
+ if (!toolName)
244
+ return void 0;
245
+ const parts = toolName.toLowerCase().split("__");
246
+ if (parts[0] !== "mcp" || parts.length < 3)
247
+ return void 0;
248
+ const tool = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
249
+ if (/^(merge|accept)(pullrequest|mergerequest)$/.test(tool))
250
+ return "pr_merged";
251
+ if (/^closeissue$/.test(tool))
252
+ return "issue_closed";
253
+ if (/^(create|open)(pullrequest|mergerequest)$/.test(tool))
254
+ return "pr_opened";
255
+ return void 0;
256
+ }
257
+ }
258
+ });
259
+
260
+ // ../packages/tool-kit/out/shellFacts.js
261
+ var require_shellFacts = __commonJS({
262
+ "../packages/tool-kit/out/shellFacts.js"(exports) {
263
+ "use strict";
264
+ Object.defineProperty(exports, "__esModule", { value: true });
265
+ exports.shellCommandFacts = shellCommandFacts2;
266
+ var gitActionClassifier_1 = require_gitActionClassifier();
267
+ var workMilestoneClassifier_1 = require_workMilestoneClassifier();
268
+ function shellCommandFacts2(command) {
269
+ const gitAction = (0, gitActionClassifier_1.classifyGitAction)(command);
270
+ const milestoneKind = (0, workMilestoneClassifier_1.classifyWorkMilestone)(command);
271
+ return {
272
+ ...gitAction !== void 0 ? { gitAction } : {},
273
+ ...(0, gitActionClassifier_1.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
274
+ ...milestoneKind !== void 0 ? { milestoneKind } : {}
275
+ };
276
+ }
200
277
  }
201
278
  });
202
279
 
@@ -590,6 +667,61 @@ var require_metricKeys = __commonJS({
590
667
  subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
591
668
  subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
592
669
  subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
670
+ advisorMessageCount: {
671
+ family: "counts",
672
+ readBy: ["diagnostic"],
673
+ note: "Claude Code only: advisor calls (a second model consulted inside one API message). Their tokens and models are already folded into the session totals and model mix, and this is the receipt for how much of that they are."
674
+ },
675
+ advisorTokensTotal: {
676
+ family: "context",
677
+ readBy: ["diagnostic"],
678
+ unit: "tokens",
679
+ note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
680
+ },
681
+ cacheCreationTokens: {
682
+ family: "context",
683
+ readBy: ["diagnostic"],
684
+ unit: "tokens",
685
+ note: "Prompt-cache writes, summed once per API message. Absent where the store never wrote the figure, which is not the same as none written."
686
+ },
687
+ cacheCreation5mTokens: {
688
+ family: "context",
689
+ readBy: ["diagnostic"],
690
+ unit: "tokens",
691
+ note: "The part of cacheCreationTokens written with the 5-minute lifetime. Absent on transcripts that only record the total."
692
+ },
693
+ cacheCreation1hTokens: {
694
+ family: "context",
695
+ readBy: ["diagnostic"],
696
+ unit: "tokens",
697
+ note: "The part of cacheCreationTokens written with the 1-hour lifetime. Absent on transcripts that only record the total."
698
+ },
699
+ headlessPromptLines: {
700
+ family: "reading",
701
+ readBy: ["diagnostic"],
702
+ unit: "lines",
703
+ note: "Claude Code only: user lines written by the Agent SDK or a headless run (entrypoint sdk-*). Nobody typed them, so promptCount leaves them out. Counted once per line across the store."
704
+ },
705
+ tokensNotCollected: {
706
+ family: "context",
707
+ readBy: ["diagnostic"],
708
+ note: "True when the store recorded no token figures for this session (Cursor builds that write a zero tokenCount, Codex rollouts from before token_count events). The token keys are then left off the event instead of being sent as 0, so absent and zero stay apart. Metrics are flat scalars with no null, so a flag beside the missing keys is the marker the contract allows."
709
+ },
710
+ unattributedSubagentTranscripts: {
711
+ family: "reading",
712
+ readBy: ["diagnostic"],
713
+ note: "Claude Code only: flat subagent transcripts whose lines name no parent session, so they could not be folded anywhere."
714
+ },
715
+ duplicateChatSessions: {
716
+ family: "reading",
717
+ readBy: ["diagnostic"],
718
+ note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
719
+ },
720
+ sessionsStartedFromBubble: {
721
+ family: "reading",
722
+ readBy: ["diagnostic"],
723
+ note: "Cursor only: sessions whose start is the earliest message rather than the header's createdAt, which can sit months before anyone typed."
724
+ },
593
725
  toolName: {
594
726
  family: "tools",
595
727
  readBy: ["backend"],
@@ -697,7 +829,9 @@ var require_out = __commonJS({
697
829
  exports.COLLABORATION_EVENT_TYPES = [
698
830
  "review_requested_of_me",
699
831
  "review_given",
700
- "pull_request_opened"
832
+ "pull_request_opened",
833
+ "pull_request_closed",
834
+ "pull_request_merged"
701
835
  ];
702
836
  exports.EVENT_METADATA_DISCLOSURE = {
703
837
  language: "edits",
@@ -709,6 +843,13 @@ var require_out = __commonJS({
709
843
  gitAction: "git",
710
844
  milestoneKind: "git",
711
845
  branchHash: "repo",
846
+ repoKey: "forge",
847
+ headRepoKey: "forge",
848
+ prCreatedAt: "git",
849
+ prClosedAt: "git",
850
+ prMergedAt: "git",
851
+ branchKey: "forge",
852
+ promptId: "turns",
712
853
  autonomyMode: "posture",
713
854
  modelClass: "model",
714
855
  modelId: "model",
@@ -758,6 +899,13 @@ var require_out = __commonJS({
758
899
  "gitAction",
759
900
  "milestoneKind",
760
901
  "branchHash",
902
+ "repoKey",
903
+ "headRepoKey",
904
+ "prCreatedAt",
905
+ "prClosedAt",
906
+ "prMergedAt",
907
+ "branchKey",
908
+ "promptId",
761
909
  "autonomyMode",
762
910
  "modelClass",
763
911
  "modelId",
@@ -827,6 +975,10 @@ var require_out = __commonJS({
827
975
  review_requested_of_me: "supervision",
828
976
  review_given: "supervision",
829
977
  pull_request_opened: "creation",
978
+ // Where a pull request of yours ended up. A boundary like a turn ending, not
979
+ // work in itself, so neutral: it must not weigh on any workload leg.
980
+ pull_request_closed: "neutral",
981
+ pull_request_merged: "neutral",
830
982
  context_pressure_high: "risk",
831
983
  agent_loop_long: "risk",
832
984
  after_hours_ai_session: "risk",
@@ -857,6 +1009,16 @@ var require_out = __commonJS({
857
1009
  // step toward an interruption count becoming a score, a streak, or something
858
1010
  // that fires on a miss. It must never become any of those.
859
1011
  supervision_interruption: "supervision",
1012
+ // The agent asked to run a tool, and the auto-mode classifier refused one.
1013
+ // Claude Code's `PermissionRequest` and `PermissionDenied` hooks. Neutral,
1014
+ // because the Notification for the same prompt is already counted above as
1015
+ // `supervision_interruption`, and counting both would weigh one prompt
1016
+ // twice. These rows exist for the public event stream: which tool asked, and
1017
+ // under which posture. `permission_requested` fires before the person
1018
+ // answers and no hook reports their answer, so neither event says whether
1019
+ // the request was granted.
1020
+ permission_requested: "neutral",
1021
+ permission_denied: "neutral",
860
1022
  // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
861
1023
  approach_churn_detected: "risk",
862
1024
  goal_drift_detected: "risk",
@@ -919,9 +1081,9 @@ var require_payload = __commonJS({
919
1081
  }
920
1082
  return void 0;
921
1083
  }
922
- function getNested2(input, path2) {
1084
+ function getNested2(input, path3) {
923
1085
  let current = input;
924
- for (const segment of path2) {
1086
+ for (const segment of path3) {
925
1087
  if (!current || typeof current !== "object")
926
1088
  return void 0;
927
1089
  current = current[segment];
@@ -929,16 +1091,16 @@ var require_payload = __commonJS({
929
1091
  return current;
930
1092
  }
931
1093
  function getNestedString3(input, paths) {
932
- for (const path2 of paths) {
933
- const value = getNested2(input, path2);
1094
+ for (const path3 of paths) {
1095
+ const value = getNested2(input, path3);
934
1096
  if (typeof value === "string" && value.trim())
935
1097
  return value;
936
1098
  }
937
1099
  return void 0;
938
1100
  }
939
1101
  function getNestedNumber(input, paths) {
940
- for (const path2 of paths) {
941
- const value = getNested2(input, path2);
1102
+ for (const path3 of paths) {
1103
+ const value = getNested2(input, path3);
942
1104
  if (typeof value === "number" && Number.isFinite(value))
943
1105
  return value;
944
1106
  }
@@ -981,122 +1143,13 @@ var require_collectorVersion = __commonJS({
981
1143
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
982
1144
  exports.describeCollectorVersion = describeCollectorVersion;
983
1145
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
984
- exports.COLLECTOR_VERSION = "0.1.35" ? "0.1.35" : exports.UNRELEASED_COLLECTOR_VERSION;
1146
+ exports.COLLECTOR_VERSION = "0.1.37" ? "0.1.37" : exports.UNRELEASED_COLLECTOR_VERSION;
985
1147
  function describeCollectorVersion(version = exports.COLLECTOR_VERSION) {
986
1148
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
987
1149
  }
988
1150
  }
989
1151
  });
990
1152
 
991
- // ../packages/agent-events/out/index.js
992
- var require_out2 = __commonJS({
993
- "../packages/agent-events/out/index.js"(exports) {
994
- "use strict";
995
- Object.defineProperty(exports, "__esModule", { value: true });
996
- exports.KNOWN_AGENTS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
997
- exports.isAgentEventV0 = isAgentEventV0;
998
- exports.parseEventLogLine = parseEventLogLine;
999
- exports.normaliseKind = normaliseKind;
1000
- exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1001
- exports.AGENT_EVENT_KINDS = [
1002
- "session.started",
1003
- "session.ended",
1004
- "prompt.submitted",
1005
- "tool.started",
1006
- "tool.completed",
1007
- "tool.failed",
1008
- "turn.completed",
1009
- "agent.waiting",
1010
- "context.compacted",
1011
- "subagent.started",
1012
- "subagent.stopped",
1013
- "other"
1014
- ];
1015
- exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1016
- function isAgentEventV0(value) {
1017
- if (!value || typeof value !== "object")
1018
- return false;
1019
- const e = value;
1020
- 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";
1021
- }
1022
- function parseEventLogLine(line) {
1023
- if (!line.trim())
1024
- return void 0;
1025
- try {
1026
- const parsed = JSON.parse(line);
1027
- return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1028
- } catch {
1029
- return void 0;
1030
- }
1031
- }
1032
- function normaliseKind(kind) {
1033
- return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1034
- }
1035
- }
1036
- });
1037
-
1038
- // ../packages/tool-kit/out/agentEvent.js
1039
- var require_agentEvent = __commonJS({
1040
- "../packages/tool-kit/out/agentEvent.js"(exports) {
1041
- "use strict";
1042
- Object.defineProperty(exports, "__esModule", { value: true });
1043
- exports.toAgentEvent = toAgentEvent;
1044
- var agent_events_1 = require_out2();
1045
- var KIND_BY_TYPE = {
1046
- create_focus_session: "session.started",
1047
- recovery_offline_period: "session.ended",
1048
- ai_prompt_submitted: "prompt.submitted",
1049
- ai_tool_call_started: "tool.started",
1050
- ai_tool_call_completed: "tool.completed",
1051
- ai_file_write: "tool.completed",
1052
- ai_file_edit: "tool.completed",
1053
- editor_verification_activity: "tool.completed",
1054
- ai_tool_call_failed: "tool.failed",
1055
- compile_error: "tool.failed",
1056
- tool_failure: "tool.failed",
1057
- ai_turn_completed: "turn.completed",
1058
- supervision_interruption: "agent.waiting",
1059
- context_compression_manual: "context.compacted",
1060
- context_compression_auto: "context.compacted",
1061
- subagent_started: "subagent.started",
1062
- subagent_stopped: "subagent.stopped"
1063
- };
1064
- function agentOf(payload) {
1065
- const host = stringField(payload.metadata?.host);
1066
- if (host)
1067
- return host;
1068
- return payload.source === "vscode_extension" ? "vscode" : payload.source;
1069
- }
1070
- function stringField(value) {
1071
- return typeof value === "string" && value.length > 0 ? value : void 0;
1072
- }
1073
- function toAgentEvent(payload) {
1074
- const metadata = payload.metadata ?? {};
1075
- const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1076
- const tool = kind.startsWith("tool.") ? stringField(metadata.toolName) : void 0;
1077
- const outcome = stringField(metadata.outcome);
1078
- return {
1079
- schema: agent_events_1.AGENT_EVENT_SCHEMA,
1080
- id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1081
- time: payload.occurredAt,
1082
- // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1083
- // writes anyway; without it the event in memory and the one on disk differ.
1084
- ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1085
- agent: agentOf(payload),
1086
- kind,
1087
- ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1088
- ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1089
- ...tool ? { tool } : {},
1090
- ...outcome && outcome !== "unknown" ? { outcome } : {},
1091
- ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1092
- ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1093
- ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1094
- sourceType: payload.eventType
1095
- };
1096
- }
1097
- }
1098
- });
1099
-
1100
1153
  // ../packages/tool-kit/out/tokenStore.js
1101
1154
  var require_tokenStore = __commonJS({
1102
1155
  "../packages/tool-kit/out/tokenStore.js"(exports) {
@@ -1148,33 +1201,33 @@ var require_tokenStore = __commonJS({
1148
1201
  exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1149
1202
  exports.readTokenFile = readTokenFile;
1150
1203
  exports.sanitizeFilePart = sanitizeFilePart;
1151
- var fs = __importStar(__require("fs"));
1204
+ var fs2 = __importStar(__require("fs"));
1152
1205
  var os2 = __importStar(__require("os"));
1153
- var path2 = __importStar(__require("path"));
1206
+ var path3 = __importStar(__require("path"));
1154
1207
  function ascendaHome(home = os2.homedir()) {
1155
- return process.env.ASCENDA_HOME ?? path2.join(home, ".ascenda");
1208
+ return process.env.ASCENDA_HOME ?? path3.join(home, ".ascenda");
1156
1209
  }
1157
1210
  function defaultTokenFilePath(toolInstallationId) {
1158
- return path2.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1211
+ return path3.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1159
1212
  }
1160
1213
  function tokenExpiryFilePath(tokenFilePath) {
1161
- return path2.join(path2.dirname(tokenFilePath), "expiry", path2.basename(tokenFilePath));
1214
+ return path3.join(path3.dirname(tokenFilePath), "expiry", path3.basename(tokenFilePath));
1162
1215
  }
1163
1216
  function persistEventWriteToken(tokenFilePath, token, expiresAt) {
1164
- const dir = path2.dirname(tokenFilePath);
1165
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1166
- fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1217
+ const dir = path3.dirname(tokenFilePath);
1218
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1219
+ fs2.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1167
1220
  if (process.platform !== "win32") {
1168
- fs.chmodSync(dir, 448);
1169
- fs.chmodSync(tokenFilePath, 384);
1221
+ fs2.chmodSync(dir, 448);
1222
+ fs2.chmodSync(tokenFilePath, 384);
1170
1223
  }
1171
1224
  const expiryFile = tokenExpiryFilePath(tokenFilePath);
1172
1225
  try {
1173
1226
  if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1174
- fs.mkdirSync(path2.dirname(expiryFile), { recursive: true, mode: 448 });
1175
- fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1227
+ fs2.mkdirSync(path3.dirname(expiryFile), { recursive: true, mode: 448 });
1228
+ fs2.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1176
1229
  } else {
1177
- fs.rmSync(expiryFile, { force: true });
1230
+ fs2.rmSync(expiryFile, { force: true });
1178
1231
  }
1179
1232
  } catch {
1180
1233
  }
@@ -1182,23 +1235,23 @@ var require_tokenStore = __commonJS({
1182
1235
  exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1183
1236
  function readTokenExpiry(tokenFilePath) {
1184
1237
  try {
1185
- const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1238
+ const recorded = Date.parse(fs2.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1186
1239
  if (Number.isFinite(recorded))
1187
1240
  return recorded;
1188
1241
  } catch {
1189
1242
  }
1190
1243
  try {
1191
- return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1244
+ return fs2.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1192
1245
  } catch {
1193
1246
  return void 0;
1194
1247
  }
1195
1248
  }
1196
1249
  function listPersistedToolInstallationIds(toolType) {
1197
1250
  const prefix = `${sanitizeFilePart(toolType)}_`;
1198
- const dir = path2.join(ascendaHome(), "tokens");
1251
+ const dir = path3.join(ascendaHome(), "tokens");
1199
1252
  let names;
1200
1253
  try {
1201
- names = fs.readdirSync(dir);
1254
+ names = fs2.readdirSync(dir);
1202
1255
  } catch {
1203
1256
  return [];
1204
1257
  }
@@ -1206,9 +1259,9 @@ var require_tokenStore = __commonJS({
1206
1259
  for (const name of names.sort()) {
1207
1260
  if (!name.startsWith(prefix) || name.length === prefix.length)
1208
1261
  continue;
1209
- const file = path2.join(dir, name);
1262
+ const file = path3.join(dir, name);
1210
1263
  try {
1211
- if (!fs.statSync(file).isFile())
1264
+ if (!fs2.statSync(file).isFile())
1212
1265
  continue;
1213
1266
  } catch {
1214
1267
  continue;
@@ -1221,9 +1274,9 @@ var require_tokenStore = __commonJS({
1221
1274
  }
1222
1275
  function readTokenFile(tokenFilePath) {
1223
1276
  try {
1224
- if (!fs.existsSync(tokenFilePath))
1277
+ if (!fs2.existsSync(tokenFilePath))
1225
1278
  return void 0;
1226
- const value = fs.readFileSync(tokenFilePath, "utf8").trim();
1279
+ const value = fs2.readFileSync(tokenFilePath, "utf8").trim();
1227
1280
  return value || void 0;
1228
1281
  } catch {
1229
1282
  return void 0;
@@ -1235,9 +1288,9 @@ var require_tokenStore = __commonJS({
1235
1288
  }
1236
1289
  });
1237
1290
 
1238
- // ../packages/tool-kit/out/credentials.js
1239
- var require_credentials = __commonJS({
1240
- "../packages/tool-kit/out/credentials.js"(exports) {
1291
+ // ../packages/tool-kit/out/stateStore.js
1292
+ var require_stateStore = __commonJS({
1293
+ "../packages/tool-kit/out/stateStore.js"(exports) {
1241
1294
  "use strict";
1242
1295
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1243
1296
  if (k2 === void 0) k2 = k;
@@ -1277,94 +1330,124 @@ var require_credentials = __commonJS({
1277
1330
  };
1278
1331
  }();
1279
1332
  Object.defineProperty(exports, "__esModule", { value: true });
1280
- exports.credentialsFilePath = credentialsFilePath;
1281
- exports.readMachineCredentials = readMachineCredentials;
1282
- exports.writeMachineCredentials = writeMachineCredentials;
1283
- exports.writeTopLevelCredentials = writeTopLevelCredentials;
1284
- exports.writeEventLogSetting = writeEventLogSetting;
1285
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
1286
- exports.readHostCredentials = readHostCredentials;
1287
- exports.writeHostCredentials = writeHostCredentials;
1288
- exports.removeHostCredentials = removeHostCredentials;
1289
- var fs = __importStar(__require("fs"));
1290
- var path2 = __importStar(__require("path"));
1333
+ exports.defaultStateFilePath = defaultStateFilePath;
1334
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
1335
+ exports.unresolvedStateFilePath = unresolvedStateFilePath;
1336
+ exports.readCollectorState = readCollectorState;
1337
+ exports.recordSendOutcome = recordSendOutcome;
1338
+ exports.recordOutboxDiscard = recordOutboxDiscard;
1339
+ exports.shouldAnnounceFailure = shouldAnnounceFailure;
1340
+ exports.markFailureNotified = markFailureNotified;
1341
+ var fs2 = __importStar(__require("fs"));
1342
+ var path3 = __importStar(__require("path"));
1291
1343
  var tokenStore_1 = require_tokenStore();
1292
- function credentialsFilePath() {
1293
- return path2.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1344
+ function defaultStateFilePath(toolInstallationId) {
1345
+ const dir = process.env.ASCENDA_STATE_DIR?.trim();
1346
+ const base = dir ? dir : path3.join((0, tokenStore_1.ascendaHome)(), "state");
1347
+ return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1294
1348
  }
1295
- function readMachineCredentials() {
1349
+ function unresolvedToolInstallationId(toolType) {
1350
+ return `${toolType}:unresolved`;
1351
+ }
1352
+ function unresolvedStateFilePath(toolType) {
1353
+ return defaultStateFilePath(unresolvedToolInstallationId(toolType));
1354
+ }
1355
+ function readCollectorState(stateFilePath) {
1296
1356
  try {
1297
- const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
1357
+ if (!fs2.existsSync(stateFilePath))
1358
+ return void 0;
1359
+ const raw = fs2.readFileSync(stateFilePath, "utf8").trim();
1298
1360
  if (!raw)
1299
1361
  return void 0;
1300
1362
  const parsed = JSON.parse(raw);
1301
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1363
+ if (!parsed || typeof parsed !== "object")
1302
1364
  return void 0;
1303
1365
  return parsed;
1304
1366
  } catch {
1305
1367
  return void 0;
1306
1368
  }
1307
1369
  }
1308
- function writeMachineCredentials(credentials) {
1309
- const file = credentialsFilePath();
1310
- fs.mkdirSync(path2.dirname(file), { recursive: true, mode: 448 });
1311
- fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
1312
- `, { encoding: "utf8", mode: 384 });
1313
- if (process.platform !== "win32") {
1314
- fs.chmodSync(path2.dirname(file), 448);
1315
- fs.chmodSync(file, 384);
1316
- }
1317
- }
1318
- function writeTopLevelCredentials(credentials) {
1319
- const existing = readMachineCredentials();
1320
- const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
1321
- writeMachineCredentials({
1322
- ...credentials,
1323
- ...eventLogPath ? { eventLogPath } : {},
1324
- ...existing?.tools ? { tools: existing.tools } : {}
1325
- });
1326
- }
1327
- function writeEventLogSetting(value) {
1328
- const existing = readMachineCredentials() ?? {};
1329
- writeMachineCredentials({ ...existing, eventLogPath: value });
1370
+ function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1371
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1372
+ const previous = readCollectorState(stateFilePath);
1373
+ const accepted = outcome === "accepted";
1374
+ const next = {
1375
+ toolInstallationId,
1376
+ lastAttemptAt: now,
1377
+ lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1378
+ lastOutcome: outcome,
1379
+ consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1380
+ ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1381
+ ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1382
+ ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1383
+ // A success closes the episode; a failure either opens one or continues
1384
+ // the one already open. Carrying `notifiedFailingSince` across a
1385
+ // continuing episode is what keeps the notice to once per outage.
1386
+ ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1387
+ ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1388
+ // Cumulative by design: a send outcome, success included, never erases
1389
+ // the record of what the outbox had to throw away.
1390
+ ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1391
+ };
1392
+ writeStateFile(stateFilePath, next);
1393
+ return next;
1330
1394
  }
1331
- function isLocalOnlyHostInstall(host, hasToken) {
1332
- const credentials = readHostCredentials(host);
1333
- if (!credentials?.localOnly)
1334
- return false;
1335
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
1336
- return false;
1337
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1338
- }
1339
- function readHostCredentials(host) {
1340
- const entry = readMachineCredentials()?.tools?.[host];
1341
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
1342
- return void 0;
1343
- return entry;
1395
+ function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1396
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1397
+ const previous = readCollectorState(stateFilePath);
1398
+ const next = {
1399
+ ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1400
+ toolInstallationId,
1401
+ lastOutcome: "outbox_discarded",
1402
+ outboxDiscarded: {
1403
+ total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1404
+ lastAt: now,
1405
+ lastCount: discard.count,
1406
+ lastReasons: discard.reasons,
1407
+ ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1408
+ }
1409
+ };
1410
+ writeStateFile(stateFilePath, next);
1411
+ return next;
1344
1412
  }
1345
- function writeHostCredentials(host, credentials) {
1346
- const existing = readMachineCredentials() ?? {};
1347
- writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1413
+ function shouldAnnounceFailure(state) {
1414
+ if (!state || state.consecutiveFailures === 0 || !state.failingSince)
1415
+ return false;
1416
+ return state.notifiedFailingSince !== state.failingSince;
1348
1417
  }
1349
- function removeHostCredentials(host) {
1350
- const existing = readMachineCredentials();
1351
- if (!existing?.tools || !(host in existing.tools))
1418
+ function markFailureNotified(stateFilePath, state) {
1419
+ if (!state.failingSince)
1352
1420
  return;
1353
- const tools = { ...existing.tools };
1354
- delete tools[host];
1355
- const next = { ...existing };
1356
- if (Object.keys(tools).length)
1357
- next.tools = tools;
1358
- else
1359
- delete next.tools;
1360
- writeMachineCredentials(next);
1421
+ writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
1422
+ }
1423
+ function writeStateFile(stateFilePath, state) {
1424
+ const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1425
+ try {
1426
+ const dir = path3.dirname(stateFilePath);
1427
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1428
+ fs2.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1429
+ `, { encoding: "utf8", mode: 384 });
1430
+ fs2.renameSync(temporaryPath, stateFilePath);
1431
+ if (process.platform !== "win32")
1432
+ fs2.chmodSync(stateFilePath, 384);
1433
+ } catch {
1434
+ try {
1435
+ if (fs2.existsSync(temporaryPath))
1436
+ fs2.unlinkSync(temporaryPath);
1437
+ } catch {
1438
+ }
1439
+ }
1440
+ }
1441
+ function truncate(value) {
1442
+ const collapsed = value.replace(/\s+/g, " ").trim();
1443
+ return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
1361
1444
  }
1362
1445
  }
1363
1446
  });
1364
1447
 
1365
- // ../packages/tool-kit/out/eventLog.js
1366
- var require_eventLog = __commonJS({
1367
- "../packages/tool-kit/out/eventLog.js"(exports) {
1448
+ // ../packages/tool-kit/out/outbox.js
1449
+ var require_outbox = __commonJS({
1450
+ "../packages/tool-kit/out/outbox.js"(exports) {
1368
1451
  "use strict";
1369
1452
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1370
1453
  if (k2 === void 0) k2 = k;
@@ -1404,354 +1487,189 @@ var require_eventLog = __commonJS({
1404
1487
  };
1405
1488
  }();
1406
1489
  Object.defineProperty(exports, "__esModule", { value: true });
1407
- exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
1408
- exports.expandUserPath = expandUserPath;
1409
- exports.defaultEventLogPath = defaultEventLogPath;
1410
- exports.resolveEventLog = resolveEventLog;
1411
- exports.resolveEventLogPath = resolveEventLogPath;
1412
- exports.describeEventLog = describeEventLog;
1413
- exports.parseEventLogFlag = parseEventLogFlag;
1414
- exports.appendEventLog = appendEventLog;
1415
- var fs = __importStar(__require("fs"));
1416
- var os2 = __importStar(__require("os"));
1417
- var path2 = __importStar(__require("path"));
1418
- var agentEvent_1 = require_agentEvent();
1419
- var credentials_1 = require_credentials();
1490
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1491
+ exports.outboxDrainEnabled = outboxDrainEnabled;
1492
+ exports.defaultOutboxFilePath = defaultOutboxFilePath;
1493
+ exports.appendToOutbox = appendToOutbox;
1494
+ exports.readOutboxSummary = readOutboxSummary;
1495
+ exports.claimOutbox = claimOutbox;
1496
+ exports.enforceOutboxBounds = enforceOutboxBounds;
1497
+ var fs2 = __importStar(__require("fs"));
1498
+ var path3 = __importStar(__require("path"));
1499
+ var stateStore_1 = require_stateStore();
1420
1500
  var tokenStore_1 = require_tokenStore();
1421
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1422
- exports.EVENT_LOG_OFF = "off";
1423
- var MAX_BYTES = 5 * 1024 * 1024;
1424
- function expandUserPath(configured) {
1425
- const value = configured?.trim();
1426
- if (!value)
1427
- return void 0;
1428
- if (value === "~")
1429
- return os2.homedir();
1430
- if (value.startsWith("~/"))
1431
- return path2.join(os2.homedir(), value.slice(2));
1432
- return path2.resolve(value);
1501
+ exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1502
+ exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1503
+ exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1504
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1505
+ var ORPHANED_CLAIM_AGE_MS = 6e4;
1506
+ var CLAIM_SUFFIX = ".draining";
1507
+ function outboxDrainEnabled(env = process.env) {
1508
+ const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1509
+ if (value === void 0 || value === "")
1510
+ return true;
1511
+ return !(value === "0" || value === "false" || value === "no" || value === "off");
1433
1512
  }
1434
- function defaultEventLogPath() {
1435
- return path2.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1513
+ function defaultOutboxFilePath(toolInstallationId) {
1514
+ const dir = path3.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1515
+ return path3.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1436
1516
  }
1437
- function resolveEventLog(options = {}) {
1438
- for (const [source, raw] of [
1439
- ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
1440
- ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
1441
- ]) {
1442
- const value = raw?.trim();
1443
- if (!value)
1444
- continue;
1445
- if (value.toLowerCase() === exports.EVENT_LOG_OFF)
1446
- return { path: void 0, source: "disabled" };
1447
- return { path: expandUserPath(value), source };
1517
+ function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1518
+ try {
1519
+ const dir = path3.dirname(outboxFilePath);
1520
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1521
+ const entry = { queuedAt: now.toISOString(), payload };
1522
+ fs2.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1523
+ `, { encoding: "utf8", mode: 384 });
1524
+ if (process.platform !== "win32")
1525
+ fs2.chmodSync(outboxFilePath, 384);
1526
+ return true;
1527
+ } catch {
1528
+ return false;
1448
1529
  }
1449
- if (options.localOnly)
1450
- return { path: defaultEventLogPath(), source: "unpaired-default" };
1451
- return { path: void 0, source: "off" };
1452
1530
  }
1453
- function resolveEventLogPath(options = {}) {
1454
- return resolveEventLog(options).path;
1531
+ function readOutboxSummary(outboxFilePath) {
1532
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs2.existsSync(file));
1533
+ if (files.length === 0)
1534
+ return void 0;
1535
+ let depth = 0;
1536
+ let unreadableLines = 0;
1537
+ let oldestQueuedAt;
1538
+ for (const file of files) {
1539
+ const { entries, unreadable } = readEntries(file);
1540
+ depth += entries.length;
1541
+ unreadableLines += unreadable;
1542
+ for (const entry of entries) {
1543
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1544
+ oldestQueuedAt = entry.queuedAt;
1545
+ }
1546
+ }
1547
+ return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1455
1548
  }
1456
- function describeEventLog(setting, command) {
1457
- switch (setting.source) {
1458
- case "env":
1459
- return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
1460
- case "credentials":
1461
- return `${setting.path} (set by ${command} --event-log)`;
1462
- case "unpaired-default":
1463
- return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
1464
- case "disabled":
1465
- return `off (turned off; ${command} --event-log to turn it on)`;
1466
- case "off":
1467
- return `off (${command} --event-log to keep a local copy of every event)`;
1549
+ function claimOutbox(outboxFilePath, now = Date.now()) {
1550
+ const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1551
+ const claimed = [];
1552
+ try {
1553
+ fs2.renameSync(outboxFilePath, claimPath);
1554
+ claimed.push(claimPath);
1555
+ } catch {
1556
+ }
1557
+ let orphanIndex = 0;
1558
+ for (const orphan of listClaimFiles(outboxFilePath)) {
1559
+ if (claimed.includes(orphan))
1560
+ continue;
1561
+ try {
1562
+ if (now - fs2.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1563
+ continue;
1564
+ const mine = `${claimPath}.${orphanIndex++}`;
1565
+ fs2.renameSync(orphan, mine);
1566
+ claimed.push(mine);
1567
+ } catch {
1568
+ }
1468
1569
  }
1570
+ if (claimed.length === 0)
1571
+ return void 0;
1572
+ const entries = [];
1573
+ let unreadable = 0;
1574
+ for (const file of claimed) {
1575
+ const read = readEntries(file);
1576
+ entries.push(...read.entries);
1577
+ unreadable += read.unreadable;
1578
+ }
1579
+ entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1580
+ let released = false;
1581
+ return {
1582
+ entries,
1583
+ unreadable,
1584
+ release(remainder) {
1585
+ if (released)
1586
+ return;
1587
+ released = true;
1588
+ if (remainder.length > 0) {
1589
+ try {
1590
+ fs2.mkdirSync(path3.dirname(outboxFilePath), { recursive: true, mode: 448 });
1591
+ fs2.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1592
+ `).join(""), { encoding: "utf8", mode: 384 });
1593
+ if (process.platform !== "win32")
1594
+ fs2.chmodSync(outboxFilePath, 384);
1595
+ } catch {
1596
+ return;
1597
+ }
1598
+ }
1599
+ for (const file of claimed) {
1600
+ try {
1601
+ fs2.unlinkSync(file);
1602
+ } catch {
1603
+ }
1604
+ }
1605
+ }
1606
+ };
1469
1607
  }
1470
- function parseEventLogFlag(argv, index) {
1471
- const peek = argv[index + 1];
1472
- if (peek !== void 0 && !peek.startsWith("-"))
1473
- return { value: peek, consumed: 1 };
1474
- return { value: defaultEventLogPath(), consumed: 0 };
1608
+ function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1609
+ const reasons = {};
1610
+ let oldestQueuedAt;
1611
+ const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1612
+ const fresh = [];
1613
+ for (const entry of entries) {
1614
+ if (entry.queuedAt < cutoff) {
1615
+ reasons.age = (reasons.age ?? 0) + 1;
1616
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1617
+ oldestQueuedAt = entry.queuedAt;
1618
+ } else {
1619
+ fresh.push(entry);
1620
+ }
1621
+ }
1622
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1623
+ if (excess > 0) {
1624
+ reasons.count = excess;
1625
+ const first = fresh[0]?.queuedAt;
1626
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1627
+ oldestQueuedAt = first;
1628
+ }
1629
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1630
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1631
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1475
1632
  }
1476
- function appendEventLog(logFilePath, entry) {
1633
+ function listClaimFiles(outboxFilePath) {
1634
+ const dir = path3.dirname(outboxFilePath);
1635
+ const prefix = `${path3.basename(outboxFilePath)}.`;
1477
1636
  try {
1478
- rotateIfLarge(logFilePath);
1479
- const dir = path2.dirname(logFilePath);
1480
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1481
- const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
1482
- fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
1483
- `, { encoding: "utf8", mode: 384 });
1484
- if (process.platform !== "win32")
1485
- fs.chmodSync(logFilePath, 384);
1637
+ return fs2.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path3.join(dir, name)).sort();
1486
1638
  } catch {
1639
+ return [];
1487
1640
  }
1488
1641
  }
1489
- function rotateIfLarge(logFilePath) {
1642
+ function readEntries(file) {
1643
+ let raw;
1490
1644
  try {
1491
- if (fs.statSync(logFilePath).size < MAX_BYTES)
1492
- return;
1493
- fs.renameSync(logFilePath, `${logFilePath}.1`);
1645
+ raw = fs2.readFileSync(file, "utf8");
1494
1646
  } catch {
1647
+ return { entries: [], unreadable: 0 };
1495
1648
  }
1496
- }
1497
- }
1498
- });
1499
-
1500
- // ../packages/tool-kit/out/http.js
1501
- var require_http = __commonJS({
1502
- "../packages/tool-kit/out/http.js"(exports) {
1503
- "use strict";
1504
- Object.defineProperty(exports, "__esModule", { value: true });
1505
- exports.AscendaApiError = void 0;
1506
- exports.createPairingSession = createPairingSession;
1507
- exports.getPairingStatus = getPairingStatus;
1508
- exports.startStudyJoin = startStudyJoin;
1509
- exports.getStudyJoinStatus = getStudyJoinStatus;
1510
- exports.readInitiatives = readInitiatives;
1511
- exports.readStudyNotices = readStudyNotices;
1512
- exports.setStudyObjection = setStudyObjection;
1513
- exports.markStudyNoticeShown = markStudyNoticeShown;
1514
- exports.renewToolToken = renewToolToken;
1515
- exports.isRetryableStatus = isRetryableStatus;
1516
- exports.postToolEvent = postToolEvent;
1517
- exports.postToolEventsBatch = postToolEventsBatch;
1518
- exports.parseIngestResponse = parseIngestResponse;
1519
- var tool_contract_1 = require_out();
1520
- var AscendaApiError = class extends Error {
1521
- status;
1522
- errorCode;
1523
- constructor(status, errorCode, body) {
1524
- super(body ?? `Ascenda API error ${status}`);
1525
- this.status = status;
1526
- this.errorCode = errorCode;
1527
- this.name = "AscendaApiError";
1528
- }
1529
- };
1530
- exports.AscendaApiError = AscendaApiError;
1531
- async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
1532
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1533
- method: "POST",
1534
- headers: { "Content-Type": "application/json" },
1535
- body: JSON.stringify({ toolInstallationId, toolType, displayName })
1536
- });
1537
- if (!response.ok)
1538
- throw new AscendaApiError(response.status, void 0, await response.text());
1539
- return await response.json();
1540
- }
1541
- async function getPairingStatus(apiBaseUrl, pairingSessionId) {
1542
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1543
- method: "GET",
1544
- headers: { Accept: "application/json" }
1545
- });
1546
- if (!response.ok)
1547
- throw new AscendaApiError(response.status, void 0, await response.text());
1548
- return await response.json();
1549
- }
1550
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1551
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1552
- method: "POST",
1553
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1554
- body: JSON.stringify({ joinCode, mode })
1555
- });
1556
- if (!response.ok)
1557
- throw await apiError(response);
1558
- return await response.json();
1559
- }
1560
- async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1561
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1562
- method: "GET",
1563
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1564
- });
1565
- if (!response.ok)
1566
- throw await apiError(response);
1567
- return await response.json();
1568
- }
1569
- async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1570
- let response;
1571
- try {
1572
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1573
- method: "GET",
1574
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1575
- signal
1576
- });
1577
- } catch (error) {
1578
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1579
- }
1580
- if (response.status === 401)
1581
- return { kind: "rejected", httpStatus: 401 };
1582
- if (!response.ok)
1583
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1584
- let body;
1585
- try {
1586
- body = await response.json();
1587
- } catch {
1588
- return { kind: "failed", reason: "the reply was not readable" };
1589
- }
1590
- if (!Array.isArray(body))
1591
- return { kind: "failed", reason: "the reply was not a list" };
1592
- return { kind: "ok", initiatives: body };
1593
- }
1594
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1595
- let response;
1596
- try {
1597
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1598
- method: "GET",
1599
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1600
- signal
1601
- });
1602
- } catch (error) {
1603
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1604
- }
1605
- if (response.status === 404)
1606
- return { kind: "absent" };
1607
- if (response.status === 401)
1608
- return { kind: "rejected", httpStatus: 401 };
1609
- if (!response.ok)
1610
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1611
- let body;
1612
- try {
1613
- body = await response.json();
1614
- } catch {
1615
- return { kind: "absent" };
1616
- }
1617
- if (!Array.isArray(body))
1618
- return { kind: "absent" };
1619
- return { kind: "ok", notices: body };
1620
- }
1621
- async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1622
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1623
- method: objected ? "POST" : "DELETE",
1624
- headers: { Authorization: `Bearer ${eventWriteToken}` }
1625
- });
1626
- if (!response.ok)
1627
- throw await apiError(response);
1628
- }
1629
- async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1630
- try {
1631
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1632
- method: "POST",
1633
- headers: { Authorization: `Bearer ${eventWriteToken}` },
1634
- signal
1635
- });
1636
- return response.ok;
1637
- } catch {
1638
- return false;
1639
- }
1640
- }
1641
- async function apiError(response) {
1642
- const body = await response.text();
1643
- let errorCode;
1644
- try {
1645
- const parsed = JSON.parse(body);
1646
- errorCode = parsed.code ?? parsed.error;
1647
- } catch {
1648
- errorCode = void 0;
1649
- }
1650
- return new AscendaApiError(response.status, errorCode, body);
1651
- }
1652
- async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1653
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1654
- method: "POST",
1655
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1656
- signal
1657
- });
1658
- if (response.status === 401)
1659
- return null;
1660
- if (!response.ok)
1661
- throw new AscendaApiError(response.status, void 0, await response.text());
1662
- return await response.json();
1663
- }
1664
- function isDeliveredStatus(value) {
1665
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1666
- }
1667
- function readSuccessBody(body) {
1668
- let parsed;
1669
- try {
1670
- parsed = JSON.parse(body);
1671
- } catch {
1672
- return { duplicates: 0 };
1673
- }
1674
- if (!parsed || typeof parsed !== "object")
1675
- return { duplicates: 0 };
1676
- const single = parsed.status;
1677
- if (isDeliveredStatus(single))
1678
- return { duplicates: single === "duplicate" ? 1 : 0 };
1679
- const raw = parsed.results;
1680
- if (!Array.isArray(raw))
1681
- return { duplicates: 0 };
1682
- const results = [];
1683
- for (const item of raw) {
1684
- if (!item || typeof item !== "object")
1685
- continue;
1686
- const { index, status, reason } = item;
1687
- if (typeof index !== "number" || typeof status !== "string")
1649
+ const entries = [];
1650
+ let unreadable = 0;
1651
+ for (const line of raw.split("\n")) {
1652
+ if (!line.trim())
1688
1653
  continue;
1689
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1690
- }
1691
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1692
- }
1693
- function isRetryableStatus(status) {
1694
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1695
- }
1696
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1697
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1698
- }
1699
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1700
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1701
- }
1702
- async function sendIngest(url, eventWriteToken, body, signal) {
1703
- try {
1704
- const response = await fetch(url, {
1705
- method: "POST",
1706
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1707
- body,
1708
- signal
1709
- });
1710
- return parseIngestResponse(response);
1711
- } catch (error) {
1712
- return {
1713
- result: "transport_error",
1714
- detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1715
- };
1716
- }
1717
- }
1718
- async function parseIngestResponse(response) {
1719
- if (response.ok) {
1720
- const outcome = { result: "accepted", httpStatus: response.status };
1721
- let read = { duplicates: 0 };
1722
1654
  try {
1723
- read = readSuccessBody(await response.text());
1655
+ const parsed = JSON.parse(line);
1656
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1657
+ unreadable += 1;
1658
+ continue;
1659
+ }
1660
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1724
1661
  } catch {
1725
- read = { duplicates: 0 };
1662
+ unreadable += 1;
1726
1663
  }
1727
- return {
1728
- ...outcome,
1729
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1730
- ...read.results !== void 0 ? { results: read.results } : {}
1731
- };
1732
- }
1733
- const body = await response.text();
1734
- let errorCode;
1735
- try {
1736
- errorCode = JSON.parse(body).error;
1737
- } catch {
1738
- errorCode = void 0;
1739
1664
  }
1740
- const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1741
- if (response.status === 401)
1742
- return { ...base, result: "auth_failed" };
1743
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1744
- return { ...base, result: "consent_missing" };
1745
- if (response.status === 400 || response.status === 422)
1746
- return { ...base, result: "validation_failed" };
1747
- return { ...base, result: "transport_error" };
1665
+ return { entries, unreadable };
1748
1666
  }
1749
1667
  }
1750
1668
  });
1751
1669
 
1752
- // ../packages/tool-kit/out/stateStore.js
1753
- var require_stateStore = __commonJS({
1754
- "../packages/tool-kit/out/stateStore.js"(exports) {
1670
+ // ../packages/tool-kit/out/backgroundDelivery.js
1671
+ var require_backgroundDelivery = __commonJS({
1672
+ "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
1755
1673
  "use strict";
1756
1674
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1757
1675
  if (k2 === void 0) k2 = k;
@@ -1791,124 +1709,270 @@ var require_stateStore = __commonJS({
1791
1709
  };
1792
1710
  }();
1793
1711
  Object.defineProperty(exports, "__esModule", { value: true });
1794
- exports.defaultStateFilePath = defaultStateFilePath;
1795
- exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
1796
- exports.unresolvedStateFilePath = unresolvedStateFilePath;
1797
- exports.readCollectorState = readCollectorState;
1798
- exports.recordSendOutcome = recordSendOutcome;
1799
- exports.recordOutboxDiscard = recordOutboxDiscard;
1800
- exports.shouldAnnounceFailure = shouldAnnounceFailure;
1801
- exports.markFailureNotified = markFailureNotified;
1802
- var fs = __importStar(__require("fs"));
1803
- var path2 = __importStar(__require("path"));
1804
- var tokenStore_1 = require_tokenStore();
1805
- function defaultStateFilePath(toolInstallationId) {
1806
- const dir = process.env.ASCENDA_STATE_DIR?.trim();
1807
- const base = dir ? dir : path2.join((0, tokenStore_1.ascendaHome)(), "state");
1808
- return path2.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1712
+ exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
1713
+ exports.hookDeliveryInline = hookDeliveryInline;
1714
+ exports.flushLockPath = flushLockPath;
1715
+ exports.startBackgroundFlush = startBackgroundFlush;
1716
+ exports.runOutboxFlush = runOutboxFlush;
1717
+ var fs2 = __importStar(__require("fs"));
1718
+ var child_process_1 = __require("child_process");
1719
+ var outbox_1 = require_outbox();
1720
+ exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
1721
+ exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
1722
+ exports.FLUSH_LOCK_FRESH_MS = 2e4;
1723
+ var FLUSH_MAX_PASSES = 20;
1724
+ var FLUSH_MAX_RUN_MS = 6e4;
1725
+ function hookDeliveryInline(env = process.env) {
1726
+ return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
1727
+ }
1728
+ function flushLockPath(outboxFilePath) {
1729
+ return `${outboxFilePath}.flushing`;
1730
+ }
1731
+ function lockIsFresh(lockPath, now) {
1732
+ try {
1733
+ return now - fs2.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1734
+ } catch {
1735
+ return false;
1736
+ }
1809
1737
  }
1810
- function unresolvedToolInstallationId(toolType) {
1811
- return `${toolType}:unresolved`;
1738
+ function touchLock(lockPath) {
1739
+ try {
1740
+ fs2.writeFileSync(lockPath, `${process.pid}
1741
+ `, { encoding: "utf8", mode: 384 });
1742
+ } catch {
1743
+ }
1812
1744
  }
1813
- function unresolvedStateFilePath(toolType) {
1814
- return defaultStateFilePath(unresolvedToolInstallationId(toolType));
1745
+ function removeLock(lockPath) {
1746
+ try {
1747
+ fs2.unlinkSync(lockPath);
1748
+ } catch {
1749
+ }
1815
1750
  }
1816
- function readCollectorState(stateFilePath) {
1751
+ function outboxHasEntries(outboxFilePath) {
1817
1752
  try {
1818
- if (!fs.existsSync(stateFilePath))
1819
- return void 0;
1820
- const raw = fs.readFileSync(stateFilePath, "utf8").trim();
1821
- if (!raw)
1822
- return void 0;
1823
- const parsed = JSON.parse(raw);
1824
- if (!parsed || typeof parsed !== "object")
1825
- return void 0;
1826
- return parsed;
1753
+ return fs2.statSync(outboxFilePath).size > 0;
1827
1754
  } catch {
1828
- return void 0;
1755
+ return false;
1829
1756
  }
1830
1757
  }
1831
- function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1832
- const now = (/* @__PURE__ */ new Date()).toISOString();
1833
- const previous = readCollectorState(stateFilePath);
1834
- const accepted = outcome === "accepted";
1835
- const next = {
1836
- toolInstallationId,
1837
- lastAttemptAt: now,
1838
- lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1839
- lastOutcome: outcome,
1840
- consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1841
- ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1842
- ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1843
- ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1844
- // A success closes the episode; a failure either opens one or continues
1845
- // the one already open. Carrying `notifiedFailingSince` across a
1846
- // continuing episode is what keeps the notice to once per outage.
1847
- ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1848
- ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1849
- // Cumulative by design: a send outcome, success included, never erases
1850
- // the record of what the outbox had to throw away.
1851
- ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1852
- };
1853
- writeStateFile(stateFilePath, next);
1854
- return next;
1758
+ function startBackgroundFlush(options) {
1759
+ const lockPath = flushLockPath(options.outboxFilePath);
1760
+ const now = options.now ?? Date.now();
1761
+ if (lockIsFresh(lockPath, now))
1762
+ return false;
1763
+ const script = options.script ?? process.argv[1];
1764
+ if (!script)
1765
+ return false;
1766
+ try {
1767
+ touchLock(lockPath);
1768
+ const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
1769
+ detached: true,
1770
+ stdio: "ignore",
1771
+ windowsHide: true,
1772
+ env: process.env
1773
+ });
1774
+ child.on("error", () => removeLock(lockPath));
1775
+ child.unref();
1776
+ return true;
1777
+ } catch {
1778
+ removeLock(lockPath);
1779
+ return false;
1780
+ }
1855
1781
  }
1856
- function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1857
- const now = (/* @__PURE__ */ new Date()).toISOString();
1858
- const previous = readCollectorState(stateFilePath);
1859
- const next = {
1860
- ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1861
- toolInstallationId,
1862
- lastOutcome: "outbox_discarded",
1863
- outboxDiscarded: {
1864
- total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1865
- lastAt: now,
1866
- lastCount: discard.count,
1867
- lastReasons: discard.reasons,
1868
- ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1782
+ async function runOutboxFlush(sender, now = Date.now) {
1783
+ const outboxFilePath = sender.outboxFilePath();
1784
+ const lockPath = flushLockPath(outboxFilePath);
1785
+ const started = now();
1786
+ let last;
1787
+ let passes = 0;
1788
+ const drain = async () => {
1789
+ while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
1790
+ passes += 1;
1791
+ touchLock(lockPath);
1792
+ last = await sender.flushOutbox();
1793
+ if (!last || last.found === 0 || last.halted || !last.sendEnabled)
1794
+ return;
1795
+ if (last.delivered === 0 && last.discarded === 0)
1796
+ return;
1869
1797
  }
1870
1798
  };
1871
- writeStateFile(stateFilePath, next);
1872
- return next;
1799
+ try {
1800
+ await drain();
1801
+ removeLock(lockPath);
1802
+ if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
1803
+ touchLock(lockPath);
1804
+ await drain();
1805
+ removeLock(lockPath);
1806
+ }
1807
+ } catch {
1808
+ removeLock(lockPath);
1809
+ }
1810
+ return last;
1873
1811
  }
1874
- function shouldAnnounceFailure(state) {
1875
- if (!state || state.consecutiveFailures === 0 || !state.failingSince)
1812
+ }
1813
+ });
1814
+
1815
+ // ../packages/agent-events/out/index.js
1816
+ var require_out2 = __commonJS({
1817
+ "../packages/agent-events/out/index.js"(exports) {
1818
+ "use strict";
1819
+ Object.defineProperty(exports, "__esModule", { value: true });
1820
+ exports.KNOWN_AGENTS = exports.WAIT_REASONS = exports.VCS_ACTIONS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1821
+ exports.isAgentEventV0 = isAgentEventV0;
1822
+ exports.parseEventLogLine = parseEventLogLine;
1823
+ exports.normaliseKind = normaliseKind;
1824
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1825
+ exports.AGENT_EVENT_KINDS = [
1826
+ "session.started",
1827
+ "session.ended",
1828
+ "prompt.submitted",
1829
+ "tool.started",
1830
+ "tool.completed",
1831
+ "tool.failed",
1832
+ "turn.completed",
1833
+ "agent.waiting",
1834
+ "permission.requested",
1835
+ "permission.denied",
1836
+ "context.compacted",
1837
+ "subagent.started",
1838
+ "subagent.stopped",
1839
+ "pull_request.opened",
1840
+ "pull_request.closed",
1841
+ "pull_request.merged",
1842
+ "other"
1843
+ ];
1844
+ exports.VCS_ACTIONS = ["commit", "push", "pr_created", "pr_merged"];
1845
+ exports.WAIT_REASONS = ["permission", "idle", "input", "other"];
1846
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1847
+ function isAgentEventV0(value) {
1848
+ if (!value || typeof value !== "object")
1876
1849
  return false;
1877
- return state.notifiedFailingSince !== state.failingSince;
1878
- }
1879
- function markFailureNotified(stateFilePath, state) {
1880
- if (!state.failingSince)
1881
- return;
1882
- writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
1850
+ const e = value;
1851
+ return e.schema === exports.AGENT_EVENT_SCHEMA && typeof e.id === "string" && e.id.length > 0 && typeof e.time === "string" && !Number.isNaN(Date.parse(e.time)) && typeof e.agent === "string" && e.agent.length > 0 && typeof e.kind === "string";
1883
1852
  }
1884
- function writeStateFile(stateFilePath, state) {
1885
- const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1853
+ function parseEventLogLine(line) {
1854
+ if (!line.trim())
1855
+ return void 0;
1886
1856
  try {
1887
- const dir = path2.dirname(stateFilePath);
1888
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1889
- fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1890
- `, { encoding: "utf8", mode: 384 });
1891
- fs.renameSync(temporaryPath, stateFilePath);
1892
- if (process.platform !== "win32")
1893
- fs.chmodSync(stateFilePath, 384);
1857
+ const parsed = JSON.parse(line);
1858
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1894
1859
  } catch {
1895
- try {
1896
- if (fs.existsSync(temporaryPath))
1897
- fs.unlinkSync(temporaryPath);
1898
- } catch {
1899
- }
1860
+ return void 0;
1900
1861
  }
1901
1862
  }
1902
- function truncate(value) {
1903
- const collapsed = value.replace(/\s+/g, " ").trim();
1904
- return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
1863
+ function normaliseKind(kind) {
1864
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1905
1865
  }
1906
1866
  }
1907
1867
  });
1908
1868
 
1909
- // ../packages/tool-kit/out/outbox.js
1910
- var require_outbox = __commonJS({
1911
- "../packages/tool-kit/out/outbox.js"(exports) {
1869
+ // ../packages/tool-kit/out/agentEvent.js
1870
+ var require_agentEvent = __commonJS({
1871
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1872
+ "use strict";
1873
+ Object.defineProperty(exports, "__esModule", { value: true });
1874
+ exports.toAgentEvent = toAgentEvent;
1875
+ var agent_events_1 = require_out2();
1876
+ var KIND_BY_TYPE = {
1877
+ create_focus_session: "session.started",
1878
+ recovery_offline_period: "session.ended",
1879
+ ai_prompt_submitted: "prompt.submitted",
1880
+ ai_tool_call_started: "tool.started",
1881
+ ai_tool_call_completed: "tool.completed",
1882
+ ai_file_write: "tool.completed",
1883
+ ai_file_edit: "tool.completed",
1884
+ editor_verification_activity: "tool.completed",
1885
+ ai_tool_call_failed: "tool.failed",
1886
+ compile_error: "tool.failed",
1887
+ tool_failure: "tool.failed",
1888
+ ai_turn_completed: "turn.completed",
1889
+ supervision_interruption: "agent.waiting",
1890
+ permission_requested: "permission.requested",
1891
+ permission_denied: "permission.denied",
1892
+ context_compression_manual: "context.compacted",
1893
+ context_compression_auto: "context.compacted",
1894
+ subagent_started: "subagent.started",
1895
+ subagent_stopped: "subagent.stopped",
1896
+ pull_request_opened: "pull_request.opened",
1897
+ pull_request_closed: "pull_request.closed",
1898
+ pull_request_merged: "pull_request.merged"
1899
+ };
1900
+ function agentOf(payload) {
1901
+ const host = stringField(payload.metadata?.host);
1902
+ if (host)
1903
+ return host;
1904
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1905
+ }
1906
+ function vcsActionOf(metadata) {
1907
+ const milestone = stringField(metadata.milestoneKind);
1908
+ if (milestone === "pr_opened")
1909
+ return "pr_created";
1910
+ if (milestone === "pr_merged")
1911
+ return "pr_merged";
1912
+ const git = stringField(metadata.gitAction);
1913
+ return git === "commit" || git === "push" ? git : void 0;
1914
+ }
1915
+ function waitReasonOf(metadata) {
1916
+ switch (stringField(metadata.interruptionKind)) {
1917
+ case "permission_request":
1918
+ return "permission";
1919
+ case "input_request":
1920
+ return "input";
1921
+ case "idle_prompt":
1922
+ return "idle";
1923
+ case void 0:
1924
+ return void 0;
1925
+ default:
1926
+ return "other";
1927
+ }
1928
+ }
1929
+ function stringField(value) {
1930
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1931
+ }
1932
+ function toAgentEvent(payload) {
1933
+ const metadata = payload.metadata ?? {};
1934
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1935
+ const tool = kind.startsWith("tool.") || kind.startsWith("permission.") ? stringField(metadata.toolName) : void 0;
1936
+ const outcome = stringField(metadata.outcome);
1937
+ const vcsAction = kind === "tool.completed" ? vcsActionOf(metadata) : void 0;
1938
+ const reason = kind === "agent.waiting" ? waitReasonOf(metadata) : void 0;
1939
+ const model = kind === "session.started" ? stringField(metadata.modelId) : void 0;
1940
+ return {
1941
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1942
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1943
+ time: payload.occurredAt,
1944
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1945
+ // writes anyway; without it the event in memory and the one on disk differ.
1946
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1947
+ agent: agentOf(payload),
1948
+ kind,
1949
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1950
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1951
+ ...tool ? { tool } : {},
1952
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1953
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1954
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1955
+ ...stringField(metadata.repoKey) ? { repoKey: metadata.repoKey } : {},
1956
+ ...stringField(metadata.branchKey) ? { branchKey: metadata.branchKey } : {},
1957
+ ...stringField(metadata.autonomyMode) ? { permissionMode: metadata.autonomyMode } : {},
1958
+ ...stringField(metadata.headRepoKey) ? { headRepoKey: metadata.headRepoKey } : {},
1959
+ ...stringField(metadata.prCreatedAt) ? { prCreatedAt: metadata.prCreatedAt } : {},
1960
+ ...stringField(metadata.prClosedAt) ? { prClosedAt: metadata.prClosedAt } : {},
1961
+ ...stringField(metadata.prMergedAt) ? { prMergedAt: metadata.prMergedAt } : {},
1962
+ ...stringField(metadata.promptId) ? { promptId: metadata.promptId } : {},
1963
+ ...vcsAction ? { vcsAction } : {},
1964
+ ...reason ? { reason } : {},
1965
+ ...model ? { model } : {},
1966
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1967
+ sourceType: payload.eventType
1968
+ };
1969
+ }
1970
+ }
1971
+ });
1972
+
1973
+ // ../packages/tool-kit/out/credentials.js
1974
+ var require_credentials = __commonJS({
1975
+ "../packages/tool-kit/out/credentials.js"(exports) {
1912
1976
  "use strict";
1913
1977
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1914
1978
  if (k2 === void 0) k2 = k;
@@ -1948,182 +2012,482 @@ var require_outbox = __commonJS({
1948
2012
  };
1949
2013
  }();
1950
2014
  Object.defineProperty(exports, "__esModule", { value: true });
1951
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1952
- exports.outboxDrainEnabled = outboxDrainEnabled;
1953
- exports.defaultOutboxFilePath = defaultOutboxFilePath;
1954
- exports.appendToOutbox = appendToOutbox;
1955
- exports.readOutboxSummary = readOutboxSummary;
1956
- exports.claimOutbox = claimOutbox;
1957
- exports.enforceOutboxBounds = enforceOutboxBounds;
1958
- var fs = __importStar(__require("fs"));
1959
- var path2 = __importStar(__require("path"));
1960
- var stateStore_1 = require_stateStore();
2015
+ exports.credentialsFilePath = credentialsFilePath;
2016
+ exports.readMachineCredentials = readMachineCredentials;
2017
+ exports.writeMachineCredentials = writeMachineCredentials;
2018
+ exports.writeTopLevelCredentials = writeTopLevelCredentials;
2019
+ exports.writeRepoKeysSetting = writeRepoKeysSetting;
2020
+ exports.writeEventLogSetting = writeEventLogSetting;
2021
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2022
+ exports.readHostCredentials = readHostCredentials;
2023
+ exports.writeHostCredentials = writeHostCredentials;
2024
+ exports.removeHostCredentials = removeHostCredentials;
2025
+ var fs2 = __importStar(__require("fs"));
2026
+ var path3 = __importStar(__require("path"));
1961
2027
  var tokenStore_1 = require_tokenStore();
1962
- exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1963
- exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1964
- exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1965
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1966
- var ORPHANED_CLAIM_AGE_MS = 6e4;
1967
- var CLAIM_SUFFIX = ".draining";
1968
- function outboxDrainEnabled(env = process.env) {
1969
- const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1970
- if (value === void 0 || value === "")
1971
- return true;
1972
- return !(value === "0" || value === "false" || value === "no" || value === "off");
1973
- }
1974
- function defaultOutboxFilePath(toolInstallationId) {
1975
- const dir = path2.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1976
- return path2.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
2028
+ function credentialsFilePath() {
2029
+ return path3.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1977
2030
  }
1978
- function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
2031
+ function readMachineCredentials() {
1979
2032
  try {
1980
- const dir = path2.dirname(outboxFilePath);
1981
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1982
- const entry = { queuedAt: now.toISOString(), payload };
1983
- fs.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1984
- `, { encoding: "utf8", mode: 384 });
1985
- if (process.platform !== "win32")
1986
- fs.chmodSync(outboxFilePath, 384);
1987
- return true;
2033
+ const raw = fs2.readFileSync(credentialsFilePath(), "utf8").trim();
2034
+ if (!raw)
2035
+ return void 0;
2036
+ const parsed = JSON.parse(raw);
2037
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2038
+ return void 0;
2039
+ return parsed;
1988
2040
  } catch {
1989
- return false;
2041
+ return void 0;
1990
2042
  }
1991
2043
  }
1992
- function readOutboxSummary(outboxFilePath) {
1993
- const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs.existsSync(file));
1994
- if (files.length === 0)
2044
+ function writeMachineCredentials(credentials) {
2045
+ const file = credentialsFilePath();
2046
+ fs2.mkdirSync(path3.dirname(file), { recursive: true, mode: 448 });
2047
+ fs2.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2048
+ `, { encoding: "utf8", mode: 384 });
2049
+ if (process.platform !== "win32") {
2050
+ fs2.chmodSync(path3.dirname(file), 448);
2051
+ fs2.chmodSync(file, 384);
2052
+ }
2053
+ }
2054
+ function writeTopLevelCredentials(credentials) {
2055
+ const existing = readMachineCredentials();
2056
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
2057
+ const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
2058
+ writeMachineCredentials({
2059
+ ...credentials,
2060
+ ...eventLogPath ? { eventLogPath } : {},
2061
+ ...repoKeys === false ? { repoKeys } : {},
2062
+ ...existing?.tools ? { tools: existing.tools } : {}
2063
+ });
2064
+ }
2065
+ function writeRepoKeysSetting(on) {
2066
+ const existing = readMachineCredentials() ?? {};
2067
+ const { repoKeys: _dropped, ...rest } = existing;
2068
+ writeMachineCredentials(on ? rest : { ...rest, repoKeys: false });
2069
+ }
2070
+ function writeEventLogSetting(value) {
2071
+ const existing = readMachineCredentials() ?? {};
2072
+ writeMachineCredentials({ ...existing, eventLogPath: value });
2073
+ }
2074
+ function isLocalOnlyHostInstall(host, hasToken) {
2075
+ const credentials = readHostCredentials(host);
2076
+ if (!credentials?.localOnly)
2077
+ return false;
2078
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2079
+ return false;
2080
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2081
+ }
2082
+ function readHostCredentials(host) {
2083
+ const entry = readMachineCredentials()?.tools?.[host];
2084
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
1995
2085
  return void 0;
1996
- let depth = 0;
1997
- let unreadableLines = 0;
1998
- let oldestQueuedAt;
1999
- for (const file of files) {
2000
- const { entries, unreadable } = readEntries(file);
2001
- depth += entries.length;
2002
- unreadableLines += unreadable;
2003
- for (const entry of entries) {
2004
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
2005
- oldestQueuedAt = entry.queuedAt;
2086
+ return entry;
2087
+ }
2088
+ function writeHostCredentials(host, credentials) {
2089
+ const existing = readMachineCredentials() ?? {};
2090
+ writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2091
+ }
2092
+ function removeHostCredentials(host) {
2093
+ const existing = readMachineCredentials();
2094
+ if (!existing?.tools || !(host in existing.tools))
2095
+ return;
2096
+ const tools = { ...existing.tools };
2097
+ delete tools[host];
2098
+ const next = { ...existing };
2099
+ if (Object.keys(tools).length)
2100
+ next.tools = tools;
2101
+ else
2102
+ delete next.tools;
2103
+ writeMachineCredentials(next);
2104
+ }
2105
+ }
2106
+ });
2107
+
2108
+ // ../packages/tool-kit/out/eventLog.js
2109
+ var require_eventLog = __commonJS({
2110
+ "../packages/tool-kit/out/eventLog.js"(exports) {
2111
+ "use strict";
2112
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2113
+ if (k2 === void 0) k2 = k;
2114
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2115
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2116
+ desc = { enumerable: true, get: function() {
2117
+ return m[k];
2118
+ } };
2119
+ }
2120
+ Object.defineProperty(o, k2, desc);
2121
+ } : function(o, m, k, k2) {
2122
+ if (k2 === void 0) k2 = k;
2123
+ o[k2] = m[k];
2124
+ });
2125
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2126
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2127
+ } : function(o, v) {
2128
+ o["default"] = v;
2129
+ });
2130
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2131
+ var ownKeys = function(o) {
2132
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2133
+ var ar = [];
2134
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2135
+ return ar;
2136
+ };
2137
+ return ownKeys(o);
2138
+ };
2139
+ return function(mod) {
2140
+ if (mod && mod.__esModule) return mod;
2141
+ var result = {};
2142
+ if (mod != null) {
2143
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2006
2144
  }
2145
+ __setModuleDefault(result, mod);
2146
+ return result;
2147
+ };
2148
+ }();
2149
+ Object.defineProperty(exports, "__esModule", { value: true });
2150
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
2151
+ exports.expandUserPath = expandUserPath;
2152
+ exports.defaultEventLogPath = defaultEventLogPath;
2153
+ exports.resolveEventLog = resolveEventLog;
2154
+ exports.resolveEventLogPath = resolveEventLogPath;
2155
+ exports.describeEventLog = describeEventLog;
2156
+ exports.parseEventLogFlag = parseEventLogFlag;
2157
+ exports.appendEventLog = appendEventLog;
2158
+ var fs2 = __importStar(__require("fs"));
2159
+ var os2 = __importStar(__require("os"));
2160
+ var path3 = __importStar(__require("path"));
2161
+ var agentEvent_1 = require_agentEvent();
2162
+ var credentials_1 = require_credentials();
2163
+ var tokenStore_1 = require_tokenStore();
2164
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
2165
+ exports.EVENT_LOG_OFF = "off";
2166
+ var MAX_BYTES = 5 * 1024 * 1024;
2167
+ function expandUserPath(configured) {
2168
+ const value = configured?.trim();
2169
+ if (!value)
2170
+ return void 0;
2171
+ if (value === "~")
2172
+ return os2.homedir();
2173
+ if (value.startsWith("~/"))
2174
+ return path3.join(os2.homedir(), value.slice(2));
2175
+ return path3.resolve(value);
2176
+ }
2177
+ function defaultEventLogPath() {
2178
+ return path3.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
2179
+ }
2180
+ function resolveEventLog(options = {}) {
2181
+ for (const [source, raw] of [
2182
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
2183
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
2184
+ ]) {
2185
+ const value = raw?.trim();
2186
+ if (!value)
2187
+ continue;
2188
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
2189
+ return { path: void 0, source: "disabled" };
2190
+ return { path: expandUserPath(value), source };
2007
2191
  }
2008
- return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
2192
+ if (options.localOnly)
2193
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
2194
+ return { path: void 0, source: "off" };
2009
2195
  }
2010
- function claimOutbox(outboxFilePath, now = Date.now()) {
2011
- const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
2012
- const claimed = [];
2196
+ function resolveEventLogPath(options = {}) {
2197
+ return resolveEventLog(options).path;
2198
+ }
2199
+ function describeEventLog(setting, command) {
2200
+ switch (setting.source) {
2201
+ case "env":
2202
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
2203
+ case "credentials":
2204
+ return `${setting.path} (set by ${command} --event-log)`;
2205
+ case "unpaired-default":
2206
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
2207
+ case "disabled":
2208
+ return `off (turned off; ${command} --event-log to turn it on)`;
2209
+ case "off":
2210
+ return `off (${command} --event-log to keep a local copy of every event)`;
2211
+ }
2212
+ }
2213
+ function parseEventLogFlag(argv, index) {
2214
+ const peek = argv[index + 1];
2215
+ if (peek !== void 0 && !peek.startsWith("-"))
2216
+ return { value: peek, consumed: 1 };
2217
+ return { value: defaultEventLogPath(), consumed: 0 };
2218
+ }
2219
+ function appendEventLog(logFilePath, entry) {
2013
2220
  try {
2014
- fs.renameSync(outboxFilePath, claimPath);
2015
- claimed.push(claimPath);
2221
+ rotateIfLarge(logFilePath);
2222
+ const dir = path3.dirname(logFilePath);
2223
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
2224
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
2225
+ fs2.appendFileSync(logFilePath, `${JSON.stringify(line)}
2226
+ `, { encoding: "utf8", mode: 384 });
2227
+ if (process.platform !== "win32")
2228
+ fs2.chmodSync(logFilePath, 384);
2016
2229
  } catch {
2017
2230
  }
2018
- let orphanIndex = 0;
2019
- for (const orphan of listClaimFiles(outboxFilePath)) {
2020
- if (claimed.includes(orphan))
2021
- continue;
2022
- try {
2023
- if (now - fs.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
2024
- continue;
2025
- const mine = `${claimPath}.${orphanIndex++}`;
2026
- fs.renameSync(orphan, mine);
2027
- claimed.push(mine);
2028
- } catch {
2029
- }
2231
+ }
2232
+ function rotateIfLarge(logFilePath) {
2233
+ try {
2234
+ if (fs2.statSync(logFilePath).size < MAX_BYTES)
2235
+ return;
2236
+ fs2.renameSync(logFilePath, `${logFilePath}.1`);
2237
+ } catch {
2030
2238
  }
2031
- if (claimed.length === 0)
2032
- return void 0;
2033
- const entries = [];
2034
- let unreadable = 0;
2035
- for (const file of claimed) {
2036
- const read = readEntries(file);
2037
- entries.push(...read.entries);
2038
- unreadable += read.unreadable;
2239
+ }
2240
+ }
2241
+ });
2242
+
2243
+ // ../packages/tool-kit/out/http.js
2244
+ var require_http = __commonJS({
2245
+ "../packages/tool-kit/out/http.js"(exports) {
2246
+ "use strict";
2247
+ Object.defineProperty(exports, "__esModule", { value: true });
2248
+ exports.AscendaApiError = void 0;
2249
+ exports.createPairingSession = createPairingSession;
2250
+ exports.getPairingStatus = getPairingStatus;
2251
+ exports.startStudyJoin = startStudyJoin;
2252
+ exports.getStudyJoinStatus = getStudyJoinStatus;
2253
+ exports.readInitiatives = readInitiatives;
2254
+ exports.readStudyNotices = readStudyNotices;
2255
+ exports.setStudyObjection = setStudyObjection;
2256
+ exports.markStudyNoticeShown = markStudyNoticeShown;
2257
+ exports.renewToolToken = renewToolToken;
2258
+ exports.isRetryableStatus = isRetryableStatus;
2259
+ exports.postToolEvent = postToolEvent;
2260
+ exports.postToolEventsBatch = postToolEventsBatch;
2261
+ exports.parseIngestResponse = parseIngestResponse;
2262
+ var tool_contract_1 = require_out();
2263
+ var AscendaApiError = class extends Error {
2264
+ status;
2265
+ errorCode;
2266
+ constructor(status, errorCode, body) {
2267
+ super(body ?? `Ascenda API error ${status}`);
2268
+ this.status = status;
2269
+ this.errorCode = errorCode;
2270
+ this.name = "AscendaApiError";
2039
2271
  }
2040
- entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
2041
- let released = false;
2042
- return {
2043
- entries,
2044
- unreadable,
2045
- release(remainder) {
2046
- if (released)
2047
- return;
2048
- released = true;
2049
- if (remainder.length > 0) {
2050
- try {
2051
- fs.mkdirSync(path2.dirname(outboxFilePath), { recursive: true, mode: 448 });
2052
- fs.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
2053
- `).join(""), { encoding: "utf8", mode: 384 });
2054
- if (process.platform !== "win32")
2055
- fs.chmodSync(outboxFilePath, 384);
2056
- } catch {
2057
- return;
2058
- }
2059
- }
2060
- for (const file of claimed) {
2061
- try {
2062
- fs.unlinkSync(file);
2063
- } catch {
2064
- }
2065
- }
2066
- }
2067
- };
2272
+ };
2273
+ exports.AscendaApiError = AscendaApiError;
2274
+ async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
2275
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
2276
+ method: "POST",
2277
+ headers: { "Content-Type": "application/json" },
2278
+ body: JSON.stringify({ toolInstallationId, toolType, displayName })
2279
+ });
2280
+ if (!response.ok)
2281
+ throw new AscendaApiError(response.status, void 0, await response.text());
2282
+ return await response.json();
2068
2283
  }
2069
- function enforceOutboxBounds(entries, bounds, now = Date.now()) {
2070
- const reasons = {};
2071
- let oldestQueuedAt;
2072
- const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
2073
- const fresh = [];
2074
- for (const entry of entries) {
2075
- if (entry.queuedAt < cutoff) {
2076
- reasons.age = (reasons.age ?? 0) + 1;
2077
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
2078
- oldestQueuedAt = entry.queuedAt;
2079
- } else {
2080
- fresh.push(entry);
2081
- }
2284
+ async function getPairingStatus(apiBaseUrl, pairingSessionId) {
2285
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
2286
+ method: "GET",
2287
+ headers: { Accept: "application/json" }
2288
+ });
2289
+ if (!response.ok)
2290
+ throw new AscendaApiError(response.status, void 0, await response.text());
2291
+ return await response.json();
2292
+ }
2293
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
2294
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2295
+ method: "POST",
2296
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2297
+ body: JSON.stringify({ joinCode, mode })
2298
+ });
2299
+ if (!response.ok)
2300
+ throw await apiError(response);
2301
+ return await response.json();
2302
+ }
2303
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
2304
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
2305
+ method: "GET",
2306
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
2307
+ });
2308
+ if (!response.ok)
2309
+ throw await apiError(response);
2310
+ return await response.json();
2311
+ }
2312
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
2313
+ let response;
2314
+ try {
2315
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
2316
+ method: "GET",
2317
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2318
+ signal
2319
+ });
2320
+ } catch (error) {
2321
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2082
2322
  }
2083
- const excess = Math.max(0, fresh.length - bounds.maxEntries);
2084
- if (excess > 0) {
2085
- reasons.count = excess;
2086
- const first = fresh[0]?.queuedAt;
2087
- if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
2088
- oldestQueuedAt = first;
2323
+ if (response.status === 401)
2324
+ return { kind: "rejected", httpStatus: 401 };
2325
+ if (!response.ok)
2326
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2327
+ let body;
2328
+ try {
2329
+ body = await response.json();
2330
+ } catch {
2331
+ return { kind: "failed", reason: "the reply was not readable" };
2089
2332
  }
2090
- const kept = excess > 0 ? fresh.slice(excess) : fresh;
2091
- const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
2092
- return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
2333
+ if (!Array.isArray(body))
2334
+ return { kind: "failed", reason: "the reply was not a list" };
2335
+ return { kind: "ok", initiatives: body };
2093
2336
  }
2094
- function listClaimFiles(outboxFilePath) {
2095
- const dir = path2.dirname(outboxFilePath);
2096
- const prefix = `${path2.basename(outboxFilePath)}.`;
2337
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
2338
+ let response;
2097
2339
  try {
2098
- return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path2.join(dir, name)).sort();
2340
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
2341
+ method: "GET",
2342
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2343
+ signal
2344
+ });
2345
+ } catch (error) {
2346
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2347
+ }
2348
+ if (response.status === 404)
2349
+ return { kind: "absent" };
2350
+ if (response.status === 401)
2351
+ return { kind: "rejected", httpStatus: 401 };
2352
+ if (!response.ok)
2353
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2354
+ let body;
2355
+ try {
2356
+ body = await response.json();
2099
2357
  } catch {
2100
- return [];
2358
+ return { kind: "absent" };
2359
+ }
2360
+ if (!Array.isArray(body))
2361
+ return { kind: "absent" };
2362
+ return { kind: "ok", notices: body };
2363
+ }
2364
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
2365
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
2366
+ method: objected ? "POST" : "DELETE",
2367
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
2368
+ });
2369
+ if (!response.ok)
2370
+ throw await apiError(response);
2371
+ }
2372
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
2373
+ try {
2374
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
2375
+ method: "POST",
2376
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
2377
+ signal
2378
+ });
2379
+ return response.ok;
2380
+ } catch {
2381
+ return false;
2382
+ }
2383
+ }
2384
+ async function apiError(response) {
2385
+ const body = await response.text();
2386
+ let errorCode;
2387
+ try {
2388
+ const parsed = JSON.parse(body);
2389
+ errorCode = parsed.code ?? parsed.error;
2390
+ } catch {
2391
+ errorCode = void 0;
2392
+ }
2393
+ return new AscendaApiError(response.status, errorCode, body);
2394
+ }
2395
+ async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
2396
+ const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
2397
+ method: "POST",
2398
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2399
+ signal
2400
+ });
2401
+ if (response.status === 401)
2402
+ return null;
2403
+ if (!response.ok)
2404
+ throw new AscendaApiError(response.status, void 0, await response.text());
2405
+ return await response.json();
2406
+ }
2407
+ function isDeliveredStatus(value) {
2408
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
2409
+ }
2410
+ function readSuccessBody(body) {
2411
+ let parsed;
2412
+ try {
2413
+ parsed = JSON.parse(body);
2414
+ } catch {
2415
+ return { duplicates: 0 };
2416
+ }
2417
+ if (!parsed || typeof parsed !== "object")
2418
+ return { duplicates: 0 };
2419
+ const single = parsed.status;
2420
+ if (isDeliveredStatus(single))
2421
+ return { duplicates: single === "duplicate" ? 1 : 0 };
2422
+ const raw = parsed.results;
2423
+ if (!Array.isArray(raw))
2424
+ return { duplicates: 0 };
2425
+ const results = [];
2426
+ for (const item of raw) {
2427
+ if (!item || typeof item !== "object")
2428
+ continue;
2429
+ const { index, status, reason } = item;
2430
+ if (typeof index !== "number" || typeof status !== "string")
2431
+ continue;
2432
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
2101
2433
  }
2434
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
2102
2435
  }
2103
- function readEntries(file) {
2104
- let raw;
2436
+ function isRetryableStatus(status) {
2437
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
2438
+ }
2439
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
2440
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
2441
+ }
2442
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
2443
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
2444
+ }
2445
+ async function sendIngest(url, eventWriteToken, body, signal) {
2105
2446
  try {
2106
- raw = fs.readFileSync(file, "utf8");
2107
- } catch {
2108
- return { entries: [], unreadable: 0 };
2447
+ const response = await fetch(url, {
2448
+ method: "POST",
2449
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2450
+ body,
2451
+ signal
2452
+ });
2453
+ return parseIngestResponse(response);
2454
+ } catch (error) {
2455
+ return {
2456
+ result: "transport_error",
2457
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
2458
+ };
2109
2459
  }
2110
- const entries = [];
2111
- let unreadable = 0;
2112
- for (const line of raw.split("\n")) {
2113
- if (!line.trim())
2114
- continue;
2460
+ }
2461
+ async function parseIngestResponse(response) {
2462
+ if (response.ok) {
2463
+ const outcome = { result: "accepted", httpStatus: response.status };
2464
+ let read = { duplicates: 0 };
2115
2465
  try {
2116
- const parsed = JSON.parse(line);
2117
- if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
2118
- unreadable += 1;
2119
- continue;
2120
- }
2121
- entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
2466
+ read = readSuccessBody(await response.text());
2122
2467
  } catch {
2123
- unreadable += 1;
2468
+ read = { duplicates: 0 };
2124
2469
  }
2470
+ return {
2471
+ ...outcome,
2472
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
2473
+ ...read.results !== void 0 ? { results: read.results } : {}
2474
+ };
2125
2475
  }
2126
- return { entries, unreadable };
2476
+ const body = await response.text();
2477
+ let errorCode;
2478
+ try {
2479
+ errorCode = JSON.parse(body).error;
2480
+ } catch {
2481
+ errorCode = void 0;
2482
+ }
2483
+ const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
2484
+ if (response.status === 401)
2485
+ return { ...base, result: "auth_failed" };
2486
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
2487
+ return { ...base, result: "consent_missing" };
2488
+ if (response.status === 400 || response.status === 422)
2489
+ return { ...base, result: "validation_failed" };
2490
+ return { ...base, result: "transport_error" };
2127
2491
  }
2128
2492
  }
2129
2493
  });
@@ -2371,11 +2735,34 @@ var require_eventSender = __commonJS({
2371
2735
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
2372
2736
  }
2373
2737
  if (this.isRetryable(outcome)) {
2374
- await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
2738
+ await new Promise((resolve3) => setTimeout(resolve3, RETRY_DELAY_MS));
2375
2739
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
2376
2740
  }
2377
2741
  return outcome;
2378
2742
  }
2743
+ /**
2744
+ * One outbox pass with nothing live to send: what a background flusher runs,
2745
+ * once per batch. Unlike the pass {@link post} makes, it may run more than
2746
+ * once per sender, because a flusher isn't on anyone's critical path.
2747
+ *
2748
+ * A halted pass is journaled here. Inside {@link post} the live send that
2749
+ * follows journals it, and a flusher has no live send, so without this an
2750
+ * outage would never reach the journal `doctor` and the notices read.
2751
+ */
2752
+ async flushOutbox() {
2753
+ await this.renewIfExpiring();
2754
+ this.outboxServiced = false;
2755
+ this.lastDrain = void 0;
2756
+ const halted = await this.serviceOutbox();
2757
+ if (halted) {
2758
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, halted.result, {
2759
+ httpStatus: halted.httpStatus,
2760
+ errorCode: halted.errorCode,
2761
+ detail: withNote(halted.detail, "kept in outbox")
2762
+ });
2763
+ }
2764
+ return this.lastDrain;
2765
+ }
2379
2766
  /** A failure that never reached a verdict. Replaying can change the answer. */
2380
2767
  isRetryable(outcome) {
2381
2768
  return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
@@ -2634,16 +3021,16 @@ var require_contextRegistry = __commonJS({
2634
3021
  exports.readWorkContextRegistry = readWorkContextRegistry;
2635
3022
  exports.recordWorkContext = recordWorkContext;
2636
3023
  exports.recordWorkContextAlias = recordWorkContextAlias;
2637
- var fs = __importStar(__require("fs"));
3024
+ var fs2 = __importStar(__require("fs"));
2638
3025
  var os2 = __importStar(__require("os"));
2639
- var path2 = __importStar(__require("path"));
3026
+ var path3 = __importStar(__require("path"));
2640
3027
  var MAX_PATHS_PER_ENTRY = 8;
2641
3028
  function workContextRegistryFilePath() {
2642
- return path2.join(os2.homedir(), ".ascenda", "work-contexts.json");
3029
+ return path3.join(os2.homedir(), ".ascenda", "work-contexts.json");
2643
3030
  }
2644
3031
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
2645
3032
  try {
2646
- const parsed = JSON.parse(fs.readFileSync(registryFilePath, "utf8"));
3033
+ const parsed = JSON.parse(fs2.readFileSync(registryFilePath, "utf8"));
2647
3034
  if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
2648
3035
  return parsed;
2649
3036
  }
@@ -2719,14 +3106,14 @@ var require_contextRegistry = __commonJS({
2719
3106
  return iso.slice(0, 10);
2720
3107
  }
2721
3108
  function writeRegistry(registryFilePath, registry) {
2722
- const dir = path2.dirname(registryFilePath);
2723
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
3109
+ const dir = path3.dirname(registryFilePath);
3110
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
2724
3111
  const tmp = `${registryFilePath}.${process.pid}.tmp`;
2725
- fs.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
3112
+ fs2.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2726
3113
  `, { encoding: "utf8", mode: 384 });
2727
- fs.renameSync(tmp, registryFilePath);
3114
+ fs2.renameSync(tmp, registryFilePath);
2728
3115
  if (process.platform !== "win32") {
2729
- fs.chmodSync(registryFilePath, 384);
3116
+ fs2.chmodSync(registryFilePath, 384);
2730
3117
  }
2731
3118
  }
2732
3119
  }
@@ -2775,12 +3162,14 @@ var require_forgeProject = __commonJS({
2775
3162
  }();
2776
3163
  Object.defineProperty(exports, "__esModule", { value: true });
2777
3164
  exports.forgeProjectHash = forgeProjectHash;
3165
+ exports.forgeRepoKey = forgeRepoKey;
3166
+ exports.forgeBranchKey = forgeBranchKey;
2778
3167
  exports.parseForgeFullName = parseForgeFullName;
2779
3168
  exports.readForgeFullName = readForgeFullName;
2780
3169
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
2781
3170
  exports.recordForgeProjectAlias = recordForgeProjectAlias;
2782
- var fs = __importStar(__require("fs"));
2783
- var path2 = __importStar(__require("path"));
3171
+ var fs2 = __importStar(__require("fs"));
3172
+ var path3 = __importStar(__require("path"));
2784
3173
  var contextRegistry_1 = require_contextRegistry();
2785
3174
  function forgeProjectHash(value) {
2786
3175
  let h = 2166136261;
@@ -2790,6 +3179,19 @@ var require_forgeProject = __commonJS({
2790
3179
  }
2791
3180
  return h.toString(16).padStart(8, "0");
2792
3181
  }
3182
+ function forgeRepoKey(fullName) {
3183
+ return forgeProjectHash(fullName.toLowerCase());
3184
+ }
3185
+ function forgeBranchKey(fullName, branch) {
3186
+ const input = `${fullName.toLowerCase()}
3187
+ ${branch}`;
3188
+ let h = 0xcbf29ce484222325n;
3189
+ for (const byte of Buffer.from(input, "utf8")) {
3190
+ h ^= BigInt(byte);
3191
+ h = BigInt.asUintN(64, h * 0x100000001b3n);
3192
+ }
3193
+ return h.toString(16).padStart(16, "0");
3194
+ }
2793
3195
  function parseForgeFullName(remoteUrl) {
2794
3196
  if (!remoteUrl)
2795
3197
  return null;
@@ -2826,7 +3228,7 @@ var require_forgeProject = __commonJS({
2826
3228
  return null;
2827
3229
  let config;
2828
3230
  try {
2829
- config = fs.readFileSync(path2.join(repositoryRoot, ".git", "config"), "utf8");
3231
+ config = fs2.readFileSync(path3.join(repositoryRoot, ".git", "config"), "utf8");
2830
3232
  } catch {
2831
3233
  return null;
2832
3234
  }
@@ -2933,31 +3335,31 @@ var require_salt = __commonJS({
2933
3335
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
2934
3336
  exports.hashWithMachineSalt = hashWithMachineSalt;
2935
3337
  var crypto = __importStar(__require("crypto"));
2936
- var fs = __importStar(__require("fs"));
2937
- var path2 = __importStar(__require("path"));
3338
+ var fs2 = __importStar(__require("fs"));
3339
+ var path3 = __importStar(__require("path"));
2938
3340
  var tokenStore_1 = require_tokenStore();
2939
3341
  function machineSaltFilePath() {
2940
- return path2.join((0, tokenStore_1.ascendaHome)(), "salt");
3342
+ return path3.join((0, tokenStore_1.ascendaHome)(), "salt");
2941
3343
  }
2942
3344
  var cache = /* @__PURE__ */ new Map();
2943
3345
  function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
2944
3346
  const hit = cache.get(saltFilePath);
2945
3347
  if (hit)
2946
3348
  return hit;
2947
- const dir = path2.dirname(saltFilePath);
2948
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
3349
+ const dir = path3.dirname(saltFilePath);
3350
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
2949
3351
  let salt;
2950
3352
  try {
2951
3353
  salt = crypto.randomBytes(32).toString("hex");
2952
- fs.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
3354
+ fs2.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2953
3355
  } catch (error) {
2954
3356
  if (error.code !== "EEXIST")
2955
3357
  throw error;
2956
- salt = fs.readFileSync(saltFilePath, "utf8").trim();
3358
+ salt = fs2.readFileSync(saltFilePath, "utf8").trim();
2957
3359
  }
2958
3360
  if (process.platform !== "win32") {
2959
- fs.chmodSync(dir, 448);
2960
- fs.chmodSync(saltFilePath, 384);
3361
+ fs2.chmodSync(dir, 448);
3362
+ fs2.chmodSync(saltFilePath, 384);
2961
3363
  }
2962
3364
  cache.set(saltFilePath, salt);
2963
3365
  return salt;
@@ -3017,8 +3419,8 @@ var require_workContext = __commonJS({
3017
3419
  exports.deriveBranchHash = deriveBranchHash;
3018
3420
  exports.readBranchName = readBranchName;
3019
3421
  exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
3020
- var fs = __importStar(__require("fs"));
3021
- var path2 = __importStar(__require("path"));
3422
+ var fs2 = __importStar(__require("fs"));
3423
+ var path3 = __importStar(__require("path"));
3022
3424
  var salt_1 = require_salt();
3023
3425
  var MAX_WALK_DEPTH = 64;
3024
3426
  function deriveWorkContext(cwd, saltFilePath) {
@@ -3049,14 +3451,14 @@ var require_workContext = __commonJS({
3049
3451
  };
3050
3452
  }
3051
3453
  function resolveRepositoryRoots(startDir) {
3052
- if (!fs.existsSync(startDir))
3454
+ if (!fs2.existsSync(startDir))
3053
3455
  return null;
3054
3456
  let dir = startDir;
3055
3457
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
3056
- const dotGit = path2.join(dir, ".git");
3458
+ const dotGit = path3.join(dir, ".git");
3057
3459
  let stat = null;
3058
3460
  try {
3059
- stat = fs.statSync(dotGit);
3461
+ stat = fs2.statSync(dotGit);
3060
3462
  } catch {
3061
3463
  stat = null;
3062
3464
  }
@@ -3067,7 +3469,7 @@ var require_workContext = __commonJS({
3067
3469
  const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
3068
3470
  return { checkoutRoot: dir, canonicalRoot, gitDir };
3069
3471
  }
3070
- const parent = path2.dirname(dir);
3472
+ const parent = path3.dirname(dir);
3071
3473
  if (parent === dir)
3072
3474
  return null;
3073
3475
  dir = parent;
@@ -3076,16 +3478,16 @@ var require_workContext = __commonJS({
3076
3478
  }
3077
3479
  function readGitdirPointer(dotGitFile, containingDir) {
3078
3480
  try {
3079
- const match = /^gitdir:\s*(.+)\s*$/m.exec(fs.readFileSync(dotGitFile, "utf8"));
3481
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(fs2.readFileSync(dotGitFile, "utf8"));
3080
3482
  if (!match)
3081
3483
  return null;
3082
- return path2.resolve(containingDir, match[1].trim());
3484
+ return path3.resolve(containingDir, match[1].trim());
3083
3485
  } catch {
3084
3486
  return null;
3085
3487
  }
3086
3488
  }
3087
3489
  function worktreeParentRoot(resolvedGitDir) {
3088
- const marker = `${path2.sep}.git${path2.sep}worktrees${path2.sep}`;
3490
+ const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
3089
3491
  const idx = resolvedGitDir.indexOf(marker);
3090
3492
  if (idx === -1)
3091
3493
  return null;
@@ -3095,12 +3497,12 @@ var require_workContext = __commonJS({
3095
3497
  const sep = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
3096
3498
  const leading = /^[\\/]/.test(startPath) ? sep : "";
3097
3499
  const segments = startPath.split(/[\\/]/).filter(Boolean);
3098
- const join2 = (count) => leading + segments.slice(0, count).join(sep);
3500
+ const join3 = (count) => leading + segments.slice(0, count).join(sep);
3099
3501
  for (let i = 0; i + 2 < segments.length; i++) {
3100
3502
  if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
3101
3503
  if (i === 0)
3102
3504
  return null;
3103
- return { checkoutRoot: join2(i + 3), canonicalRoot: join2(i), gitDir: null };
3505
+ return { checkoutRoot: join3(i + 3), canonicalRoot: join3(i), gitDir: null };
3104
3506
  }
3105
3507
  }
3106
3508
  for (let i = 0; i + 1 < segments.length; i++) {
@@ -3110,7 +3512,7 @@ var require_workContext = __commonJS({
3110
3512
  continue;
3111
3513
  const repoName = folder.slice(0, -suffix.length);
3112
3514
  const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep);
3113
- return { checkoutRoot: join2(i + 2), canonicalRoot, gitDir: null };
3515
+ return { checkoutRoot: join3(i + 2), canonicalRoot, gitDir: null };
3114
3516
  }
3115
3517
  return null;
3116
3518
  }
@@ -3158,7 +3560,7 @@ var require_workContext = __commonJS({
3158
3560
  return null;
3159
3561
  let head;
3160
3562
  try {
3161
- head = fs.readFileSync(path2.join(gitDir, "HEAD"), "utf8").trim();
3563
+ head = fs2.readFileSync(path3.join(gitDir, "HEAD"), "utf8").trim();
3162
3564
  } catch {
3163
3565
  return null;
3164
3566
  }
@@ -3176,6 +3578,95 @@ var require_workContext = __commonJS({
3176
3578
  }
3177
3579
  });
3178
3580
 
3581
+ // ../packages/tool-kit/out/forgeKeys.js
3582
+ var require_forgeKeys = __commonJS({
3583
+ "../packages/tool-kit/out/forgeKeys.js"(exports) {
3584
+ "use strict";
3585
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3586
+ if (k2 === void 0) k2 = k;
3587
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3588
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3589
+ desc = { enumerable: true, get: function() {
3590
+ return m[k];
3591
+ } };
3592
+ }
3593
+ Object.defineProperty(o, k2, desc);
3594
+ } : function(o, m, k, k2) {
3595
+ if (k2 === void 0) k2 = k;
3596
+ o[k2] = m[k];
3597
+ });
3598
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3599
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3600
+ } : function(o, v) {
3601
+ o["default"] = v;
3602
+ });
3603
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3604
+ var ownKeys = function(o) {
3605
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3606
+ var ar = [];
3607
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3608
+ return ar;
3609
+ };
3610
+ return ownKeys(o);
3611
+ };
3612
+ return function(mod) {
3613
+ if (mod && mod.__esModule) return mod;
3614
+ var result = {};
3615
+ if (mod != null) {
3616
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3617
+ }
3618
+ __setModuleDefault(result, mod);
3619
+ return result;
3620
+ };
3621
+ }();
3622
+ Object.defineProperty(exports, "__esModule", { value: true });
3623
+ exports.REPO_KEYS_ENV_VAR = void 0;
3624
+ exports.repoKeysEnabled = repoKeysEnabled;
3625
+ exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd;
3626
+ var fs2 = __importStar(__require("fs"));
3627
+ var path3 = __importStar(__require("path"));
3628
+ var credentials_1 = require_credentials();
3629
+ var forgeProject_1 = require_forgeProject();
3630
+ var workContext_1 = require_workContext();
3631
+ exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
3632
+ function repoKeysEnabled() {
3633
+ const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
3634
+ if (env === "off" || env === "0" || env === "false")
3635
+ return false;
3636
+ if (env === "on" || env === "1" || env === "true")
3637
+ return true;
3638
+ return (0, credentials_1.readMachineCredentials)()?.repoKeys !== false;
3639
+ }
3640
+ function readDefaultBranch(repositoryRoot) {
3641
+ try {
3642
+ const head = fs2.readFileSync(path3.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
3643
+ const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
3644
+ return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
3645
+ } catch {
3646
+ return null;
3647
+ }
3648
+ }
3649
+ function deriveForgeKeysForCwd(cwd) {
3650
+ try {
3651
+ if (!cwd || !repoKeysEnabled())
3652
+ return {};
3653
+ const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
3654
+ const fullName = (0, forgeProject_1.readForgeFullName)(root);
3655
+ if (!root || !fullName)
3656
+ return {};
3657
+ const branch = (0, workContext_1.readBranchName)(cwd);
3658
+ const onDefault = branch !== null && branch === readDefaultBranch(root);
3659
+ return {
3660
+ repoKey: (0, forgeProject_1.forgeRepoKey)(fullName),
3661
+ ...branch && !onDefault ? { branchKey: (0, forgeProject_1.forgeBranchKey)(fullName, branch) } : {}
3662
+ };
3663
+ } catch {
3664
+ return {};
3665
+ }
3666
+ }
3667
+ }
3668
+ });
3669
+
3179
3670
  // ../packages/tool-kit/out/hookAdapter.js
3180
3671
  var require_hookAdapter = __commonJS({
3181
3672
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
@@ -3185,13 +3676,18 @@ var require_hookAdapter = __commonJS({
3185
3676
  exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
3186
3677
  exports.resolveContextHashes = resolveContextHashes;
3187
3678
  exports.loadCliAgentConfig = loadCliAgentConfig;
3679
+ exports.withForgeKeys = withForgeKeys;
3680
+ exports.withPromptId = withPromptId;
3188
3681
  exports.deliverHookEvents = deliverHookEvents2;
3682
+ exports.flushHookOutbox = flushHookOutbox2;
3189
3683
  var contextRegistry_1 = require_contextRegistry();
3190
3684
  var credentials_1 = require_credentials();
3191
3685
  var forgeProject_1 = require_forgeProject();
3192
3686
  var eventLog_1 = require_eventLog();
3687
+ var forgeKeys_1 = require_forgeKeys();
3193
3688
  var eventSender_1 = require_eventSender();
3194
3689
  var stateStore_1 = require_stateStore();
3690
+ var backgroundDelivery_1 = require_backgroundDelivery();
3195
3691
  var tokenStore_1 = require_tokenStore();
3196
3692
  var workContext_1 = require_workContext();
3197
3693
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -3244,6 +3740,19 @@ var require_hookAdapter = __commonJS({
3244
3740
  };
3245
3741
  }
3246
3742
  function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
3743
+ const pairing = loadCliAgentPairing(toolType, identity);
3744
+ const contextHashes = resolveContextHashes(cwd);
3745
+ return {
3746
+ ...pairing,
3747
+ // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3748
+ // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3749
+ // an empty string, grouping unrelated rows under a value naming no session.
3750
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3751
+ workspaceHash: contextHashes.workspaceHash,
3752
+ projectHash: contextHashes.projectHash
3753
+ };
3754
+ }
3755
+ function loadCliAgentPairing(toolType, identity) {
3247
3756
  const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
3248
3757
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3249
3758
  const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
@@ -3254,26 +3763,33 @@ var require_hookAdapter = __commonJS({
3254
3763
  throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
3255
3764
  if (!fileToken)
3256
3765
  (0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3257
- const contextHashes = resolveContextHashes(cwd);
3258
3766
  return {
3259
3767
  apiBaseUrl,
3260
3768
  toolInstallationId,
3261
3769
  eventWriteToken,
3262
3770
  tokenFilePath,
3263
- // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3264
- // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3265
- // an empty string, grouping unrelated rows under a value naming no session.
3266
- sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3267
- workspaceHash: contextHashes.workspaceHash,
3268
- projectHash: contextHashes.projectHash,
3269
3771
  // Agents await command hooks; fail fast rather than stall the user's turn.
3270
3772
  timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
3271
3773
  };
3272
3774
  }
3775
+ function withForgeKeys(events, cwd) {
3776
+ const keys = (0, forgeKeys_1.deriveForgeKeysForCwd)(cwd ?? process.cwd());
3777
+ if (!keys.repoKey)
3778
+ return events;
3779
+ return events.map((event) => ({ ...event, metadata: { ...keys, ...event.metadata } }));
3780
+ }
3781
+ function withPromptId(events, promptId) {
3782
+ if (!promptId)
3783
+ return events;
3784
+ return events.map((event) => ({ ...event, metadata: { promptId, ...event.metadata } }));
3785
+ }
3273
3786
  async function deliverHookEvents2(events, options) {
3274
3787
  if (events.length === 0)
3275
3788
  return;
3276
- const notice = options.onNotice ?? ((message) => console.error(message));
3789
+ events = withPromptId(events, options.promptId);
3790
+ if (options.forgeKeys)
3791
+ events = withForgeKeys(events, options.cwd);
3792
+ const notice = options.onNotice ?? ((message2) => console.error(message2));
3277
3793
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3278
3794
  if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3279
3795
  const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
@@ -3304,21 +3820,55 @@ var require_hookAdapter = __commonJS({
3304
3820
  projectHash: config.projectHash,
3305
3821
  timeoutMs: config.timeoutMs
3306
3822
  });
3307
- for (const event of events) {
3308
- const result = await sender.send(event);
3309
- if (result === "accepted")
3310
- continue;
3311
- if (result === "consent_missing") {
3312
- notice("Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.");
3313
- } else if (result === "auth_failed") {
3314
- notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
3315
- } else if (result === "transport_error") {
3316
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
3317
- } else {
3318
- notice(`Ascenda telemetry rejected: ${result}`);
3823
+ if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
3824
+ for (const event of events) {
3825
+ const result = await sender.send(event);
3826
+ if (result === "accepted")
3827
+ continue;
3828
+ const message2 = noticeFor(result);
3829
+ if (message2)
3830
+ notice(message2);
3831
+ return;
3319
3832
  }
3320
3833
  return;
3321
3834
  }
3835
+ for (const event of events)
3836
+ sender.queue(event);
3837
+ (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
3838
+ const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
3839
+ const message = last ? noticeFor(last) : void 0;
3840
+ if (message)
3841
+ notice(message);
3842
+ }
3843
+ function noticeFor(result) {
3844
+ if (result === "accepted" || result === "duplicate")
3845
+ return void 0;
3846
+ if (result === "consent_missing")
3847
+ return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
3848
+ if (result === "auth_failed")
3849
+ return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
3850
+ if (result === "transport_error")
3851
+ return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
3852
+ if (result === "outbox_discarded")
3853
+ return void 0;
3854
+ return `Ascenda telemetry rejected: ${result}`;
3855
+ }
3856
+ async function flushHookOutbox2(options) {
3857
+ let config;
3858
+ try {
3859
+ config = loadCliAgentPairing(options.toolType, options);
3860
+ } catch {
3861
+ return;
3862
+ }
3863
+ const sender = new eventSender_1.AscendaEventSender({
3864
+ apiBaseUrl: config.apiBaseUrl,
3865
+ toolInstallationId: config.toolInstallationId,
3866
+ source: options.source,
3867
+ eventWriteToken: config.eventWriteToken,
3868
+ tokenFilePath: config.tokenFilePath,
3869
+ timeoutMs: config.timeoutMs
3870
+ });
3871
+ await (0, backgroundDelivery_1.runOutboxFlush)(sender);
3322
3872
  }
3323
3873
  function logUnsent(logFile, events, options) {
3324
3874
  const contextHashes = resolveContextHashes(options.cwd);
@@ -3501,7 +4051,7 @@ var require_studyJoin = __commonJS({
3501
4051
  const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3502
4052
  const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3503
4053
  while (Date.now() < deadline) {
3504
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
4054
+ await new Promise((resolve3) => setTimeout(resolve3, pollIntervalMs));
3505
4055
  let poll;
3506
4056
  try {
3507
4057
  poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
@@ -3564,7 +4114,7 @@ var require_studyJoin = __commonJS({
3564
4114
  return true;
3565
4115
  }
3566
4116
  function askChoice(stdin, stdout) {
3567
- return new Promise((resolve) => {
4117
+ return new Promise((resolve3) => {
3568
4118
  const rl = readline.createInterface({ input: stdin, output: stdout });
3569
4119
  let settled = false;
3570
4120
  const finish = (value) => {
@@ -3572,7 +4122,7 @@ var require_studyJoin = __commonJS({
3572
4122
  return;
3573
4123
  settled = true;
3574
4124
  rl.close();
3575
- resolve(value.trim());
4125
+ resolve3(value.trim());
3576
4126
  };
3577
4127
  rl.question("Choice [Not now]: ", finish);
3578
4128
  rl.once("close", () => finish(""));
@@ -3820,52 +4370,6 @@ var require_initiatives = __commonJS({
3820
4370
  }
3821
4371
  });
3822
4372
 
3823
- // ../packages/tool-kit/out/setupDisclosure.js
3824
- var require_setupDisclosure = __commonJS({
3825
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3826
- "use strict";
3827
- Object.defineProperty(exports, "__esModule", { value: true });
3828
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3829
- exports.renderSetupDisclosure = renderSetupDisclosure;
3830
- exports.FAMILY_SENTENCES = {
3831
- 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",
3832
- 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",
3833
- tools: "the name of each tool your agent calls",
3834
- outcome: "whether a call succeeded, failed, or was interrupted",
3835
- clock: "your machine's offset from UTC, so an evening is read as an evening",
3836
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3837
- model: "which model served the session, by name and by tier",
3838
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3839
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
3840
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3841
- context: "how full the context window got",
3842
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3843
- 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",
3844
- 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"
3845
- };
3846
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3847
- exports.REFUSALS = [
3848
- "Never your prompts, your agent's replies, or anything inside a file.",
3849
- "Never a file path, a command line, or a repository or branch name.",
3850
- "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."
3851
- ];
3852
- exports.FREE_TEXT_KEYS = ["message"];
3853
- function renderSetupDisclosure({ sends, displayName }) {
3854
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3855
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3856
- const lines = [
3857
- `What this sends from ${displayName}, once paired:`,
3858
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3859
- "",
3860
- ...exports.REFUSALS.map((line) => ` ${line}`),
3861
- "",
3862
- " Turn it off by revoking this tool in the Ascenda app."
3863
- ];
3864
- return lines.join("\n");
3865
- }
3866
- }
3867
- });
3868
-
3869
4373
  // ../packages/tool-kit/out/hookRunner.js
3870
4374
  var require_hookRunner = __commonJS({
3871
4375
  "../packages/tool-kit/out/hookRunner.js"(exports) {
@@ -3910,9 +4414,11 @@ var require_hookRunner = __commonJS({
3910
4414
  Object.defineProperty(exports, "__esModule", { value: true });
3911
4415
  exports.hookRunnerPaths = hookRunnerPaths;
3912
4416
  exports.hookLauncherScript = hookLauncherScript;
4417
+ exports.isDowngrade = isDowngrade;
3913
4418
  exports.installHookRunner = installHookRunner;
3914
4419
  exports.removeHookRunner = removeHookRunner;
3915
4420
  exports.hookRunnerCommand = hookRunnerCommand;
4421
+ exports.writeAtomically = writeAtomically;
3916
4422
  exports.lastHookPath = lastHookPath;
3917
4423
  exports.stampLastHook = stampLastHook2;
3918
4424
  exports.readLastHook = readLastHook;
@@ -3920,12 +4426,13 @@ var require_hookRunner = __commonJS({
3920
4426
  exports.resolveHookNode = resolveHookNode;
3921
4427
  exports.tidyHomePath = tidyHomePath;
3922
4428
  var child_process_1 = __require("child_process");
3923
- var fs = __importStar(__require("fs"));
3924
- var path2 = __importStar(__require("path"));
4429
+ var fs2 = __importStar(__require("fs"));
4430
+ var path3 = __importStar(__require("path"));
4431
+ var collectorVersion_1 = require_collectorVersion();
3925
4432
  var tokenStore_1 = require_tokenStore();
3926
4433
  function hookRunnerPaths(binaryName) {
3927
- const launcher = path2.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3928
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
4434
+ const launcher = path3.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
4435
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
3929
4436
  }
3930
4437
  var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3931
4438
  function hookLauncherScript(options) {
@@ -4019,62 +4526,98 @@ var require_hookRunner = __commonJS({
4019
4526
  ""
4020
4527
  ].join("\n");
4021
4528
  }
4529
+ function releaseOf(version) {
4530
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version ?? "").trim());
4531
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
4532
+ }
4533
+ function isDowngrade(installed, incoming) {
4534
+ const have = releaseOf(installed);
4535
+ const want = releaseOf(incoming);
4536
+ if (!have || !want)
4537
+ return false;
4538
+ for (let i = 0; i < 3; i++) {
4539
+ if (have[i] !== want[i])
4540
+ return have[i] > want[i];
4541
+ }
4542
+ return false;
4543
+ }
4544
+ function readInstalledVersion(file) {
4545
+ try {
4546
+ return fs2.readFileSync(file, "utf8").trim() || void 0;
4547
+ } catch {
4548
+ return void 0;
4549
+ }
4550
+ }
4022
4551
  function installHookRunner(options) {
4023
4552
  const paths = hookRunnerPaths(options.binaryName);
4024
4553
  if (options.dryRun)
4025
4554
  return paths.launcher;
4026
- const source = path2.resolve(options.source ?? process.argv[1]);
4027
- fs.mkdirSync(path2.dirname(paths.launcher), { recursive: true });
4555
+ const source = path3.resolve(options.source ?? process.argv[1]);
4556
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
4557
+ const installed = readInstalledVersion(paths.version);
4558
+ const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
4559
+ if (installed && fs2.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4560
+ options.onKeptNewer?.(installed, incoming);
4561
+ if (process.platform !== "win32" && !fs2.existsSync(paths.launcher))
4562
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4563
+ return paths.launcher;
4564
+ }
4565
+ fs2.mkdirSync(path3.dirname(paths.launcher), { recursive: true });
4028
4566
  if (process.platform === "win32") {
4029
- if (source !== path2.resolve(paths.launcher))
4030
- fs.copyFileSync(source, paths.launcher);
4567
+ if (source !== path3.resolve(paths.launcher))
4568
+ fs2.copyFileSync(source, paths.launcher);
4569
+ writeAtomically(paths.version, `${incoming}
4570
+ `, 420);
4031
4571
  return paths.launcher;
4032
4572
  }
4033
- if (source !== path2.resolve(paths.bundle))
4034
- writeAtomically(paths.bundle, fs.readFileSync(source), 493);
4573
+ if (source !== path3.resolve(paths.bundle))
4574
+ writeAtomically(paths.bundle, fs2.readFileSync(source), 493);
4035
4575
  writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4036
4576
  writeAtomically(paths.record, `${process.execPath}
4037
4577
  `, 420);
4038
- fs.rmSync(paths.noNode, { force: true });
4578
+ if (source !== path3.resolve(paths.bundle))
4579
+ writeAtomically(paths.version, `${incoming}
4580
+ `, 420);
4581
+ fs2.rmSync(paths.noNode, { force: true });
4039
4582
  return paths.launcher;
4040
4583
  }
4041
4584
  function removeHookRunner(binaryName) {
4042
4585
  const removed = [];
4043
4586
  for (const file of Object.values(hookRunnerPaths(binaryName))) {
4044
- if (!fs.existsSync(file))
4587
+ if (!fs2.existsSync(file))
4045
4588
  continue;
4046
- fs.rmSync(file, { force: true });
4589
+ fs2.rmSync(file, { force: true });
4047
4590
  removed.push(file);
4048
4591
  }
4049
4592
  return removed;
4050
4593
  }
4051
- function hookRunnerCommand(launcher) {
4052
- return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4594
+ function hookRunnerCommand(launcher, platform = process.platform) {
4595
+ return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4053
4596
  }
4054
4597
  function writeAtomically(target, contents, mode) {
4055
4598
  const tmp = `${target}.${process.pid}.tmp`;
4056
- fs.writeFileSync(tmp, contents, { mode });
4057
- fs.chmodSync(tmp, mode);
4058
- fs.renameSync(tmp, target);
4599
+ fs2.writeFileSync(tmp, contents, { mode });
4600
+ fs2.chmodSync(tmp, mode);
4601
+ fs2.renameSync(tmp, target);
4059
4602
  }
4060
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path2.join((0, tokenStore_1.ascendaHome)(), "state");
4603
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join((0, tokenStore_1.ascendaHome)(), "state");
4061
4604
  function lastHookPath(tool) {
4062
- return path2.join(stateDir(), `${tool}-last-hook.json`);
4605
+ return path3.join(stateDir(), `${tool}-last-hook.json`);
4063
4606
  }
4064
4607
  function stampLastHook2(tool, event, now = /* @__PURE__ */ new Date()) {
4065
4608
  try {
4066
- fs.mkdirSync(stateDir(), { recursive: true });
4609
+ fs2.mkdirSync(stateDir(), { recursive: true });
4067
4610
  const file = lastHookPath(tool);
4068
4611
  const tmp = `${file}.${process.pid}.tmp`;
4069
- fs.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
4612
+ fs2.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
4070
4613
  `, { mode: 384 });
4071
- fs.renameSync(tmp, file);
4614
+ fs2.renameSync(tmp, file);
4072
4615
  } catch {
4073
4616
  }
4074
4617
  }
4075
4618
  function readLastHook(tool) {
4076
4619
  try {
4077
- const parsed = JSON.parse(fs.readFileSync(lastHookPath(tool), "utf8"));
4620
+ const parsed = JSON.parse(fs2.readFileSync(lastHookPath(tool), "utf8"));
4078
4621
  if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
4079
4622
  return void 0;
4080
4623
  return { event: parsed.event, at: parsed.at };
@@ -4097,7 +4640,7 @@ var require_hookRunner = __commonJS({
4097
4640
  return `${Math.round(hours / 24)} days ago`;
4098
4641
  }
4099
4642
  function resolveHookNode(launcher) {
4100
- if (!fs.existsSync(launcher))
4643
+ if (!fs2.existsSync(launcher))
4101
4644
  return { problem: "the hook launcher is not installed" };
4102
4645
  const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
4103
4646
  encoding: "utf8",
@@ -4108,13 +4651,122 @@ var require_hookRunner = __commonJS({
4108
4651
  if (probe.status !== 0 || !node) {
4109
4652
  return { problem: (probe.stderr ?? "").trim() || "the launcher found no Node it can run" };
4110
4653
  }
4111
- const version = (0, child_process_1.spawnSync)(node, ["--version"], { encoding: "utf8", timeout: 5e3 });
4112
- if (version.status !== 0)
4113
- return { node, how, problem: `${node} did not run` };
4114
- return { node, how, version: version.stdout.trim() };
4654
+ const version = (0, child_process_1.spawnSync)(node, ["--version"], { encoding: "utf8", timeout: 5e3 });
4655
+ if (version.status !== 0)
4656
+ return { node, how, problem: `${node} did not run` };
4657
+ return { node, how, version: version.stdout.trim() };
4658
+ }
4659
+ function tidyHomePath(file, home = process.env.HOME ?? "") {
4660
+ return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
4661
+ }
4662
+ }
4663
+ });
4664
+
4665
+ // ../packages/tool-kit/out/settingsFile.js
4666
+ var require_settingsFile = __commonJS({
4667
+ "../packages/tool-kit/out/settingsFile.js"(exports) {
4668
+ "use strict";
4669
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4670
+ if (k2 === void 0) k2 = k;
4671
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4672
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4673
+ desc = { enumerable: true, get: function() {
4674
+ return m[k];
4675
+ } };
4676
+ }
4677
+ Object.defineProperty(o, k2, desc);
4678
+ } : function(o, m, k, k2) {
4679
+ if (k2 === void 0) k2 = k;
4680
+ o[k2] = m[k];
4681
+ });
4682
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4683
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4684
+ } : function(o, v) {
4685
+ o["default"] = v;
4686
+ });
4687
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4688
+ var ownKeys = function(o) {
4689
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4690
+ var ar = [];
4691
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4692
+ return ar;
4693
+ };
4694
+ return ownKeys(o);
4695
+ };
4696
+ return function(mod) {
4697
+ if (mod && mod.__esModule) return mod;
4698
+ var result = {};
4699
+ if (mod != null) {
4700
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4701
+ }
4702
+ __setModuleDefault(result, mod);
4703
+ return result;
4704
+ };
4705
+ }();
4706
+ Object.defineProperty(exports, "__esModule", { value: true });
4707
+ exports.replaceSettingsFile = replaceSettingsFile;
4708
+ var fs2 = __importStar(__require("fs"));
4709
+ var path3 = __importStar(__require("path"));
4710
+ var hookRunner_1 = require_hookRunner();
4711
+ function replaceSettingsFile(settingsFile, contents) {
4712
+ const exists = fs2.existsSync(settingsFile);
4713
+ const target = exists ? fs2.realpathSync(settingsFile) : settingsFile;
4714
+ if (exists) {
4715
+ const backup = `${settingsFile}.ascenda-backup`;
4716
+ if (!fs2.existsSync(backup))
4717
+ fs2.copyFileSync(target, backup);
4718
+ }
4719
+ fs2.mkdirSync(path3.dirname(target), { recursive: true });
4720
+ const mode = exists ? fs2.statSync(target).mode & 511 : 420;
4721
+ (0, hookRunner_1.writeAtomically)(target, contents, mode);
4115
4722
  }
4116
- function tidyHomePath(file, home = process.env.HOME ?? "") {
4117
- return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
4723
+ }
4724
+ });
4725
+
4726
+ // ../packages/tool-kit/out/setupDisclosure.js
4727
+ var require_setupDisclosure = __commonJS({
4728
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
4729
+ "use strict";
4730
+ Object.defineProperty(exports, "__esModule", { value: true });
4731
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
4732
+ exports.renderSetupDisclosure = renderSetupDisclosure;
4733
+ exports.FAMILY_SENTENCES = {
4734
+ session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
4735
+ counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
4736
+ tools: "the name of each tool your agent calls",
4737
+ outcome: "whether a call succeeded, failed, or was interrupted",
4738
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
4739
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
4740
+ model: "which model served the session, by name and by tier",
4741
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
4742
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
4743
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
4744
+ context: "how full the context window got",
4745
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, input_request, idle_prompt, or other, and that it asked permission for a tool or had one refused in auto mode, with the tool's name",
4746
+ subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
4747
+ forge: "for a GitHub repository, one digest of owner/repo and one of the branch, which anyone who guesses the names can reproduce, so a pull request can be matched to your session (turn off with setup --no-repo-keys)",
4748
+ turns: "an opaque id your agent gives each prompt, so one turn's events group together",
4749
+ reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
4750
+ };
4751
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
4752
+ exports.REFUSALS = [
4753
+ "Never your prompts, your agent's replies, or anything inside a file.",
4754
+ "Never a file path, a command line, or a repository or branch name.",
4755
+ "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
4756
+ ];
4757
+ exports.FREE_TEXT_KEYS = ["message"];
4758
+ function renderSetupDisclosure({ sends, displayName }) {
4759
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
4760
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
4761
+ const lines = [
4762
+ `What this sends from ${displayName}, once paired:`,
4763
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
4764
+ "",
4765
+ ...exports.REFUSALS.map((line) => ` ${line}`),
4766
+ "",
4767
+ " Turn it off by revoking this tool in the Ascenda app."
4768
+ ];
4769
+ return lines.join("\n");
4118
4770
  }
4119
4771
  }
4120
4772
  });
@@ -4170,22 +4822,22 @@ var require_saverHandoff = __commonJS({
4170
4822
  exports.heldForSaver = heldForSaver;
4171
4823
  exports.readSaverStatuses = readSaverStatuses;
4172
4824
  exports.probeSocket = probeSocket;
4173
- var fs = __importStar(__require("fs"));
4825
+ var fs2 = __importStar(__require("fs"));
4174
4826
  var net = __importStar(__require("net"));
4175
4827
  var os2 = __importStar(__require("os"));
4176
- var path2 = __importStar(__require("path"));
4828
+ var path3 = __importStar(__require("path"));
4177
4829
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
4178
4830
  function saverContainerDir() {
4179
- return process.env.ASCENDA_SAVER_CONTAINER ?? path2.join(os2.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
4831
+ return process.env.ASCENDA_SAVER_CONTAINER ?? path3.join(os2.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
4180
4832
  }
4181
4833
  function saverSupportDir() {
4182
- return path2.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
4834
+ return path3.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
4183
4835
  }
4184
4836
  function saverReplayPath() {
4185
- return path2.join(saverContainerDir(), "l.replay.json");
4837
+ return path3.join(saverContainerDir(), "l.replay.json");
4186
4838
  }
4187
4839
  function saverStatusDir() {
4188
- return path2.join(saverSupportDir(), "status");
4840
+ return path3.join(saverSupportDir(), "status");
4189
4841
  }
4190
4842
  exports.SAVER_REPLAY_WINDOW_MS = 30 * 60 * 1e3;
4191
4843
  var SAVER_REPLAY_MAX = 32;
@@ -4194,7 +4846,7 @@ var require_saverHandoff = __commonJS({
4194
4846
  try {
4195
4847
  if (process.env.ASCENDA_LIVE_BUS_SOCKET && !process.env.ASCENDA_SAVER_CONTAINER)
4196
4848
  return;
4197
- if (!fs.existsSync(saverSupportDir()))
4849
+ if (!fs2.existsSync(saverSupportDir()))
4198
4850
  return;
4199
4851
  const wire = signal;
4200
4852
  const tool = wire.tool;
@@ -4208,15 +4860,15 @@ var require_saverHandoff = __commonJS({
4208
4860
  kept.sort((a, b) => a.at - b.at);
4209
4861
  const body = JSON.stringify({ schema: exports.SAVER_REPLAY_SCHEMA, signals: kept.slice(-SAVER_REPLAY_MAX) });
4210
4862
  const tmp = `${file}.${process.pid}.tmp`;
4211
- fs.writeFileSync(tmp, `${body}
4863
+ fs2.writeFileSync(tmp, `${body}
4212
4864
  `, { mode: 384 });
4213
- fs.renameSync(tmp, file);
4865
+ fs2.renameSync(tmp, file);
4214
4866
  } catch {
4215
4867
  }
4216
4868
  }
4217
4869
  function readHeld(file) {
4218
4870
  try {
4219
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
4871
+ const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
4220
4872
  if (parsed.schema !== exports.SAVER_REPLAY_SCHEMA || !Array.isArray(parsed.signals))
4221
4873
  return [];
4222
4874
  return parsed.signals.filter((held) => typeof held === "object" && held !== null && typeof held.tool === "string" && typeof held.session === "string" && typeof held.event === "string" && typeof held.at === "number");
@@ -4233,14 +4885,14 @@ var require_saverHandoff = __commonJS({
4233
4885
  function readSaverStatuses(now = Date.now()) {
4234
4886
  let names;
4235
4887
  try {
4236
- names = fs.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
4888
+ names = fs2.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
4237
4889
  } catch {
4238
4890
  return [];
4239
4891
  }
4240
4892
  const readings = [];
4241
4893
  for (const name of names) {
4242
4894
  try {
4243
- const status = JSON.parse(fs.readFileSync(path2.join(saverStatusDir(), name), "utf8"));
4895
+ const status = JSON.parse(fs2.readFileSync(path3.join(saverStatusDir(), name), "utf8"));
4244
4896
  if (typeof status.pid !== "number" || typeof status.updatedAt !== "string")
4245
4897
  continue;
4246
4898
  readings.push({ ...status, alive: processAlive(status.pid), ageMs: now - Date.parse(status.updatedAt) });
@@ -4258,14 +4910,14 @@ var require_saverHandoff = __commonJS({
4258
4910
  }
4259
4911
  }
4260
4912
  function probeSocket(socketPath, timeoutMs = 300) {
4261
- return new Promise((resolve) => {
4913
+ return new Promise((resolve3) => {
4262
4914
  try {
4263
- if (!fs.statSync(socketPath).isSocket()) {
4264
- resolve("absent");
4915
+ if (!fs2.statSync(socketPath).isSocket()) {
4916
+ resolve3("absent");
4265
4917
  return;
4266
4918
  }
4267
4919
  } catch {
4268
- resolve("absent");
4920
+ resolve3("absent");
4269
4921
  return;
4270
4922
  }
4271
4923
  let settled = false;
@@ -4275,7 +4927,7 @@ var require_saverHandoff = __commonJS({
4275
4927
  settled = true;
4276
4928
  clearTimeout(timer);
4277
4929
  socket.destroy();
4278
- resolve(state);
4930
+ resolve3(state);
4279
4931
  };
4280
4932
  const socket = net.createConnection(socketPath);
4281
4933
  const timer = setTimeout(() => finish("unreachable"), timeoutMs);
@@ -4335,10 +4987,10 @@ var require_liveBus = __commonJS({
4335
4987
  exports.bucketPromptSize = bucketPromptSize2;
4336
4988
  exports.emitLiveSignal = emitLiveSignal2;
4337
4989
  exports.deliverLine = deliverLine;
4338
- var fs = __importStar(__require("fs"));
4990
+ var fs2 = __importStar(__require("fs"));
4339
4991
  var net = __importStar(__require("net"));
4340
4992
  var os2 = __importStar(__require("os"));
4341
- var path2 = __importStar(__require("path"));
4993
+ var path3 = __importStar(__require("path"));
4342
4994
  var hookSet_1 = require_hookSet();
4343
4995
  var saverHandoff_1 = require_saverHandoff();
4344
4996
  var WRITE_TIMEOUT_MS = 50;
@@ -4351,9 +5003,9 @@ var require_liveBus = __commonJS({
4351
5003
  return [override];
4352
5004
  const home = os2.homedir();
4353
5005
  return [
4354
- path2.join(home, ".ascenda", "live.sock"),
4355
- path2.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4356
- path2.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
5006
+ path3.join(home, ".ascenda", "live.sock"),
5007
+ path3.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
5008
+ path3.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4357
5009
  ];
4358
5010
  }
4359
5011
  function existingSocketCandidates() {
@@ -4362,7 +5014,7 @@ var require_liveBus = __commonJS({
4362
5014
  return candidates;
4363
5015
  return candidates.filter((candidate) => {
4364
5016
  try {
4365
- return fs.statSync(candidate).isSocket();
5017
+ return fs2.statSync(candidate).isSocket();
4366
5018
  } catch {
4367
5019
  return false;
4368
5020
  }
@@ -4399,10 +5051,10 @@ var require_liveBus = __commonJS({
4399
5051
  });
4400
5052
  }
4401
5053
  function deliverLine(line) {
4402
- return new Promise((resolve) => {
5054
+ return new Promise((resolve3) => {
4403
5055
  const candidates = existingSocketCandidates();
4404
5056
  if (candidates.length === 0) {
4405
- resolve(void 0);
5057
+ resolve3(void 0);
4406
5058
  return;
4407
5059
  }
4408
5060
  let settled = false;
@@ -4421,7 +5073,7 @@ var require_liveBus = __commonJS({
4421
5073
  settled = true;
4422
5074
  clearTimeout(timer);
4423
5075
  drop();
4424
- resolve(accepted);
5076
+ resolve3(accepted);
4425
5077
  };
4426
5078
  const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4427
5079
  const tryFrom = (index) => {
@@ -4621,7 +5273,7 @@ var require_liveSignalDoctor = __commonJS({
4621
5273
  if (accepted !== saverSocket)
4622
5274
  return { tone: "ok", text: `the desktop app took it (${accepted})` };
4623
5275
  for (let waited = 0; waited < 2e3; waited += 100) {
4624
- await new Promise((resolve) => setTimeout(resolve, 100));
5276
+ await new Promise((resolve3) => setTimeout(resolve3, 100));
4625
5277
  const answered = (0, saverHandoff_1.readSaverStatuses)().find((status) => status.lastPingSession === session);
4626
5278
  if (answered)
4627
5279
  return { tone: "ok", text: `OK. The screen saver (pid ${answered.pid}) received it` };
@@ -4884,12 +5536,14 @@ var require_cliAgentSetup = __commonJS({
4884
5536
  exports.runCliAgentSetup = runCliAgentSetup2;
4885
5537
  exports.writeHookSettings = writeHookSettings;
4886
5538
  exports.registeredHookSets = registeredHookSets;
5539
+ exports.ourHookPositions = ourHookPositions;
5540
+ exports.trustProblemLines = trustProblemLines;
4887
5541
  exports.findStaleHookCommands = findStaleHookCommands;
4888
5542
  exports.cliAgentRegistrations = cliAgentRegistrations;
4889
5543
  var crypto = __importStar(__require("crypto"));
4890
- var fs = __importStar(__require("fs"));
5544
+ var fs2 = __importStar(__require("fs"));
4891
5545
  var os2 = __importStar(__require("os"));
4892
- var path2 = __importStar(__require("path"));
5546
+ var path3 = __importStar(__require("path"));
4893
5547
  var collectorVersion_1 = require_collectorVersion();
4894
5548
  var credentials_1 = require_credentials();
4895
5549
  var eventLog_1 = require_eventLog();
@@ -4897,6 +5551,7 @@ var require_cliAgentSetup = __commonJS({
4897
5551
  var http_1 = require_http();
4898
5552
  var hookSet_1 = require_hookSet();
4899
5553
  var initiatives_1 = require_initiatives();
5554
+ var settingsFile_1 = require_settingsFile();
4900
5555
  var setupDisclosure_1 = require_setupDisclosure();
4901
5556
  var hookRunner_1 = require_hookRunner();
4902
5557
  var liveSignalDoctor_1 = require_liveSignalDoctor();
@@ -4933,6 +5588,10 @@ Options
4933
5588
  --no-pair install without pairing: local features on, nothing sent
4934
5589
  --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
4935
5590
  On by default when not paired; machine-wide, shared by every agent
5591
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
5592
+ repository gets a key and, off its default branch, a branch key, so a pull
5593
+ request can be matched to a session. They are digests anyone who guesses the
5594
+ names can reproduce. Machine-wide. --repo-keys turns them back on
4936
5595
  --scope user|project where hooks are registered (default user: every project)
4937
5596
  --project-dir <path> project root for --scope project (default cwd)
4938
5597
  --dry-run print what would change, write nothing
@@ -4989,6 +5648,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4989
5648
  });
4990
5649
  if (options.eventLog !== void 0)
4991
5650
  (0, credentials_1.writeEventLogSetting)(options.eventLog);
5651
+ if (options.repoKeys !== void 0)
5652
+ (0, credentials_1.writeRepoKeysSetting)(options.repoKeys);
4992
5653
  }
4993
5654
  if (isHomeProject(options)) {
4994
5655
  detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
@@ -5062,7 +5723,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5062
5723
  return 0;
5063
5724
  }
5064
5725
  function isHomeProject(options) {
5065
- return options.scope === "project" && path2.resolve(options.projectDir) === path2.resolve(os2.homedir());
5726
+ return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os2.homedir());
5066
5727
  }
5067
5728
  function parseArgs(argv, spec) {
5068
5729
  const options = {
@@ -5117,7 +5778,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5117
5778
  break;
5118
5779
  }
5119
5780
  case "--project-dir":
5120
- options.projectDir = path2.resolve(next());
5781
+ options.projectDir = path3.resolve(next());
5121
5782
  break;
5122
5783
  case "--dry-run":
5123
5784
  options.dryRun = true;
@@ -5128,6 +5789,12 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5128
5789
  i += consumed;
5129
5790
  break;
5130
5791
  }
5792
+ case "--repo-keys":
5793
+ options.repoKeys = true;
5794
+ break;
5795
+ case "--no-repo-keys":
5796
+ options.repoKeys = false;
5797
+ break;
5131
5798
  case "--no-pair":
5132
5799
  // `--no-pairing` is the spelling this landed under first. Both appeared
5133
5800
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -5251,19 +5918,24 @@ Pairing ${status.status}. Run setup again.`);
5251
5918
  console.log(" Waiting...");
5252
5919
  announced = true;
5253
5920
  }
5254
- await new Promise((resolve) => setTimeout(resolve, 2e3));
5921
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
5255
5922
  }
5256
5923
  console.error("\nPairing timed out. Run setup again.");
5257
5924
  return void 0;
5258
5925
  }
5259
5926
  function installBinary(spec, dryRun) {
5260
- return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
5927
+ return (0, hookRunner_1.installHookRunner)({
5928
+ binaryName: spec.binaryName,
5929
+ setupCommand: `npx ${spec.packageName} setup`,
5930
+ dryRun,
5931
+ onKeptNewer: (installed, incoming) => console.log(` Kept the installed hook bundle (${installed}) rather than replace it with this older ${incoming}. Run setup from the newer version to change it.`)
5932
+ });
5261
5933
  }
5262
5934
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
5263
5935
  let settings = { ...spec.settings.scaffold ?? {} };
5264
- const exists = fs.existsSync(settingsFile);
5936
+ const exists = fs2.existsSync(settingsFile);
5265
5937
  if (exists) {
5266
- const raw = fs.readFileSync(settingsFile, "utf8").trim();
5938
+ const raw = fs2.readFileSync(settingsFile, "utf8").trim();
5267
5939
  if (raw) {
5268
5940
  try {
5269
5941
  settings = JSON.parse(raw);
@@ -5277,13 +5949,12 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5277
5949
  const command = hookCommand(binary, spec);
5278
5950
  const hooks = { ...settings.hooks ?? {} };
5279
5951
  for (const event of spec.hookEvents) {
5280
- const kept = (hooks[event] ?? []).filter((entry) => !isOurs(entry, spec));
5281
- hooks[event] = [...kept, spec.settings.entry(command, event)];
5952
+ hooks[event] = placeOurEntry(hooks[event] ?? [], spec.settings.entry(command, event), spec);
5282
5953
  }
5283
5954
  const updated = { ...settings, hooks };
5284
5955
  const serialised = `${JSON.stringify(updated, null, 2)}
5285
5956
  `;
5286
- if (exists && fs.readFileSync(settingsFile, "utf8") === serialised)
5957
+ if (exists && fs2.readFileSync(settingsFile, "utf8") === serialised)
5287
5958
  return false;
5288
5959
  if (dryRun) {
5289
5960
  console.log(`
@@ -5291,10 +5962,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5291
5962
  ${serialised}`);
5292
5963
  return true;
5293
5964
  }
5294
- if (exists)
5295
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5296
- fs.mkdirSync(path2.dirname(settingsFile), { recursive: true });
5297
- fs.writeFileSync(settingsFile, serialised, "utf8");
5965
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
5298
5966
  return true;
5299
5967
  }
5300
5968
  function hookCommand(binary, spec) {
@@ -5304,35 +5972,137 @@ ${serialised}`);
5304
5972
  const sets = /* @__PURE__ */ new Map();
5305
5973
  for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
5306
5974
  for (const entry of entries ?? []) {
5307
- if (!isOurs(entry, spec))
5308
- continue;
5309
- const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
5310
- sets.set(event, Math.min(set, sets.get(event) ?? set));
5975
+ for (const command of commandsOf(entry, spec)) {
5976
+ if (!isOurCommand(command, spec))
5977
+ continue;
5978
+ const set = (0, hookSet_1.hookSetOfCommand)(command);
5979
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5980
+ }
5311
5981
  }
5312
5982
  }
5313
5983
  return sets;
5314
5984
  }
5315
- function isOurs(entry, spec) {
5985
+ function ourHookPositions(settings, spec) {
5986
+ const found = [];
5987
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5988
+ (groups ?? []).forEach((group, groupIndex) => {
5989
+ const handlers = group?.hooks;
5990
+ if (Array.isArray(handlers)) {
5991
+ handlers.forEach((handler, handlerIndex) => {
5992
+ if (isOurs({ hooks: [handler] }, spec))
5993
+ found.push({ event, group: groupIndex, handler: handlerIndex });
5994
+ });
5995
+ } else if (isOurs(group, spec)) {
5996
+ found.push({ event, group: groupIndex, handler: 0 });
5997
+ }
5998
+ });
5999
+ }
6000
+ return found;
6001
+ }
6002
+ function trustProblemLines(spec, settingsFile, settings, indent) {
6003
+ if (!spec.trust)
6004
+ return [];
6005
+ const ours = ourHookPositions(settings, spec);
6006
+ if (ours.length === 0)
6007
+ return [];
6008
+ const report = spec.trust.check(settingsFile, ours);
6009
+ const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os2.homedir());
6010
+ const lines = [];
6011
+ if (report.unreadable) {
6012
+ lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
6013
+ }
6014
+ if (report.untrusted.length) {
6015
+ const names = [...new Set(report.untrusted.map((position) => position.event))].join(", ");
6016
+ lines.push(`${report.untrusted.length} of ${ours.length} hooks are not approved in ${where} (${names}). ${spec.displayName} skips them without a message, so nothing is sent for those events.`);
6017
+ }
6018
+ for (const entry of report.stale)
6019
+ lines.push(entry);
6020
+ if (lines.length)
6021
+ lines.push(spec.trust.fix);
6022
+ return lines.map((line) => `${indent}${line}`);
6023
+ }
6024
+ function commandsOf(entry, spec) {
6025
+ if (spec.settings.grouped) {
6026
+ return innerHooks(entry).map(commandOfHook).filter((command2) => typeof command2 === "string");
6027
+ }
5316
6028
  const command = spec.settings.commandOf(entry);
5317
- return typeof command === "string" && command.includes(spec.binaryName);
6029
+ return typeof command === "string" ? [command] : [];
6030
+ }
6031
+ function innerHooks(entry) {
6032
+ const hooks = entry && typeof entry === "object" ? entry.hooks : void 0;
6033
+ return Array.isArray(hooks) ? hooks : [];
6034
+ }
6035
+ function commandOfHook(hook) {
6036
+ return hook && typeof hook === "object" ? hook.command : void 0;
6037
+ }
6038
+ function isOurCommand(command, spec) {
6039
+ return command.includes(spec.binaryName);
6040
+ }
6041
+ function isOurs(entry, spec) {
6042
+ return commandsOf(entry, spec).some((command) => isOurCommand(command, spec));
6043
+ }
6044
+ function isOurInnerHook(hook, spec) {
6045
+ const command = commandOfHook(hook);
6046
+ return typeof command === "string" && isOurCommand(command, spec);
6047
+ }
6048
+ function withoutOurEntries(entries, spec) {
6049
+ if (!spec.settings.grouped)
6050
+ return entries.filter((entry) => !isOurs(entry, spec));
6051
+ const kept = [];
6052
+ for (const entry of entries) {
6053
+ if (!isOurs(entry, spec)) {
6054
+ kept.push(entry);
6055
+ continue;
6056
+ }
6057
+ const others = innerHooks(entry).filter((hook) => !isOurInnerHook(hook, spec));
6058
+ if (others.length)
6059
+ kept.push({ ...entry, hooks: others });
6060
+ }
6061
+ return kept;
6062
+ }
6063
+ function placeOurEntry(entries, wanted, spec) {
6064
+ if (!spec.settings.grouped)
6065
+ return [...withoutOurEntries(entries, spec), wanted];
6066
+ const replacements = innerHooks(wanted);
6067
+ let placed = false;
6068
+ const result = [];
6069
+ for (const entry of entries) {
6070
+ if (!isOurs(entry, spec)) {
6071
+ result.push(entry);
6072
+ continue;
6073
+ }
6074
+ const matcher = entry.matcher;
6075
+ const matchesAll = matcher === void 0 || matcher === "";
6076
+ const next = [];
6077
+ for (const hook of innerHooks(entry)) {
6078
+ if (!isOurInnerHook(hook, spec))
6079
+ next.push(hook);
6080
+ else if (!placed && matchesAll) {
6081
+ next.push(...replacements);
6082
+ placed = true;
6083
+ }
6084
+ }
6085
+ if (next.length)
6086
+ result.push({ ...entry, hooks: next });
6087
+ }
6088
+ return placed ? result : [...result, wanted];
5318
6089
  }
5319
6090
  function findStaleHookCommands(settings, binary, spec) {
5320
6091
  const stale = /* @__PURE__ */ new Set();
5321
6092
  for (const entries of Object.values(settings.hooks ?? {})) {
5322
6093
  for (const entry of entries ?? []) {
5323
- const command = spec.settings.commandOf(entry);
5324
- if (typeof command !== "string")
5325
- continue;
5326
- if (!/ascenda/i.test(command) || command.includes(binary))
5327
- continue;
5328
- stale.add(command);
6094
+ for (const command of commandsOf(entry, spec)) {
6095
+ if (!/ascenda/i.test(command) || command.includes(binary))
6096
+ continue;
6097
+ stale.add(command);
6098
+ }
5329
6099
  }
5330
6100
  }
5331
6101
  return [...stale];
5332
6102
  }
5333
6103
  function readSettings(settingsFile) {
5334
6104
  try {
5335
- return JSON.parse(fs.readFileSync(settingsFile, "utf8"));
6105
+ return JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
5336
6106
  } catch {
5337
6107
  return {};
5338
6108
  }
@@ -5351,7 +6121,7 @@ ${serialised}`);
5351
6121
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
5352
6122
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
5353
6123
  console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5354
- console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
6124
+ console.log(`hook binary ${fs2.existsSync(binary) ? binary : "\u2014 not installed"}`);
5355
6125
  const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5356
6126
  if (node) {
5357
6127
  console.log(node.problem ? `node \u2014 ${node.problem}. Install Node 20 or newer, then run setup again` : `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
@@ -5369,6 +6139,14 @@ ${serialised}`);
5369
6139
  const oldest = Math.min(...sets);
5370
6140
  console.log(oldest < spec.hookSet ? `hook set ${oldest}, this version registers ${spec.hookSet}. Upgrade: npx ${spec.packageName} setup${options.scope === "user" ? " --scope user" : ""}` : `hook set ${spec.hookSet} (current)`);
5371
6141
  }
6142
+ const trustLines = trustProblemLines(spec, settingsFile, settings, "");
6143
+ if (trustLines.length) {
6144
+ console.log(`not trusted ${trustLines[0]}`);
6145
+ for (const line of trustLines.slice(1))
6146
+ console.log(` ${line}`);
6147
+ } else if (spec.trust && registered > 0) {
6148
+ console.log("trust every registered hook is approved");
6149
+ }
5372
6150
  if (stale.length) {
5373
6151
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
5374
6152
  for (const command of stale)
@@ -5390,7 +6168,7 @@ ${serialised}`);
5390
6168
  await notices.markShown();
5391
6169
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
5392
6170
  const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5393
- const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
6171
+ const healthy = paired && wired && fs2.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
5394
6172
  return healthy ? 0 : 1;
5395
6173
  }
5396
6174
  function countRegistered(settings, spec) {
@@ -5411,7 +6189,7 @@ ${serialised}`);
5411
6189
  file: (0, hookRunner_1.tidyHomePath)(file, home),
5412
6190
  registered,
5413
6191
  scope,
5414
- homeProject: scope === "project" && path2.resolve(projectDir) === path2.resolve(home)
6192
+ homeProject: scope === "project" && path3.resolve(projectDir) === path3.resolve(home)
5415
6193
  });
5416
6194
  }
5417
6195
  return found;
@@ -5433,12 +6211,37 @@ ${serialised}`);
5433
6211
  } catch (error) {
5434
6212
  lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
5435
6213
  }
6214
+ if (spec.trust) {
6215
+ const found = trustDoctorLines(spec, options.projectDir, ui);
6216
+ if (found.length)
6217
+ lines.push("", ...found);
6218
+ }
5436
6219
  lines.push("", ...accountLines(ui, spec));
5437
6220
  const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
5438
6221
  lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5439
6222
  console.log(lines.join("\n"));
5440
6223
  return 0;
5441
6224
  }
6225
+ function trustDoctorLines(spec, projectDir, ui) {
6226
+ const userFile = spec.settings.settingsPath("user", projectDir);
6227
+ const projectFile = spec.settings.settingsPath("project", projectDir);
6228
+ const files = userFile === projectFile ? [userFile] : [userFile, projectFile];
6229
+ const out = [];
6230
+ for (const file of files) {
6231
+ const settings = readSettings(file);
6232
+ if (ourHookPositions(settings, spec).length === 0)
6233
+ continue;
6234
+ const problems = trustProblemLines(spec, file, settings, "");
6235
+ if (problems.length === 0) {
6236
+ out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os2.homedir())} is approved`);
6237
+ continue;
6238
+ }
6239
+ out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
6240
+ for (const line of problems.slice(1))
6241
+ out.push(`${" ".repeat(25)}${line}`);
6242
+ }
6243
+ return out;
6244
+ }
5442
6245
  function accountLines(ui, spec) {
5443
6246
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5444
6247
  const id = credentials?.toolInstallationId;
@@ -5466,13 +6269,13 @@ ${serialised}`);
5466
6269
  ];
5467
6270
  }
5468
6271
  function removeOurHookEntries(settingsFile, spec) {
5469
- if (!fs.existsSync(settingsFile))
6272
+ if (!fs2.existsSync(settingsFile))
5470
6273
  return true;
5471
6274
  try {
5472
- const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
6275
+ const settings = JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
5473
6276
  const hooks = { ...settings.hooks ?? {} };
5474
6277
  for (const event of Object.keys(hooks)) {
5475
- const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
6278
+ const kept = withoutOurEntries(hooks[event], spec);
5476
6279
  if (kept.length)
5477
6280
  hooks[event] = kept;
5478
6281
  else
@@ -5481,9 +6284,8 @@ ${serialised}`);
5481
6284
  const updated = { ...settings, hooks };
5482
6285
  if (!Object.keys(hooks).length)
5483
6286
  delete updated.hooks;
5484
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5485
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5486
- `, "utf8");
6287
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
6288
+ `);
5487
6289
  return true;
5488
6290
  } catch {
5489
6291
  return false;
@@ -5491,7 +6293,7 @@ ${serialised}`);
5491
6293
  }
5492
6294
  function uninstall(options, spec) {
5493
6295
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
5494
- if (fs.existsSync(settingsFile)) {
6296
+ if (fs2.existsSync(settingsFile)) {
5495
6297
  if (!removeOurHookEntries(settingsFile, spec)) {
5496
6298
  console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
5497
6299
  return 1;
@@ -5506,7 +6308,7 @@ ${serialised}`);
5506
6308
  (0, credentials_1.removeHostCredentials)(spec.host);
5507
6309
  console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
5508
6310
  }
5509
- console.log(`tokens left in ${path2.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
6311
+ console.log(`tokens left in ${path3.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
5510
6312
  return 0;
5511
6313
  }
5512
6314
  }
@@ -5555,24 +6357,39 @@ var require_turnState = __commonJS({
5555
6357
  }();
5556
6358
  Object.defineProperty(exports, "__esModule", { value: true });
5557
6359
  exports.recordTurnStart = recordTurnStart2;
6360
+ exports.readTurnPromptId = readTurnPromptId2;
5558
6361
  exports.consumeTurnDurationMs = consumeTurnDurationMs2;
5559
- var fs = __importStar(__require("fs"));
5560
- var path2 = __importStar(__require("path"));
6362
+ var crypto_1 = __require("crypto");
6363
+ var fs2 = __importStar(__require("fs"));
6364
+ var path3 = __importStar(__require("path"));
5561
6365
  var tokenStore_1 = require_tokenStore();
5562
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path2.join((0, tokenStore_1.ascendaHome)(), "state");
6366
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join((0, tokenStore_1.ascendaHome)(), "state");
5563
6367
  function turnFile(agent, sessionId) {
5564
- return path2.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
6368
+ return path3.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
5565
6369
  }
5566
6370
  function sanitize(value) {
5567
6371
  return value.replace(/[^a-zA-Z0-9._-]/g, "_");
5568
6372
  }
5569
6373
  function recordTurnStart2(agent, sessionId, now = Date.now()) {
5570
6374
  if (!sessionId)
5571
- return;
6375
+ return void 0;
6376
+ try {
6377
+ const promptId = (0, crypto_1.randomUUID)();
6378
+ fs2.mkdirSync(stateDir(), { recursive: true });
6379
+ fs2.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
6380
+ return promptId;
6381
+ } catch {
6382
+ return void 0;
6383
+ }
6384
+ }
6385
+ function readTurnPromptId2(agent, sessionId) {
6386
+ if (!sessionId)
6387
+ return void 0;
5572
6388
  try {
5573
- fs.mkdirSync(stateDir(), { recursive: true });
5574
- fs.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
6389
+ const id = fs2.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
6390
+ return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
5575
6391
  } catch {
6392
+ return void 0;
5576
6393
  }
5577
6394
  }
5578
6395
  function consumeTurnDurationMs2(agent, sessionId, now = Date.now()) {
@@ -5580,8 +6397,8 @@ var require_turnState = __commonJS({
5580
6397
  return void 0;
5581
6398
  const file = turnFile(agent, sessionId);
5582
6399
  try {
5583
- const started = Number(fs.readFileSync(file, "utf8").trim());
5584
- fs.rmSync(file, { force: true });
6400
+ const started = Number(fs2.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
6401
+ fs2.rmSync(file, { force: true });
5585
6402
  if (!Number.isFinite(started) || started <= 0 || started > now)
5586
6403
  return void 0;
5587
6404
  return now - started;
@@ -5592,6 +6409,100 @@ var require_turnState = __commonJS({
5592
6409
  }
5593
6410
  });
5594
6411
 
6412
+ // ../packages/tool-kit/out/pluginBundle.js
6413
+ var require_pluginBundle = __commonJS({
6414
+ "../packages/tool-kit/out/pluginBundle.js"(exports) {
6415
+ "use strict";
6416
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
6417
+ if (k2 === void 0) k2 = k;
6418
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6419
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6420
+ desc = { enumerable: true, get: function() {
6421
+ return m[k];
6422
+ } };
6423
+ }
6424
+ Object.defineProperty(o, k2, desc);
6425
+ } : function(o, m, k, k2) {
6426
+ if (k2 === void 0) k2 = k;
6427
+ o[k2] = m[k];
6428
+ });
6429
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
6430
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
6431
+ } : function(o, v) {
6432
+ o["default"] = v;
6433
+ });
6434
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
6435
+ var ownKeys = function(o) {
6436
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
6437
+ var ar = [];
6438
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
6439
+ return ar;
6440
+ };
6441
+ return ownKeys(o);
6442
+ };
6443
+ return function(mod) {
6444
+ if (mod && mod.__esModule) return mod;
6445
+ var result = {};
6446
+ if (mod != null) {
6447
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
6448
+ }
6449
+ __setModuleDefault(result, mod);
6450
+ return result;
6451
+ };
6452
+ }();
6453
+ Object.defineProperty(exports, "__esModule", { value: true });
6454
+ exports.pluginBundlePaths = pluginBundlePaths;
6455
+ exports.installPluginBundle = installPluginBundle;
6456
+ exports.describePluginBundleOutcome = describePluginBundleOutcome;
6457
+ var fs2 = __importStar(__require("fs"));
6458
+ var path3 = __importStar(__require("path"));
6459
+ var collectorVersion_1 = require_collectorVersion();
6460
+ var hookRunner_1 = require_hookRunner();
6461
+ var tokenStore_1 = require_tokenStore();
6462
+ function pluginBundlePaths(name) {
6463
+ const base = path3.join((0, tokenStore_1.ascendaHome)(), "plugin", name);
6464
+ return { bundle: `${base}.mjs`, version: `${base}.version`, checked: `${base}.checked` };
6465
+ }
6466
+ function installPluginBundle(options) {
6467
+ const paths = pluginBundlePaths(options.name);
6468
+ const source = path3.resolve(options.source ?? process.argv[1]);
6469
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
6470
+ const installed = readVersion(paths.version);
6471
+ const present = fs2.existsSync(paths.bundle);
6472
+ if (source === path3.resolve(paths.bundle))
6473
+ return { kind: "current", version: installed ?? incoming };
6474
+ if (present && installed && (0, hookRunner_1.isDowngrade)(installed, incoming))
6475
+ return { kind: "kept-newer", installed, incoming };
6476
+ const contents = fs2.readFileSync(source);
6477
+ if (present && installed === incoming && contents.equals(fs2.readFileSync(paths.bundle))) {
6478
+ return { kind: "current", version: incoming };
6479
+ }
6480
+ fs2.mkdirSync(path3.dirname(paths.bundle), { recursive: true });
6481
+ (0, hookRunner_1.writeAtomically)(paths.bundle, contents, 420);
6482
+ (0, hookRunner_1.writeAtomically)(paths.version, `${incoming}
6483
+ `, 420);
6484
+ return present && installed ? { kind: "installed", version: incoming, replaced: installed } : { kind: "installed", version: incoming };
6485
+ }
6486
+ function describePluginBundleOutcome(outcome, bundle) {
6487
+ switch (outcome.kind) {
6488
+ case "installed":
6489
+ 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}`;
6490
+ case "current":
6491
+ return `The plugin's bundle is already ${outcome.version}: ${bundle}`;
6492
+ case "kept-newer":
6493
+ return `Kept the plugin's bundle at ${outcome.installed}. This copy is the older ${outcome.incoming}.`;
6494
+ }
6495
+ }
6496
+ function readVersion(file) {
6497
+ try {
6498
+ return fs2.readFileSync(file, "utf8").trim() || void 0;
6499
+ } catch {
6500
+ return void 0;
6501
+ }
6502
+ }
6503
+ }
6504
+ });
6505
+
5595
6506
  // ../packages/tool-kit/out/agentProcess.js
5596
6507
  var require_agentProcess = __commonJS({
5597
6508
  "../packages/tool-kit/out/agentProcess.js"(exports) {
@@ -5640,14 +6551,14 @@ var require_agentProcess = __commonJS({
5640
6551
  exports.findAgentPid = findAgentPid2;
5641
6552
  exports.livePidFields = livePidFields;
5642
6553
  var child_process_1 = __require("child_process");
5643
- var path2 = __importStar(__require("path"));
6554
+ var path3 = __importStar(__require("path"));
5644
6555
  exports.AGENT_PROCESS = {
5645
6556
  claude_code: {
5646
- executable: (command) => path2.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
6557
+ executable: (command) => path3.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
5647
6558
  scriptMarkers: ["@anthropic-ai/claude-code"]
5648
6559
  },
5649
6560
  codex: {
5650
- executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path2.basename(command)),
6561
+ executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path3.basename(command)),
5651
6562
  args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
5652
6563
  },
5653
6564
  gemini_cli: {
@@ -5701,7 +6612,7 @@ var require_agentProcess = __commonJS({
5701
6612
  if (rule.executable(info.command)) {
5702
6613
  return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
5703
6614
  }
5704
- if (markers.length > 0 && SCRIPT_RUNTIME.test(path2.basename(info.command))) {
6615
+ if (markers.length > 0 && SCRIPT_RUNTIME.test(path3.basename(info.command))) {
5705
6616
  const args = argsLookup(pid);
5706
6617
  const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
5707
6618
  if (marker !== void 0) {
@@ -5736,10 +6647,11 @@ var require_out3 = __commonJS({
5736
6647
  "../packages/tool-kit/out/index.js"(exports) {
5737
6648
  "use strict";
5738
6649
  Object.defineProperty(exports, "__esModule", { value: true });
5739
- 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;
5740
- 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;
5741
- 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;
5742
- 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;
6650
+ 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;
6651
+ 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;
6652
+ 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;
6653
+ 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;
6654
+ 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;
5743
6655
  var commandClassifier_1 = require_commandClassifier();
5744
6656
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5745
6657
  return commandClassifier_1.classifyCommand;
@@ -5758,9 +6670,16 @@ var require_out3 = __commonJS({
5758
6670
  Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
5759
6671
  return workMilestoneClassifier_1.classifyWorkMilestone;
5760
6672
  } });
6673
+ Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
6674
+ return workMilestoneClassifier_1.classifyMcpWorkMilestone;
6675
+ } });
5761
6676
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
5762
6677
  return workMilestoneClassifier_1.invitesDebrief;
5763
6678
  } });
6679
+ var shellFacts_1 = require_shellFacts();
6680
+ Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
6681
+ return shellFacts_1.shellCommandFacts;
6682
+ } });
5764
6683
  var autonomyBand_1 = require_autonomyBand();
5765
6684
  Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
5766
6685
  return autonomyBand_1.autonomyBand;
@@ -5830,6 +6749,28 @@ var require_out3 = __commonJS({
5830
6749
  Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
5831
6750
  return collectorVersion_1.describeCollectorVersion;
5832
6751
  } });
6752
+ var backgroundDelivery_1 = require_backgroundDelivery();
6753
+ Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
6754
+ return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
6755
+ } });
6756
+ Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
6757
+ return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
6758
+ } });
6759
+ Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
6760
+ return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
6761
+ } });
6762
+ Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
6763
+ return backgroundDelivery_1.flushLockPath;
6764
+ } });
6765
+ Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
6766
+ return backgroundDelivery_1.hookDeliveryInline;
6767
+ } });
6768
+ Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
6769
+ return backgroundDelivery_1.runOutboxFlush;
6770
+ } });
6771
+ Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
6772
+ return backgroundDelivery_1.startBackgroundFlush;
6773
+ } });
5833
6774
  var eventSender_1 = require_eventSender();
5834
6775
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
5835
6776
  return eventSender_1.AscendaEventSender;
@@ -5888,9 +6829,18 @@ var require_out3 = __commonJS({
5888
6829
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
5889
6830
  return hookAdapter_1.deliverHookEvents;
5890
6831
  } });
6832
+ Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
6833
+ return hookAdapter_1.flushHookOutbox;
6834
+ } });
5891
6835
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
5892
6836
  return hookAdapter_1.loadCliAgentConfig;
5893
6837
  } });
6838
+ Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
6839
+ return hookAdapter_1.withForgeKeys;
6840
+ } });
6841
+ Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
6842
+ return hookAdapter_1.withPromptId;
6843
+ } });
5894
6844
  Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
5895
6845
  return hookAdapter_1.resolveCliAgentInstallationId;
5896
6846
  } });
@@ -5907,12 +6857,18 @@ var require_out3 = __commonJS({
5907
6857
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
5908
6858
  return cliAgentSetup_1.isCliAgentManagementCommand;
5909
6859
  } });
6860
+ Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
6861
+ return cliAgentSetup_1.ourHookPositions;
6862
+ } });
5910
6863
  Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5911
6864
  return cliAgentSetup_1.registeredHookSets;
5912
6865
  } });
5913
6866
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
5914
6867
  return cliAgentSetup_1.runCliAgentSetup;
5915
6868
  } });
6869
+ Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
6870
+ return cliAgentSetup_1.trustProblemLines;
6871
+ } });
5916
6872
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
5917
6873
  return cliAgentSetup_1.writeHookSettings;
5918
6874
  } });
@@ -5954,6 +6910,9 @@ var require_out3 = __commonJS({
5954
6910
  Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
5955
6911
  return credentials_1.writeEventLogSetting;
5956
6912
  } });
6913
+ Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
6914
+ return credentials_1.writeRepoKeysSetting;
6915
+ } });
5957
6916
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5958
6917
  return credentials_1.writeMachineCredentials;
5959
6918
  } });
@@ -5964,6 +6923,9 @@ var require_out3 = __commonJS({
5964
6923
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
5965
6924
  return turnState_1.consumeTurnDurationMs;
5966
6925
  } });
6926
+ Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
6927
+ return turnState_1.readTurnPromptId;
6928
+ } });
5967
6929
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
5968
6930
  return turnState_1.recordTurnStart;
5969
6931
  } });
@@ -6098,6 +7060,12 @@ var require_out3 = __commonJS({
6098
7060
  Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
6099
7061
  return forgeProject_1.forgeProjectHash;
6100
7062
  } });
7063
+ Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
7064
+ return forgeProject_1.forgeRepoKey;
7065
+ } });
7066
+ Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
7067
+ return forgeProject_1.forgeBranchKey;
7068
+ } });
6101
7069
  Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
6102
7070
  return forgeProject_1.parseForgeFullName;
6103
7071
  } });
@@ -6110,6 +7078,16 @@ var require_out3 = __commonJS({
6110
7078
  Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
6111
7079
  return forgeProject_1.recordForgeProjectAlias;
6112
7080
  } });
7081
+ var forgeKeys_1 = require_forgeKeys();
7082
+ Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
7083
+ return forgeKeys_1.REPO_KEYS_ENV_VAR;
7084
+ } });
7085
+ Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
7086
+ return forgeKeys_1.deriveForgeKeysForCwd;
7087
+ } });
7088
+ Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
7089
+ return forgeKeys_1.repoKeysEnabled;
7090
+ } });
6113
7091
  var liveBus_1 = require_liveBus();
6114
7092
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
6115
7093
  return liveBus_1.emitLiveSignal;
@@ -6180,6 +7158,9 @@ var require_out3 = __commonJS({
6180
7158
  Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
6181
7159
  return hookRunner_1.installHookRunner;
6182
7160
  } });
7161
+ Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
7162
+ return hookRunner_1.isDowngrade;
7163
+ } });
6183
7164
  Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
6184
7165
  return hookRunner_1.lastHookPath;
6185
7166
  } });
@@ -6198,6 +7179,23 @@ var require_out3 = __commonJS({
6198
7179
  Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
6199
7180
  return hookRunner_1.tidyHomePath;
6200
7181
  } });
7182
+ Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
7183
+ return hookRunner_1.writeAtomically;
7184
+ } });
7185
+ var settingsFile_1 = require_settingsFile();
7186
+ Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
7187
+ return settingsFile_1.replaceSettingsFile;
7188
+ } });
7189
+ var pluginBundle_1 = require_pluginBundle();
7190
+ Object.defineProperty(exports, "describePluginBundleOutcome", { enumerable: true, get: function() {
7191
+ return pluginBundle_1.describePluginBundleOutcome;
7192
+ } });
7193
+ Object.defineProperty(exports, "installPluginBundle", { enumerable: true, get: function() {
7194
+ return pluginBundle_1.installPluginBundle;
7195
+ } });
7196
+ Object.defineProperty(exports, "pluginBundlePaths", { enumerable: true, get: function() {
7197
+ return pluginBundle_1.pluginBundlePaths;
7198
+ } });
6201
7199
  var liveSignalDoctor_1 = require_liveSignalDoctor();
6202
7200
  Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
6203
7201
  return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
@@ -6381,6 +7379,12 @@ function mapEvent(hookName, input, turnDurationMs) {
6381
7379
  // the count is that a gate was reached, when, and in which session.
6382
7380
  case "PermissionRequest":
6383
7381
  return [{ eventType: "supervision_interruption", severity: "low", metadata: withHost({ interruptionKind: "permission_request" }) }];
7382
+ // Codex 0.146 and later. The session is over, whatever the `reason`: Codex
7383
+ // sends "other" for every ending today, so it is carried only as the
7384
+ // catalog's own word and never branched on. Same row as Claude Code's
7385
+ // `SessionEnd`, so the two sum.
7386
+ case "SessionEnd":
7387
+ return mapSessionEnd(input);
6384
7388
  // The subagent lifecycle is still deliberately unmapped: it is not an
6385
7389
  // interruption of the person, and it is out of scope here.
6386
7390
  case "SubagentStart":
@@ -6395,6 +7399,17 @@ function mapSessionStart(input) {
6395
7399
  if (source && source !== "startup" && source !== "resume") return [];
6396
7400
  return [{ eventType: "create_focus_session", severity: "low", metadata: withHost({ activity: "session_started", ...autonomyModeMetadata(input) }) }];
6397
7401
  }
7402
+ function mapSessionEnd(input) {
7403
+ const raw = input["reason"];
7404
+ return [{
7405
+ eventType: "recovery_offline_period",
7406
+ severity: "low",
7407
+ metadata: withHost({
7408
+ activity: "session_ended",
7409
+ ...raw === void 0 || raw === null ? {} : { sessionEndReason: classifySessionEndReason(raw) }
7410
+ })
7411
+ }];
7412
+ }
6398
7413
  function mapUserPromptSubmit(input) {
6399
7414
  const prompt = (0, import_tool_kit.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit.getNestedString)(input, [["payload", "prompt"]]);
6400
7415
  const autonomy = autonomyModeMetadata(input);
@@ -6408,10 +7423,10 @@ function mapPostToolUse(input) {
6408
7423
  const toolName = getToolName(input);
6409
7424
  const safeToolName = sanitiseToolName(toolName);
6410
7425
  const outcome = (0, import_tool_kit.inferOutcome)(input);
6411
- const command = (0, import_tool_kit.getString)(input, ["command"]) ?? (0, import_tool_kit.getNestedString)(input, [["tool_input", "command"], ["input", "command"]]);
7426
+ const command = getCommand(input);
6412
7427
  const commandClass = (0, import_tool_kit.classifyCommand)(command);
6413
7428
  const lowered = toolName?.toLowerCase();
6414
- const isShell = lowered === "bash" || lowered === "shell" || lowered === "local_shell";
7429
+ const isShell = lowered === "bash" || lowered === "shell" || lowered === "local_shell" || lowered === "exec_command" || lowered === "shell_command";
6415
7430
  const autonomy = autonomyModeMetadata(input);
6416
7431
  if (outcome === "failure") {
6417
7432
  if (isShell && (0, import_tool_kit.isVerificationCommand)(commandClass)) {
@@ -6425,7 +7440,8 @@ function mapPostToolUse(input) {
6425
7440
  if (isShell && (0, import_tool_kit.isVerificationCommand)(commandClass)) {
6426
7441
  return [{ eventType: "editor_verification_activity", severity: "low", metadata: withHost({ toolName: safeToolName, commandClass, outcome, activity: "ai_test_or_build_run", ...autonomy }) }];
6427
7442
  }
6428
- return [{ eventType: "ai_tool_call_completed", severity: "low", metadata: withHost({ toolName: safeToolName, commandClass, outcome, ...autonomy }) }];
7443
+ const facts = isShell && outcome === "success" ? (0, import_tool_kit.shellCommandFacts)(command) : {};
7444
+ return [{ eventType: "ai_tool_call_completed", severity: "low", metadata: withHost({ toolName: safeToolName, commandClass, outcome, ...facts, ...autonomy }) }];
6429
7445
  }
6430
7446
  function mapPreCompact(input) {
6431
7447
  const trigger = (0, import_tool_kit.getString)(input, ["trigger", "reason"]);
@@ -6468,8 +7484,32 @@ var AUTONOMY_BY_PERMISSION_MODE = {
6468
7484
  dontask: "dont_ask",
6469
7485
  bypasspermissions: "bypass_permissions"
6470
7486
  };
7487
+ var SESSION_END_REASONS = ["clear", "resume", "logout", "prompt_input_exit", "other"];
7488
+ function classifySessionEndReason(raw) {
7489
+ if (typeof raw !== "string") return "unknown";
7490
+ const value = raw.trim().toLowerCase();
7491
+ return SESSION_END_REASONS.includes(value) ? value : "unknown";
7492
+ }
6471
7493
  function getToolName(input) {
6472
- return (0, import_tool_kit.getString)(input, ["tool_name", "toolName", "name"]);
7494
+ return (0, import_tool_kit.getString)(input, ["tool_name", "toolName", "name"])?.replace(/^functions\./i, "");
7495
+ }
7496
+ function getCommand(input) {
7497
+ const direct = (0, import_tool_kit.getString)(input, ["command"]);
7498
+ if (direct !== void 0) return unwrapShell(direct);
7499
+ const toolInput = (0, import_tool_kit.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit.getNested)(input, ["input"]);
7500
+ if (!toolInput || typeof toolInput !== "object") return void 0;
7501
+ const raw = toolInput["command"] ?? toolInput["cmd"];
7502
+ if (typeof raw === "string") return unwrapShell(raw);
7503
+ if (Array.isArray(raw) && raw.every((word) => typeof word === "string")) {
7504
+ const argv = raw;
7505
+ const script = argv.length >= 3 && /^-[a-z]*c$/i.test(argv[1]) ? argv[argv.length - 1] : argv.join(" ");
7506
+ return unwrapShell(script);
7507
+ }
7508
+ return void 0;
7509
+ }
7510
+ function unwrapShell(command) {
7511
+ const wrapped = /^\s*(?:\S*\/)?(?:ba|z|da)?sh\s+-[a-z]*c\s+(["'])([\s\S]*)\1\s*$/i.exec(command);
7512
+ return wrapped ? wrapped[2] : command;
6473
7513
  }
6474
7514
  function sanitiseToolName(toolName) {
6475
7515
  if (!toolName) return "unknown";
@@ -6497,6 +7537,11 @@ function liveSignalFor(hookName, input) {
6497
7537
  return { event: "stop" };
6498
7538
  case "PermissionRequest":
6499
7539
  return { event: "awaiting" };
7540
+ // Closing Codex mid-turn runs no `Stop`, so without this the session held
7541
+ // its level until it went stale. A `halted` never creates a session and is
7542
+ // ignored for one that already stopped.
7543
+ case "SessionEnd":
7544
+ return { event: "halted" };
6500
7545
  default:
6501
7546
  return void 0;
6502
7547
  }
@@ -6504,7 +7549,66 @@ function liveSignalFor(hookName, input) {
6504
7549
 
6505
7550
  // src/setup.ts
6506
7551
  import * as os from "os";
7552
+ import * as path2 from "path";
7553
+
7554
+ // src/hookTrust.ts
7555
+ import * as fs from "fs";
6507
7556
  import * as path from "path";
7557
+ var HEADER = /^\s*\[\s*hooks\s*\.\s*state\s*\.\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*\]/;
7558
+ function parseApprovalKeys(toml) {
7559
+ const keys = [];
7560
+ for (const line of toml.split(/\r?\n/)) {
7561
+ const match = HEADER.exec(line);
7562
+ if (!match) continue;
7563
+ const quoted = match[1];
7564
+ const key = quoted.startsWith("'") ? quoted.slice(1, -1) : unescapeBasicString(quoted.slice(1, -1));
7565
+ const parts = /^(.*):([^:]+):(\d+):(\d+)$/.exec(key);
7566
+ if (!parts) continue;
7567
+ keys.push({ file: parts[1], event: parts[2], group: Number(parts[3]), handler: Number(parts[4]) });
7568
+ }
7569
+ return keys;
7570
+ }
7571
+ function unescapeBasicString(value) {
7572
+ return value.replace(/\\(["\\])/g, "$1");
7573
+ }
7574
+ var eventId = (event) => event.toLowerCase().replace(/[^a-z]/g, "");
7575
+ var fileId = (file) => {
7576
+ const slashed = file.replace(/\\/g, "/");
7577
+ return process.platform === "win32" || /^[A-Za-z]:\//.test(slashed) ? slashed.toLowerCase() : slashed;
7578
+ };
7579
+ function checkCodexHookTrust(settingsFile, ours) {
7580
+ const approvalsFile = path.join(path.dirname(settingsFile), "config.toml");
7581
+ let toml = "";
7582
+ try {
7583
+ toml = fs.readFileSync(approvalsFile, "utf8");
7584
+ } catch (error) {
7585
+ if (error.code !== "ENOENT") return { approvalsFile, untrusted: [], stale: [], unreadable: true };
7586
+ }
7587
+ const here = fileId(path.resolve(settingsFile));
7588
+ const keys = parseApprovalKeys(toml).filter((key) => fileId(key.file) === here);
7589
+ const approved = (position) => keys.some((key) => eventId(key.event) === eventId(position.event) && key.group === position.group && key.handler === position.handler);
7590
+ const untrusted = ours.filter((position) => !approved(position));
7591
+ const ourEvents = new Set(ours.map((position) => eventId(position.event)));
7592
+ const stale = [];
7593
+ for (const key of keys) {
7594
+ if (!ourEvents.has(eventId(key.event))) continue;
7595
+ if (ours.some((position) => eventId(position.event) === eventId(key.event) && position.group === key.group && position.handler === key.handler)) continue;
7596
+ stale.push(`An approval for ${key.event} (group ${key.group}, handler ${key.handler}) points at a hook that has moved or gone.`);
7597
+ }
7598
+ if (untrusted.length === 0 && stale.length === 0 && changedAfterApproval(settingsFile, approvalsFile)) {
7599
+ stale.push("The hooks file was changed after the last approval was recorded, so a changed command may be waiting for re-approval.");
7600
+ }
7601
+ return { approvalsFile, untrusted, stale };
7602
+ }
7603
+ function changedAfterApproval(hooksFile, approvalsFile) {
7604
+ try {
7605
+ return fs.statSync(hooksFile).mtimeMs > fs.statSync(approvalsFile).mtimeMs;
7606
+ } catch {
7607
+ return false;
7608
+ }
7609
+ }
7610
+
7611
+ // src/setup.ts
6508
7612
  var HOOK_EVENTS = [
6509
7613
  "SessionStart",
6510
7614
  "UserPromptSubmit",
@@ -6513,9 +7617,17 @@ var HOOK_EVENTS = [
6513
7617
  "PreCompact",
6514
7618
  "PostCompact",
6515
7619
  "Stop",
6516
- "PermissionRequest"
7620
+ "PermissionRequest",
7621
+ // Codex 0.146 and later; an older Codex ignores an event it doesn't know.
7622
+ "SessionEnd"
6517
7623
  ];
6518
7624
  var HOOK_TIMEOUT_SECONDS = 10;
7625
+ function codexHome() {
7626
+ const configured = process.env.CODEX_HOME?.trim();
7627
+ return configured ? path2.resolve(configured) : path2.join(os.homedir(), ".codex");
7628
+ }
7629
+ var SESSION_END_TIMEOUT_SECONDS = 3;
7630
+ var hookTimeoutSeconds = (event) => event === "SessionEnd" ? SESSION_END_TIMEOUT_SECONDS : HOOK_TIMEOUT_SECONDS;
6519
7631
  var SETUP = {
6520
7632
  host: CODEX_HOST,
6521
7633
  displayName: "Codex CLI",
@@ -6524,25 +7636,30 @@ var SETUP = {
6524
7636
  binaryName: "ascenda-codex-hook",
6525
7637
  hookEvents: HOOK_EVENTS,
6526
7638
  restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not run them.",
6527
- // Codex reports the posture it was working under and its approval gate; it
6528
- // sends no model, no git action and no per-file change size.
6529
- sends: ["posture", "waiting"],
7639
+ // Codex reports the posture it was working under, its approval gate, and
7640
+ // the git action or milestone a shell command reached. It sends no model and
7641
+ // no per-file change size.
7642
+ sends: ["posture", "waiting", "git", "turns", "forge"],
7643
+ trust: {
7644
+ check: checkCodexHookTrust,
7645
+ fix: "Restart Codex and open /hooks, then approve the Ascenda hooks. A hook whose command changed needs approving again."
7646
+ },
6530
7647
  settings: {
6531
- settingsPath: (scope, projectDir) => scope === "user" ? path.join(os.homedir(), ".codex", "hooks.json") : path.join(projectDir, ".codex", "hooks.json"),
7648
+ settingsPath: (scope, projectDir) => scope === "user" ? path2.join(codexHome(), "hooks.json") : path2.join(projectDir, ".codex", "hooks.json"),
6532
7649
  // Codex nests as Gemini does — each event maps to an array of
6533
7650
  // { hooks: [{ type, command }] } — but reads the event from argv rather
6534
7651
  // than stdin, so unlike Gemini the name has to be on the command line.
6535
- entry: (command, event) => ({ hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }),
6536
- commandOf: (entry) => {
6537
- const group = entry;
6538
- const command = group?.hooks?.find((hook) => typeof hook?.command === "string")?.command;
6539
- return typeof command === "string" ? command : void 0;
6540
- }
7652
+ entry: (command, event) => ({ hooks: [{ type: "command", command: `${command} ${event}`, timeout: hookTimeoutSeconds(event) }] }),
7653
+ grouped: true
6541
7654
  }
6542
7655
  };
6543
7656
 
6544
7657
  // src/cli.ts
6545
7658
  async function main() {
7659
+ if (process.argv[2] === import_tool_kit3.OUTBOX_FLUSH_COMMAND) {
7660
+ await (0, import_tool_kit3.flushHookOutbox)({ toolType: ASCENDA_TOOL_TYPE, host: CODEX_HOST, source: "cli_agent" });
7661
+ return;
7662
+ }
6546
7663
  const command = process.argv[2];
6547
7664
  if ((0, import_tool_kit3.isCliAgentManagementCommand)(command)) {
6548
7665
  managementExitCode = await (0, import_tool_kit3.runCliAgentSetup)(process.argv.slice(2), SETUP);
@@ -6557,8 +7674,10 @@ async function main() {
6557
7674
  const sessionId = typeof input.session_id === "string" ? input.session_id : void 0;
6558
7675
  let turnDurationMs;
6559
7676
  (0, import_tool_kit3.stampLastHook)(CODEX_HOST, hookName);
6560
- if (hookName === "UserPromptSubmit") (0, import_tool_kit3.recordTurnStart)(CODEX_HOST, sessionId);
7677
+ const promptId = hookName === "UserPromptSubmit" ? (0, import_tool_kit3.recordTurnStart)(CODEX_HOST, sessionId) : (0, import_tool_kit3.readTurnPromptId)(CODEX_HOST, sessionId);
6561
7678
  if (hookName === "Stop") turnDurationMs = (0, import_tool_kit3.consumeTurnDurationMs)(CODEX_HOST, sessionId);
7679
+ const workDir = typeof input.cwd === "string" ? input.cwd : void 0;
7680
+ if (hookName === "SessionEnd") process.env.ASCENDA_HTTP_TIMEOUT_MS ??= "1500";
6562
7681
  await emitLive(hookName, input, sessionId);
6563
7682
  await (0, import_tool_kit3.deliverHookEvents)(mapCodexEvent(hookName, input, turnDurationMs), {
6564
7683
  toolType: ASCENDA_TOOL_TYPE,
@@ -6566,6 +7685,9 @@ async function main() {
6566
7685
  setupCommand: `npx ${SETUP.packageName} setup`,
6567
7686
  source: "cli_agent",
6568
7687
  sessionId,
7688
+ promptId,
7689
+ cwd: workDir,
7690
+ forgeKeys: true,
6569
7691
  onNotice: emitSystemMessage
6570
7692
  });
6571
7693
  }