@ascenda-one/claude-code-hooks 0.1.13 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -12,9 +12,16 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
12
12
  if (typeof require !== "undefined") return require.apply(this, arguments);
13
13
  throw Error('Dynamic require of "' + x + '" is not supported');
14
14
  });
15
+ var __esm = (fn, res) => function __init() {
16
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
17
+ };
15
18
  var __commonJS = (cb, mod) => function __require2() {
16
19
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
20
  };
21
+ var __export = (target, all) => {
22
+ for (var name in all)
23
+ __defProp(target, name, { get: all[name], enumerable: true });
24
+ };
18
25
  var __copyProps = (to, from, except, desc) => {
19
26
  if (from && typeof from === "object" || typeof from === "function") {
20
27
  for (let key of __getOwnPropNames(from))
@@ -323,9 +330,9 @@ var require_payload = __commonJS({
323
330
  }
324
331
  return void 0;
325
332
  }
326
- function getNested2(input, path) {
333
+ function getNested2(input, path3) {
327
334
  let current = input;
328
- for (const segment of path) {
335
+ for (const segment of path3) {
329
336
  if (!current || typeof current !== "object")
330
337
  return void 0;
331
338
  current = current[segment];
@@ -333,16 +340,16 @@ var require_payload = __commonJS({
333
340
  return current;
334
341
  }
335
342
  function getNestedString3(input, paths) {
336
- for (const path of paths) {
337
- const value = getNested2(input, path);
343
+ for (const path3 of paths) {
344
+ const value = getNested2(input, path3);
338
345
  if (typeof value === "string" && value.trim())
339
346
  return value;
340
347
  }
341
348
  return void 0;
342
349
  }
343
350
  function getNestedNumber2(input, paths) {
344
- for (const path of paths) {
345
- const value = getNested2(input, path);
351
+ for (const path3 of paths) {
352
+ const value = getNested2(input, path3);
346
353
  if (typeof value === "number" && Number.isFinite(value))
347
354
  return value;
348
355
  }
@@ -377,12 +384,155 @@ var require_payload = __commonJS({
377
384
  }
378
385
  });
379
386
 
387
+ // ../packages/tool-contract/out/metricKeys.js
388
+ var require_metricKeys = __commonJS({
389
+ "../packages/tool-contract/out/metricKeys.js"(exports) {
390
+ "use strict";
391
+ Object.defineProperty(exports, "__esModule", { value: true });
392
+ exports.METRIC_KEYS = void 0;
393
+ exports.backendMetricKeys = backendMetricKeys;
394
+ var CONTEXT_WINDOW_CANONICAL_ALIASES = [
395
+ "contextWindowPeakPct",
396
+ "context_window_peak_pct",
397
+ "contextWindowPct",
398
+ "context_window_pct"
399
+ ];
400
+ var CONTEXT_WINDOW_CURSOR_PERCENT_ALIASES = ["contextUsagePercent"];
401
+ exports.METRIC_KEYS = {
402
+ // ── Read by a backend reader ────────────────────────────────────────────
403
+ contextWindowPeakPct: {
404
+ readBy: ["backend", "handoff"],
405
+ backendAliases: CONTEXT_WINDOW_CANONICAL_ALIASES,
406
+ unit: "fraction of the context window (0\u20131; uncapped for >200k contexts)",
407
+ note: "Claude Code reports a true per-session peak. Cursor reports its composer's last known occupancy under the same key \u2014 the closest its store can answer, and not the same measurement."
408
+ },
409
+ contextUsagePercent: {
410
+ readBy: ["backend", "handoff"],
411
+ backendAliases: CONTEXT_WINDOW_CURSOR_PERCENT_ALIASES,
412
+ unit: "percent (0\u2013100)",
413
+ note: "Cursor's own column name. Superseded by contextWindowPeakPct on the wire; kept because the handoff reads it and imported rows carry it. Unit-explicit on the backend: always divided by 100, never put through the fraction-or-percent heuristic."
414
+ },
415
+ promptCount: { readBy: ["backend", "handoff"], backendAliases: ["promptCount", "prompt_count"] },
416
+ sessionMinutes: { readBy: ["backend"], backendAliases: ["sessionMinutes", "session_minutes"], unit: "minutes" },
417
+ durationBucket: { readBy: ["backend", "handoff"], backendAliases: ["durationBucket", "duration_bucket"] },
418
+ afterHoursPrompts: { readBy: ["backend", "handoff"], backendAliases: ["afterHoursPrompts", "after_hours_prompts"] },
419
+ inputTokens: { readBy: ["backend"], backendAliases: ["inputTokens", "input_tokens"], unit: "tokens" },
420
+ outputTokens: { readBy: ["backend"], backendAliases: ["outputTokens", "output_tokens"], unit: "tokens" },
421
+ cacheReadTokens: { readBy: ["backend"], backendAliases: ["cacheReadTokens", "cache_read_tokens"], unit: "tokens" },
422
+ queuedPrompts: { readBy: ["backend"], backendAliases: ["queuedPrompts", "queued_prompts"] },
423
+ linesChangedBucket: { readBy: ["backend"], backendAliases: ["linesChangedBucket", "lines_changed_bucket"] },
424
+ // ── Read by the local handoff only ──────────────────────────────────────
425
+ activeMinutes: { readBy: ["handoff"], unit: "minutes" },
426
+ afterHoursRequests: { readBy: ["handoff"] },
427
+ approximateLintErrorsCount: { readBy: ["handoff"] },
428
+ canceledCount: { readBy: ["handoff"] },
429
+ chatEditCount: { readBy: ["handoff"] },
430
+ compactionCount: {
431
+ readBy: ["handoff"],
432
+ note: "The backend counts context_compression_* event rows, not this key. Both are emitted; this one is for the handoff."
433
+ },
434
+ contextWindowPeakTokens: {
435
+ readBy: ["handoff"],
436
+ unit: "tokens",
437
+ note: "The measured quantity, with no assumed denominator. Prefer this to the ratio for any within-person baseline."
438
+ },
439
+ date: { readBy: ["handoff"] },
440
+ errorCount: { readBy: ["handoff"] },
441
+ filesChangedCount: { readBy: ["handoff"] },
442
+ humanChangesCount: { readBy: ["handoff"] },
443
+ linesAdded: { readBy: ["handoff"] },
444
+ linesRemoved: { readBy: ["handoff"] },
445
+ primaryModel: { readBy: ["handoff"] },
446
+ requestCount: { readBy: ["handoff"] },
447
+ sessionStartedAt: { readBy: ["handoff"] },
448
+ subagentComposers: { readBy: ["handoff"] },
449
+ subagentToolCallCount: {
450
+ readBy: ["handoff"],
451
+ note: "Claude Code only: calls made inside subagent transcripts, kept out of toolCallCount so the main-loop count matches what the wire events carry."
452
+ },
453
+ subagentTranscripts: { readBy: ["handoff"] },
454
+ toolCallCount: {
455
+ readBy: ["handoff"],
456
+ note: "The backend counts ai_tool_call_started event rows, not this key \u2014 same split as compactionCount. Deduplicated on the tool-call id; see each extractor for what one call means in its store."
457
+ },
458
+ toolCallsUndated: {
459
+ readBy: ["handoff"],
460
+ note: "Cursor only: calls whose every record carries an empty createdAt. Counted in toolCallCount, but no event exists for them \u2014 the wire total is smaller than this session count by exactly this number."
461
+ },
462
+ toolFailureCount: { readBy: ["handoff"] },
463
+ totalEntryCount: { readBy: ["handoff"] },
464
+ userModifiedEditCount: {
465
+ readBy: ["handoff"],
466
+ note: "Null, never 0 \u2014 Claude Code never sets userModified true, so 0 would assert 'no AI edit was ever corrected by hand'."
467
+ },
468
+ // ── Diagnostic: read by nobody, on purpose ──────────────────────────────
469
+ abandonedPromptCount: { readBy: ["diagnostic"] },
470
+ // Epoch-marker metrics. The marker is local-only and never reaches the wire
471
+ // (see EXTRACTION_EPOCH_KIND), but it travels as a NormalizedHistoricalEvent
472
+ // and so is keyed by the same vocabulary.
473
+ windowOldest: { readBy: ["handoff"], note: "Oldest event the extraction saw \u2014 the marker's left edge." },
474
+ windowNewest: { readBy: ["handoff"], note: "Newest event the extraction saw \u2014 the marker's right edge." },
475
+ projectsWithNoReadableTranscript: { readBy: ["diagnostic"] },
476
+ unparsedComposerHeaders: { readBy: ["diagnostic"] },
477
+ unknownComposerHeaderTypes: { readBy: ["diagnostic"] },
478
+ orphanedBubbles: { readBy: ["diagnostic"] },
479
+ orphanedSubagentBubbles: { readBy: ["diagnostic"] },
480
+ sessionsWithoutTimeline: { readBy: ["diagnostic"] },
481
+ emptyComposers: { readBy: ["diagnostic"] },
482
+ apiErrorCount: { readBy: ["diagnostic"] },
483
+ assistantTurns: { readBy: ["diagnostic"] },
484
+ compactionAutoCount: { readBy: ["diagnostic"] },
485
+ compactionManualCount: { readBy: ["diagnostic"] },
486
+ editDayCount: { readBy: ["diagnostic"] },
487
+ emptyChatSessions: { readBy: ["diagnostic"] },
488
+ gitBranch: { readBy: ["diagnostic"] },
489
+ linesChanged: { readBy: ["diagnostic"] },
490
+ malformedChatSessionLines: { readBy: ["diagnostic"] },
491
+ malformedHistoryEntries: { readBy: ["diagnostic"] },
492
+ mode: { readBy: ["diagnostic"] },
493
+ modelCount: { readBy: ["diagnostic"] },
494
+ modelSwitchCount: { readBy: ["diagnostic"] },
495
+ rapidRepromptCount: { readBy: ["diagnostic"] },
496
+ schemaUnreadable: { readBy: ["diagnostic"] },
497
+ sessionCount: { readBy: ["diagnostic"] },
498
+ sessionsFromBubbleTimeline: { readBy: ["diagnostic"] },
499
+ sessionsFromCheckpointTimeline: { readBy: ["diagnostic"] },
500
+ sessionsFromRecencyTimeline: { readBy: ["diagnostic"] },
501
+ subagentAssistantTurns: { readBy: ["diagnostic"] },
502
+ subagentPrompts: { readBy: ["diagnostic"] },
503
+ subagentTokensTotal: { readBy: ["diagnostic"] },
504
+ toolName: {
505
+ readBy: ["diagnostic"],
506
+ note: "Set per ai_tool_call_started event by #43's extractors and shipped in wire metadata, but no reader resolves it server-side yet (the backend's ToolName column is MCP audit, not telemetry). Registered after the fact: #38 and #43 merged past each other, and the union caught it on the next compile \u2014 metaLines all over again."
507
+ },
508
+ toolResultCount: { readBy: ["diagnostic"] },
509
+ toolResultErrorCount: { readBy: ["diagnostic"] },
510
+ unknownBubbles: { readBy: ["diagnostic"] },
511
+ unknownLines: { readBy: ["diagnostic"] },
512
+ metaLines: {
513
+ readBy: ["diagnostic"],
514
+ note: 'Recognised-but-skipped transcript machinery (file-history-snapshot, queued-command, \u2026). Split out of unknownLines by #43 so that number keeps meaning "a type nobody has looked at". Registered here after the fact: #41 and #43 merged past each other, and the union caught it on the next compile \u2014 which is this module doing its job.'
515
+ },
516
+ unparsedBubbles: { readBy: ["diagnostic"] },
517
+ unparsedChatSessionFiles: { readBy: ["diagnostic"] },
518
+ unparsedHistoryFiles: { readBy: ["diagnostic"] },
519
+ unparsedLines: { readBy: ["diagnostic"] },
520
+ unreadableChatSessionFiles: { readBy: ["diagnostic"] },
521
+ unreadableHistoryFiles: { readBy: ["diagnostic"] },
522
+ unrecognisedChatSessionFiles: { readBy: ["diagnostic"] }
523
+ };
524
+ function backendMetricKeys() {
525
+ return Object.entries(exports.METRIC_KEYS).filter(([, spec]) => spec.readBy.includes("backend")).map(([key, spec]) => [key, spec.backendAliases ?? [key]]);
526
+ }
527
+ }
528
+ });
529
+
380
530
  // ../packages/tool-contract/out/index.js
381
531
  var require_out = __commonJS({
382
532
  "../packages/tool-contract/out/index.js"(exports) {
383
533
  "use strict";
384
534
  Object.defineProperty(exports, "__esModule", { value: true });
385
- exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = void 0;
535
+ exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = void 0;
386
536
  exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = [
387
537
  "approach_churn_detected",
388
538
  "goal_drift_detected",
@@ -441,6 +591,13 @@ var require_out = __commonJS({
441
591
  exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = "workflow_telemetry";
442
592
  exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = "historical_import";
443
593
  exports.ASCENDA_SEMANTIC_PROVENANCE = "semantic_work_signals";
594
+ var metricKeys_1 = require_metricKeys();
595
+ Object.defineProperty(exports, "METRIC_KEYS", { enumerable: true, get: function() {
596
+ return metricKeys_1.METRIC_KEYS;
597
+ } });
598
+ Object.defineProperty(exports, "backendMetricKeys", { enumerable: true, get: function() {
599
+ return metricKeys_1.backendMetricKeys;
600
+ } });
444
601
  }
445
602
  });
446
603
 
@@ -490,9 +647,9 @@ var require_eventLog = __commonJS({
490
647
  exports.expandUserPath = expandUserPath;
491
648
  exports.resolveEventLogPath = resolveEventLogPath2;
492
649
  exports.appendEventLog = appendEventLog2;
493
- var fs2 = __importStar(__require("fs"));
494
- var os = __importStar(__require("os"));
495
- var path = __importStar(__require("path"));
650
+ var fs4 = __importStar(__require("fs"));
651
+ var os2 = __importStar(__require("os"));
652
+ var path3 = __importStar(__require("path"));
496
653
  exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
497
654
  var MAX_BYTES = 5 * 1024 * 1024;
498
655
  function expandUserPath(configured) {
@@ -500,10 +657,10 @@ var require_eventLog = __commonJS({
500
657
  if (!value)
501
658
  return void 0;
502
659
  if (value === "~")
503
- return os.homedir();
660
+ return os2.homedir();
504
661
  if (value.startsWith("~/"))
505
- return path.join(os.homedir(), value.slice(2));
506
- return path.resolve(value);
662
+ return path3.join(os2.homedir(), value.slice(2));
663
+ return path3.resolve(value);
507
664
  }
508
665
  function resolveEventLogPath2() {
509
666
  return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
@@ -511,20 +668,20 @@ var require_eventLog = __commonJS({
511
668
  function appendEventLog2(logFilePath, entry) {
512
669
  try {
513
670
  rotateIfLarge(logFilePath);
514
- const dir = path.dirname(logFilePath);
515
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
516
- fs2.appendFileSync(logFilePath, `${JSON.stringify(entry)}
671
+ const dir = path3.dirname(logFilePath);
672
+ fs4.mkdirSync(dir, { recursive: true, mode: 448 });
673
+ fs4.appendFileSync(logFilePath, `${JSON.stringify(entry)}
517
674
  `, { encoding: "utf8", mode: 384 });
518
675
  if (process.platform !== "win32")
519
- fs2.chmodSync(logFilePath, 384);
676
+ fs4.chmodSync(logFilePath, 384);
520
677
  } catch {
521
678
  }
522
679
  }
523
680
  function rotateIfLarge(logFilePath) {
524
681
  try {
525
- if (fs2.statSync(logFilePath).size < MAX_BYTES)
682
+ if (fs4.statSync(logFilePath).size < MAX_BYTES)
526
683
  return;
527
- fs2.renameSync(logFilePath, `${logFilePath}.1`);
684
+ fs4.renameSync(logFilePath, `${logFilePath}.1`);
528
685
  } catch {
529
686
  }
530
687
  }
@@ -537,8 +694,8 @@ var require_http = __commonJS({
537
694
  "use strict";
538
695
  Object.defineProperty(exports, "__esModule", { value: true });
539
696
  exports.AscendaApiError = void 0;
540
- exports.createPairingSession = createPairingSession2;
541
- exports.getPairingStatus = getPairingStatus2;
697
+ exports.createPairingSession = createPairingSession3;
698
+ exports.getPairingStatus = getPairingStatus3;
542
699
  exports.renewToolToken = renewToolToken;
543
700
  exports.isRetryableStatus = isRetryableStatus;
544
701
  exports.postToolEvent = postToolEvent;
@@ -555,7 +712,7 @@ var require_http = __commonJS({
555
712
  }
556
713
  };
557
714
  exports.AscendaApiError = AscendaApiError2;
558
- async function createPairingSession2(apiBaseUrl, toolInstallationId, toolType, displayName) {
715
+ async function createPairingSession3(apiBaseUrl, toolInstallationId, toolType, displayName) {
559
716
  const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
560
717
  method: "POST",
561
718
  headers: { "Content-Type": "application/json" },
@@ -565,7 +722,7 @@ var require_http = __commonJS({
565
722
  throw new AscendaApiError2(response.status, void 0, await response.text());
566
723
  return await response.json();
567
724
  }
568
- async function getPairingStatus2(apiBaseUrl, pairingSessionId) {
725
+ async function getPairingStatus3(apiBaseUrl, pairingSessionId) {
569
726
  const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
570
727
  method: "GET",
571
728
  headers: { Accept: "application/json" }
@@ -675,30 +832,34 @@ var require_tokenStore = __commonJS({
675
832
  };
676
833
  }();
677
834
  Object.defineProperty(exports, "__esModule", { value: true });
678
- exports.defaultTokenFilePath = defaultTokenFilePath3;
679
- exports.persistEventWriteToken = persistEventWriteToken3;
680
- exports.readTokenFile = readTokenFile2;
835
+ exports.ascendaHome = ascendaHome3;
836
+ exports.defaultTokenFilePath = defaultTokenFilePath4;
837
+ exports.persistEventWriteToken = persistEventWriteToken4;
838
+ exports.readTokenFile = readTokenFile3;
681
839
  exports.sanitizeFilePart = sanitizeFilePart;
682
- var fs2 = __importStar(__require("fs"));
683
- var os = __importStar(__require("os"));
684
- var path = __importStar(__require("path"));
685
- function defaultTokenFilePath3(toolInstallationId) {
686
- return path.join(os.homedir(), ".ascenda", "tokens", sanitizeFilePart(toolInstallationId));
687
- }
688
- function persistEventWriteToken3(tokenFilePath, token) {
689
- const dir = path.dirname(tokenFilePath);
690
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
691
- fs2.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
840
+ var fs4 = __importStar(__require("fs"));
841
+ var os2 = __importStar(__require("os"));
842
+ var path3 = __importStar(__require("path"));
843
+ function ascendaHome3() {
844
+ return process.env.ASCENDA_HOME ?? path3.join(os2.homedir(), ".ascenda");
845
+ }
846
+ function defaultTokenFilePath4(toolInstallationId) {
847
+ return path3.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
848
+ }
849
+ function persistEventWriteToken4(tokenFilePath, token) {
850
+ const dir = path3.dirname(tokenFilePath);
851
+ fs4.mkdirSync(dir, { recursive: true, mode: 448 });
852
+ fs4.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
692
853
  if (process.platform !== "win32") {
693
- fs2.chmodSync(dir, 448);
694
- fs2.chmodSync(tokenFilePath, 384);
854
+ fs4.chmodSync(dir, 448);
855
+ fs4.chmodSync(tokenFilePath, 384);
695
856
  }
696
857
  }
697
- function readTokenFile2(tokenFilePath) {
858
+ function readTokenFile3(tokenFilePath) {
698
859
  try {
699
- if (!fs2.existsSync(tokenFilePath))
860
+ if (!fs4.existsSync(tokenFilePath))
700
861
  return void 0;
701
- const value = fs2.readFileSync(tokenFilePath, "utf8").trim();
862
+ const value = fs4.readFileSync(tokenFilePath, "utf8").trim();
702
863
  return value || void 0;
703
864
  } catch {
704
865
  return void 0;
@@ -757,20 +918,20 @@ var require_stateStore = __commonJS({
757
918
  exports.recordSendOutcome = recordSendOutcome;
758
919
  exports.shouldAnnounceFailure = shouldAnnounceFailure2;
759
920
  exports.markFailureNotified = markFailureNotified2;
760
- var fs2 = __importStar(__require("fs"));
761
- var os = __importStar(__require("os"));
762
- var path = __importStar(__require("path"));
921
+ var fs4 = __importStar(__require("fs"));
922
+ var os2 = __importStar(__require("os"));
923
+ var path3 = __importStar(__require("path"));
763
924
  var tokenStore_1 = require_tokenStore();
764
925
  function defaultStateFilePath2(toolInstallationId) {
765
926
  const dir = process.env.ASCENDA_STATE_DIR?.trim();
766
- const base = dir ? dir : path.join(os.homedir(), ".ascenda", "state");
767
- return path.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
927
+ const base = dir ? dir : path3.join(os2.homedir(), ".ascenda", "state");
928
+ return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
768
929
  }
769
930
  function readCollectorState2(stateFilePath) {
770
931
  try {
771
- if (!fs2.existsSync(stateFilePath))
932
+ if (!fs4.existsSync(stateFilePath))
772
933
  return void 0;
773
- const raw = fs2.readFileSync(stateFilePath, "utf8").trim();
934
+ const raw = fs4.readFileSync(stateFilePath, "utf8").trim();
774
935
  if (!raw)
775
936
  return void 0;
776
937
  const parsed = JSON.parse(raw);
@@ -816,17 +977,17 @@ var require_stateStore = __commonJS({
816
977
  function writeStateFile(stateFilePath, state) {
817
978
  const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
818
979
  try {
819
- const dir = path.dirname(stateFilePath);
820
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
821
- fs2.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
980
+ const dir = path3.dirname(stateFilePath);
981
+ fs4.mkdirSync(dir, { recursive: true, mode: 448 });
982
+ fs4.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
822
983
  `, { encoding: "utf8", mode: 384 });
823
- fs2.renameSync(temporaryPath, stateFilePath);
984
+ fs4.renameSync(temporaryPath, stateFilePath);
824
985
  if (process.platform !== "win32")
825
- fs2.chmodSync(stateFilePath, 384);
986
+ fs4.chmodSync(stateFilePath, 384);
826
987
  } catch {
827
988
  try {
828
- if (fs2.existsSync(temporaryPath))
829
- fs2.unlinkSync(temporaryPath);
989
+ if (fs4.existsSync(temporaryPath))
990
+ fs4.unlinkSync(temporaryPath);
830
991
  } catch {
831
992
  }
832
993
  }
@@ -992,7 +1153,7 @@ var require_eventSender = __commonJS({
992
1153
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
993
1154
  }
994
1155
  if (outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus))) {
995
- await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
1156
+ await new Promise((resolve2) => setTimeout(resolve2, RETRY_DELAY_MS));
996
1157
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
997
1158
  }
998
1159
  return outcome;
@@ -1089,16 +1250,16 @@ var require_contextRegistry = __commonJS({
1089
1250
  exports.readWorkContextRegistry = readWorkContextRegistry;
1090
1251
  exports.recordWorkContext = recordWorkContext2;
1091
1252
  exports.recordWorkContextAlias = recordWorkContextAlias;
1092
- var fs2 = __importStar(__require("fs"));
1093
- var os = __importStar(__require("os"));
1094
- var path = __importStar(__require("path"));
1253
+ var fs4 = __importStar(__require("fs"));
1254
+ var os2 = __importStar(__require("os"));
1255
+ var path3 = __importStar(__require("path"));
1095
1256
  var MAX_PATHS_PER_ENTRY = 8;
1096
1257
  function workContextRegistryFilePath() {
1097
- return path.join(os.homedir(), ".ascenda", "work-contexts.json");
1258
+ return path3.join(os2.homedir(), ".ascenda", "work-contexts.json");
1098
1259
  }
1099
1260
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
1100
1261
  try {
1101
- const parsed = JSON.parse(fs2.readFileSync(registryFilePath, "utf8"));
1262
+ const parsed = JSON.parse(fs4.readFileSync(registryFilePath, "utf8"));
1102
1263
  if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
1103
1264
  return parsed;
1104
1265
  }
@@ -1174,14 +1335,14 @@ var require_contextRegistry = __commonJS({
1174
1335
  return iso.slice(0, 10);
1175
1336
  }
1176
1337
  function writeRegistry(registryFilePath, registry) {
1177
- const dir = path.dirname(registryFilePath);
1178
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1338
+ const dir = path3.dirname(registryFilePath);
1339
+ fs4.mkdirSync(dir, { recursive: true, mode: 448 });
1179
1340
  const tmp = `${registryFilePath}.${process.pid}.tmp`;
1180
- fs2.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
1341
+ fs4.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
1181
1342
  `, { encoding: "utf8", mode: 384 });
1182
- fs2.renameSync(tmp, registryFilePath);
1343
+ fs4.renameSync(tmp, registryFilePath);
1183
1344
  if (process.platform !== "win32") {
1184
- fs2.chmodSync(registryFilePath, 384);
1345
+ fs4.chmodSync(registryFilePath, 384);
1185
1346
  }
1186
1347
  }
1187
1348
  }
@@ -1232,32 +1393,32 @@ var require_salt = __commonJS({
1232
1393
  exports.machineSaltFilePath = machineSaltFilePath;
1233
1394
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
1234
1395
  exports.hashWithMachineSalt = hashWithMachineSalt;
1235
- var crypto = __importStar(__require("crypto"));
1236
- var fs2 = __importStar(__require("fs"));
1237
- var os = __importStar(__require("os"));
1238
- var path = __importStar(__require("path"));
1396
+ var crypto2 = __importStar(__require("crypto"));
1397
+ var fs4 = __importStar(__require("fs"));
1398
+ var os2 = __importStar(__require("os"));
1399
+ var path3 = __importStar(__require("path"));
1239
1400
  function machineSaltFilePath() {
1240
- return path.join(os.homedir(), ".ascenda", "salt");
1401
+ return path3.join(os2.homedir(), ".ascenda", "salt");
1241
1402
  }
1242
1403
  var cache = /* @__PURE__ */ new Map();
1243
1404
  function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
1244
1405
  const hit = cache.get(saltFilePath);
1245
1406
  if (hit)
1246
1407
  return hit;
1247
- const dir = path.dirname(saltFilePath);
1248
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1408
+ const dir = path3.dirname(saltFilePath);
1409
+ fs4.mkdirSync(dir, { recursive: true, mode: 448 });
1249
1410
  let salt;
1250
1411
  try {
1251
- salt = crypto.randomBytes(32).toString("hex");
1252
- fs2.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
1412
+ salt = crypto2.randomBytes(32).toString("hex");
1413
+ fs4.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
1253
1414
  } catch (error) {
1254
1415
  if (error.code !== "EEXIST")
1255
1416
  throw error;
1256
- salt = fs2.readFileSync(saltFilePath, "utf8").trim();
1417
+ salt = fs4.readFileSync(saltFilePath, "utf8").trim();
1257
1418
  }
1258
1419
  if (process.platform !== "win32") {
1259
- fs2.chmodSync(dir, 448);
1260
- fs2.chmodSync(saltFilePath, 384);
1420
+ fs4.chmodSync(dir, 448);
1421
+ fs4.chmodSync(saltFilePath, 384);
1261
1422
  }
1262
1423
  cache.set(saltFilePath, salt);
1263
1424
  return salt;
@@ -1265,7 +1426,7 @@ var require_salt = __commonJS({
1265
1426
  function hashWithMachineSalt(value, saltFilePath) {
1266
1427
  if (!value)
1267
1428
  return null;
1268
- return crypto.createHash("sha256").update(readOrCreateMachineSalt(saltFilePath)).update("\0").update(value).digest("hex").slice(0, 16);
1429
+ return crypto2.createHash("sha256").update(readOrCreateMachineSalt(saltFilePath)).update("\0").update(value).digest("hex").slice(0, 16);
1269
1430
  }
1270
1431
  }
1271
1432
  });
@@ -1313,8 +1474,8 @@ var require_workContext = __commonJS({
1313
1474
  }();
1314
1475
  Object.defineProperty(exports, "__esModule", { value: true });
1315
1476
  exports.deriveWorkContext = deriveWorkContext2;
1316
- var fs2 = __importStar(__require("fs"));
1317
- var path = __importStar(__require("path"));
1477
+ var fs4 = __importStar(__require("fs"));
1478
+ var path3 = __importStar(__require("path"));
1318
1479
  var salt_1 = require_salt();
1319
1480
  var MAX_WALK_DEPTH = 64;
1320
1481
  function deriveWorkContext2(cwd, saltFilePath) {
@@ -1343,14 +1504,14 @@ var require_workContext = __commonJS({
1343
1504
  };
1344
1505
  }
1345
1506
  function resolveRepositoryRoots(startDir) {
1346
- if (!fs2.existsSync(startDir))
1507
+ if (!fs4.existsSync(startDir))
1347
1508
  return null;
1348
1509
  let dir = startDir;
1349
1510
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
1350
- const dotGit = path.join(dir, ".git");
1511
+ const dotGit = path3.join(dir, ".git");
1351
1512
  let stat = null;
1352
1513
  try {
1353
- stat = fs2.statSync(dotGit);
1514
+ stat = fs4.statSync(dotGit);
1354
1515
  } catch {
1355
1516
  stat = null;
1356
1517
  }
@@ -1358,7 +1519,7 @@ var require_workContext = __commonJS({
1358
1519
  return { checkoutRoot: dir, canonicalRoot: dir };
1359
1520
  if (stat?.isFile())
1360
1521
  return { checkoutRoot: dir, canonicalRoot: worktreeParentRoot(dotGit, dir) ?? dir };
1361
- const parent = path.dirname(dir);
1522
+ const parent = path3.dirname(dir);
1362
1523
  if (parent === dir)
1363
1524
  return null;
1364
1525
  dir = parent;
@@ -1368,15 +1529,15 @@ var require_workContext = __commonJS({
1368
1529
  function worktreeParentRoot(dotGitFile, containingDir) {
1369
1530
  let gitdir;
1370
1531
  try {
1371
- const match = /^gitdir:\s*(.+)\s*$/m.exec(fs2.readFileSync(dotGitFile, "utf8"));
1532
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(fs4.readFileSync(dotGitFile, "utf8"));
1372
1533
  if (!match)
1373
1534
  return null;
1374
1535
  gitdir = match[1].trim();
1375
1536
  } catch {
1376
1537
  return null;
1377
1538
  }
1378
- const resolved = path.resolve(containingDir, gitdir);
1379
- const marker = `${path.sep}.git${path.sep}worktrees${path.sep}`;
1539
+ const resolved = path3.resolve(containingDir, gitdir);
1540
+ const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
1380
1541
  const idx = resolved.indexOf(marker);
1381
1542
  if (idx === -1)
1382
1543
  return null;
@@ -1554,12 +1715,12 @@ var require_turnState = __commonJS({
1554
1715
  Object.defineProperty(exports, "__esModule", { value: true });
1555
1716
  exports.recordTurnStart = recordTurnStart;
1556
1717
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
1557
- var fs2 = __importStar(__require("fs"));
1558
- var os = __importStar(__require("os"));
1559
- var path = __importStar(__require("path"));
1560
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join(os.homedir(), ".ascenda", "state");
1718
+ var fs4 = __importStar(__require("fs"));
1719
+ var os2 = __importStar(__require("os"));
1720
+ var path3 = __importStar(__require("path"));
1721
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join(os2.homedir(), ".ascenda", "state");
1561
1722
  function turnFile(agent, sessionId) {
1562
- return path.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
1723
+ return path3.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
1563
1724
  }
1564
1725
  function sanitize(value) {
1565
1726
  return value.replace(/[^a-zA-Z0-9._-]/g, "_");
@@ -1568,8 +1729,8 @@ var require_turnState = __commonJS({
1568
1729
  if (!sessionId)
1569
1730
  return;
1570
1731
  try {
1571
- fs2.mkdirSync(stateDir(), { recursive: true });
1572
- fs2.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
1732
+ fs4.mkdirSync(stateDir(), { recursive: true });
1733
+ fs4.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
1573
1734
  } catch {
1574
1735
  }
1575
1736
  }
@@ -1578,8 +1739,8 @@ var require_turnState = __commonJS({
1578
1739
  return void 0;
1579
1740
  const file = turnFile(agent, sessionId);
1580
1741
  try {
1581
- const started = Number(fs2.readFileSync(file, "utf8").trim());
1582
- fs2.rmSync(file, { force: true });
1742
+ const started = Number(fs4.readFileSync(file, "utf8").trim());
1743
+ fs4.rmSync(file, { force: true });
1583
1744
  if (!Number.isFinite(started) || started <= 0 || started > now)
1584
1745
  return void 0;
1585
1746
  return now - started;
@@ -1636,27 +1797,29 @@ var require_liveBus = __commonJS({
1636
1797
  exports.liveBusSocketPath = liveBusSocketPath;
1637
1798
  exports.bucketPromptSize = bucketPromptSize2;
1638
1799
  exports.emitLiveSignal = emitLiveSignal2;
1639
- var fs2 = __importStar(__require("fs"));
1800
+ var fs4 = __importStar(__require("fs"));
1640
1801
  var net = __importStar(__require("net"));
1641
- var os = __importStar(__require("os"));
1642
- var path = __importStar(__require("path"));
1802
+ var os2 = __importStar(__require("os"));
1803
+ var path3 = __importStar(__require("path"));
1643
1804
  var WRITE_TIMEOUT_MS = 50;
1644
1805
  var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
1806
+ var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
1645
1807
  function liveBusSocketCandidates() {
1646
1808
  const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
1647
1809
  if (override)
1648
1810
  return [override];
1649
- const home = os.homedir();
1811
+ const home = os2.homedir();
1650
1812
  return [
1651
- path.join(home, ".ascenda", "live.sock"),
1652
- path.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock")
1813
+ path3.join(home, ".ascenda", "live.sock"),
1814
+ path3.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
1815
+ path3.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
1653
1816
  ];
1654
1817
  }
1655
1818
  function liveBusSocketPath() {
1656
1819
  const candidates = liveBusSocketCandidates();
1657
1820
  for (const candidate of candidates) {
1658
1821
  try {
1659
- if (fs2.statSync(candidate).isSocket())
1822
+ if (fs4.statSync(candidate).isSocket())
1660
1823
  return candidate;
1661
1824
  } catch {
1662
1825
  }
@@ -1674,7 +1837,7 @@ var require_liveBus = __commonJS({
1674
1837
  return "xl";
1675
1838
  }
1676
1839
  function emitLiveSignal2(signal) {
1677
- return new Promise((resolve) => {
1840
+ return new Promise((resolve2) => {
1678
1841
  let settled = false;
1679
1842
  const done = () => {
1680
1843
  if (settled)
@@ -1684,13 +1847,13 @@ var require_liveBus = __commonJS({
1684
1847
  socket.destroy();
1685
1848
  } catch {
1686
1849
  }
1687
- resolve();
1850
+ resolve2();
1688
1851
  };
1689
1852
  let socket;
1690
1853
  try {
1691
1854
  socket = net.createConnection(liveBusSocketPath());
1692
1855
  } catch {
1693
- resolve();
1856
+ resolve2();
1694
1857
  return;
1695
1858
  }
1696
1859
  const timer = setTimeout(done, WRITE_TIMEOUT_MS);
@@ -1721,8 +1884,8 @@ var require_out2 = __commonJS({
1721
1884
  "../packages/tool-kit/out/index.js"(exports) {
1722
1885
  "use strict";
1723
1886
  Object.defineProperty(exports, "__esModule", { value: true });
1724
- exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.defaultTokenFilePath = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.resolveContextHashes = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.AscendaSemanticEventError = exports.AscendaEventSender = 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.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
1725
- exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = void 0;
1887
+ exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.defaultTokenFilePath = exports.ascendaHome = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.resolveContextHashes = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.AscendaSemanticEventError = exports.AscendaEventSender = 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.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
1888
+ exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.workContextRegistryFilePath = void 0;
1726
1889
  var commandClassifier_1 = require_commandClassifier();
1727
1890
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
1728
1891
  return commandClassifier_1.classifyCommand;
@@ -1836,6 +1999,9 @@ var require_out2 = __commonJS({
1836
1999
  return turnState_1.recordTurnStart;
1837
2000
  } });
1838
2001
  var tokenStore_1 = require_tokenStore();
2002
+ Object.defineProperty(exports, "ascendaHome", { enumerable: true, get: function() {
2003
+ return tokenStore_1.ascendaHome;
2004
+ } });
1839
2005
  Object.defineProperty(exports, "defaultTokenFilePath", { enumerable: true, get: function() {
1840
2006
  return tokenStore_1.defaultTokenFilePath;
1841
2007
  } });
@@ -1929,77 +2095,86 @@ var require_out2 = __commonJS({
1929
2095
  }
1930
2096
  });
1931
2097
 
1932
- // src/cli.ts
1933
- var import_tool_kit6 = __toESM(require_out2(), 1);
1934
- import { randomUUID } from "node:crypto";
1935
- import * as fs from "node:fs";
1936
-
1937
- // src/ascendaClient.ts
1938
- var import_tool_kit = __toESM(require_out2(), 1);
1939
- var import_tool_kit2 = __toESM(require_out2(), 1);
1940
- var AscendaClient = class {
1941
- sender;
1942
- constructor(config) {
1943
- this.sender = new import_tool_kit.AscendaEventSender({
1944
- apiBaseUrl: config.apiBaseUrl,
1945
- toolInstallationId: config.toolInstallationId,
1946
- source: "claude_code",
1947
- eventWriteToken: config.eventWriteToken,
1948
- tokenFilePath: config.tokenFilePath,
1949
- stateFilePath: config.stateFilePath,
1950
- sessionId: config.sessionId,
1951
- workspaceHash: config.workspaceHash,
1952
- projectHash: config.projectHash
1953
- });
1954
- }
1955
- /** The journal entry written by the most recent {@link send}. */
1956
- get state() {
1957
- return this.sender.state;
2098
+ // src/paths.ts
2099
+ import * as fs from "fs";
2100
+ import * as path from "path";
2101
+ function hookBinPath() {
2102
+ return path.join((0, import_tool_kit3.ascendaHome)(), "bin", "ascenda-claude-hook");
2103
+ }
2104
+ function credentialsFilePath() {
2105
+ return path.join((0, import_tool_kit3.ascendaHome)(), "credentials.json");
2106
+ }
2107
+ function readCredentials() {
2108
+ try {
2109
+ const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
2110
+ if (!raw) return void 0;
2111
+ const parsed = JSON.parse(raw);
2112
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
2113
+ return parsed;
2114
+ } catch {
2115
+ return void 0;
1958
2116
  }
1959
- async send(mapped) {
1960
- return this.sender.send(mapped);
2117
+ }
2118
+ function writeCredentials(credentials) {
2119
+ const file = credentialsFilePath();
2120
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2121
+ fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2122
+ `, { encoding: "utf8", mode: 384 });
2123
+ if (process.platform !== "win32") {
2124
+ fs.chmodSync(path.dirname(file), 448);
2125
+ fs.chmodSync(file, 384);
1961
2126
  }
1962
- async renewEventToken() {
1963
- return this.sender.renewEventToken();
2127
+ }
2128
+ var import_tool_kit3;
2129
+ var init_paths = __esm({
2130
+ "src/paths.ts"() {
2131
+ "use strict";
2132
+ import_tool_kit3 = __toESM(require_out2(), 1);
1964
2133
  }
1965
- };
1966
-
1967
- // src/config.ts
1968
- var import_tool_kit3 = __toESM(require_out2(), 1);
2134
+ });
1969
2135
 
1970
2136
  // src/types.ts
1971
- var import_tool_contract = __toESM(require_out(), 1);
1972
- var CLAUDE_HOOK_EVENT_NAMES = [
1973
- "SessionStart",
1974
- "UserPromptSubmit",
1975
- "PreToolUse",
1976
- "PostToolUse",
1977
- "PostToolUseFailure",
1978
- "PreCompact",
1979
- "PostCompact",
1980
- "Stop",
1981
- "Notification"
1982
- ];
1983
2137
  function isClaudeHookEventName(value) {
1984
2138
  return CLAUDE_HOOK_EVENT_NAMES.includes(value);
1985
2139
  }
1986
- var ASCENDA_TOOL_TYPE = "claude_code";
1987
- var CLAUDE_HOST = "claude_code";
2140
+ var import_tool_contract, CLAUDE_HOOK_EVENT_NAMES, ASCENDA_TOOL_TYPE, CLAUDE_HOST;
2141
+ var init_types = __esm({
2142
+ "src/types.ts"() {
2143
+ "use strict";
2144
+ import_tool_contract = __toESM(require_out(), 1);
2145
+ CLAUDE_HOOK_EVENT_NAMES = [
2146
+ "SessionStart",
2147
+ "UserPromptSubmit",
2148
+ "PreToolUse",
2149
+ "PostToolUse",
2150
+ "PostToolUseFailure",
2151
+ "PreCompact",
2152
+ "PostCompact",
2153
+ "Stop",
2154
+ "Notification"
2155
+ ];
2156
+ ASCENDA_TOOL_TYPE = "claude_code";
2157
+ CLAUDE_HOST = "claude_code";
2158
+ }
2159
+ });
1988
2160
 
1989
2161
  // src/config.ts
1990
2162
  function resolveStateFilePath(toolInstallationId) {
1991
- return process.env.ASCENDA_STATE_FILE ?? (0, import_tool_kit3.defaultStateFilePath)(toolInstallationId);
2163
+ return process.env.ASCENDA_STATE_FILE ?? (0, import_tool_kit4.defaultStateFilePath)(toolInstallationId);
1992
2164
  }
1993
2165
  function loadConfigFromEnv() {
1994
- const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
1995
- const toolInstallationIdRaw = process.env.ASCENDA_TOOL_INSTALLATION_ID;
1996
- if (!toolInstallationIdRaw) throw new Error("Missing ASCENDA_TOOL_INSTALLATION_ID");
2166
+ const credentials = readCredentials();
2167
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
2168
+ const toolInstallationIdRaw = process.env.ASCENDA_TOOL_INSTALLATION_ID ?? credentials?.toolInstallationId;
2169
+ if (!toolInstallationIdRaw) {
2170
+ throw new Error("Not configured: no ASCENDA_TOOL_INSTALLATION_ID and no pairing in ~/.ascenda/credentials.json. Run: npx @ascenda-one/claude-code-hooks setup");
2171
+ }
1997
2172
  const toolInstallationId = normalizeToolInstallationId(toolInstallationIdRaw);
1998
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit3.defaultTokenFilePath)(toolInstallationId);
1999
- const fileToken = (0, import_tool_kit3.readTokenFile)(tokenFilePath);
2173
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit4.defaultTokenFilePath)(toolInstallationId);
2174
+ const fileToken = (0, import_tool_kit4.readTokenFile)(tokenFilePath);
2000
2175
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
2001
2176
  if (!eventWriteToken) throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
2002
- if (!fileToken) (0, import_tool_kit3.persistEventWriteToken)(tokenFilePath, eventWriteToken);
2177
+ if (!fileToken) (0, import_tool_kit4.persistEventWriteToken)(tokenFilePath, eventWriteToken);
2003
2178
  return {
2004
2179
  apiBaseUrl,
2005
2180
  toolInstallationId,
@@ -2024,12 +2199,384 @@ function normalizeToolInstallationId(value) {
2024
2199
  if (trimmed.startsWith("claude_tool_")) return `${ASCENDA_TOOL_TYPE}:${trimmed.slice("claude_tool_".length)}`;
2025
2200
  return `${ASCENDA_TOOL_TYPE}:${trimmed}`;
2026
2201
  }
2202
+ var import_tool_kit4, DEFAULT_API_BASE_URL;
2203
+ var init_config = __esm({
2204
+ "src/config.ts"() {
2205
+ "use strict";
2206
+ import_tool_kit4 = __toESM(require_out2(), 1);
2207
+ init_paths();
2208
+ init_types();
2209
+ DEFAULT_API_BASE_URL = "https://api.ascenda.one";
2210
+ }
2211
+ });
2212
+
2213
+ // src/setup.ts
2214
+ var setup_exports = {};
2215
+ __export(setup_exports, {
2216
+ findStaleHookCommands: () => findStaleHookCommands,
2217
+ runSetup: () => runSetup,
2218
+ writeSettings: () => writeSettings
2219
+ });
2220
+ import * as crypto from "crypto";
2221
+ import * as fs2 from "fs";
2222
+ import * as os from "os";
2223
+ import * as path2 from "path";
2224
+ async function runSetup(argv) {
2225
+ let options;
2226
+ try {
2227
+ options = parseArgs(argv);
2228
+ } catch (error) {
2229
+ console.error(error instanceof Error ? error.message : String(error));
2230
+ return 1;
2231
+ }
2232
+ if (options.action === "help") {
2233
+ console.log(USAGE);
2234
+ return 0;
2235
+ }
2236
+ if (options.action === "status") return printStatus(options);
2237
+ if (options.action === "uninstall") return uninstall(options);
2238
+ const apiBaseUrl = (options.apiBaseUrl ?? readCredentials()?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
2239
+ console.log(`Ascenda setup \u2014 ${apiBaseUrl}`);
2240
+ const identity = await resolveIdentity(apiBaseUrl, options);
2241
+ if (!identity) return 1;
2242
+ console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
2243
+ const binary = installBinary(options.dryRun);
2244
+ console.log(` hook binary ${binary}`);
2245
+ if (!options.dryRun) {
2246
+ writeCredentials({ apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
2247
+ }
2248
+ console.log(` credentials ${credentialsFilePath()}`);
2249
+ const settingsFile = settingsPath(options);
2250
+ const written = writeSettings(settingsFile, binary, options.dryRun);
2251
+ if (written === null) return 1;
2252
+ console.log(` hooks ${settingsFile} (${HOOK_EVENTS.length} events${written ? "" : ", already current"})`);
2253
+ if (options.dryRun) {
2254
+ console.log("\nDry run \u2014 nothing was written.");
2255
+ return 0;
2256
+ }
2257
+ console.log("\nDone. Restart Claude Code in this project to load the hooks.");
2258
+ console.log(`Check anytime: npx @ascenda-one/claude-code-hooks status`);
2259
+ return 0;
2260
+ }
2261
+ function parseArgs(argv) {
2262
+ const options = {
2263
+ scope: "project",
2264
+ projectDir: process.env.CLAUDE_PROJECT_DIR ?? process.cwd(),
2265
+ dryRun: false,
2266
+ action: "install"
2267
+ };
2268
+ for (let i = 0; i < argv.length; i++) {
2269
+ const arg = argv[i];
2270
+ const next = () => {
2271
+ const value = argv[++i];
2272
+ if (value === void 0) throw new Error(`${arg} needs a value`);
2273
+ return value;
2274
+ };
2275
+ switch (arg) {
2276
+ case "setup":
2277
+ case "install":
2278
+ options.action = "install";
2279
+ break;
2280
+ case "status":
2281
+ options.action = "status";
2282
+ break;
2283
+ case "uninstall":
2284
+ options.action = "uninstall";
2285
+ break;
2286
+ case "--api-base-url":
2287
+ options.apiBaseUrl = next();
2288
+ break;
2289
+ case "--local": {
2290
+ const peek = argv[i + 1];
2291
+ const port = peek && /^\d+$/.test(peek) ? argv[++i] : "4477";
2292
+ options.apiBaseUrl = `http://localhost:${port}`;
2293
+ break;
2294
+ }
2295
+ case "--tool-installation-id":
2296
+ options.toolInstallationId = next();
2297
+ break;
2298
+ case "--token":
2299
+ options.token = next();
2300
+ break;
2301
+ case "--scope": {
2302
+ const value = next();
2303
+ if (value !== "project" && value !== "user") throw new Error(`--scope must be project or user, got ${value}`);
2304
+ options.scope = value;
2305
+ break;
2306
+ }
2307
+ case "--project-dir":
2308
+ options.projectDir = path2.resolve(next());
2309
+ break;
2310
+ case "--dry-run":
2311
+ options.dryRun = true;
2312
+ break;
2313
+ case "-h":
2314
+ case "--help":
2315
+ options.action = "help";
2316
+ break;
2317
+ default:
2318
+ throw new Error(`unknown argument: ${arg}
2319
+
2320
+ ${USAGE}`);
2321
+ }
2322
+ }
2323
+ return options;
2324
+ }
2325
+ async function resolveIdentity(apiBaseUrl, options) {
2326
+ const existingId = options.toolInstallationId ?? readCredentials()?.toolInstallationId;
2327
+ if (existingId && options.token) {
2328
+ if (!options.dryRun) (0, import_tool_kit7.persistEventWriteToken)((0, import_tool_kit7.defaultTokenFilePath)(existingId), options.token);
2329
+ return { toolInstallationId: existingId, paired: false };
2330
+ }
2331
+ if (existingId && (0, import_tool_kit7.readTokenFile)((0, import_tool_kit7.defaultTokenFilePath)(existingId))) {
2332
+ return { toolInstallationId: existingId, paired: false };
2333
+ }
2334
+ if (options.dryRun) {
2335
+ return { toolInstallationId: existingId ?? `${ASCENDA_TOOL_TYPE}:<paired at run time>`, paired: false };
2336
+ }
2337
+ const toolInstallationId = existingId ?? `${ASCENDA_TOOL_TYPE}:${crypto.randomUUID()}`;
2338
+ let session;
2339
+ try {
2340
+ session = await (0, import_tool_kit7.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os.hostname()}`);
2341
+ } catch (error) {
2342
+ console.error(`
2343
+ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
2344
+ console.error("Start the local dev server and use --local, or pass --api-base-url for your backend.");
2345
+ return void 0;
2346
+ }
2347
+ const token = await pollForToken(apiBaseUrl, session.pairingSessionId, session.code, session.expiresAt);
2348
+ if (!token) return void 0;
2349
+ (0, import_tool_kit7.persistEventWriteToken)((0, import_tool_kit7.defaultTokenFilePath)(toolInstallationId), token);
2350
+ return { toolInstallationId, paired: true };
2351
+ }
2352
+ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
2353
+ const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
2354
+ let announced = false;
2355
+ while (Date.now() < deadline) {
2356
+ const status = await (0, import_tool_kit7.getPairingStatus)(apiBaseUrl, pairingSessionId);
2357
+ if (status.status === "paired" && status.eventWriteToken) return status.eventWriteToken;
2358
+ if (status.status === "expired" || status.status === "cancelled") {
2359
+ console.error(`
2360
+ Pairing ${status.status}. Run setup again.`);
2361
+ return void 0;
2362
+ }
2363
+ if (!announced) {
2364
+ console.log(`
2365
+ Confirm in the Ascenda app \u2014 code ${code}`);
2366
+ console.log(" Waiting...");
2367
+ announced = true;
2368
+ }
2369
+ await new Promise((resolve2) => setTimeout(resolve2, 2e3));
2370
+ }
2371
+ console.error("\nPairing timed out. Run setup again.");
2372
+ return void 0;
2373
+ }
2374
+ function installBinary(dryRun) {
2375
+ const target = hookBinPath();
2376
+ if (dryRun) return target;
2377
+ const source = process.argv[1];
2378
+ fs2.mkdirSync(path2.dirname(target), { recursive: true });
2379
+ if (path2.resolve(source) !== path2.resolve(target)) {
2380
+ fs2.copyFileSync(source, target);
2381
+ }
2382
+ if (process.platform !== "win32") fs2.chmodSync(target, 493);
2383
+ return target;
2384
+ }
2385
+ function settingsPath(options) {
2386
+ return options.scope === "user" ? path2.join(os.homedir(), ".claude", "settings.json") : path2.join(options.projectDir, ".claude", "settings.local.json");
2387
+ }
2388
+ function writeSettings(settingsFile, binary, dryRun) {
2389
+ let settings = {};
2390
+ const exists = fs2.existsSync(settingsFile);
2391
+ if (exists) {
2392
+ const raw = fs2.readFileSync(settingsFile, "utf8").trim();
2393
+ if (raw) {
2394
+ try {
2395
+ settings = JSON.parse(raw);
2396
+ } catch {
2397
+ console.error(`
2398
+ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
2399
+ return null;
2400
+ }
2401
+ }
2402
+ }
2403
+ const command = hookCommand(binary);
2404
+ const hooks = { ...settings.hooks ?? {} };
2405
+ for (const event of HOOK_EVENTS) {
2406
+ const kept = (hooks[event] ?? []).filter((group) => !isOurs(group));
2407
+ hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
2408
+ }
2409
+ const updated = { ...settings, hooks };
2410
+ const serialised = `${JSON.stringify(updated, null, 2)}
2411
+ `;
2412
+ if (exists && fs2.readFileSync(settingsFile, "utf8") === serialised) return false;
2413
+ if (dryRun) {
2414
+ console.log(`
2415
+ --- ${settingsFile} (dry run) ---
2416
+ ${serialised}`);
2417
+ return true;
2418
+ }
2419
+ if (exists) fs2.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
2420
+ fs2.mkdirSync(path2.dirname(settingsFile), { recursive: true });
2421
+ fs2.writeFileSync(settingsFile, serialised, "utf8");
2422
+ return true;
2423
+ }
2424
+ function hookCommand(binary) {
2425
+ return `"${process.execPath}" "${binary}"`;
2426
+ }
2427
+ function isOurs(group) {
2428
+ return (group.hooks ?? []).some((entry) => typeof entry.command === "string" && entry.command.includes(HOOK_MARKER));
2429
+ }
2430
+ function findStaleHookCommands(settings, binary) {
2431
+ const stale = /* @__PURE__ */ new Set();
2432
+ for (const groups of Object.values(settings.hooks ?? {})) {
2433
+ for (const group of groups ?? []) {
2434
+ for (const entry of group.hooks ?? []) {
2435
+ const command = entry?.command;
2436
+ if (typeof command !== "string") continue;
2437
+ if (!/ascenda/i.test(command) || command.includes(binary)) continue;
2438
+ stale.add(command);
2439
+ }
2440
+ }
2441
+ }
2442
+ return [...stale];
2443
+ }
2444
+ function printStatus(options) {
2445
+ const credentials = readCredentials();
2446
+ const settingsFile = settingsPath(options);
2447
+ const binary = hookBinPath();
2448
+ const tokenFile = credentials?.toolInstallationId ? (0, import_tool_kit7.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
2449
+ const settings = (() => {
2450
+ try {
2451
+ return JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
2452
+ } catch {
2453
+ return {};
2454
+ }
2455
+ })();
2456
+ const registered = HOOK_EVENTS.filter((event) => (settings.hooks?.[event] ?? []).some(isOurs)).length;
2457
+ const stale = findStaleHookCommands(settings, binary);
2458
+ console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
2459
+ console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}`);
2460
+ console.log(`token ${tokenFile && (0, import_tool_kit7.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
2461
+ console.log(`hook binary ${fs2.existsSync(binary) ? binary : "\u2014 not installed"}`);
2462
+ console.log(`hooks ${registered}/${HOOK_EVENTS.length} registered in ${settingsFile}`);
2463
+ if (stale.length) {
2464
+ console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
2465
+ for (const command of stale) console.log(` ${command}`);
2466
+ console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
2467
+ }
2468
+ const healthy = credentials?.toolInstallationId && registered === HOOK_EVENTS.length && fs2.existsSync(binary) && !stale.length;
2469
+ return healthy ? 0 : 1;
2470
+ }
2471
+ function uninstall(options) {
2472
+ const settingsFile = settingsPath(options);
2473
+ if (fs2.existsSync(settingsFile)) {
2474
+ try {
2475
+ const settings = JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
2476
+ const hooks = { ...settings.hooks ?? {} };
2477
+ for (const event of Object.keys(hooks)) {
2478
+ const kept = hooks[event].filter((group) => !isOurs(group));
2479
+ if (kept.length) hooks[event] = kept;
2480
+ else delete hooks[event];
2481
+ }
2482
+ const updated = { ...settings, hooks };
2483
+ if (!Object.keys(hooks).length) delete updated.hooks;
2484
+ fs2.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
2485
+ fs2.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
2486
+ `, "utf8");
2487
+ console.log(`hooks removed from ${settingsFile}`);
2488
+ } catch {
2489
+ console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
2490
+ return 1;
2491
+ }
2492
+ }
2493
+ const binary = hookBinPath();
2494
+ if (fs2.existsSync(binary)) {
2495
+ fs2.rmSync(binary);
2496
+ console.log(`removed ${binary}`);
2497
+ }
2498
+ const credentials = credentialsFilePath();
2499
+ if (fs2.existsSync(credentials)) {
2500
+ fs2.rmSync(credentials);
2501
+ console.log(`removed ${credentials}`);
2502
+ }
2503
+ console.log(`tokens left in ${path2.join((0, import_tool_kit7.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
2504
+ return 0;
2505
+ }
2506
+ var import_tool_kit7, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, USAGE;
2507
+ var init_setup = __esm({
2508
+ "src/setup.ts"() {
2509
+ "use strict";
2510
+ import_tool_kit7 = __toESM(require_out2(), 1);
2511
+ init_config();
2512
+ init_paths();
2513
+ init_types();
2514
+ HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PreCompact", "PostCompact", "Stop"];
2515
+ HOOK_TIMEOUT_SECONDS = 5;
2516
+ HOOK_MARKER = "ascenda-claude-hook";
2517
+ USAGE = `ascenda-claude-hook setup \u2014 wire Claude Code to Ascenda telemetry
2518
+
2519
+ npx @ascenda-one/claude-code-hooks setup [options]
2520
+ npx @ascenda-one/claude-code-hooks status
2521
+ npx @ascenda-one/claude-code-hooks uninstall
2522
+
2523
+ Options
2524
+ --api-base-url <url> ingest host (default ${DEFAULT_API_BASE_URL})
2525
+ --local [port] shorthand for the local dev server (default port 4477)
2526
+ --tool-installation-id <id> reuse an existing pairing instead of creating one
2527
+ --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
2528
+ --scope project|user where hooks are registered (default project)
2529
+ --project-dir <path> project root for --scope project (default cwd)
2530
+ --dry-run print what would change, write nothing
2531
+ -h, --help
2532
+ `;
2533
+ }
2534
+ });
2535
+
2536
+ // src/cli.ts
2537
+ var import_tool_kit8 = __toESM(require_out2(), 1);
2538
+ import { randomUUID as randomUUID2 } from "node:crypto";
2539
+ import * as fs3 from "node:fs";
2540
+
2541
+ // src/ascendaClient.ts
2542
+ var import_tool_kit = __toESM(require_out2(), 1);
2543
+ var import_tool_kit2 = __toESM(require_out2(), 1);
2544
+ var AscendaClient = class {
2545
+ sender;
2546
+ constructor(config) {
2547
+ this.sender = new import_tool_kit.AscendaEventSender({
2548
+ apiBaseUrl: config.apiBaseUrl,
2549
+ toolInstallationId: config.toolInstallationId,
2550
+ source: "claude_code",
2551
+ eventWriteToken: config.eventWriteToken,
2552
+ tokenFilePath: config.tokenFilePath,
2553
+ stateFilePath: config.stateFilePath,
2554
+ sessionId: config.sessionId,
2555
+ workspaceHash: config.workspaceHash,
2556
+ projectHash: config.projectHash
2557
+ });
2558
+ }
2559
+ /** The journal entry written by the most recent {@link send}. */
2560
+ get state() {
2561
+ return this.sender.state;
2562
+ }
2563
+ async send(mapped) {
2564
+ return this.sender.send(mapped);
2565
+ }
2566
+ async renewEventToken() {
2567
+ return this.sender.renewEventToken();
2568
+ }
2569
+ };
2570
+
2571
+ // src/cli.ts
2572
+ init_config();
2027
2573
 
2028
2574
  // src/mapClaudeEvent.ts
2029
- var import_tool_kit5 = __toESM(require_out2(), 1);
2575
+ var import_tool_kit6 = __toESM(require_out2(), 1);
2576
+ init_types();
2030
2577
 
2031
2578
  // src/safeExtract.ts
2032
- var import_tool_kit4 = __toESM(require_out2(), 1);
2579
+ var import_tool_kit5 = __toESM(require_out2(), 1);
2033
2580
 
2034
2581
  // src/mapClaudeEvent.ts
2035
2582
  function mapClaudeEvent(hookName, input) {
@@ -2067,22 +2614,22 @@ function mapEvent(hookName, input) {
2067
2614
  }
2068
2615
  }
2069
2616
  function isNewSessionStart(input) {
2070
- const source = (0, import_tool_kit4.getString)(input, ["source"]);
2617
+ const source = (0, import_tool_kit5.getString)(input, ["source"]);
2071
2618
  return !source || source === "startup" || source === "resume";
2072
2619
  }
2073
2620
  function milestoneInviting(input) {
2074
- if ((0, import_tool_kit4.outcomeForHook)("PostToolUse", input) !== "success") return false;
2075
- const command = (0, import_tool_kit4.getString)(input, ["command"]) ?? (0, import_tool_kit4.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
2076
- return (0, import_tool_kit5.invitesDebrief)((0, import_tool_kit5.classifyWorkMilestone)(command));
2621
+ if ((0, import_tool_kit5.outcomeForHook)("PostToolUse", input) !== "success") return false;
2622
+ const command = (0, import_tool_kit5.getString)(input, ["command"]) ?? (0, import_tool_kit5.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
2623
+ return (0, import_tool_kit6.invitesDebrief)((0, import_tool_kit6.classifyWorkMilestone)(command));
2077
2624
  }
2078
2625
  function mapSessionStart(input) {
2079
2626
  if (!isNewSessionStart(input)) return [];
2080
2627
  return [{ eventType: "create_focus_session", severity: "low", metadata: { activity: "session_started" } }];
2081
2628
  }
2082
2629
  function mapUserPromptSubmit(input) {
2083
- const prompt = (0, import_tool_kit4.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit4.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
2630
+ const prompt = (0, import_tool_kit5.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit5.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
2084
2631
  const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown" } }];
2085
- if ((0, import_tool_kit4.looksLikeCorrection)(prompt)) {
2632
+ if ((0, import_tool_kit5.looksLikeCorrection)(prompt)) {
2086
2633
  events.push({ eventType: "ai_correction_prompt", severity: "medium", metadata: { reason: "repeated_reprompting", trigger: "inferred" } });
2087
2634
  }
2088
2635
  return events;
@@ -2093,20 +2640,20 @@ function mapPreToolUse(input) {
2093
2640
  function mapPostToolUse(hookName, input) {
2094
2641
  const toolName = getToolName(input);
2095
2642
  const safeToolName = sanitiseToolName(toolName);
2096
- const outcome = (0, import_tool_kit4.outcomeForHook)(hookName, input);
2097
- const durationMs = (0, import_tool_kit4.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit4.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
2098
- const command = (0, import_tool_kit4.getString)(input, ["command"]) ?? (0, import_tool_kit4.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
2099
- const commandClass = (0, import_tool_kit5.classifyCommand)(command);
2100
- const gitAction = outcome === "success" ? (0, import_tool_kit5.classifyGitAction)(command) : void 0;
2101
- const milestoneKind = outcome === "success" ? (0, import_tool_kit5.classifyWorkMilestone)(command) : void 0;
2643
+ const outcome = (0, import_tool_kit5.outcomeForHook)(hookName, input);
2644
+ const durationMs = (0, import_tool_kit5.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit5.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
2645
+ const command = (0, import_tool_kit5.getString)(input, ["command"]) ?? (0, import_tool_kit5.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
2646
+ const commandClass = (0, import_tool_kit6.classifyCommand)(command);
2647
+ const gitAction = outcome === "success" ? (0, import_tool_kit6.classifyGitAction)(command) : void 0;
2648
+ const milestoneKind = outcome === "success" ? (0, import_tool_kit6.classifyWorkMilestone)(command) : void 0;
2102
2649
  if (outcome === "cancelled") {
2103
- return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit4.bucketDurationMs)(durationMs), reason: "manual_interrupt" } }];
2650
+ return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "manual_interrupt" } }];
2104
2651
  }
2105
2652
  if (outcome === "failure") {
2106
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit5.isVerificationCommand)(commandClass)) {
2107
- return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit4.bucketDurationMs)(durationMs), reason: "test_failure" } }];
2653
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit6.isVerificationCommand)(commandClass)) {
2654
+ return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "test_failure" } }];
2108
2655
  }
2109
- return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit4.bucketDurationMs)(durationMs), reason: "tool_failure" } }];
2656
+ return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "tool_failure" } }];
2110
2657
  }
2111
2658
  if (isWriteTool(toolName)) {
2112
2659
  const linesChanged = computeLinesChanged(toolName, input);
@@ -2116,18 +2663,18 @@ function mapPostToolUse(hookName, input) {
2116
2663
  metadata: {
2117
2664
  toolName: safeToolName,
2118
2665
  outcome,
2119
- durationBucket: (0, import_tool_kit4.bucketDurationMs)(durationMs),
2666
+ durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs),
2120
2667
  // The boundary C2/the macOS work-self-report card triggers on: at
2121
2668
  // "200+" this is the "substantial accepted change" moment. No
2122
2669
  // second event type exists for this — the bucket on the existing
2123
2670
  // creation event *is* the boundary, deliberately, since the write
2124
2671
  // already happened; there is nothing else to mark.
2125
- ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit4.bucketLinesChanged)(linesChanged) } : {}
2672
+ ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit5.bucketLinesChanged)(linesChanged) } : {}
2126
2673
  }
2127
2674
  }];
2128
2675
  }
2129
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit5.isVerificationCommand)(commandClass)) {
2130
- return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit4.bucketDurationMs)(durationMs), activity: "ai_test_or_build_run" } }];
2676
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit6.isVerificationCommand)(commandClass)) {
2677
+ return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), activity: "ai_test_or_build_run" } }];
2131
2678
  }
2132
2679
  return [{
2133
2680
  eventType: "ai_tool_call_completed",
@@ -2136,13 +2683,13 @@ function mapPostToolUse(hookName, input) {
2136
2683
  toolName: safeToolName,
2137
2684
  commandClass,
2138
2685
  outcome,
2139
- durationBucket: (0, import_tool_kit4.bucketDurationMs)(durationMs),
2686
+ durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs),
2140
2687
  // The boundary and rework signal both ride this existing event rather
2141
2688
  // than minting a type: the backend already reads `gitAction` off any
2142
2689
  // event, and a commit is not a different *kind* of thing happening, it
2143
2690
  // is a fact about the tool call that just happened.
2144
2691
  ...gitAction !== void 0 ? { gitAction } : {},
2145
- ...(0, import_tool_kit5.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
2692
+ ...(0, import_tool_kit6.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
2146
2693
  // Same reasoning as `gitAction` above, one grain coarser: a milestone is
2147
2694
  // a fact about the tool call that just happened, not a different kind of
2148
2695
  // event. It rides here so the record carries the work's own rhythm —
@@ -2152,23 +2699,23 @@ function mapPostToolUse(hookName, input) {
2152
2699
  }];
2153
2700
  }
2154
2701
  function mapPreCompact(input) {
2155
- const trigger = (0, import_tool_kit4.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit4.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
2702
+ const trigger = (0, import_tool_kit5.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit5.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
2156
2703
  const isManual = trigger?.toLowerCase().includes("manual") ?? false;
2157
2704
  return [{ eventType: isManual ? "context_compression_manual" : "context_compression_auto", severity: isManual ? "medium" : "high", metadata: { trigger: isManual ? "manual" : "auto", reason: "context_limit" } }];
2158
2705
  }
2159
2706
  function mapStop(input) {
2160
- const durationMs = (0, import_tool_kit4.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit4.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
2161
- const durationBucket = (0, import_tool_kit4.bucketDurationMs)(durationMs);
2707
+ const durationMs = (0, import_tool_kit5.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit5.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
2708
+ const durationBucket = (0, import_tool_kit5.bucketDurationMs)(durationMs);
2162
2709
  if (durationBucket === "30-60m" || durationBucket === "60m+") {
2163
2710
  return [{ eventType: "agent_loop_long", severity: durationBucket === "60m+" ? "high" : "medium", metadata: { durationBucket, reason: "long_session", trigger: "inferred" } }];
2164
2711
  }
2165
2712
  return [];
2166
2713
  }
2167
2714
  function getToolName(input) {
2168
- return (0, import_tool_kit4.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit4.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
2715
+ return (0, import_tool_kit5.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit5.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
2169
2716
  }
2170
2717
  function computeLinesChanged(toolName, input) {
2171
- const toolInput = (0, import_tool_kit4.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit4.getNested)(input, ["input"]) ?? (0, import_tool_kit4.getNested)(input, ["parameters"]);
2718
+ const toolInput = (0, import_tool_kit5.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit5.getNested)(input, ["input"]) ?? (0, import_tool_kit5.getNested)(input, ["parameters"]);
2172
2719
  if (!toolInput || typeof toolInput !== "object") return void 0;
2173
2720
  const record = toolInput;
2174
2721
  switch (toolName?.toLowerCase()) {
@@ -2214,6 +2761,7 @@ function sanitiseToolName(toolName) {
2214
2761
  }
2215
2762
 
2216
2763
  // src/cli.ts
2764
+ init_types();
2217
2765
  var INTENTION_INVITE = "Ascenda tip: if it's natural, you can ask what would make this session count before diving in \u2014 one line is enough. Not a required step, and skip it entirely if the user is already mid-task.";
2218
2766
  var MILESTONE_DEBRIEF_INVITE = "Ascenda tip: that finished a piece of work. If the moment suits, it's worth a short debrief \u2014 what moved, what's still unresolved, and what you'd do differently next time. One or two lines. Skip it if they're already onto the next thing.";
2219
2767
  async function runPair() {
@@ -2221,8 +2769,8 @@ async function runPair() {
2221
2769
  const flagIndex = process.argv.indexOf("--tool-type");
2222
2770
  const toolType = flagIndex !== -1 ? (process.argv[flagIndex + 1] ?? "").trim() || ASCENDA_TOOL_TYPE : ASCENDA_TOOL_TYPE;
2223
2771
  const existing = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2224
- const toolInstallationId = existing && existing.includes(":") ? existing : `${toolType}:${randomUUID()}`;
2225
- const session = await (0, import_tool_kit6.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
2772
+ const toolInstallationId = existing && existing.includes(":") ? existing : `${toolType}:${randomUUID2()}`;
2773
+ const session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
2226
2774
  const code = session.deviceCode ?? session.code;
2227
2775
  await writeStdout(
2228
2776
  `
@@ -2235,8 +2783,8 @@ Waiting for confirmation (expires ${session.expiresAt})...
2235
2783
  );
2236
2784
  const deadline = Date.now() + 11 * 60 * 1e3;
2237
2785
  while (Date.now() < deadline) {
2238
- await new Promise((resolve) => setTimeout(resolve, 3e3));
2239
- const status = await (0, import_tool_kit6.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
2786
+ await new Promise((resolve2) => setTimeout(resolve2, 3e3));
2787
+ const status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
2240
2788
  if (status.status === "pending") continue;
2241
2789
  if (status.status !== "paired") {
2242
2790
  process.stderr.write(`Pairing ${status.status}. Run the command again for a fresh code.
@@ -2252,8 +2800,8 @@ Waiting for confirmation (expires ${session.expiresAt})...
2252
2800
  process.exitCode = 1;
2253
2801
  return;
2254
2802
  }
2255
- const tokenFilePath = (0, import_tool_kit6.defaultTokenFilePath)(pairedId);
2256
- (0, import_tool_kit6.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
2803
+ const tokenFilePath = (0, import_tool_kit8.defaultTokenFilePath)(pairedId);
2804
+ (0, import_tool_kit8.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
2257
2805
  await writeStdout(
2258
2806
  `Paired. Write token saved to ${tokenFilePath}
2259
2807
 
@@ -2268,9 +2816,14 @@ One step left \u2014 add this to your shell profile (~/.zshrc), then restart Cla
2268
2816
  process.stderr.write("Timed out waiting for confirmation. Run the command again for a fresh code.\n");
2269
2817
  process.exitCode = 1;
2270
2818
  }
2819
+ var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
2271
2820
  async function main() {
2272
2821
  const command = process.argv[2];
2273
- if (!command) throw new Error("Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | doctor");
2822
+ if (!command) {
2823
+ throw new Error(
2824
+ "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | doctor | setup | status | uninstall"
2825
+ );
2826
+ }
2274
2827
  if (command === "pair") {
2275
2828
  await runPair();
2276
2829
  return;
@@ -2279,8 +2832,15 @@ async function main() {
2279
2832
  await runDoctor();
2280
2833
  return;
2281
2834
  }
2835
+ if (MANAGEMENT_COMMANDS.has(command)) {
2836
+ const { runSetup: runSetup2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
2837
+ setupExitCode = await runSetup2(process.argv.slice(2));
2838
+ return;
2839
+ }
2282
2840
  if (!isClaudeHookEventName(command)) {
2283
- throw new Error(`Unknown command "${command}". Expected a Claude Code hook name, "pair" or "doctor".`);
2841
+ throw new Error(
2842
+ `Unknown command "${command}". Expected a Claude Code hook name, "pair", "doctor", "setup", "status" or "uninstall".`
2843
+ );
2284
2844
  }
2285
2845
  const hookName = command;
2286
2846
  const input = await readJsonFromStdin();
@@ -2297,18 +2857,18 @@ async function main() {
2297
2857
  await writeStdout(JSON.stringify({
2298
2858
  hookSpecificOutput: { hookEventName: hookName, additionalContext: contextParts.join("\n\n") }
2299
2859
  }));
2300
- if (pending) (0, import_tool_kit6.markFailureNotified)(pending.stateFilePath, pending.state);
2860
+ if (pending) (0, import_tool_kit8.markFailureNotified)(pending.stateFilePath, pending.state);
2301
2861
  }
2302
2862
  await emitLive(hookName, input);
2303
2863
  const mappedEvents = mapClaudeEvent(hookName, input);
2304
2864
  if (!mappedEvents.length) return;
2305
- const workContext = (0, import_tool_kit6.deriveWorkContext)((0, import_tool_kit6.getString)(input, ["cwd"]) ?? process.cwd());
2306
- if (workContext) (0, import_tool_kit6.recordWorkContext)(workContext);
2865
+ const workContext = (0, import_tool_kit8.deriveWorkContext)((0, import_tool_kit8.getString)(input, ["cwd"]) ?? process.cwd());
2866
+ if (workContext) (0, import_tool_kit8.recordWorkContext)(workContext);
2307
2867
  let config;
2308
2868
  try {
2309
2869
  config = loadConfigFromEnv();
2310
2870
  } catch (error) {
2311
- const logFile = (0, import_tool_kit6.resolveEventLogPath)();
2871
+ const logFile = (0, import_tool_kit8.resolveEventLogPath)();
2312
2872
  if (!logFile) throw error;
2313
2873
  for (const event of mappedEvents) logUnsent(logFile, event, workContext);
2314
2874
  return;
@@ -2333,18 +2893,18 @@ async function emitLive(hookName, input) {
2333
2893
  const event = hookName === "UserPromptSubmit" ? "prompt_submitted" : hookName === "PreToolUse" ? "tool_call" : hookName === "PreCompact" ? "compaction" : hookName === "PostToolUseFailure" ? "tool_failure" : hookName === "Stop" ? "stop" : void 0;
2334
2894
  if (!event) return;
2335
2895
  try {
2336
- const prompt = event === "prompt_submitted" ? (0, import_tool_kit6.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]) : void 0;
2337
- const promptSource = event === "prompt_submitted" ? (0, import_tool_kit6.getString)(input, ["promptSource", "prompt_source"]) : void 0;
2896
+ const prompt = event === "prompt_submitted" ? (0, import_tool_kit8.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit8.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]) : void 0;
2897
+ const promptSource = event === "prompt_submitted" ? (0, import_tool_kit8.getString)(input, ["promptSource", "prompt_source"]) : void 0;
2338
2898
  const queued = promptSource === void 0 ? void 0 : promptSource === "queued";
2339
- await (0, import_tool_kit6.emitLiveSignal)({
2899
+ await (0, import_tool_kit8.emitLiveSignal)({
2340
2900
  tool: process.env.ASCENDA_TOOL_TYPE ?? "claude_code",
2341
2901
  // Concurrent sessions must count as separate streams for the X gauge.
2342
2902
  // Without a session id every window collapses into one, so fall back to
2343
2903
  // this process's parent — still per-session in practice, since Claude
2344
2904
  // Code spawns hooks from the session process.
2345
- session: (0, import_tool_kit6.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
2905
+ session: (0, import_tool_kit8.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
2346
2906
  event,
2347
- ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit6.bucketPromptSize)(prompt) } : {},
2907
+ ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit8.bucketPromptSize)(prompt) } : {},
2348
2908
  ...queued !== void 0 ? { queued } : {}
2349
2909
  });
2350
2910
  } catch {
@@ -2356,8 +2916,8 @@ function pendingFailureNotice(hookName) {
2356
2916
  const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2357
2917
  if (!rawId) return void 0;
2358
2918
  const stateFilePath = resolveStateFilePath(normalizeToolInstallationId(rawId));
2359
- const state = (0, import_tool_kit6.readCollectorState)(stateFilePath);
2360
- if (!(0, import_tool_kit6.shouldAnnounceFailure)(state) || !state) return void 0;
2919
+ const state = (0, import_tool_kit8.readCollectorState)(stateFilePath);
2920
+ if (!(0, import_tool_kit8.shouldAnnounceFailure)(state) || !state) return void 0;
2361
2921
  const since = state.lastSuccessAt ? `since ${state.lastSuccessAt}` : "and has never succeeded on this machine";
2362
2922
  return {
2363
2923
  text: `Ascenda note: work telemetry has not been reaching Ascenda ${since} (${describeOutcome(state)}). Your work is unaffected and nothing was lost from this session. Run \`npx @ascenda-one/claude-code-hooks doctor\` for details, or \`npx @ascenda-one/claude-code-hooks pair\` to reconnect. This note appears once.`,
@@ -2381,8 +2941,8 @@ function describeOutcome(state) {
2381
2941
  }
2382
2942
  }
2383
2943
  function writeStdout(text) {
2384
- return new Promise((resolve) => {
2385
- process.stdout.write(text, () => resolve());
2944
+ return new Promise((resolve2) => {
2945
+ process.stdout.write(text, () => resolve2());
2386
2946
  });
2387
2947
  }
2388
2948
  async function runDoctor() {
@@ -2398,12 +2958,12 @@ async function runDoctor() {
2398
2958
  return;
2399
2959
  }
2400
2960
  const toolInstallationId = normalizeToolInstallationId(rawId);
2401
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit6.defaultTokenFilePath)(toolInstallationId);
2961
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId);
2402
2962
  lines.push(` Token file ${tokenFilePath}`);
2403
2963
  lines.push(` Token ${describeToken(tokenFilePath)}`);
2404
2964
  const stateFilePath = resolveStateFilePath(toolInstallationId);
2405
2965
  lines.push(` Journal ${stateFilePath}`);
2406
- const state = (0, import_tool_kit6.readCollectorState)(stateFilePath);
2966
+ const state = (0, import_tool_kit8.readCollectorState)(stateFilePath);
2407
2967
  if (!state) {
2408
2968
  lines.push(" Last outcome (no journal yet \u2014 no send attempted since this version was installed)");
2409
2969
  } else {
@@ -2433,10 +2993,10 @@ async function liveRoundTrip() {
2433
2993
  }
2434
2994
  function describeToken(tokenFilePath) {
2435
2995
  try {
2436
- if (!fs.existsSync(tokenFilePath)) {
2996
+ if (!fs3.existsSync(tokenFilePath)) {
2437
2997
  return process.env.ASCENDA_EVENT_WRITE_TOKEN ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : "MISSING \u2014 run `pair`";
2438
2998
  }
2439
- const stat = fs.statSync(tokenFilePath);
2999
+ const stat = fs3.statSync(tokenFilePath);
2440
3000
  const ageDays = Math.floor((Date.now() - stat.mtimeMs) / 864e5);
2441
3001
  return `present, last written ${stat.mtime.toISOString()} (${ageDays}d ago)`;
2442
3002
  } catch (error) {
@@ -2444,14 +3004,14 @@ function describeToken(tokenFilePath) {
2444
3004
  }
2445
3005
  }
2446
3006
  function logUnsent(logFile, event, workContext) {
2447
- const payload = (0, import_tool_kit6.buildEventPayload)({
3007
+ const payload = (0, import_tool_kit8.buildEventPayload)({
2448
3008
  toolInstallationId: `${ASCENDA_TOOL_TYPE}:unpaired`,
2449
3009
  source: "claude_code",
2450
3010
  sessionId: process.env.ASCENDA_SESSION_ID ?? null,
2451
3011
  workspaceHash: envHashOverride("ASCENDA_WORKSPACE_HASH") ?? workContext?.workspaceHash ?? null,
2452
3012
  projectHash: envHashOverride("ASCENDA_PROJECT_HASH") ?? workContext?.projectHash ?? null
2453
3013
  }, event);
2454
- (0, import_tool_kit6.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery: "not_sent", payload });
3014
+ (0, import_tool_kit8.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery: "not_sent", payload });
2455
3015
  }
2456
3016
  async function readJsonFromStdin() {
2457
3017
  const chunks = [];
@@ -2464,6 +3024,7 @@ async function readJsonFromStdin() {
2464
3024
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
2465
3025
  return parsed;
2466
3026
  }
3027
+ var setupExitCode;
2467
3028
  main().catch((error) => {
2468
3029
  console.error(error instanceof Error ? error.message : String(error));
2469
- }).finally(() => process.exit(process.exitCode ?? 0));
3030
+ }).finally(() => process.exit(setupExitCode ?? process.exitCode ?? 0));