@ascenda-one/agent-mcp 0.1.35 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +1716 -822
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -153,25 +153,66 @@ var require_gitActionClassifier = __commonJS({
153
153
  if (!/\bgit\b/.test(value))
154
154
  return void 0;
155
155
  const heads = (0, commandHeads_1.commandHeads)(value);
156
- if (heads.some((h) => /^git\s+commit\b/.test(h) && /\s--amend\b/.test(h)))
156
+ const commands = heads.map(parseGitCommand).filter((c) => c !== void 0);
157
+ if (commands.some((c) => c.verb === "commit" && c.args.includes("--amend")))
157
158
  return "amend";
158
- if (heads.some((h) => /^git\s+revert\b/.test(h)))
159
+ if (commands.some((c) => c.verb === "revert"))
159
160
  return "revert";
160
- if (heads.some((h) => /^git\s+reset\b/.test(h) && /\s--hard\b/.test(h)))
161
+ if (commands.some((c) => c.verb === "reset" && c.args.includes("--hard")))
161
162
  return "reset_hard";
162
- if (heads.some((h) => /^git\s+restore\b/.test(h) && !/\s--staged\b/.test(h)))
163
+ if (commands.some(discardsWork))
163
164
  return "restore";
164
- if (heads.some((h) => /^git\s+checkout\b.*\s--\s/.test(h)))
165
- return "restore";
166
- if (heads.some((h) => /^git\s+push\b/.test(h)))
165
+ if (commands.some((c) => c.verb === "push"))
167
166
  return "push";
168
- if (heads.some((h) => /^git\s+commit\b/.test(h)))
167
+ if (commands.some((c) => c.verb === "commit"))
169
168
  return "commit";
170
169
  return void 0;
171
170
  }
172
171
  function isReworkGitAction(action) {
173
172
  return action === "revert" || action === "reset_hard" || action === "restore";
174
173
  }
174
+ var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path"]);
175
+ function parseGitCommand(head) {
176
+ const words = head.split(/\s+/);
177
+ if (words[0] !== "git")
178
+ return void 0;
179
+ let i = 1;
180
+ while (i < words.length && words[i].startsWith("-")) {
181
+ i += GLOBAL_OPTIONS_WITH_VALUE.has(words[i]) ? 2 : 1;
182
+ }
183
+ if (i >= words.length)
184
+ return void 0;
185
+ return { verb: words[i], args: words.slice(i + 1) };
186
+ }
187
+ function discardsWork({ verb, args }) {
188
+ switch (verb) {
189
+ case "restore":
190
+ return !args.includes("--staged");
191
+ case "switch":
192
+ return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
193
+ case "clean": {
194
+ const flags = args.filter((a) => /^-[a-z]+$/.test(a)).join("");
195
+ const dryRun = args.includes("--dry-run") || flags.includes("n");
196
+ return !dryRun && (args.includes("--force") || flags.includes("f"));
197
+ }
198
+ case "checkout":
199
+ return checkoutDiscards(args);
200
+ default:
201
+ return false;
202
+ }
203
+ }
204
+ function checkoutDiscards(args) {
205
+ if (args.includes("--"))
206
+ return true;
207
+ if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
208
+ return false;
209
+ const words = args.filter((a) => !a.startsWith("-"));
210
+ if (words.length >= 2)
211
+ return true;
212
+ if (words.length === 1)
213
+ return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
214
+ return false;
215
+ }
175
216
  }
176
217
  });
177
218
 
@@ -182,6 +223,7 @@ var require_workMilestoneClassifier = __commonJS({
182
223
  Object.defineProperty(exports, "__esModule", { value: true });
183
224
  exports.classifyWorkMilestone = classifyWorkMilestone;
184
225
  exports.invitesDebrief = invitesDebrief;
226
+ exports.classifyMcpWorkMilestone = classifyMcpWorkMilestone;
185
227
  var commandHeads_1 = require_commandHeads();
186
228
  function classifyWorkMilestone(command) {
187
229
  if (!command)
@@ -201,6 +243,41 @@ var require_workMilestoneClassifier = __commonJS({
201
243
  function invitesDebrief(kind) {
202
244
  return kind === "pr_merged" || kind === "issue_closed";
203
245
  }
246
+ function classifyMcpWorkMilestone(toolName) {
247
+ if (!toolName)
248
+ return void 0;
249
+ const parts = toolName.toLowerCase().split("__");
250
+ if (parts[0] !== "mcp" || parts.length < 3)
251
+ return void 0;
252
+ const tool = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
253
+ if (/^(merge|accept)(pullrequest|mergerequest)$/.test(tool))
254
+ return "pr_merged";
255
+ if (/^closeissue$/.test(tool))
256
+ return "issue_closed";
257
+ if (/^(create|open)(pullrequest|mergerequest)$/.test(tool))
258
+ return "pr_opened";
259
+ return void 0;
260
+ }
261
+ }
262
+ });
263
+
264
+ // ../packages/tool-kit/out/shellFacts.js
265
+ var require_shellFacts = __commonJS({
266
+ "../packages/tool-kit/out/shellFacts.js"(exports) {
267
+ "use strict";
268
+ Object.defineProperty(exports, "__esModule", { value: true });
269
+ exports.shellCommandFacts = shellCommandFacts;
270
+ var gitActionClassifier_1 = require_gitActionClassifier();
271
+ var workMilestoneClassifier_1 = require_workMilestoneClassifier();
272
+ function shellCommandFacts(command) {
273
+ const gitAction = (0, gitActionClassifier_1.classifyGitAction)(command);
274
+ const milestoneKind = (0, workMilestoneClassifier_1.classifyWorkMilestone)(command);
275
+ return {
276
+ ...gitAction !== void 0 ? { gitAction } : {},
277
+ ...(0, gitActionClassifier_1.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
278
+ ...milestoneKind !== void 0 ? { milestoneKind } : {}
279
+ };
280
+ }
204
281
  }
205
282
  });
206
283
 
@@ -594,6 +671,61 @@ var require_metricKeys = __commonJS({
594
671
  subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
595
672
  subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
596
673
  subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
674
+ advisorMessageCount: {
675
+ family: "counts",
676
+ readBy: ["diagnostic"],
677
+ note: "Claude Code only: advisor calls (a second model consulted inside one API message). Their tokens and models are already folded into the session totals and model mix, and this is the receipt for how much of that they are."
678
+ },
679
+ advisorTokensTotal: {
680
+ family: "context",
681
+ readBy: ["diagnostic"],
682
+ unit: "tokens",
683
+ note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
684
+ },
685
+ cacheCreationTokens: {
686
+ family: "context",
687
+ readBy: ["diagnostic"],
688
+ unit: "tokens",
689
+ note: "Prompt-cache writes, summed once per API message. Absent where the store never wrote the figure, which is not the same as none written."
690
+ },
691
+ cacheCreation5mTokens: {
692
+ family: "context",
693
+ readBy: ["diagnostic"],
694
+ unit: "tokens",
695
+ note: "The part of cacheCreationTokens written with the 5-minute lifetime. Absent on transcripts that only record the total."
696
+ },
697
+ cacheCreation1hTokens: {
698
+ family: "context",
699
+ readBy: ["diagnostic"],
700
+ unit: "tokens",
701
+ note: "The part of cacheCreationTokens written with the 1-hour lifetime. Absent on transcripts that only record the total."
702
+ },
703
+ headlessPromptLines: {
704
+ family: "reading",
705
+ readBy: ["diagnostic"],
706
+ unit: "lines",
707
+ note: "Claude Code only: user lines written by the Agent SDK or a headless run (entrypoint sdk-*). Nobody typed them, so promptCount leaves them out. Counted once per line across the store."
708
+ },
709
+ tokensNotCollected: {
710
+ family: "context",
711
+ readBy: ["diagnostic"],
712
+ note: "True when the store recorded no token figures for this session (Cursor builds that write a zero tokenCount, Codex rollouts from before token_count events). The token keys are then left off the event instead of being sent as 0, so absent and zero stay apart. Metrics are flat scalars with no null, so a flag beside the missing keys is the marker the contract allows."
713
+ },
714
+ unattributedSubagentTranscripts: {
715
+ family: "reading",
716
+ readBy: ["diagnostic"],
717
+ note: "Claude Code only: flat subagent transcripts whose lines name no parent session, so they could not be folded anywhere."
718
+ },
719
+ duplicateChatSessions: {
720
+ family: "reading",
721
+ readBy: ["diagnostic"],
722
+ note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
723
+ },
724
+ sessionsStartedFromBubble: {
725
+ family: "reading",
726
+ readBy: ["diagnostic"],
727
+ note: "Cursor only: sessions whose start is the earliest message rather than the header's createdAt, which can sit months before anyone typed."
728
+ },
597
729
  toolName: {
598
730
  family: "tools",
599
731
  readBy: ["backend"],
@@ -701,7 +833,9 @@ var require_out = __commonJS({
701
833
  exports.COLLABORATION_EVENT_TYPES = [
702
834
  "review_requested_of_me",
703
835
  "review_given",
704
- "pull_request_opened"
836
+ "pull_request_opened",
837
+ "pull_request_closed",
838
+ "pull_request_merged"
705
839
  ];
706
840
  exports.EVENT_METADATA_DISCLOSURE = {
707
841
  language: "edits",
@@ -713,6 +847,13 @@ var require_out = __commonJS({
713
847
  gitAction: "git",
714
848
  milestoneKind: "git",
715
849
  branchHash: "repo",
850
+ repoKey: "forge",
851
+ headRepoKey: "forge",
852
+ prCreatedAt: "git",
853
+ prClosedAt: "git",
854
+ prMergedAt: "git",
855
+ branchKey: "forge",
856
+ promptId: "turns",
716
857
  autonomyMode: "posture",
717
858
  modelClass: "model",
718
859
  modelId: "model",
@@ -762,6 +903,13 @@ var require_out = __commonJS({
762
903
  "gitAction",
763
904
  "milestoneKind",
764
905
  "branchHash",
906
+ "repoKey",
907
+ "headRepoKey",
908
+ "prCreatedAt",
909
+ "prClosedAt",
910
+ "prMergedAt",
911
+ "branchKey",
912
+ "promptId",
765
913
  "autonomyMode",
766
914
  "modelClass",
767
915
  "modelId",
@@ -831,6 +979,10 @@ var require_out = __commonJS({
831
979
  review_requested_of_me: "supervision",
832
980
  review_given: "supervision",
833
981
  pull_request_opened: "creation",
982
+ // Where a pull request of yours ended up. A boundary like a turn ending, not
983
+ // work in itself, so neutral: it must not weigh on any workload leg.
984
+ pull_request_closed: "neutral",
985
+ pull_request_merged: "neutral",
834
986
  context_pressure_high: "risk",
835
987
  agent_loop_long: "risk",
836
988
  after_hours_ai_session: "risk",
@@ -861,6 +1013,16 @@ var require_out = __commonJS({
861
1013
  // step toward an interruption count becoming a score, a streak, or something
862
1014
  // that fires on a miss. It must never become any of those.
863
1015
  supervision_interruption: "supervision",
1016
+ // The agent asked to run a tool, and the auto-mode classifier refused one.
1017
+ // Claude Code's `PermissionRequest` and `PermissionDenied` hooks. Neutral,
1018
+ // because the Notification for the same prompt is already counted above as
1019
+ // `supervision_interruption`, and counting both would weigh one prompt
1020
+ // twice. These rows exist for the public event stream: which tool asked, and
1021
+ // under which posture. `permission_requested` fires before the person
1022
+ // answers and no hook reports their answer, so neither event says whether
1023
+ // the request was granted.
1024
+ permission_requested: "neutral",
1025
+ permission_denied: "neutral",
864
1026
  // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
865
1027
  approach_churn_detected: "risk",
866
1028
  goal_drift_detected: "risk",
@@ -985,122 +1147,13 @@ var require_collectorVersion = __commonJS({
985
1147
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
986
1148
  exports.describeCollectorVersion = describeCollectorVersion;
987
1149
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
988
- exports.COLLECTOR_VERSION = "0.1.35" ? "0.1.35" : exports.UNRELEASED_COLLECTOR_VERSION;
1150
+ exports.COLLECTOR_VERSION = "0.1.36" ? "0.1.36" : exports.UNRELEASED_COLLECTOR_VERSION;
989
1151
  function describeCollectorVersion(version2 = exports.COLLECTOR_VERSION) {
990
1152
  return version2 === exports.UNRELEASED_COLLECTOR_VERSION ? `${version2} (built from a checkout, not a release)` : version2;
991
1153
  }
992
1154
  }
993
1155
  });
994
1156
 
995
- // ../packages/agent-events/out/index.js
996
- var require_out2 = __commonJS({
997
- "../packages/agent-events/out/index.js"(exports) {
998
- "use strict";
999
- Object.defineProperty(exports, "__esModule", { value: true });
1000
- exports.KNOWN_AGENTS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1001
- exports.isAgentEventV0 = isAgentEventV0;
1002
- exports.parseEventLogLine = parseEventLogLine;
1003
- exports.normaliseKind = normaliseKind;
1004
- exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1005
- exports.AGENT_EVENT_KINDS = [
1006
- "session.started",
1007
- "session.ended",
1008
- "prompt.submitted",
1009
- "tool.started",
1010
- "tool.completed",
1011
- "tool.failed",
1012
- "turn.completed",
1013
- "agent.waiting",
1014
- "context.compacted",
1015
- "subagent.started",
1016
- "subagent.stopped",
1017
- "other"
1018
- ];
1019
- exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1020
- function isAgentEventV0(value) {
1021
- if (!value || typeof value !== "object")
1022
- return false;
1023
- const e = value;
1024
- 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";
1025
- }
1026
- function parseEventLogLine(line) {
1027
- if (!line.trim())
1028
- return void 0;
1029
- try {
1030
- const parsed = JSON.parse(line);
1031
- return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1032
- } catch {
1033
- return void 0;
1034
- }
1035
- }
1036
- function normaliseKind(kind) {
1037
- return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1038
- }
1039
- }
1040
- });
1041
-
1042
- // ../packages/tool-kit/out/agentEvent.js
1043
- var require_agentEvent = __commonJS({
1044
- "../packages/tool-kit/out/agentEvent.js"(exports) {
1045
- "use strict";
1046
- Object.defineProperty(exports, "__esModule", { value: true });
1047
- exports.toAgentEvent = toAgentEvent;
1048
- var agent_events_1 = require_out2();
1049
- var KIND_BY_TYPE = {
1050
- create_focus_session: "session.started",
1051
- recovery_offline_period: "session.ended",
1052
- ai_prompt_submitted: "prompt.submitted",
1053
- ai_tool_call_started: "tool.started",
1054
- ai_tool_call_completed: "tool.completed",
1055
- ai_file_write: "tool.completed",
1056
- ai_file_edit: "tool.completed",
1057
- editor_verification_activity: "tool.completed",
1058
- ai_tool_call_failed: "tool.failed",
1059
- compile_error: "tool.failed",
1060
- tool_failure: "tool.failed",
1061
- ai_turn_completed: "turn.completed",
1062
- supervision_interruption: "agent.waiting",
1063
- context_compression_manual: "context.compacted",
1064
- context_compression_auto: "context.compacted",
1065
- subagent_started: "subagent.started",
1066
- subagent_stopped: "subagent.stopped"
1067
- };
1068
- function agentOf(payload) {
1069
- const host = stringField(payload.metadata?.host);
1070
- if (host)
1071
- return host;
1072
- return payload.source === "vscode_extension" ? "vscode" : payload.source;
1073
- }
1074
- function stringField(value) {
1075
- return typeof value === "string" && value.length > 0 ? value : void 0;
1076
- }
1077
- function toAgentEvent(payload) {
1078
- const metadata = payload.metadata ?? {};
1079
- const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1080
- const tool = kind.startsWith("tool.") ? stringField(metadata.toolName) : void 0;
1081
- const outcome = stringField(metadata.outcome);
1082
- return {
1083
- schema: agent_events_1.AGENT_EVENT_SCHEMA,
1084
- id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1085
- time: payload.occurredAt,
1086
- // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1087
- // writes anyway; without it the event in memory and the one on disk differ.
1088
- ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1089
- agent: agentOf(payload),
1090
- kind,
1091
- ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1092
- ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1093
- ...tool ? { tool } : {},
1094
- ...outcome && outcome !== "unknown" ? { outcome } : {},
1095
- ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1096
- ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1097
- ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1098
- sourceType: payload.eventType
1099
- };
1100
- }
1101
- }
1102
- });
1103
-
1104
1157
  // ../packages/tool-kit/out/tokenStore.js
1105
1158
  var require_tokenStore = __commonJS({
1106
1159
  "../packages/tool-kit/out/tokenStore.js"(exports) {
@@ -1239,9 +1292,9 @@ var require_tokenStore = __commonJS({
1239
1292
  }
1240
1293
  });
1241
1294
 
1242
- // ../packages/tool-kit/out/credentials.js
1243
- var require_credentials = __commonJS({
1244
- "../packages/tool-kit/out/credentials.js"(exports) {
1295
+ // ../packages/tool-kit/out/stateStore.js
1296
+ var require_stateStore = __commonJS({
1297
+ "../packages/tool-kit/out/stateStore.js"(exports) {
1245
1298
  "use strict";
1246
1299
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1247
1300
  if (k2 === void 0) k2 = k;
@@ -1281,94 +1334,124 @@ var require_credentials = __commonJS({
1281
1334
  };
1282
1335
  }();
1283
1336
  Object.defineProperty(exports, "__esModule", { value: true });
1284
- exports.credentialsFilePath = credentialsFilePath;
1285
- exports.readMachineCredentials = readMachineCredentials;
1286
- exports.writeMachineCredentials = writeMachineCredentials;
1287
- exports.writeTopLevelCredentials = writeTopLevelCredentials;
1288
- exports.writeEventLogSetting = writeEventLogSetting;
1289
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
1290
- exports.readHostCredentials = readHostCredentials;
1291
- exports.writeHostCredentials = writeHostCredentials;
1292
- exports.removeHostCredentials = removeHostCredentials;
1337
+ exports.defaultStateFilePath = defaultStateFilePath;
1338
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
1339
+ exports.unresolvedStateFilePath = unresolvedStateFilePath;
1340
+ exports.readCollectorState = readCollectorState;
1341
+ exports.recordSendOutcome = recordSendOutcome;
1342
+ exports.recordOutboxDiscard = recordOutboxDiscard;
1343
+ exports.shouldAnnounceFailure = shouldAnnounceFailure;
1344
+ exports.markFailureNotified = markFailureNotified;
1293
1345
  var fs = __importStar(__require("fs"));
1294
1346
  var path = __importStar(__require("path"));
1295
1347
  var tokenStore_1 = require_tokenStore();
1296
- function credentialsFilePath() {
1297
- return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1348
+ function defaultStateFilePath(toolInstallationId) {
1349
+ const dir = process.env.ASCENDA_STATE_DIR?.trim();
1350
+ const base = dir ? dir : path.join((0, tokenStore_1.ascendaHome)(), "state");
1351
+ return path.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1298
1352
  }
1299
- function readMachineCredentials() {
1353
+ function unresolvedToolInstallationId(toolType) {
1354
+ return `${toolType}:unresolved`;
1355
+ }
1356
+ function unresolvedStateFilePath(toolType) {
1357
+ return defaultStateFilePath(unresolvedToolInstallationId(toolType));
1358
+ }
1359
+ function readCollectorState(stateFilePath) {
1300
1360
  try {
1301
- const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
1361
+ if (!fs.existsSync(stateFilePath))
1362
+ return void 0;
1363
+ const raw = fs.readFileSync(stateFilePath, "utf8").trim();
1302
1364
  if (!raw)
1303
1365
  return void 0;
1304
1366
  const parsed = JSON.parse(raw);
1305
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1367
+ if (!parsed || typeof parsed !== "object")
1306
1368
  return void 0;
1307
1369
  return parsed;
1308
1370
  } catch {
1309
1371
  return void 0;
1310
1372
  }
1311
1373
  }
1312
- function writeMachineCredentials(credentials) {
1313
- const file = credentialsFilePath();
1314
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
1315
- fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
1316
- `, { encoding: "utf8", mode: 384 });
1317
- if (process.platform !== "win32") {
1318
- fs.chmodSync(path.dirname(file), 448);
1319
- fs.chmodSync(file, 384);
1320
- }
1321
- }
1322
- function writeTopLevelCredentials(credentials) {
1323
- const existing = readMachineCredentials();
1324
- const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
1325
- writeMachineCredentials({
1326
- ...credentials,
1327
- ...eventLogPath ? { eventLogPath } : {},
1328
- ...existing?.tools ? { tools: existing.tools } : {}
1329
- });
1374
+ function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1375
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1376
+ const previous = readCollectorState(stateFilePath);
1377
+ const accepted = outcome === "accepted";
1378
+ const next = {
1379
+ toolInstallationId,
1380
+ lastAttemptAt: now,
1381
+ lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1382
+ lastOutcome: outcome,
1383
+ consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1384
+ ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1385
+ ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1386
+ ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1387
+ // A success closes the episode; a failure either opens one or continues
1388
+ // the one already open. Carrying `notifiedFailingSince` across a
1389
+ // continuing episode is what keeps the notice to once per outage.
1390
+ ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1391
+ ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1392
+ // Cumulative by design: a send outcome, success included, never erases
1393
+ // the record of what the outbox had to throw away.
1394
+ ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1395
+ };
1396
+ writeStateFile(stateFilePath, next);
1397
+ return next;
1330
1398
  }
1331
- function writeEventLogSetting(value) {
1332
- const existing = readMachineCredentials() ?? {};
1333
- writeMachineCredentials({ ...existing, eventLogPath: value });
1399
+ function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1400
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1401
+ const previous = readCollectorState(stateFilePath);
1402
+ const next = {
1403
+ ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1404
+ toolInstallationId,
1405
+ lastOutcome: "outbox_discarded",
1406
+ outboxDiscarded: {
1407
+ total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1408
+ lastAt: now,
1409
+ lastCount: discard.count,
1410
+ lastReasons: discard.reasons,
1411
+ ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1412
+ }
1413
+ };
1414
+ writeStateFile(stateFilePath, next);
1415
+ return next;
1334
1416
  }
1335
- function isLocalOnlyHostInstall(host, hasToken) {
1336
- const credentials = readHostCredentials(host);
1337
- if (!credentials?.localOnly)
1338
- return false;
1339
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
1417
+ function shouldAnnounceFailure(state) {
1418
+ if (!state || state.consecutiveFailures === 0 || !state.failingSince)
1340
1419
  return false;
1341
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1420
+ return state.notifiedFailingSince !== state.failingSince;
1342
1421
  }
1343
- function readHostCredentials(host) {
1344
- const entry = readMachineCredentials()?.tools?.[host];
1345
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
1346
- return void 0;
1347
- return entry;
1422
+ function markFailureNotified(stateFilePath, state) {
1423
+ if (!state.failingSince)
1424
+ return;
1425
+ writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
1348
1426
  }
1349
- function writeHostCredentials(host, credentials) {
1350
- const existing = readMachineCredentials() ?? {};
1351
- writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1427
+ function writeStateFile(stateFilePath, state) {
1428
+ const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1429
+ try {
1430
+ const dir = path.dirname(stateFilePath);
1431
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
1432
+ fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1433
+ `, { encoding: "utf8", mode: 384 });
1434
+ fs.renameSync(temporaryPath, stateFilePath);
1435
+ if (process.platform !== "win32")
1436
+ fs.chmodSync(stateFilePath, 384);
1437
+ } catch {
1438
+ try {
1439
+ if (fs.existsSync(temporaryPath))
1440
+ fs.unlinkSync(temporaryPath);
1441
+ } catch {
1442
+ }
1443
+ }
1352
1444
  }
1353
- function removeHostCredentials(host) {
1354
- const existing = readMachineCredentials();
1355
- if (!existing?.tools || !(host in existing.tools))
1356
- return;
1357
- const tools = { ...existing.tools };
1358
- delete tools[host];
1359
- const next = { ...existing };
1360
- if (Object.keys(tools).length)
1361
- next.tools = tools;
1362
- else
1363
- delete next.tools;
1364
- writeMachineCredentials(next);
1445
+ function truncate(value) {
1446
+ const collapsed = value.replace(/\s+/g, " ").trim();
1447
+ return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
1365
1448
  }
1366
1449
  }
1367
1450
  });
1368
1451
 
1369
- // ../packages/tool-kit/out/eventLog.js
1370
- var require_eventLog = __commonJS({
1371
- "../packages/tool-kit/out/eventLog.js"(exports) {
1452
+ // ../packages/tool-kit/out/outbox.js
1453
+ var require_outbox = __commonJS({
1454
+ "../packages/tool-kit/out/outbox.js"(exports) {
1372
1455
  "use strict";
1373
1456
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1374
1457
  if (k2 === void 0) k2 = k;
@@ -1408,354 +1491,492 @@ var require_eventLog = __commonJS({
1408
1491
  };
1409
1492
  }();
1410
1493
  Object.defineProperty(exports, "__esModule", { value: true });
1411
- exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
1412
- exports.expandUserPath = expandUserPath;
1413
- exports.defaultEventLogPath = defaultEventLogPath;
1414
- exports.resolveEventLog = resolveEventLog;
1415
- exports.resolveEventLogPath = resolveEventLogPath;
1416
- exports.describeEventLog = describeEventLog;
1417
- exports.parseEventLogFlag = parseEventLogFlag;
1418
- exports.appendEventLog = appendEventLog;
1494
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1495
+ exports.outboxDrainEnabled = outboxDrainEnabled;
1496
+ exports.defaultOutboxFilePath = defaultOutboxFilePath;
1497
+ exports.appendToOutbox = appendToOutbox;
1498
+ exports.readOutboxSummary = readOutboxSummary;
1499
+ exports.claimOutbox = claimOutbox;
1500
+ exports.enforceOutboxBounds = enforceOutboxBounds;
1419
1501
  var fs = __importStar(__require("fs"));
1420
- var os = __importStar(__require("os"));
1421
1502
  var path = __importStar(__require("path"));
1422
- var agentEvent_1 = require_agentEvent();
1423
- var credentials_1 = require_credentials();
1503
+ var stateStore_1 = require_stateStore();
1424
1504
  var tokenStore_1 = require_tokenStore();
1425
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1426
- exports.EVENT_LOG_OFF = "off";
1427
- var MAX_BYTES = 5 * 1024 * 1024;
1428
- function expandUserPath(configured) {
1429
- const value = configured?.trim();
1430
- if (!value)
1431
- return void 0;
1432
- if (value === "~")
1433
- return os.homedir();
1434
- if (value.startsWith("~/"))
1435
- return path.join(os.homedir(), value.slice(2));
1436
- return path.resolve(value);
1437
- }
1438
- function defaultEventLogPath() {
1439
- return path.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1440
- }
1441
- function resolveEventLog(options = {}) {
1442
- for (const [source, raw] of [
1443
- ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
1444
- ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
1445
- ]) {
1446
- const value = raw?.trim();
1447
- if (!value)
1448
- continue;
1449
- if (value.toLowerCase() === exports.EVENT_LOG_OFF)
1450
- return { path: void 0, source: "disabled" };
1451
- return { path: expandUserPath(value), source };
1452
- }
1453
- if (options.localOnly)
1454
- return { path: defaultEventLogPath(), source: "unpaired-default" };
1455
- return { path: void 0, source: "off" };
1456
- }
1457
- function resolveEventLogPath(options = {}) {
1458
- return resolveEventLog(options).path;
1459
- }
1460
- function describeEventLog(setting, command) {
1461
- switch (setting.source) {
1462
- case "env":
1463
- return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
1464
- case "credentials":
1465
- return `${setting.path} (set by ${command} --event-log)`;
1466
- case "unpaired-default":
1467
- return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
1468
- case "disabled":
1469
- return `off (turned off; ${command} --event-log to turn it on)`;
1470
- case "off":
1471
- return `off (${command} --event-log to keep a local copy of every event)`;
1472
- }
1505
+ exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1506
+ exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1507
+ exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1508
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1509
+ var ORPHANED_CLAIM_AGE_MS = 6e4;
1510
+ var CLAIM_SUFFIX = ".draining";
1511
+ function outboxDrainEnabled(env = process.env) {
1512
+ const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1513
+ if (value === void 0 || value === "")
1514
+ return true;
1515
+ return !(value === "0" || value === "false" || value === "no" || value === "off");
1473
1516
  }
1474
- function parseEventLogFlag(argv, index) {
1475
- const peek = argv[index + 1];
1476
- if (peek !== void 0 && !peek.startsWith("-"))
1477
- return { value: peek, consumed: 1 };
1478
- return { value: defaultEventLogPath(), consumed: 0 };
1517
+ function defaultOutboxFilePath(toolInstallationId) {
1518
+ const dir = path.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1519
+ return path.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1479
1520
  }
1480
- function appendEventLog(logFilePath, entry) {
1521
+ function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1481
1522
  try {
1482
- rotateIfLarge(logFilePath);
1483
- const dir = path.dirname(logFilePath);
1523
+ const dir = path.dirname(outboxFilePath);
1484
1524
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1485
- const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
1486
- fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
1525
+ const entry = { queuedAt: now.toISOString(), payload };
1526
+ fs.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1487
1527
  `, { encoding: "utf8", mode: 384 });
1488
1528
  if (process.platform !== "win32")
1489
- fs.chmodSync(logFilePath, 384);
1529
+ fs.chmodSync(outboxFilePath, 384);
1530
+ return true;
1490
1531
  } catch {
1532
+ return false;
1491
1533
  }
1492
1534
  }
1493
- function rotateIfLarge(logFilePath) {
1535
+ function readOutboxSummary(outboxFilePath) {
1536
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs.existsSync(file));
1537
+ if (files.length === 0)
1538
+ return void 0;
1539
+ let depth = 0;
1540
+ let unreadableLines = 0;
1541
+ let oldestQueuedAt;
1542
+ for (const file of files) {
1543
+ const { entries, unreadable } = readEntries(file);
1544
+ depth += entries.length;
1545
+ unreadableLines += unreadable;
1546
+ for (const entry of entries) {
1547
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1548
+ oldestQueuedAt = entry.queuedAt;
1549
+ }
1550
+ }
1551
+ return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1552
+ }
1553
+ function claimOutbox(outboxFilePath, now = Date.now()) {
1554
+ const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1555
+ const claimed = [];
1494
1556
  try {
1495
- if (fs.statSync(logFilePath).size < MAX_BYTES)
1496
- return;
1497
- fs.renameSync(logFilePath, `${logFilePath}.1`);
1557
+ fs.renameSync(outboxFilePath, claimPath);
1558
+ claimed.push(claimPath);
1498
1559
  } catch {
1499
1560
  }
1500
- }
1501
- }
1502
- });
1503
-
1504
- // ../packages/tool-kit/out/http.js
1505
- var require_http = __commonJS({
1506
- "../packages/tool-kit/out/http.js"(exports) {
1507
- "use strict";
1508
- Object.defineProperty(exports, "__esModule", { value: true });
1509
- exports.AscendaApiError = void 0;
1510
- exports.createPairingSession = createPairingSession;
1511
- exports.getPairingStatus = getPairingStatus;
1512
- exports.startStudyJoin = startStudyJoin;
1513
- exports.getStudyJoinStatus = getStudyJoinStatus;
1514
- exports.readInitiatives = readInitiatives;
1515
- exports.readStudyNotices = readStudyNotices;
1516
- exports.setStudyObjection = setStudyObjection;
1517
- exports.markStudyNoticeShown = markStudyNoticeShown;
1518
- exports.renewToolToken = renewToolToken;
1519
- exports.isRetryableStatus = isRetryableStatus;
1520
- exports.postToolEvent = postToolEvent;
1521
- exports.postToolEventsBatch = postToolEventsBatch;
1522
- exports.parseIngestResponse = parseIngestResponse;
1523
- var tool_contract_1 = require_out();
1524
- var AscendaApiError = class extends Error {
1525
- status;
1526
- errorCode;
1527
- constructor(status, errorCode, body) {
1528
- super(body ?? `Ascenda API error ${status}`);
1529
- this.status = status;
1530
- this.errorCode = errorCode;
1531
- this.name = "AscendaApiError";
1561
+ let orphanIndex = 0;
1562
+ for (const orphan of listClaimFiles(outboxFilePath)) {
1563
+ if (claimed.includes(orphan))
1564
+ continue;
1565
+ try {
1566
+ if (now - fs.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1567
+ continue;
1568
+ const mine = `${claimPath}.${orphanIndex++}`;
1569
+ fs.renameSync(orphan, mine);
1570
+ claimed.push(mine);
1571
+ } catch {
1572
+ }
1532
1573
  }
1533
- };
1534
- exports.AscendaApiError = AscendaApiError;
1535
- async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
1536
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1537
- method: "POST",
1538
- headers: { "Content-Type": "application/json" },
1539
- body: JSON.stringify({ toolInstallationId, toolType, displayName })
1540
- });
1541
- if (!response.ok)
1542
- throw new AscendaApiError(response.status, void 0, await response.text());
1543
- return await response.json();
1544
- }
1545
- async function getPairingStatus(apiBaseUrl, pairingSessionId) {
1546
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1547
- method: "GET",
1548
- headers: { Accept: "application/json" }
1549
- });
1550
- if (!response.ok)
1551
- throw new AscendaApiError(response.status, void 0, await response.text());
1552
- return await response.json();
1574
+ if (claimed.length === 0)
1575
+ return void 0;
1576
+ const entries = [];
1577
+ let unreadable = 0;
1578
+ for (const file of claimed) {
1579
+ const read = readEntries(file);
1580
+ entries.push(...read.entries);
1581
+ unreadable += read.unreadable;
1582
+ }
1583
+ entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1584
+ let released = false;
1585
+ return {
1586
+ entries,
1587
+ unreadable,
1588
+ release(remainder) {
1589
+ if (released)
1590
+ return;
1591
+ released = true;
1592
+ if (remainder.length > 0) {
1593
+ try {
1594
+ fs.mkdirSync(path.dirname(outboxFilePath), { recursive: true, mode: 448 });
1595
+ fs.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1596
+ `).join(""), { encoding: "utf8", mode: 384 });
1597
+ if (process.platform !== "win32")
1598
+ fs.chmodSync(outboxFilePath, 384);
1599
+ } catch {
1600
+ return;
1601
+ }
1602
+ }
1603
+ for (const file of claimed) {
1604
+ try {
1605
+ fs.unlinkSync(file);
1606
+ } catch {
1607
+ }
1608
+ }
1609
+ }
1610
+ };
1553
1611
  }
1554
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1555
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1556
- method: "POST",
1557
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1558
- body: JSON.stringify({ joinCode, mode })
1559
- });
1560
- if (!response.ok)
1561
- throw await apiError(response);
1562
- return await response.json();
1612
+ function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1613
+ const reasons = {};
1614
+ let oldestQueuedAt;
1615
+ const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1616
+ const fresh = [];
1617
+ for (const entry of entries) {
1618
+ if (entry.queuedAt < cutoff) {
1619
+ reasons.age = (reasons.age ?? 0) + 1;
1620
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1621
+ oldestQueuedAt = entry.queuedAt;
1622
+ } else {
1623
+ fresh.push(entry);
1624
+ }
1625
+ }
1626
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1627
+ if (excess > 0) {
1628
+ reasons.count = excess;
1629
+ const first = fresh[0]?.queuedAt;
1630
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1631
+ oldestQueuedAt = first;
1632
+ }
1633
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1634
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1635
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1563
1636
  }
1564
- async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1565
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1566
- method: "GET",
1567
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1568
- });
1569
- if (!response.ok)
1570
- throw await apiError(response);
1571
- return await response.json();
1637
+ function listClaimFiles(outboxFilePath) {
1638
+ const dir = path.dirname(outboxFilePath);
1639
+ const prefix = `${path.basename(outboxFilePath)}.`;
1640
+ try {
1641
+ return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
1642
+ } catch {
1643
+ return [];
1644
+ }
1572
1645
  }
1573
- async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1574
- let response;
1646
+ function readEntries(file) {
1647
+ let raw;
1575
1648
  try {
1576
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1577
- method: "GET",
1578
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1579
- signal
1580
- });
1581
- } catch (error2) {
1582
- return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1649
+ raw = fs.readFileSync(file, "utf8");
1650
+ } catch {
1651
+ return { entries: [], unreadable: 0 };
1583
1652
  }
1584
- if (response.status === 401)
1585
- return { kind: "rejected", httpStatus: 401 };
1586
- if (!response.ok)
1587
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1588
- let body;
1653
+ const entries = [];
1654
+ let unreadable = 0;
1655
+ for (const line of raw.split("\n")) {
1656
+ if (!line.trim())
1657
+ continue;
1658
+ try {
1659
+ const parsed = JSON.parse(line);
1660
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1661
+ unreadable += 1;
1662
+ continue;
1663
+ }
1664
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1665
+ } catch {
1666
+ unreadable += 1;
1667
+ }
1668
+ }
1669
+ return { entries, unreadable };
1670
+ }
1671
+ }
1672
+ });
1673
+
1674
+ // ../packages/tool-kit/out/backgroundDelivery.js
1675
+ var require_backgroundDelivery = __commonJS({
1676
+ "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
1677
+ "use strict";
1678
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1679
+ if (k2 === void 0) k2 = k;
1680
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1681
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1682
+ desc = { enumerable: true, get: function() {
1683
+ return m[k];
1684
+ } };
1685
+ }
1686
+ Object.defineProperty(o, k2, desc);
1687
+ } : function(o, m, k, k2) {
1688
+ if (k2 === void 0) k2 = k;
1689
+ o[k2] = m[k];
1690
+ });
1691
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1692
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1693
+ } : function(o, v) {
1694
+ o["default"] = v;
1695
+ });
1696
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1697
+ var ownKeys = function(o) {
1698
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1699
+ var ar = [];
1700
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1701
+ return ar;
1702
+ };
1703
+ return ownKeys(o);
1704
+ };
1705
+ return function(mod) {
1706
+ if (mod && mod.__esModule) return mod;
1707
+ var result = {};
1708
+ if (mod != null) {
1709
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1710
+ }
1711
+ __setModuleDefault(result, mod);
1712
+ return result;
1713
+ };
1714
+ }();
1715
+ Object.defineProperty(exports, "__esModule", { value: true });
1716
+ exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
1717
+ exports.hookDeliveryInline = hookDeliveryInline;
1718
+ exports.flushLockPath = flushLockPath;
1719
+ exports.startBackgroundFlush = startBackgroundFlush;
1720
+ exports.runOutboxFlush = runOutboxFlush;
1721
+ var fs = __importStar(__require("fs"));
1722
+ var child_process_1 = __require("child_process");
1723
+ var outbox_1 = require_outbox();
1724
+ exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
1725
+ exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
1726
+ exports.FLUSH_LOCK_FRESH_MS = 2e4;
1727
+ var FLUSH_MAX_PASSES = 20;
1728
+ var FLUSH_MAX_RUN_MS = 6e4;
1729
+ function hookDeliveryInline(env = process.env) {
1730
+ return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
1731
+ }
1732
+ function flushLockPath(outboxFilePath) {
1733
+ return `${outboxFilePath}.flushing`;
1734
+ }
1735
+ function lockIsFresh(lockPath, now) {
1589
1736
  try {
1590
- body = await response.json();
1737
+ return now - fs.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1591
1738
  } catch {
1592
- return { kind: "failed", reason: "the reply was not readable" };
1739
+ return false;
1593
1740
  }
1594
- if (!Array.isArray(body))
1595
- return { kind: "failed", reason: "the reply was not a list" };
1596
- return { kind: "ok", initiatives: body };
1597
1741
  }
1598
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1599
- let response;
1742
+ function touchLock(lockPath) {
1600
1743
  try {
1601
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1602
- method: "GET",
1603
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1604
- signal
1605
- });
1606
- } catch (error2) {
1607
- return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1744
+ fs.writeFileSync(lockPath, `${process.pid}
1745
+ `, { encoding: "utf8", mode: 384 });
1746
+ } catch {
1608
1747
  }
1609
- if (response.status === 404)
1610
- return { kind: "absent" };
1611
- if (response.status === 401)
1612
- return { kind: "rejected", httpStatus: 401 };
1613
- if (!response.ok)
1614
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1615
- let body;
1748
+ }
1749
+ function removeLock(lockPath) {
1616
1750
  try {
1617
- body = await response.json();
1751
+ fs.unlinkSync(lockPath);
1618
1752
  } catch {
1619
- return { kind: "absent" };
1620
1753
  }
1621
- if (!Array.isArray(body))
1622
- return { kind: "absent" };
1623
- return { kind: "ok", notices: body };
1624
1754
  }
1625
- async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1626
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1627
- method: objected ? "POST" : "DELETE",
1628
- headers: { Authorization: `Bearer ${eventWriteToken}` }
1629
- });
1630
- if (!response.ok)
1631
- throw await apiError(response);
1755
+ function outboxHasEntries(outboxFilePath) {
1756
+ try {
1757
+ return fs.statSync(outboxFilePath).size > 0;
1758
+ } catch {
1759
+ return false;
1760
+ }
1632
1761
  }
1633
- async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1762
+ function startBackgroundFlush(options) {
1763
+ const lockPath = flushLockPath(options.outboxFilePath);
1764
+ const now = options.now ?? Date.now();
1765
+ if (lockIsFresh(lockPath, now))
1766
+ return false;
1767
+ const script = options.script ?? process.argv[1];
1768
+ if (!script)
1769
+ return false;
1634
1770
  try {
1635
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1636
- method: "POST",
1637
- headers: { Authorization: `Bearer ${eventWriteToken}` },
1638
- signal
1771
+ touchLock(lockPath);
1772
+ const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
1773
+ detached: true,
1774
+ stdio: "ignore",
1775
+ windowsHide: true,
1776
+ env: process.env
1639
1777
  });
1640
- return response.ok;
1778
+ child.on("error", () => removeLock(lockPath));
1779
+ child.unref();
1780
+ return true;
1641
1781
  } catch {
1782
+ removeLock(lockPath);
1642
1783
  return false;
1643
1784
  }
1644
1785
  }
1645
- async function apiError(response) {
1646
- const body = await response.text();
1647
- let errorCode;
1786
+ async function runOutboxFlush(sender, now = Date.now) {
1787
+ const outboxFilePath = sender.outboxFilePath();
1788
+ const lockPath = flushLockPath(outboxFilePath);
1789
+ const started = now();
1790
+ let last;
1791
+ let passes = 0;
1792
+ const drain = async () => {
1793
+ while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
1794
+ passes += 1;
1795
+ touchLock(lockPath);
1796
+ last = await sender.flushOutbox();
1797
+ if (!last || last.found === 0 || last.halted || !last.sendEnabled)
1798
+ return;
1799
+ if (last.delivered === 0 && last.discarded === 0)
1800
+ return;
1801
+ }
1802
+ };
1648
1803
  try {
1649
- const parsed = JSON.parse(body);
1650
- errorCode = parsed.code ?? parsed.error;
1804
+ await drain();
1805
+ removeLock(lockPath);
1806
+ if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
1807
+ touchLock(lockPath);
1808
+ await drain();
1809
+ removeLock(lockPath);
1810
+ }
1651
1811
  } catch {
1652
- errorCode = void 0;
1812
+ removeLock(lockPath);
1653
1813
  }
1654
- return new AscendaApiError(response.status, errorCode, body);
1655
- }
1656
- async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1657
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1658
- method: "POST",
1659
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1660
- signal
1661
- });
1662
- if (response.status === 401)
1663
- return null;
1664
- if (!response.ok)
1665
- throw new AscendaApiError(response.status, void 0, await response.text());
1666
- return await response.json();
1814
+ return last;
1667
1815
  }
1668
- function isDeliveredStatus(value) {
1669
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1816
+ }
1817
+ });
1818
+
1819
+ // ../packages/agent-events/out/index.js
1820
+ var require_out2 = __commonJS({
1821
+ "../packages/agent-events/out/index.js"(exports) {
1822
+ "use strict";
1823
+ Object.defineProperty(exports, "__esModule", { value: true });
1824
+ exports.KNOWN_AGENTS = exports.WAIT_REASONS = exports.VCS_ACTIONS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1825
+ exports.isAgentEventV0 = isAgentEventV0;
1826
+ exports.parseEventLogLine = parseEventLogLine;
1827
+ exports.normaliseKind = normaliseKind;
1828
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1829
+ exports.AGENT_EVENT_KINDS = [
1830
+ "session.started",
1831
+ "session.ended",
1832
+ "prompt.submitted",
1833
+ "tool.started",
1834
+ "tool.completed",
1835
+ "tool.failed",
1836
+ "turn.completed",
1837
+ "agent.waiting",
1838
+ "permission.requested",
1839
+ "permission.denied",
1840
+ "context.compacted",
1841
+ "subagent.started",
1842
+ "subagent.stopped",
1843
+ "pull_request.opened",
1844
+ "pull_request.closed",
1845
+ "pull_request.merged",
1846
+ "other"
1847
+ ];
1848
+ exports.VCS_ACTIONS = ["commit", "push", "pr_created", "pr_merged"];
1849
+ exports.WAIT_REASONS = ["permission", "idle", "input", "other"];
1850
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1851
+ function isAgentEventV0(value) {
1852
+ if (!value || typeof value !== "object")
1853
+ return false;
1854
+ const e = value;
1855
+ return e.schema === exports.AGENT_EVENT_SCHEMA && typeof e.id === "string" && e.id.length > 0 && typeof e.time === "string" && !Number.isNaN(Date.parse(e.time)) && typeof e.agent === "string" && e.agent.length > 0 && typeof e.kind === "string";
1670
1856
  }
1671
- function readSuccessBody(body) {
1672
- let parsed;
1857
+ function parseEventLogLine(line) {
1858
+ if (!line.trim())
1859
+ return void 0;
1673
1860
  try {
1674
- parsed = JSON.parse(body);
1861
+ const parsed = JSON.parse(line);
1862
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1675
1863
  } catch {
1676
- return { duplicates: 0 };
1677
- }
1678
- if (!parsed || typeof parsed !== "object")
1679
- return { duplicates: 0 };
1680
- const single = parsed.status;
1681
- if (isDeliveredStatus(single))
1682
- return { duplicates: single === "duplicate" ? 1 : 0 };
1683
- const raw = parsed.results;
1684
- if (!Array.isArray(raw))
1685
- return { duplicates: 0 };
1686
- const results = [];
1687
- for (const item of raw) {
1688
- if (!item || typeof item !== "object")
1689
- continue;
1690
- const { index, status, reason } = item;
1691
- if (typeof index !== "number" || typeof status !== "string")
1692
- continue;
1693
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1864
+ return void 0;
1694
1865
  }
1695
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1696
- }
1697
- function isRetryableStatus(status) {
1698
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1699
1866
  }
1700
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1701
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1867
+ function normaliseKind(kind) {
1868
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1702
1869
  }
1703
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1704
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1870
+ }
1871
+ });
1872
+
1873
+ // ../packages/tool-kit/out/agentEvent.js
1874
+ var require_agentEvent = __commonJS({
1875
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1876
+ "use strict";
1877
+ Object.defineProperty(exports, "__esModule", { value: true });
1878
+ exports.toAgentEvent = toAgentEvent;
1879
+ var agent_events_1 = require_out2();
1880
+ var KIND_BY_TYPE = {
1881
+ create_focus_session: "session.started",
1882
+ recovery_offline_period: "session.ended",
1883
+ ai_prompt_submitted: "prompt.submitted",
1884
+ ai_tool_call_started: "tool.started",
1885
+ ai_tool_call_completed: "tool.completed",
1886
+ ai_file_write: "tool.completed",
1887
+ ai_file_edit: "tool.completed",
1888
+ editor_verification_activity: "tool.completed",
1889
+ ai_tool_call_failed: "tool.failed",
1890
+ compile_error: "tool.failed",
1891
+ tool_failure: "tool.failed",
1892
+ ai_turn_completed: "turn.completed",
1893
+ supervision_interruption: "agent.waiting",
1894
+ permission_requested: "permission.requested",
1895
+ permission_denied: "permission.denied",
1896
+ context_compression_manual: "context.compacted",
1897
+ context_compression_auto: "context.compacted",
1898
+ subagent_started: "subagent.started",
1899
+ subagent_stopped: "subagent.stopped",
1900
+ pull_request_opened: "pull_request.opened",
1901
+ pull_request_closed: "pull_request.closed",
1902
+ pull_request_merged: "pull_request.merged"
1903
+ };
1904
+ function agentOf(payload) {
1905
+ const host = stringField(payload.metadata?.host);
1906
+ if (host)
1907
+ return host;
1908
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1705
1909
  }
1706
- async function sendIngest(url, eventWriteToken, body, signal) {
1707
- try {
1708
- const response = await fetch(url, {
1709
- method: "POST",
1710
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1711
- body,
1712
- signal
1713
- });
1714
- return parseIngestResponse(response);
1715
- } catch (error2) {
1716
- return {
1717
- result: "transport_error",
1718
- detail: error2 instanceof Error ? `${error2.name}: ${error2.message}` : String(error2)
1719
- };
1910
+ function vcsActionOf(metadata) {
1911
+ const milestone = stringField(metadata.milestoneKind);
1912
+ if (milestone === "pr_opened")
1913
+ return "pr_created";
1914
+ if (milestone === "pr_merged")
1915
+ return "pr_merged";
1916
+ const git = stringField(metadata.gitAction);
1917
+ return git === "commit" || git === "push" ? git : void 0;
1918
+ }
1919
+ function waitReasonOf(metadata) {
1920
+ switch (stringField(metadata.interruptionKind)) {
1921
+ case "permission_request":
1922
+ return "permission";
1923
+ case "input_request":
1924
+ return "input";
1925
+ case "idle_prompt":
1926
+ return "idle";
1927
+ case void 0:
1928
+ return void 0;
1929
+ default:
1930
+ return "other";
1720
1931
  }
1721
1932
  }
1722
- async function parseIngestResponse(response) {
1723
- if (response.ok) {
1724
- const outcome = { result: "accepted", httpStatus: response.status };
1725
- let read = { duplicates: 0 };
1726
- try {
1727
- read = readSuccessBody(await response.text());
1728
- } catch {
1729
- read = { duplicates: 0 };
1730
- }
1731
- return {
1732
- ...outcome,
1733
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1734
- ...read.results !== void 0 ? { results: read.results } : {}
1735
- };
1736
- }
1737
- const body = await response.text();
1738
- let errorCode;
1739
- try {
1740
- errorCode = JSON.parse(body).error;
1741
- } catch {
1742
- errorCode = void 0;
1743
- }
1744
- const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
1745
- if (response.status === 401)
1746
- return { ...base, result: "auth_failed" };
1747
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1748
- return { ...base, result: "consent_missing" };
1749
- if (response.status === 400 || response.status === 422)
1750
- return { ...base, result: "validation_failed" };
1751
- return { ...base, result: "transport_error" };
1933
+ function stringField(value) {
1934
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1935
+ }
1936
+ function toAgentEvent(payload) {
1937
+ const metadata = payload.metadata ?? {};
1938
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1939
+ const tool = kind.startsWith("tool.") || kind.startsWith("permission.") ? stringField(metadata.toolName) : void 0;
1940
+ const outcome = stringField(metadata.outcome);
1941
+ const vcsAction = kind === "tool.completed" ? vcsActionOf(metadata) : void 0;
1942
+ const reason = kind === "agent.waiting" ? waitReasonOf(metadata) : void 0;
1943
+ const model = kind === "session.started" ? stringField(metadata.modelId) : void 0;
1944
+ return {
1945
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1946
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1947
+ time: payload.occurredAt,
1948
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1949
+ // writes anyway; without it the event in memory and the one on disk differ.
1950
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1951
+ agent: agentOf(payload),
1952
+ kind,
1953
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1954
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1955
+ ...tool ? { tool } : {},
1956
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1957
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1958
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1959
+ ...stringField(metadata.repoKey) ? { repoKey: metadata.repoKey } : {},
1960
+ ...stringField(metadata.branchKey) ? { branchKey: metadata.branchKey } : {},
1961
+ ...stringField(metadata.autonomyMode) ? { permissionMode: metadata.autonomyMode } : {},
1962
+ ...stringField(metadata.headRepoKey) ? { headRepoKey: metadata.headRepoKey } : {},
1963
+ ...stringField(metadata.prCreatedAt) ? { prCreatedAt: metadata.prCreatedAt } : {},
1964
+ ...stringField(metadata.prClosedAt) ? { prClosedAt: metadata.prClosedAt } : {},
1965
+ ...stringField(metadata.prMergedAt) ? { prMergedAt: metadata.prMergedAt } : {},
1966
+ ...stringField(metadata.promptId) ? { promptId: metadata.promptId } : {},
1967
+ ...vcsAction ? { vcsAction } : {},
1968
+ ...reason ? { reason } : {},
1969
+ ...model ? { model } : {},
1970
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1971
+ sourceType: payload.eventType
1972
+ };
1752
1973
  }
1753
1974
  }
1754
1975
  });
1755
1976
 
1756
- // ../packages/tool-kit/out/stateStore.js
1757
- var require_stateStore = __commonJS({
1758
- "../packages/tool-kit/out/stateStore.js"(exports) {
1977
+ // ../packages/tool-kit/out/credentials.js
1978
+ var require_credentials = __commonJS({
1979
+ "../packages/tool-kit/out/credentials.js"(exports) {
1759
1980
  "use strict";
1760
1981
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1761
1982
  if (k2 === void 0) k2 = k;
@@ -1795,124 +2016,102 @@ var require_stateStore = __commonJS({
1795
2016
  };
1796
2017
  }();
1797
2018
  Object.defineProperty(exports, "__esModule", { value: true });
1798
- exports.defaultStateFilePath = defaultStateFilePath;
1799
- exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
1800
- exports.unresolvedStateFilePath = unresolvedStateFilePath;
1801
- exports.readCollectorState = readCollectorState;
1802
- exports.recordSendOutcome = recordSendOutcome;
1803
- exports.recordOutboxDiscard = recordOutboxDiscard;
1804
- exports.shouldAnnounceFailure = shouldAnnounceFailure;
1805
- exports.markFailureNotified = markFailureNotified;
2019
+ exports.credentialsFilePath = credentialsFilePath;
2020
+ exports.readMachineCredentials = readMachineCredentials;
2021
+ exports.writeMachineCredentials = writeMachineCredentials;
2022
+ exports.writeTopLevelCredentials = writeTopLevelCredentials;
2023
+ exports.writeRepoKeysSetting = writeRepoKeysSetting;
2024
+ exports.writeEventLogSetting = writeEventLogSetting;
2025
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2026
+ exports.readHostCredentials = readHostCredentials;
2027
+ exports.writeHostCredentials = writeHostCredentials;
2028
+ exports.removeHostCredentials = removeHostCredentials;
1806
2029
  var fs = __importStar(__require("fs"));
1807
2030
  var path = __importStar(__require("path"));
1808
2031
  var tokenStore_1 = require_tokenStore();
1809
- function defaultStateFilePath(toolInstallationId) {
1810
- const dir = process.env.ASCENDA_STATE_DIR?.trim();
1811
- const base = dir ? dir : path.join((0, tokenStore_1.ascendaHome)(), "state");
1812
- return path.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1813
- }
1814
- function unresolvedToolInstallationId(toolType) {
1815
- return `${toolType}:unresolved`;
1816
- }
1817
- function unresolvedStateFilePath(toolType) {
1818
- return defaultStateFilePath(unresolvedToolInstallationId(toolType));
2032
+ function credentialsFilePath() {
2033
+ return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1819
2034
  }
1820
- function readCollectorState(stateFilePath) {
2035
+ function readMachineCredentials() {
1821
2036
  try {
1822
- if (!fs.existsSync(stateFilePath))
1823
- return void 0;
1824
- const raw = fs.readFileSync(stateFilePath, "utf8").trim();
2037
+ const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
1825
2038
  if (!raw)
1826
2039
  return void 0;
1827
2040
  const parsed = JSON.parse(raw);
1828
- if (!parsed || typeof parsed !== "object")
2041
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1829
2042
  return void 0;
1830
2043
  return parsed;
1831
2044
  } catch {
1832
2045
  return void 0;
1833
2046
  }
1834
2047
  }
1835
- function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1836
- const now = (/* @__PURE__ */ new Date()).toISOString();
1837
- const previous = readCollectorState(stateFilePath);
1838
- const accepted = outcome === "accepted";
1839
- const next = {
1840
- toolInstallationId,
1841
- lastAttemptAt: now,
1842
- lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1843
- lastOutcome: outcome,
1844
- consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1845
- ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1846
- ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1847
- ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1848
- // A success closes the episode; a failure either opens one or continues
1849
- // the one already open. Carrying `notifiedFailingSince` across a
1850
- // continuing episode is what keeps the notice to once per outage.
1851
- ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1852
- ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1853
- // Cumulative by design: a send outcome, success included, never erases
1854
- // the record of what the outbox had to throw away.
1855
- ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1856
- };
1857
- writeStateFile(stateFilePath, next);
1858
- return next;
2048
+ function writeMachineCredentials(credentials) {
2049
+ const file = credentialsFilePath();
2050
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2051
+ fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2052
+ `, { encoding: "utf8", mode: 384 });
2053
+ if (process.platform !== "win32") {
2054
+ fs.chmodSync(path.dirname(file), 448);
2055
+ fs.chmodSync(file, 384);
2056
+ }
1859
2057
  }
1860
- function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1861
- const now = (/* @__PURE__ */ new Date()).toISOString();
1862
- const previous = readCollectorState(stateFilePath);
1863
- const next = {
1864
- ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1865
- toolInstallationId,
1866
- lastOutcome: "outbox_discarded",
1867
- outboxDiscarded: {
1868
- total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1869
- lastAt: now,
1870
- lastCount: discard.count,
1871
- lastReasons: discard.reasons,
1872
- ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1873
- }
1874
- };
1875
- writeStateFile(stateFilePath, next);
1876
- return next;
2058
+ function writeTopLevelCredentials(credentials) {
2059
+ const existing = readMachineCredentials();
2060
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
2061
+ const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
2062
+ writeMachineCredentials({
2063
+ ...credentials,
2064
+ ...eventLogPath ? { eventLogPath } : {},
2065
+ ...repoKeys === false ? { repoKeys } : {},
2066
+ ...existing?.tools ? { tools: existing.tools } : {}
2067
+ });
1877
2068
  }
1878
- function shouldAnnounceFailure(state) {
1879
- if (!state || state.consecutiveFailures === 0 || !state.failingSince)
2069
+ function writeRepoKeysSetting(on) {
2070
+ const existing = readMachineCredentials() ?? {};
2071
+ const { repoKeys: _dropped, ...rest } = existing;
2072
+ writeMachineCredentials(on ? rest : { ...rest, repoKeys: false });
2073
+ }
2074
+ function writeEventLogSetting(value) {
2075
+ const existing = readMachineCredentials() ?? {};
2076
+ writeMachineCredentials({ ...existing, eventLogPath: value });
2077
+ }
2078
+ function isLocalOnlyHostInstall(host, hasToken) {
2079
+ const credentials = readHostCredentials(host);
2080
+ if (!credentials?.localOnly)
1880
2081
  return false;
1881
- return state.notifiedFailingSince !== state.failingSince;
2082
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2083
+ return false;
2084
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1882
2085
  }
1883
- function markFailureNotified(stateFilePath, state) {
1884
- if (!state.failingSince)
1885
- return;
1886
- writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
2086
+ function readHostCredentials(host) {
2087
+ const entry = readMachineCredentials()?.tools?.[host];
2088
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
2089
+ return void 0;
2090
+ return entry;
1887
2091
  }
1888
- function writeStateFile(stateFilePath, state) {
1889
- const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1890
- try {
1891
- const dir = path.dirname(stateFilePath);
1892
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1893
- fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1894
- `, { encoding: "utf8", mode: 384 });
1895
- fs.renameSync(temporaryPath, stateFilePath);
1896
- if (process.platform !== "win32")
1897
- fs.chmodSync(stateFilePath, 384);
1898
- } catch {
1899
- try {
1900
- if (fs.existsSync(temporaryPath))
1901
- fs.unlinkSync(temporaryPath);
1902
- } catch {
1903
- }
1904
- }
2092
+ function writeHostCredentials(host, credentials) {
2093
+ const existing = readMachineCredentials() ?? {};
2094
+ writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1905
2095
  }
1906
- function truncate(value) {
1907
- const collapsed = value.replace(/\s+/g, " ").trim();
1908
- return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
2096
+ function removeHostCredentials(host) {
2097
+ const existing = readMachineCredentials();
2098
+ if (!existing?.tools || !(host in existing.tools))
2099
+ return;
2100
+ const tools = { ...existing.tools };
2101
+ delete tools[host];
2102
+ const next = { ...existing };
2103
+ if (Object.keys(tools).length)
2104
+ next.tools = tools;
2105
+ else
2106
+ delete next.tools;
2107
+ writeMachineCredentials(next);
1909
2108
  }
1910
2109
  }
1911
2110
  });
1912
2111
 
1913
- // ../packages/tool-kit/out/outbox.js
1914
- var require_outbox = __commonJS({
1915
- "../packages/tool-kit/out/outbox.js"(exports) {
2112
+ // ../packages/tool-kit/out/eventLog.js
2113
+ var require_eventLog = __commonJS({
2114
+ "../packages/tool-kit/out/eventLog.js"(exports) {
1916
2115
  "use strict";
1917
2116
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1918
2117
  if (k2 === void 0) k2 = k;
@@ -1952,182 +2151,347 @@ var require_outbox = __commonJS({
1952
2151
  };
1953
2152
  }();
1954
2153
  Object.defineProperty(exports, "__esModule", { value: true });
1955
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1956
- exports.outboxDrainEnabled = outboxDrainEnabled;
1957
- exports.defaultOutboxFilePath = defaultOutboxFilePath;
1958
- exports.appendToOutbox = appendToOutbox;
1959
- exports.readOutboxSummary = readOutboxSummary;
1960
- exports.claimOutbox = claimOutbox;
1961
- exports.enforceOutboxBounds = enforceOutboxBounds;
2154
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
2155
+ exports.expandUserPath = expandUserPath;
2156
+ exports.defaultEventLogPath = defaultEventLogPath;
2157
+ exports.resolveEventLog = resolveEventLog;
2158
+ exports.resolveEventLogPath = resolveEventLogPath;
2159
+ exports.describeEventLog = describeEventLog;
2160
+ exports.parseEventLogFlag = parseEventLogFlag;
2161
+ exports.appendEventLog = appendEventLog;
1962
2162
  var fs = __importStar(__require("fs"));
2163
+ var os = __importStar(__require("os"));
1963
2164
  var path = __importStar(__require("path"));
1964
- var stateStore_1 = require_stateStore();
2165
+ var agentEvent_1 = require_agentEvent();
2166
+ var credentials_1 = require_credentials();
1965
2167
  var tokenStore_1 = require_tokenStore();
1966
- exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1967
- exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1968
- exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1969
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1970
- var ORPHANED_CLAIM_AGE_MS = 6e4;
1971
- var CLAIM_SUFFIX = ".draining";
1972
- function outboxDrainEnabled(env = process.env) {
1973
- const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1974
- if (value === void 0 || value === "")
1975
- return true;
1976
- return !(value === "0" || value === "false" || value === "no" || value === "off");
2168
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
2169
+ exports.EVENT_LOG_OFF = "off";
2170
+ var MAX_BYTES = 5 * 1024 * 1024;
2171
+ function expandUserPath(configured) {
2172
+ const value = configured?.trim();
2173
+ if (!value)
2174
+ return void 0;
2175
+ if (value === "~")
2176
+ return os.homedir();
2177
+ if (value.startsWith("~/"))
2178
+ return path.join(os.homedir(), value.slice(2));
2179
+ return path.resolve(value);
1977
2180
  }
1978
- function defaultOutboxFilePath(toolInstallationId) {
1979
- const dir = path.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1980
- return path.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
2181
+ function defaultEventLogPath() {
2182
+ return path.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1981
2183
  }
1982
- function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
2184
+ function resolveEventLog(options = {}) {
2185
+ for (const [source, raw] of [
2186
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
2187
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
2188
+ ]) {
2189
+ const value = raw?.trim();
2190
+ if (!value)
2191
+ continue;
2192
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
2193
+ return { path: void 0, source: "disabled" };
2194
+ return { path: expandUserPath(value), source };
2195
+ }
2196
+ if (options.localOnly)
2197
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
2198
+ return { path: void 0, source: "off" };
2199
+ }
2200
+ function resolveEventLogPath(options = {}) {
2201
+ return resolveEventLog(options).path;
2202
+ }
2203
+ function describeEventLog(setting, command) {
2204
+ switch (setting.source) {
2205
+ case "env":
2206
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
2207
+ case "credentials":
2208
+ return `${setting.path} (set by ${command} --event-log)`;
2209
+ case "unpaired-default":
2210
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
2211
+ case "disabled":
2212
+ return `off (turned off; ${command} --event-log to turn it on)`;
2213
+ case "off":
2214
+ return `off (${command} --event-log to keep a local copy of every event)`;
2215
+ }
2216
+ }
2217
+ function parseEventLogFlag(argv, index) {
2218
+ const peek = argv[index + 1];
2219
+ if (peek !== void 0 && !peek.startsWith("-"))
2220
+ return { value: peek, consumed: 1 };
2221
+ return { value: defaultEventLogPath(), consumed: 0 };
2222
+ }
2223
+ function appendEventLog(logFilePath, entry) {
1983
2224
  try {
1984
- const dir = path.dirname(outboxFilePath);
2225
+ rotateIfLarge(logFilePath);
2226
+ const dir = path.dirname(logFilePath);
1985
2227
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1986
- const entry = { queuedAt: now.toISOString(), payload };
1987
- fs.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
2228
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
2229
+ fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
1988
2230
  `, { encoding: "utf8", mode: 384 });
1989
2231
  if (process.platform !== "win32")
1990
- fs.chmodSync(outboxFilePath, 384);
1991
- return true;
2232
+ fs.chmodSync(logFilePath, 384);
1992
2233
  } catch {
1993
- return false;
1994
- }
1995
- }
1996
- function readOutboxSummary(outboxFilePath) {
1997
- const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs.existsSync(file));
1998
- if (files.length === 0)
1999
- return void 0;
2000
- let depth = 0;
2001
- let unreadableLines = 0;
2002
- let oldestQueuedAt;
2003
- for (const file of files) {
2004
- const { entries, unreadable } = readEntries(file);
2005
- depth += entries.length;
2006
- unreadableLines += unreadable;
2007
- for (const entry of entries) {
2008
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
2009
- oldestQueuedAt = entry.queuedAt;
2010
- }
2011
2234
  }
2012
- return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
2013
2235
  }
2014
- function claimOutbox(outboxFilePath, now = Date.now()) {
2015
- const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
2016
- const claimed = [];
2236
+ function rotateIfLarge(logFilePath) {
2017
2237
  try {
2018
- fs.renameSync(outboxFilePath, claimPath);
2019
- claimed.push(claimPath);
2238
+ if (fs.statSync(logFilePath).size < MAX_BYTES)
2239
+ return;
2240
+ fs.renameSync(logFilePath, `${logFilePath}.1`);
2020
2241
  } catch {
2021
2242
  }
2022
- let orphanIndex = 0;
2023
- for (const orphan of listClaimFiles(outboxFilePath)) {
2024
- if (claimed.includes(orphan))
2025
- continue;
2026
- try {
2027
- if (now - fs.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
2028
- continue;
2029
- const mine = `${claimPath}.${orphanIndex++}`;
2030
- fs.renameSync(orphan, mine);
2031
- claimed.push(mine);
2032
- } catch {
2033
- }
2243
+ }
2244
+ }
2245
+ });
2246
+
2247
+ // ../packages/tool-kit/out/http.js
2248
+ var require_http = __commonJS({
2249
+ "../packages/tool-kit/out/http.js"(exports) {
2250
+ "use strict";
2251
+ Object.defineProperty(exports, "__esModule", { value: true });
2252
+ exports.AscendaApiError = void 0;
2253
+ exports.createPairingSession = createPairingSession;
2254
+ exports.getPairingStatus = getPairingStatus;
2255
+ exports.startStudyJoin = startStudyJoin;
2256
+ exports.getStudyJoinStatus = getStudyJoinStatus;
2257
+ exports.readInitiatives = readInitiatives;
2258
+ exports.readStudyNotices = readStudyNotices;
2259
+ exports.setStudyObjection = setStudyObjection;
2260
+ exports.markStudyNoticeShown = markStudyNoticeShown;
2261
+ exports.renewToolToken = renewToolToken;
2262
+ exports.isRetryableStatus = isRetryableStatus;
2263
+ exports.postToolEvent = postToolEvent;
2264
+ exports.postToolEventsBatch = postToolEventsBatch;
2265
+ exports.parseIngestResponse = parseIngestResponse;
2266
+ var tool_contract_1 = require_out();
2267
+ var AscendaApiError = class extends Error {
2268
+ status;
2269
+ errorCode;
2270
+ constructor(status, errorCode, body) {
2271
+ super(body ?? `Ascenda API error ${status}`);
2272
+ this.status = status;
2273
+ this.errorCode = errorCode;
2274
+ this.name = "AscendaApiError";
2034
2275
  }
2035
- if (claimed.length === 0)
2036
- return void 0;
2037
- const entries = [];
2038
- let unreadable = 0;
2039
- for (const file of claimed) {
2040
- const read = readEntries(file);
2041
- entries.push(...read.entries);
2042
- unreadable += read.unreadable;
2276
+ };
2277
+ exports.AscendaApiError = AscendaApiError;
2278
+ async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
2279
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
2280
+ method: "POST",
2281
+ headers: { "Content-Type": "application/json" },
2282
+ body: JSON.stringify({ toolInstallationId, toolType, displayName })
2283
+ });
2284
+ if (!response.ok)
2285
+ throw new AscendaApiError(response.status, void 0, await response.text());
2286
+ return await response.json();
2287
+ }
2288
+ async function getPairingStatus(apiBaseUrl, pairingSessionId) {
2289
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
2290
+ method: "GET",
2291
+ headers: { Accept: "application/json" }
2292
+ });
2293
+ if (!response.ok)
2294
+ throw new AscendaApiError(response.status, void 0, await response.text());
2295
+ return await response.json();
2296
+ }
2297
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
2298
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2299
+ method: "POST",
2300
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2301
+ body: JSON.stringify({ joinCode, mode })
2302
+ });
2303
+ if (!response.ok)
2304
+ throw await apiError(response);
2305
+ return await response.json();
2306
+ }
2307
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
2308
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
2309
+ method: "GET",
2310
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
2311
+ });
2312
+ if (!response.ok)
2313
+ throw await apiError(response);
2314
+ return await response.json();
2315
+ }
2316
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
2317
+ let response;
2318
+ try {
2319
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
2320
+ method: "GET",
2321
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2322
+ signal
2323
+ });
2324
+ } catch (error2) {
2325
+ return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2043
2326
  }
2044
- entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
2045
- let released = false;
2046
- return {
2047
- entries,
2048
- unreadable,
2049
- release(remainder) {
2050
- if (released)
2051
- return;
2052
- released = true;
2053
- if (remainder.length > 0) {
2054
- try {
2055
- fs.mkdirSync(path.dirname(outboxFilePath), { recursive: true, mode: 448 });
2056
- fs.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
2057
- `).join(""), { encoding: "utf8", mode: 384 });
2058
- if (process.platform !== "win32")
2059
- fs.chmodSync(outboxFilePath, 384);
2060
- } catch {
2061
- return;
2062
- }
2063
- }
2064
- for (const file of claimed) {
2065
- try {
2066
- fs.unlinkSync(file);
2067
- } catch {
2068
- }
2069
- }
2070
- }
2071
- };
2327
+ if (response.status === 401)
2328
+ return { kind: "rejected", httpStatus: 401 };
2329
+ if (!response.ok)
2330
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2331
+ let body;
2332
+ try {
2333
+ body = await response.json();
2334
+ } catch {
2335
+ return { kind: "failed", reason: "the reply was not readable" };
2336
+ }
2337
+ if (!Array.isArray(body))
2338
+ return { kind: "failed", reason: "the reply was not a list" };
2339
+ return { kind: "ok", initiatives: body };
2072
2340
  }
2073
- function enforceOutboxBounds(entries, bounds, now = Date.now()) {
2074
- const reasons = {};
2075
- let oldestQueuedAt;
2076
- const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
2077
- const fresh = [];
2078
- for (const entry of entries) {
2079
- if (entry.queuedAt < cutoff) {
2080
- reasons.age = (reasons.age ?? 0) + 1;
2081
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
2082
- oldestQueuedAt = entry.queuedAt;
2083
- } else {
2084
- fresh.push(entry);
2085
- }
2341
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
2342
+ let response;
2343
+ try {
2344
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
2345
+ method: "GET",
2346
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2347
+ signal
2348
+ });
2349
+ } catch (error2) {
2350
+ return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2086
2351
  }
2087
- const excess = Math.max(0, fresh.length - bounds.maxEntries);
2088
- if (excess > 0) {
2089
- reasons.count = excess;
2090
- const first = fresh[0]?.queuedAt;
2091
- if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
2092
- oldestQueuedAt = first;
2352
+ if (response.status === 404)
2353
+ return { kind: "absent" };
2354
+ if (response.status === 401)
2355
+ return { kind: "rejected", httpStatus: 401 };
2356
+ if (!response.ok)
2357
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2358
+ let body;
2359
+ try {
2360
+ body = await response.json();
2361
+ } catch {
2362
+ return { kind: "absent" };
2363
+ }
2364
+ if (!Array.isArray(body))
2365
+ return { kind: "absent" };
2366
+ return { kind: "ok", notices: body };
2367
+ }
2368
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
2369
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
2370
+ method: objected ? "POST" : "DELETE",
2371
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
2372
+ });
2373
+ if (!response.ok)
2374
+ throw await apiError(response);
2375
+ }
2376
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
2377
+ try {
2378
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
2379
+ method: "POST",
2380
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
2381
+ signal
2382
+ });
2383
+ return response.ok;
2384
+ } catch {
2385
+ return false;
2093
2386
  }
2094
- const kept = excess > 0 ? fresh.slice(excess) : fresh;
2095
- const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
2096
- return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
2097
2387
  }
2098
- function listClaimFiles(outboxFilePath) {
2099
- const dir = path.dirname(outboxFilePath);
2100
- const prefix = `${path.basename(outboxFilePath)}.`;
2388
+ async function apiError(response) {
2389
+ const body = await response.text();
2390
+ let errorCode;
2101
2391
  try {
2102
- return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
2392
+ const parsed = JSON.parse(body);
2393
+ errorCode = parsed.code ?? parsed.error;
2103
2394
  } catch {
2104
- return [];
2395
+ errorCode = void 0;
2105
2396
  }
2397
+ return new AscendaApiError(response.status, errorCode, body);
2106
2398
  }
2107
- function readEntries(file) {
2108
- let raw;
2399
+ async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
2400
+ const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
2401
+ method: "POST",
2402
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2403
+ signal
2404
+ });
2405
+ if (response.status === 401)
2406
+ return null;
2407
+ if (!response.ok)
2408
+ throw new AscendaApiError(response.status, void 0, await response.text());
2409
+ return await response.json();
2410
+ }
2411
+ function isDeliveredStatus(value) {
2412
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
2413
+ }
2414
+ function readSuccessBody(body) {
2415
+ let parsed;
2109
2416
  try {
2110
- raw = fs.readFileSync(file, "utf8");
2417
+ parsed = JSON.parse(body);
2111
2418
  } catch {
2112
- return { entries: [], unreadable: 0 };
2419
+ return { duplicates: 0 };
2113
2420
  }
2114
- const entries = [];
2115
- let unreadable = 0;
2116
- for (const line of raw.split("\n")) {
2117
- if (!line.trim())
2421
+ if (!parsed || typeof parsed !== "object")
2422
+ return { duplicates: 0 };
2423
+ const single = parsed.status;
2424
+ if (isDeliveredStatus(single))
2425
+ return { duplicates: single === "duplicate" ? 1 : 0 };
2426
+ const raw = parsed.results;
2427
+ if (!Array.isArray(raw))
2428
+ return { duplicates: 0 };
2429
+ const results = [];
2430
+ for (const item of raw) {
2431
+ if (!item || typeof item !== "object")
2432
+ continue;
2433
+ const { index, status, reason } = item;
2434
+ if (typeof index !== "number" || typeof status !== "string")
2118
2435
  continue;
2436
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
2437
+ }
2438
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
2439
+ }
2440
+ function isRetryableStatus(status) {
2441
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
2442
+ }
2443
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
2444
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
2445
+ }
2446
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
2447
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
2448
+ }
2449
+ async function sendIngest(url, eventWriteToken, body, signal) {
2450
+ try {
2451
+ const response = await fetch(url, {
2452
+ method: "POST",
2453
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2454
+ body,
2455
+ signal
2456
+ });
2457
+ return parseIngestResponse(response);
2458
+ } catch (error2) {
2459
+ return {
2460
+ result: "transport_error",
2461
+ detail: error2 instanceof Error ? `${error2.name}: ${error2.message}` : String(error2)
2462
+ };
2463
+ }
2464
+ }
2465
+ async function parseIngestResponse(response) {
2466
+ if (response.ok) {
2467
+ const outcome = { result: "accepted", httpStatus: response.status };
2468
+ let read = { duplicates: 0 };
2119
2469
  try {
2120
- const parsed = JSON.parse(line);
2121
- if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
2122
- unreadable += 1;
2123
- continue;
2124
- }
2125
- entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
2470
+ read = readSuccessBody(await response.text());
2126
2471
  } catch {
2127
- unreadable += 1;
2472
+ read = { duplicates: 0 };
2128
2473
  }
2474
+ return {
2475
+ ...outcome,
2476
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
2477
+ ...read.results !== void 0 ? { results: read.results } : {}
2478
+ };
2129
2479
  }
2130
- return { entries, unreadable };
2480
+ const body = await response.text();
2481
+ let errorCode;
2482
+ try {
2483
+ errorCode = JSON.parse(body).error;
2484
+ } catch {
2485
+ errorCode = void 0;
2486
+ }
2487
+ const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
2488
+ if (response.status === 401)
2489
+ return { ...base, result: "auth_failed" };
2490
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
2491
+ return { ...base, result: "consent_missing" };
2492
+ if (response.status === 400 || response.status === 422)
2493
+ return { ...base, result: "validation_failed" };
2494
+ return { ...base, result: "transport_error" };
2131
2495
  }
2132
2496
  }
2133
2497
  });
@@ -2380,6 +2744,29 @@ var require_eventSender = __commonJS({
2380
2744
  }
2381
2745
  return outcome;
2382
2746
  }
2747
+ /**
2748
+ * One outbox pass with nothing live to send: what a background flusher runs,
2749
+ * once per batch. Unlike the pass {@link post} makes, it may run more than
2750
+ * once per sender, because a flusher isn't on anyone's critical path.
2751
+ *
2752
+ * A halted pass is journaled here. Inside {@link post} the live send that
2753
+ * follows journals it, and a flusher has no live send, so without this an
2754
+ * outage would never reach the journal `doctor` and the notices read.
2755
+ */
2756
+ async flushOutbox() {
2757
+ await this.renewIfExpiring();
2758
+ this.outboxServiced = false;
2759
+ this.lastDrain = void 0;
2760
+ const halted = await this.serviceOutbox();
2761
+ if (halted) {
2762
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, halted.result, {
2763
+ httpStatus: halted.httpStatus,
2764
+ errorCode: halted.errorCode,
2765
+ detail: withNote(halted.detail, "kept in outbox")
2766
+ });
2767
+ }
2768
+ return this.lastDrain;
2769
+ }
2383
2770
  /** A failure that never reached a verdict. Replaying can change the answer. */
2384
2771
  isRetryable(outcome) {
2385
2772
  return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
@@ -2779,6 +3166,8 @@ var require_forgeProject = __commonJS({
2779
3166
  }();
2780
3167
  Object.defineProperty(exports, "__esModule", { value: true });
2781
3168
  exports.forgeProjectHash = forgeProjectHash;
3169
+ exports.forgeRepoKey = forgeRepoKey;
3170
+ exports.forgeBranchKey = forgeBranchKey;
2782
3171
  exports.parseForgeFullName = parseForgeFullName;
2783
3172
  exports.readForgeFullName = readForgeFullName;
2784
3173
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
@@ -2794,6 +3183,19 @@ var require_forgeProject = __commonJS({
2794
3183
  }
2795
3184
  return h.toString(16).padStart(8, "0");
2796
3185
  }
3186
+ function forgeRepoKey(fullName) {
3187
+ return forgeProjectHash(fullName.toLowerCase());
3188
+ }
3189
+ function forgeBranchKey(fullName, branch) {
3190
+ const input = `${fullName.toLowerCase()}
3191
+ ${branch}`;
3192
+ let h = 0xcbf29ce484222325n;
3193
+ for (const byte of Buffer.from(input, "utf8")) {
3194
+ h ^= BigInt(byte);
3195
+ h = BigInt.asUintN(64, h * 0x100000001b3n);
3196
+ }
3197
+ return h.toString(16).padStart(16, "0");
3198
+ }
2797
3199
  function parseForgeFullName(remoteUrl) {
2798
3200
  if (!remoteUrl)
2799
3201
  return null;
@@ -3180,6 +3582,95 @@ var require_workContext = __commonJS({
3180
3582
  }
3181
3583
  });
3182
3584
 
3585
+ // ../packages/tool-kit/out/forgeKeys.js
3586
+ var require_forgeKeys = __commonJS({
3587
+ "../packages/tool-kit/out/forgeKeys.js"(exports) {
3588
+ "use strict";
3589
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3590
+ if (k2 === void 0) k2 = k;
3591
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3592
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3593
+ desc = { enumerable: true, get: function() {
3594
+ return m[k];
3595
+ } };
3596
+ }
3597
+ Object.defineProperty(o, k2, desc);
3598
+ } : function(o, m, k, k2) {
3599
+ if (k2 === void 0) k2 = k;
3600
+ o[k2] = m[k];
3601
+ });
3602
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3603
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3604
+ } : function(o, v) {
3605
+ o["default"] = v;
3606
+ });
3607
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3608
+ var ownKeys = function(o) {
3609
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3610
+ var ar = [];
3611
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3612
+ return ar;
3613
+ };
3614
+ return ownKeys(o);
3615
+ };
3616
+ return function(mod) {
3617
+ if (mod && mod.__esModule) return mod;
3618
+ var result = {};
3619
+ if (mod != null) {
3620
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3621
+ }
3622
+ __setModuleDefault(result, mod);
3623
+ return result;
3624
+ };
3625
+ }();
3626
+ Object.defineProperty(exports, "__esModule", { value: true });
3627
+ exports.REPO_KEYS_ENV_VAR = void 0;
3628
+ exports.repoKeysEnabled = repoKeysEnabled;
3629
+ exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd;
3630
+ var fs = __importStar(__require("fs"));
3631
+ var path = __importStar(__require("path"));
3632
+ var credentials_1 = require_credentials();
3633
+ var forgeProject_1 = require_forgeProject();
3634
+ var workContext_1 = require_workContext();
3635
+ exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
3636
+ function repoKeysEnabled() {
3637
+ const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
3638
+ if (env === "off" || env === "0" || env === "false")
3639
+ return false;
3640
+ if (env === "on" || env === "1" || env === "true")
3641
+ return true;
3642
+ return (0, credentials_1.readMachineCredentials)()?.repoKeys !== false;
3643
+ }
3644
+ function readDefaultBranch(repositoryRoot) {
3645
+ try {
3646
+ const head = fs.readFileSync(path.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
3647
+ const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
3648
+ return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
3649
+ } catch {
3650
+ return null;
3651
+ }
3652
+ }
3653
+ function deriveForgeKeysForCwd(cwd) {
3654
+ try {
3655
+ if (!cwd || !repoKeysEnabled())
3656
+ return {};
3657
+ const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
3658
+ const fullName = (0, forgeProject_1.readForgeFullName)(root);
3659
+ if (!root || !fullName)
3660
+ return {};
3661
+ const branch = (0, workContext_1.readBranchName)(cwd);
3662
+ const onDefault = branch !== null && branch === readDefaultBranch(root);
3663
+ return {
3664
+ repoKey: (0, forgeProject_1.forgeRepoKey)(fullName),
3665
+ ...branch && !onDefault ? { branchKey: (0, forgeProject_1.forgeBranchKey)(fullName, branch) } : {}
3666
+ };
3667
+ } catch {
3668
+ return {};
3669
+ }
3670
+ }
3671
+ }
3672
+ });
3673
+
3183
3674
  // ../packages/tool-kit/out/hookAdapter.js
3184
3675
  var require_hookAdapter = __commonJS({
3185
3676
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
@@ -3189,13 +3680,18 @@ var require_hookAdapter = __commonJS({
3189
3680
  exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
3190
3681
  exports.resolveContextHashes = resolveContextHashes;
3191
3682
  exports.loadCliAgentConfig = loadCliAgentConfig;
3683
+ exports.withForgeKeys = withForgeKeys;
3684
+ exports.withPromptId = withPromptId;
3192
3685
  exports.deliverHookEvents = deliverHookEvents;
3686
+ exports.flushHookOutbox = flushHookOutbox;
3193
3687
  var contextRegistry_1 = require_contextRegistry();
3194
3688
  var credentials_1 = require_credentials();
3195
3689
  var forgeProject_1 = require_forgeProject();
3196
3690
  var eventLog_1 = require_eventLog();
3691
+ var forgeKeys_1 = require_forgeKeys();
3197
3692
  var eventSender_1 = require_eventSender();
3198
3693
  var stateStore_1 = require_stateStore();
3694
+ var backgroundDelivery_1 = require_backgroundDelivery();
3199
3695
  var tokenStore_1 = require_tokenStore();
3200
3696
  var workContext_1 = require_workContext();
3201
3697
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -3248,6 +3744,19 @@ var require_hookAdapter = __commonJS({
3248
3744
  };
3249
3745
  }
3250
3746
  function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
3747
+ const pairing = loadCliAgentPairing(toolType, identity);
3748
+ const contextHashes = resolveContextHashes(cwd);
3749
+ return {
3750
+ ...pairing,
3751
+ // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3752
+ // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3753
+ // an empty string, grouping unrelated rows under a value naming no session.
3754
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3755
+ workspaceHash: contextHashes.workspaceHash,
3756
+ projectHash: contextHashes.projectHash
3757
+ };
3758
+ }
3759
+ function loadCliAgentPairing(toolType, identity) {
3251
3760
  const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
3252
3761
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3253
3762
  const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
@@ -3258,26 +3767,33 @@ var require_hookAdapter = __commonJS({
3258
3767
  throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
3259
3768
  if (!fileToken)
3260
3769
  (0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3261
- const contextHashes = resolveContextHashes(cwd);
3262
3770
  return {
3263
3771
  apiBaseUrl,
3264
3772
  toolInstallationId,
3265
3773
  eventWriteToken,
3266
3774
  tokenFilePath,
3267
- // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3268
- // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3269
- // an empty string, grouping unrelated rows under a value naming no session.
3270
- sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3271
- workspaceHash: contextHashes.workspaceHash,
3272
- projectHash: contextHashes.projectHash,
3273
3775
  // Agents await command hooks; fail fast rather than stall the user's turn.
3274
3776
  timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
3275
3777
  };
3276
3778
  }
3779
+ function withForgeKeys(events, cwd) {
3780
+ const keys = (0, forgeKeys_1.deriveForgeKeysForCwd)(cwd ?? process.cwd());
3781
+ if (!keys.repoKey)
3782
+ return events;
3783
+ return events.map((event) => ({ ...event, metadata: { ...keys, ...event.metadata } }));
3784
+ }
3785
+ function withPromptId(events, promptId) {
3786
+ if (!promptId)
3787
+ return events;
3788
+ return events.map((event) => ({ ...event, metadata: { promptId, ...event.metadata } }));
3789
+ }
3277
3790
  async function deliverHookEvents(events, options) {
3278
3791
  if (events.length === 0)
3279
3792
  return;
3280
- const notice = options.onNotice ?? ((message) => console.error(message));
3793
+ events = withPromptId(events, options.promptId);
3794
+ if (options.forgeKeys)
3795
+ events = withForgeKeys(events, options.cwd);
3796
+ const notice = options.onNotice ?? ((message2) => console.error(message2));
3281
3797
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3282
3798
  if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3283
3799
  const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
@@ -3303,26 +3819,60 @@ var require_hookAdapter = __commonJS({
3303
3819
  source: options.source,
3304
3820
  eventWriteToken: config2.eventWriteToken,
3305
3821
  tokenFilePath: config2.tokenFilePath,
3306
- sessionId: config2.sessionId,
3307
- workspaceHash: config2.workspaceHash,
3308
- projectHash: config2.projectHash,
3822
+ sessionId: config2.sessionId,
3823
+ workspaceHash: config2.workspaceHash,
3824
+ projectHash: config2.projectHash,
3825
+ timeoutMs: config2.timeoutMs
3826
+ });
3827
+ if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
3828
+ for (const event of events) {
3829
+ const result = await sender.send(event);
3830
+ if (result === "accepted")
3831
+ continue;
3832
+ const message2 = noticeFor(result);
3833
+ if (message2)
3834
+ notice(message2);
3835
+ return;
3836
+ }
3837
+ return;
3838
+ }
3839
+ for (const event of events)
3840
+ sender.queue(event);
3841
+ (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
3842
+ const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
3843
+ const message = last ? noticeFor(last) : void 0;
3844
+ if (message)
3845
+ notice(message);
3846
+ }
3847
+ function noticeFor(result) {
3848
+ if (result === "accepted" || result === "duplicate")
3849
+ return void 0;
3850
+ if (result === "consent_missing")
3851
+ return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
3852
+ if (result === "auth_failed")
3853
+ return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
3854
+ if (result === "transport_error")
3855
+ return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
3856
+ if (result === "outbox_discarded")
3857
+ return void 0;
3858
+ return `Ascenda telemetry rejected: ${result}`;
3859
+ }
3860
+ async function flushHookOutbox(options) {
3861
+ let config2;
3862
+ try {
3863
+ config2 = loadCliAgentPairing(options.toolType, options);
3864
+ } catch {
3865
+ return;
3866
+ }
3867
+ const sender = new eventSender_1.AscendaEventSender({
3868
+ apiBaseUrl: config2.apiBaseUrl,
3869
+ toolInstallationId: config2.toolInstallationId,
3870
+ source: options.source,
3871
+ eventWriteToken: config2.eventWriteToken,
3872
+ tokenFilePath: config2.tokenFilePath,
3309
3873
  timeoutMs: config2.timeoutMs
3310
3874
  });
3311
- for (const event of events) {
3312
- const result = await sender.send(event);
3313
- if (result === "accepted")
3314
- continue;
3315
- if (result === "consent_missing") {
3316
- notice("Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.");
3317
- } else if (result === "auth_failed") {
3318
- notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
3319
- } else if (result === "transport_error") {
3320
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
3321
- } else {
3322
- notice(`Ascenda telemetry rejected: ${result}`);
3323
- }
3324
- return;
3325
- }
3875
+ await (0, backgroundDelivery_1.runOutboxFlush)(sender);
3326
3876
  }
3327
3877
  function logUnsent(logFile, events, options) {
3328
3878
  const contextHashes = resolveContextHashes(options.cwd);
@@ -3824,52 +4374,6 @@ var require_initiatives = __commonJS({
3824
4374
  }
3825
4375
  });
3826
4376
 
3827
- // ../packages/tool-kit/out/setupDisclosure.js
3828
- var require_setupDisclosure = __commonJS({
3829
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3830
- "use strict";
3831
- Object.defineProperty(exports, "__esModule", { value: true });
3832
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3833
- exports.renderSetupDisclosure = renderSetupDisclosure;
3834
- exports.FAMILY_SENTENCES = {
3835
- 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",
3836
- 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",
3837
- tools: "the name of each tool your agent calls",
3838
- outcome: "whether a call succeeded, failed, or was interrupted",
3839
- clock: "your machine's offset from UTC, so an evening is read as an evening",
3840
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3841
- model: "which model served the session, by name and by tier",
3842
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3843
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
3844
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3845
- context: "how full the context window got",
3846
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3847
- 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",
3848
- 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"
3849
- };
3850
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3851
- exports.REFUSALS = [
3852
- "Never your prompts, your agent's replies, or anything inside a file.",
3853
- "Never a file path, a command line, or a repository or branch name.",
3854
- "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."
3855
- ];
3856
- exports.FREE_TEXT_KEYS = ["message"];
3857
- function renderSetupDisclosure({ sends, displayName }) {
3858
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3859
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3860
- const lines = [
3861
- `What this sends from ${displayName}, once paired:`,
3862
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3863
- "",
3864
- ...exports.REFUSALS.map((line) => ` ${line}`),
3865
- "",
3866
- " Turn it off by revoking this tool in the Ascenda app."
3867
- ];
3868
- return lines.join("\n");
3869
- }
3870
- }
3871
- });
3872
-
3873
4377
  // ../packages/tool-kit/out/hookRunner.js
3874
4378
  var require_hookRunner = __commonJS({
3875
4379
  "../packages/tool-kit/out/hookRunner.js"(exports) {
@@ -3914,9 +4418,11 @@ var require_hookRunner = __commonJS({
3914
4418
  Object.defineProperty(exports, "__esModule", { value: true });
3915
4419
  exports.hookRunnerPaths = hookRunnerPaths;
3916
4420
  exports.hookLauncherScript = hookLauncherScript;
4421
+ exports.isDowngrade = isDowngrade;
3917
4422
  exports.installHookRunner = installHookRunner;
3918
4423
  exports.removeHookRunner = removeHookRunner;
3919
4424
  exports.hookRunnerCommand = hookRunnerCommand;
4425
+ exports.writeAtomically = writeAtomically;
3920
4426
  exports.lastHookPath = lastHookPath;
3921
4427
  exports.stampLastHook = stampLastHook;
3922
4428
  exports.readLastHook = readLastHook;
@@ -3926,10 +4432,11 @@ var require_hookRunner = __commonJS({
3926
4432
  var child_process_1 = __require("child_process");
3927
4433
  var fs = __importStar(__require("fs"));
3928
4434
  var path = __importStar(__require("path"));
4435
+ var collectorVersion_1 = require_collectorVersion();
3929
4436
  var tokenStore_1 = require_tokenStore();
3930
4437
  function hookRunnerPaths(binaryName) {
3931
4438
  const launcher = path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3932
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
4439
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
3933
4440
  }
3934
4441
  var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3935
4442
  function hookLauncherScript(options) {
@@ -4023,21 +4530,57 @@ var require_hookRunner = __commonJS({
4023
4530
  ""
4024
4531
  ].join("\n");
4025
4532
  }
4533
+ function releaseOf(version2) {
4534
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version2 ?? "").trim());
4535
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
4536
+ }
4537
+ function isDowngrade(installed, incoming) {
4538
+ const have = releaseOf(installed);
4539
+ const want = releaseOf(incoming);
4540
+ if (!have || !want)
4541
+ return false;
4542
+ for (let i = 0; i < 3; i++) {
4543
+ if (have[i] !== want[i])
4544
+ return have[i] > want[i];
4545
+ }
4546
+ return false;
4547
+ }
4548
+ function readInstalledVersion(file) {
4549
+ try {
4550
+ return fs.readFileSync(file, "utf8").trim() || void 0;
4551
+ } catch {
4552
+ return void 0;
4553
+ }
4554
+ }
4026
4555
  function installHookRunner(options) {
4027
4556
  const paths = hookRunnerPaths(options.binaryName);
4028
4557
  if (options.dryRun)
4029
4558
  return paths.launcher;
4030
4559
  const source = path.resolve(options.source ?? process.argv[1]);
4560
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
4561
+ const installed = readInstalledVersion(paths.version);
4562
+ const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
4563
+ if (installed && fs.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4564
+ options.onKeptNewer?.(installed, incoming);
4565
+ if (process.platform !== "win32" && !fs.existsSync(paths.launcher))
4566
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4567
+ return paths.launcher;
4568
+ }
4031
4569
  fs.mkdirSync(path.dirname(paths.launcher), { recursive: true });
4032
4570
  if (process.platform === "win32") {
4033
4571
  if (source !== path.resolve(paths.launcher))
4034
4572
  fs.copyFileSync(source, paths.launcher);
4573
+ writeAtomically(paths.version, `${incoming}
4574
+ `, 420);
4035
4575
  return paths.launcher;
4036
4576
  }
4037
4577
  if (source !== path.resolve(paths.bundle))
4038
4578
  writeAtomically(paths.bundle, fs.readFileSync(source), 493);
4039
4579
  writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4040
4580
  writeAtomically(paths.record, `${process.execPath}
4581
+ `, 420);
4582
+ if (source !== path.resolve(paths.bundle))
4583
+ writeAtomically(paths.version, `${incoming}
4041
4584
  `, 420);
4042
4585
  fs.rmSync(paths.noNode, { force: true });
4043
4586
  return paths.launcher;
@@ -4052,8 +4595,8 @@ var require_hookRunner = __commonJS({
4052
4595
  }
4053
4596
  return removed;
4054
4597
  }
4055
- function hookRunnerCommand(launcher) {
4056
- return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4598
+ function hookRunnerCommand(launcher, platform = process.platform) {
4599
+ return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4057
4600
  }
4058
4601
  function writeAtomically(target, contents, mode) {
4059
4602
  const tmp = `${target}.${process.pid}.tmp`;
@@ -4123,6 +4666,115 @@ var require_hookRunner = __commonJS({
4123
4666
  }
4124
4667
  });
4125
4668
 
4669
+ // ../packages/tool-kit/out/settingsFile.js
4670
+ var require_settingsFile = __commonJS({
4671
+ "../packages/tool-kit/out/settingsFile.js"(exports) {
4672
+ "use strict";
4673
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4674
+ if (k2 === void 0) k2 = k;
4675
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4676
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4677
+ desc = { enumerable: true, get: function() {
4678
+ return m[k];
4679
+ } };
4680
+ }
4681
+ Object.defineProperty(o, k2, desc);
4682
+ } : function(o, m, k, k2) {
4683
+ if (k2 === void 0) k2 = k;
4684
+ o[k2] = m[k];
4685
+ });
4686
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4687
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4688
+ } : function(o, v) {
4689
+ o["default"] = v;
4690
+ });
4691
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4692
+ var ownKeys = function(o) {
4693
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4694
+ var ar = [];
4695
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4696
+ return ar;
4697
+ };
4698
+ return ownKeys(o);
4699
+ };
4700
+ return function(mod) {
4701
+ if (mod && mod.__esModule) return mod;
4702
+ var result = {};
4703
+ if (mod != null) {
4704
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4705
+ }
4706
+ __setModuleDefault(result, mod);
4707
+ return result;
4708
+ };
4709
+ }();
4710
+ Object.defineProperty(exports, "__esModule", { value: true });
4711
+ exports.replaceSettingsFile = replaceSettingsFile;
4712
+ var fs = __importStar(__require("fs"));
4713
+ var path = __importStar(__require("path"));
4714
+ var hookRunner_1 = require_hookRunner();
4715
+ function replaceSettingsFile(settingsFile, contents) {
4716
+ const exists = fs.existsSync(settingsFile);
4717
+ const target = exists ? fs.realpathSync(settingsFile) : settingsFile;
4718
+ if (exists) {
4719
+ const backup = `${settingsFile}.ascenda-backup`;
4720
+ if (!fs.existsSync(backup))
4721
+ fs.copyFileSync(target, backup);
4722
+ }
4723
+ fs.mkdirSync(path.dirname(target), { recursive: true });
4724
+ const mode = exists ? fs.statSync(target).mode & 511 : 420;
4725
+ (0, hookRunner_1.writeAtomically)(target, contents, mode);
4726
+ }
4727
+ }
4728
+ });
4729
+
4730
+ // ../packages/tool-kit/out/setupDisclosure.js
4731
+ var require_setupDisclosure = __commonJS({
4732
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
4733
+ "use strict";
4734
+ Object.defineProperty(exports, "__esModule", { value: true });
4735
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
4736
+ exports.renderSetupDisclosure = renderSetupDisclosure;
4737
+ exports.FAMILY_SENTENCES = {
4738
+ session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
4739
+ counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
4740
+ tools: "the name of each tool your agent calls",
4741
+ outcome: "whether a call succeeded, failed, or was interrupted",
4742
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
4743
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
4744
+ model: "which model served the session, by name and by tier",
4745
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
4746
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
4747
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
4748
+ context: "how full the context window got",
4749
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, input_request, idle_prompt, or other, and that it asked permission for a tool or had one refused in auto mode, with the tool's name",
4750
+ subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
4751
+ forge: "for a GitHub repository, one digest of owner/repo and one of the branch, which anyone who guesses the names can reproduce, so a pull request can be matched to your session (turn off with setup --no-repo-keys)",
4752
+ turns: "an opaque id your agent gives each prompt, so one turn's events group together",
4753
+ reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
4754
+ };
4755
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
4756
+ exports.REFUSALS = [
4757
+ "Never your prompts, your agent's replies, or anything inside a file.",
4758
+ "Never a file path, a command line, or a repository or branch name.",
4759
+ "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
4760
+ ];
4761
+ exports.FREE_TEXT_KEYS = ["message"];
4762
+ function renderSetupDisclosure({ sends, displayName }) {
4763
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
4764
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
4765
+ const lines = [
4766
+ `What this sends from ${displayName}, once paired:`,
4767
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
4768
+ "",
4769
+ ...exports.REFUSALS.map((line) => ` ${line}`),
4770
+ "",
4771
+ " Turn it off by revoking this tool in the Ascenda app."
4772
+ ];
4773
+ return lines.join("\n");
4774
+ }
4775
+ }
4776
+ });
4777
+
4126
4778
  // ../packages/tool-kit/out/saverHandoff.js
4127
4779
  var require_saverHandoff = __commonJS({
4128
4780
  "../packages/tool-kit/out/saverHandoff.js"(exports) {
@@ -4888,6 +5540,8 @@ var require_cliAgentSetup = __commonJS({
4888
5540
  exports.runCliAgentSetup = runCliAgentSetup;
4889
5541
  exports.writeHookSettings = writeHookSettings;
4890
5542
  exports.registeredHookSets = registeredHookSets;
5543
+ exports.ourHookPositions = ourHookPositions;
5544
+ exports.trustProblemLines = trustProblemLines;
4891
5545
  exports.findStaleHookCommands = findStaleHookCommands;
4892
5546
  exports.cliAgentRegistrations = cliAgentRegistrations;
4893
5547
  var crypto = __importStar(__require("crypto"));
@@ -4901,6 +5555,7 @@ var require_cliAgentSetup = __commonJS({
4901
5555
  var http_1 = require_http();
4902
5556
  var hookSet_1 = require_hookSet();
4903
5557
  var initiatives_1 = require_initiatives();
5558
+ var settingsFile_1 = require_settingsFile();
4904
5559
  var setupDisclosure_1 = require_setupDisclosure();
4905
5560
  var hookRunner_1 = require_hookRunner();
4906
5561
  var liveSignalDoctor_1 = require_liveSignalDoctor();
@@ -4937,6 +5592,10 @@ Options
4937
5592
  --no-pair install without pairing: local features on, nothing sent
4938
5593
  --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
4939
5594
  On by default when not paired; machine-wide, shared by every agent
5595
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
5596
+ repository gets a key and, off its default branch, a branch key, so a pull
5597
+ request can be matched to a session. They are digests anyone who guesses the
5598
+ names can reproduce. Machine-wide. --repo-keys turns them back on
4940
5599
  --scope user|project where hooks are registered (default user: every project)
4941
5600
  --project-dir <path> project root for --scope project (default cwd)
4942
5601
  --dry-run print what would change, write nothing
@@ -4993,6 +5652,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4993
5652
  });
4994
5653
  if (options.eventLog !== void 0)
4995
5654
  (0, credentials_1.writeEventLogSetting)(options.eventLog);
5655
+ if (options.repoKeys !== void 0)
5656
+ (0, credentials_1.writeRepoKeysSetting)(options.repoKeys);
4996
5657
  }
4997
5658
  if (isHomeProject(options)) {
4998
5659
  detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
@@ -5132,6 +5793,12 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5132
5793
  i += consumed;
5133
5794
  break;
5134
5795
  }
5796
+ case "--repo-keys":
5797
+ options.repoKeys = true;
5798
+ break;
5799
+ case "--no-repo-keys":
5800
+ options.repoKeys = false;
5801
+ break;
5135
5802
  case "--no-pair":
5136
5803
  // `--no-pairing` is the spelling this landed under first. Both appeared
5137
5804
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -5261,7 +5928,12 @@ Pairing ${status.status}. Run setup again.`);
5261
5928
  return void 0;
5262
5929
  }
5263
5930
  function installBinary(spec, dryRun) {
5264
- return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
5931
+ return (0, hookRunner_1.installHookRunner)({
5932
+ binaryName: spec.binaryName,
5933
+ setupCommand: `npx ${spec.packageName} setup`,
5934
+ dryRun,
5935
+ onKeptNewer: (installed, incoming) => console.log(` Kept the installed hook bundle (${installed}) rather than replace it with this older ${incoming}. Run setup from the newer version to change it.`)
5936
+ });
5265
5937
  }
5266
5938
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
5267
5939
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -5281,8 +5953,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5281
5953
  const command = hookCommand(binary, spec);
5282
5954
  const hooks = { ...settings.hooks ?? {} };
5283
5955
  for (const event of spec.hookEvents) {
5284
- const kept = (hooks[event] ?? []).filter((entry) => !isOurs(entry, spec));
5285
- hooks[event] = [...kept, spec.settings.entry(command, event)];
5956
+ hooks[event] = placeOurEntry(hooks[event] ?? [], spec.settings.entry(command, event), spec);
5286
5957
  }
5287
5958
  const updated = { ...settings, hooks };
5288
5959
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -5295,10 +5966,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5295
5966
  ${serialised}`);
5296
5967
  return true;
5297
5968
  }
5298
- if (exists)
5299
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5300
- fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
5301
- fs.writeFileSync(settingsFile, serialised, "utf8");
5969
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
5302
5970
  return true;
5303
5971
  }
5304
5972
  function hookCommand(binary, spec) {
@@ -5308,28 +5976,130 @@ ${serialised}`);
5308
5976
  const sets = /* @__PURE__ */ new Map();
5309
5977
  for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
5310
5978
  for (const entry of entries ?? []) {
5311
- if (!isOurs(entry, spec))
5312
- continue;
5313
- const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
5314
- sets.set(event, Math.min(set, sets.get(event) ?? set));
5979
+ for (const command of commandsOf(entry, spec)) {
5980
+ if (!isOurCommand(command, spec))
5981
+ continue;
5982
+ const set = (0, hookSet_1.hookSetOfCommand)(command);
5983
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5984
+ }
5315
5985
  }
5316
5986
  }
5317
5987
  return sets;
5318
5988
  }
5319
- function isOurs(entry, spec) {
5989
+ function ourHookPositions(settings, spec) {
5990
+ const found = [];
5991
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5992
+ (groups ?? []).forEach((group, groupIndex) => {
5993
+ const handlers = group?.hooks;
5994
+ if (Array.isArray(handlers)) {
5995
+ handlers.forEach((handler, handlerIndex) => {
5996
+ if (isOurs({ hooks: [handler] }, spec))
5997
+ found.push({ event, group: groupIndex, handler: handlerIndex });
5998
+ });
5999
+ } else if (isOurs(group, spec)) {
6000
+ found.push({ event, group: groupIndex, handler: 0 });
6001
+ }
6002
+ });
6003
+ }
6004
+ return found;
6005
+ }
6006
+ function trustProblemLines(spec, settingsFile, settings, indent) {
6007
+ if (!spec.trust)
6008
+ return [];
6009
+ const ours = ourHookPositions(settings, spec);
6010
+ if (ours.length === 0)
6011
+ return [];
6012
+ const report = spec.trust.check(settingsFile, ours);
6013
+ const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os.homedir());
6014
+ const lines = [];
6015
+ if (report.unreadable) {
6016
+ lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
6017
+ }
6018
+ if (report.untrusted.length) {
6019
+ const names = [...new Set(report.untrusted.map((position) => position.event))].join(", ");
6020
+ lines.push(`${report.untrusted.length} of ${ours.length} hooks are not approved in ${where} (${names}). ${spec.displayName} skips them without a message, so nothing is sent for those events.`);
6021
+ }
6022
+ for (const entry of report.stale)
6023
+ lines.push(entry);
6024
+ if (lines.length)
6025
+ lines.push(spec.trust.fix);
6026
+ return lines.map((line) => `${indent}${line}`);
6027
+ }
6028
+ function commandsOf(entry, spec) {
6029
+ if (spec.settings.grouped) {
6030
+ return innerHooks(entry).map(commandOfHook).filter((command2) => typeof command2 === "string");
6031
+ }
5320
6032
  const command = spec.settings.commandOf(entry);
5321
- return typeof command === "string" && command.includes(spec.binaryName);
6033
+ return typeof command === "string" ? [command] : [];
6034
+ }
6035
+ function innerHooks(entry) {
6036
+ const hooks = entry && typeof entry === "object" ? entry.hooks : void 0;
6037
+ return Array.isArray(hooks) ? hooks : [];
6038
+ }
6039
+ function commandOfHook(hook) {
6040
+ return hook && typeof hook === "object" ? hook.command : void 0;
6041
+ }
6042
+ function isOurCommand(command, spec) {
6043
+ return command.includes(spec.binaryName);
6044
+ }
6045
+ function isOurs(entry, spec) {
6046
+ return commandsOf(entry, spec).some((command) => isOurCommand(command, spec));
6047
+ }
6048
+ function isOurInnerHook(hook, spec) {
6049
+ const command = commandOfHook(hook);
6050
+ return typeof command === "string" && isOurCommand(command, spec);
6051
+ }
6052
+ function withoutOurEntries(entries, spec) {
6053
+ if (!spec.settings.grouped)
6054
+ return entries.filter((entry) => !isOurs(entry, spec));
6055
+ const kept = [];
6056
+ for (const entry of entries) {
6057
+ if (!isOurs(entry, spec)) {
6058
+ kept.push(entry);
6059
+ continue;
6060
+ }
6061
+ const others = innerHooks(entry).filter((hook) => !isOurInnerHook(hook, spec));
6062
+ if (others.length)
6063
+ kept.push({ ...entry, hooks: others });
6064
+ }
6065
+ return kept;
6066
+ }
6067
+ function placeOurEntry(entries, wanted, spec) {
6068
+ if (!spec.settings.grouped)
6069
+ return [...withoutOurEntries(entries, spec), wanted];
6070
+ const replacements = innerHooks(wanted);
6071
+ let placed = false;
6072
+ const result = [];
6073
+ for (const entry of entries) {
6074
+ if (!isOurs(entry, spec)) {
6075
+ result.push(entry);
6076
+ continue;
6077
+ }
6078
+ const matcher = entry.matcher;
6079
+ const matchesAll = matcher === void 0 || matcher === "";
6080
+ const next = [];
6081
+ for (const hook of innerHooks(entry)) {
6082
+ if (!isOurInnerHook(hook, spec))
6083
+ next.push(hook);
6084
+ else if (!placed && matchesAll) {
6085
+ next.push(...replacements);
6086
+ placed = true;
6087
+ }
6088
+ }
6089
+ if (next.length)
6090
+ result.push({ ...entry, hooks: next });
6091
+ }
6092
+ return placed ? result : [...result, wanted];
5322
6093
  }
5323
6094
  function findStaleHookCommands(settings, binary, spec) {
5324
6095
  const stale = /* @__PURE__ */ new Set();
5325
6096
  for (const entries of Object.values(settings.hooks ?? {})) {
5326
6097
  for (const entry of entries ?? []) {
5327
- const command = spec.settings.commandOf(entry);
5328
- if (typeof command !== "string")
5329
- continue;
5330
- if (!/ascenda/i.test(command) || command.includes(binary))
5331
- continue;
5332
- stale.add(command);
6098
+ for (const command of commandsOf(entry, spec)) {
6099
+ if (!/ascenda/i.test(command) || command.includes(binary))
6100
+ continue;
6101
+ stale.add(command);
6102
+ }
5333
6103
  }
5334
6104
  }
5335
6105
  return [...stale];
@@ -5373,6 +6143,14 @@ ${serialised}`);
5373
6143
  const oldest = Math.min(...sets);
5374
6144
  console.log(oldest < spec.hookSet ? `hook set ${oldest}, this version registers ${spec.hookSet}. Upgrade: npx ${spec.packageName} setup${options.scope === "user" ? " --scope user" : ""}` : `hook set ${spec.hookSet} (current)`);
5375
6145
  }
6146
+ const trustLines = trustProblemLines(spec, settingsFile, settings, "");
6147
+ if (trustLines.length) {
6148
+ console.log(`not trusted ${trustLines[0]}`);
6149
+ for (const line of trustLines.slice(1))
6150
+ console.log(` ${line}`);
6151
+ } else if (spec.trust && registered > 0) {
6152
+ console.log("trust every registered hook is approved");
6153
+ }
5376
6154
  if (stale.length) {
5377
6155
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
5378
6156
  for (const command of stale)
@@ -5394,7 +6172,7 @@ ${serialised}`);
5394
6172
  await notices.markShown();
5395
6173
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
5396
6174
  const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5397
- const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
6175
+ const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
5398
6176
  return healthy ? 0 : 1;
5399
6177
  }
5400
6178
  function countRegistered(settings, spec) {
@@ -5437,12 +6215,37 @@ ${serialised}`);
5437
6215
  } catch (error2) {
5438
6216
  lines.push(` Live signal (could not be checked: ${error2 instanceof Error ? error2.message : String(error2)})`);
5439
6217
  }
6218
+ if (spec.trust) {
6219
+ const found = trustDoctorLines(spec, options.projectDir, ui);
6220
+ if (found.length)
6221
+ lines.push("", ...found);
6222
+ }
5440
6223
  lines.push("", ...accountLines(ui, spec));
5441
6224
  const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
5442
6225
  lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5443
6226
  console.log(lines.join("\n"));
5444
6227
  return 0;
5445
6228
  }
6229
+ function trustDoctorLines(spec, projectDir, ui) {
6230
+ const userFile = spec.settings.settingsPath("user", projectDir);
6231
+ const projectFile = spec.settings.settingsPath("project", projectDir);
6232
+ const files = userFile === projectFile ? [userFile] : [userFile, projectFile];
6233
+ const out = [];
6234
+ for (const file of files) {
6235
+ const settings = readSettings(file);
6236
+ if (ourHookPositions(settings, spec).length === 0)
6237
+ continue;
6238
+ const problems = trustProblemLines(spec, file, settings, "");
6239
+ if (problems.length === 0) {
6240
+ out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os.homedir())} is approved`);
6241
+ continue;
6242
+ }
6243
+ out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
6244
+ for (const line of problems.slice(1))
6245
+ out.push(`${" ".repeat(25)}${line}`);
6246
+ }
6247
+ return out;
6248
+ }
5446
6249
  function accountLines(ui, spec) {
5447
6250
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5448
6251
  const id = credentials?.toolInstallationId;
@@ -5476,7 +6279,7 @@ ${serialised}`);
5476
6279
  const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
5477
6280
  const hooks = { ...settings.hooks ?? {} };
5478
6281
  for (const event of Object.keys(hooks)) {
5479
- const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
6282
+ const kept = withoutOurEntries(hooks[event], spec);
5480
6283
  if (kept.length)
5481
6284
  hooks[event] = kept;
5482
6285
  else
@@ -5485,9 +6288,8 @@ ${serialised}`);
5485
6288
  const updated = { ...settings, hooks };
5486
6289
  if (!Object.keys(hooks).length)
5487
6290
  delete updated.hooks;
5488
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5489
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5490
- `, "utf8");
6291
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
6292
+ `);
5491
6293
  return true;
5492
6294
  } catch {
5493
6295
  return false;
@@ -5559,7 +6361,9 @@ var require_turnState = __commonJS({
5559
6361
  }();
5560
6362
  Object.defineProperty(exports, "__esModule", { value: true });
5561
6363
  exports.recordTurnStart = recordTurnStart;
6364
+ exports.readTurnPromptId = readTurnPromptId;
5562
6365
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
6366
+ var crypto_1 = __require("crypto");
5563
6367
  var fs = __importStar(__require("fs"));
5564
6368
  var path = __importStar(__require("path"));
5565
6369
  var tokenStore_1 = require_tokenStore();
@@ -5572,11 +6376,24 @@ var require_turnState = __commonJS({
5572
6376
  }
5573
6377
  function recordTurnStart(agent, sessionId, now = Date.now()) {
5574
6378
  if (!sessionId)
5575
- return;
6379
+ return void 0;
5576
6380
  try {
6381
+ const promptId = (0, crypto_1.randomUUID)();
5577
6382
  fs.mkdirSync(stateDir(), { recursive: true });
5578
- fs.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
6383
+ fs.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
6384
+ return promptId;
5579
6385
  } catch {
6386
+ return void 0;
6387
+ }
6388
+ }
6389
+ function readTurnPromptId(agent, sessionId) {
6390
+ if (!sessionId)
6391
+ return void 0;
6392
+ try {
6393
+ const id = fs.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
6394
+ return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
6395
+ } catch {
6396
+ return void 0;
5580
6397
  }
5581
6398
  }
5582
6399
  function consumeTurnDurationMs(agent, sessionId, now = Date.now()) {
@@ -5584,7 +6401,7 @@ var require_turnState = __commonJS({
5584
6401
  return void 0;
5585
6402
  const file = turnFile(agent, sessionId);
5586
6403
  try {
5587
- const started = Number(fs.readFileSync(file, "utf8").trim());
6404
+ const started = Number(fs.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
5588
6405
  fs.rmSync(file, { force: true });
5589
6406
  if (!Number.isFinite(started) || started <= 0 || started > now)
5590
6407
  return void 0;
@@ -5740,10 +6557,11 @@ var require_out3 = __commonJS({
5740
6557
  "../packages/tool-kit/out/index.js"(exports) {
5741
6558
  "use strict";
5742
6559
  Object.defineProperty(exports, "__esModule", { value: true });
5743
- 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;
5744
- 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;
5745
- 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;
5746
- 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;
6560
+ exports.resolveEventLog = exports.parseEventLogFlag = exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.startBackgroundFlush = exports.runOutboxFlush = exports.hookDeliveryInline = exports.flushLockPath = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = exports.FLUSH_LOCK_FRESH_MS = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.shellCommandFacts = exports.invitesDebrief = exports.classifyMcpWorkMilestone = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
6561
+ exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.readTurnPromptId = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeRepoKeysSetting = exports.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.trustProblemLines = exports.runCliAgentSetup = exports.registeredHookSets = exports.ourHookPositions = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.withPromptId = exports.withForgeKeys = exports.loadCliAgentConfig = exports.flushHookOutbox = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = void 0;
6562
+ exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.repoKeysEnabled = exports.deriveForgeKeysForCwd = exports.REPO_KEYS_ENV_VAR = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeBranchKey = exports.forgeRepoKey = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = void 0;
6563
+ exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.replaceSettingsFile = exports.writeAtomically = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.isDowngrade = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = void 0;
6564
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = void 0;
5747
6565
  var commandClassifier_1 = require_commandClassifier();
5748
6566
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5749
6567
  return commandClassifier_1.classifyCommand;
@@ -5762,9 +6580,16 @@ var require_out3 = __commonJS({
5762
6580
  Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
5763
6581
  return workMilestoneClassifier_1.classifyWorkMilestone;
5764
6582
  } });
6583
+ Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
6584
+ return workMilestoneClassifier_1.classifyMcpWorkMilestone;
6585
+ } });
5765
6586
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
5766
6587
  return workMilestoneClassifier_1.invitesDebrief;
5767
6588
  } });
6589
+ var shellFacts_1 = require_shellFacts();
6590
+ Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
6591
+ return shellFacts_1.shellCommandFacts;
6592
+ } });
5768
6593
  var autonomyBand_1 = require_autonomyBand();
5769
6594
  Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
5770
6595
  return autonomyBand_1.autonomyBand;
@@ -5834,6 +6659,28 @@ var require_out3 = __commonJS({
5834
6659
  Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
5835
6660
  return collectorVersion_1.describeCollectorVersion;
5836
6661
  } });
6662
+ var backgroundDelivery_1 = require_backgroundDelivery();
6663
+ Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
6664
+ return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
6665
+ } });
6666
+ Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
6667
+ return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
6668
+ } });
6669
+ Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
6670
+ return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
6671
+ } });
6672
+ Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
6673
+ return backgroundDelivery_1.flushLockPath;
6674
+ } });
6675
+ Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
6676
+ return backgroundDelivery_1.hookDeliveryInline;
6677
+ } });
6678
+ Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
6679
+ return backgroundDelivery_1.runOutboxFlush;
6680
+ } });
6681
+ Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
6682
+ return backgroundDelivery_1.startBackgroundFlush;
6683
+ } });
5837
6684
  var eventSender_1 = require_eventSender();
5838
6685
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
5839
6686
  return eventSender_1.AscendaEventSender;
@@ -5892,9 +6739,18 @@ var require_out3 = __commonJS({
5892
6739
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
5893
6740
  return hookAdapter_1.deliverHookEvents;
5894
6741
  } });
6742
+ Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
6743
+ return hookAdapter_1.flushHookOutbox;
6744
+ } });
5895
6745
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
5896
6746
  return hookAdapter_1.loadCliAgentConfig;
5897
6747
  } });
6748
+ Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
6749
+ return hookAdapter_1.withForgeKeys;
6750
+ } });
6751
+ Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
6752
+ return hookAdapter_1.withPromptId;
6753
+ } });
5898
6754
  Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
5899
6755
  return hookAdapter_1.resolveCliAgentInstallationId;
5900
6756
  } });
@@ -5911,12 +6767,18 @@ var require_out3 = __commonJS({
5911
6767
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
5912
6768
  return cliAgentSetup_1.isCliAgentManagementCommand;
5913
6769
  } });
6770
+ Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
6771
+ return cliAgentSetup_1.ourHookPositions;
6772
+ } });
5914
6773
  Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5915
6774
  return cliAgentSetup_1.registeredHookSets;
5916
6775
  } });
5917
6776
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
5918
6777
  return cliAgentSetup_1.runCliAgentSetup;
5919
6778
  } });
6779
+ Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
6780
+ return cliAgentSetup_1.trustProblemLines;
6781
+ } });
5920
6782
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
5921
6783
  return cliAgentSetup_1.writeHookSettings;
5922
6784
  } });
@@ -5958,6 +6820,9 @@ var require_out3 = __commonJS({
5958
6820
  Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
5959
6821
  return credentials_1.writeEventLogSetting;
5960
6822
  } });
6823
+ Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
6824
+ return credentials_1.writeRepoKeysSetting;
6825
+ } });
5961
6826
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5962
6827
  return credentials_1.writeMachineCredentials;
5963
6828
  } });
@@ -5968,6 +6833,9 @@ var require_out3 = __commonJS({
5968
6833
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
5969
6834
  return turnState_1.consumeTurnDurationMs;
5970
6835
  } });
6836
+ Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
6837
+ return turnState_1.readTurnPromptId;
6838
+ } });
5971
6839
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
5972
6840
  return turnState_1.recordTurnStart;
5973
6841
  } });
@@ -6102,6 +6970,12 @@ var require_out3 = __commonJS({
6102
6970
  Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
6103
6971
  return forgeProject_1.forgeProjectHash;
6104
6972
  } });
6973
+ Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
6974
+ return forgeProject_1.forgeRepoKey;
6975
+ } });
6976
+ Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
6977
+ return forgeProject_1.forgeBranchKey;
6978
+ } });
6105
6979
  Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
6106
6980
  return forgeProject_1.parseForgeFullName;
6107
6981
  } });
@@ -6114,6 +6988,16 @@ var require_out3 = __commonJS({
6114
6988
  Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
6115
6989
  return forgeProject_1.recordForgeProjectAlias;
6116
6990
  } });
6991
+ var forgeKeys_1 = require_forgeKeys();
6992
+ Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
6993
+ return forgeKeys_1.REPO_KEYS_ENV_VAR;
6994
+ } });
6995
+ Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
6996
+ return forgeKeys_1.deriveForgeKeysForCwd;
6997
+ } });
6998
+ Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
6999
+ return forgeKeys_1.repoKeysEnabled;
7000
+ } });
6117
7001
  var liveBus_1 = require_liveBus();
6118
7002
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
6119
7003
  return liveBus_1.emitLiveSignal;
@@ -6184,6 +7068,9 @@ var require_out3 = __commonJS({
6184
7068
  Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
6185
7069
  return hookRunner_1.installHookRunner;
6186
7070
  } });
7071
+ Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
7072
+ return hookRunner_1.isDowngrade;
7073
+ } });
6187
7074
  Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
6188
7075
  return hookRunner_1.lastHookPath;
6189
7076
  } });
@@ -6202,6 +7089,13 @@ var require_out3 = __commonJS({
6202
7089
  Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
6203
7090
  return hookRunner_1.tidyHomePath;
6204
7091
  } });
7092
+ Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
7093
+ return hookRunner_1.writeAtomically;
7094
+ } });
7095
+ var settingsFile_1 = require_settingsFile();
7096
+ Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
7097
+ return settingsFile_1.replaceSettingsFile;
7098
+ } });
6205
7099
  var liveSignalDoctor_1 = require_liveSignalDoctor();
6206
7100
  Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
6207
7101
  return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;