@ascenda-one/claude-code-hooks 0.1.8 → 0.1.9

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
@@ -415,6 +415,93 @@ var require_out = __commonJS({
415
415
  }
416
416
  });
417
417
 
418
+ // ../packages/tool-kit/out/eventLog.js
419
+ var require_eventLog = __commonJS({
420
+ "../packages/tool-kit/out/eventLog.js"(exports) {
421
+ "use strict";
422
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
423
+ if (k2 === void 0) k2 = k;
424
+ var desc = Object.getOwnPropertyDescriptor(m, k);
425
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
426
+ desc = { enumerable: true, get: function() {
427
+ return m[k];
428
+ } };
429
+ }
430
+ Object.defineProperty(o, k2, desc);
431
+ } : function(o, m, k, k2) {
432
+ if (k2 === void 0) k2 = k;
433
+ o[k2] = m[k];
434
+ });
435
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
436
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
437
+ } : function(o, v) {
438
+ o["default"] = v;
439
+ });
440
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
441
+ var ownKeys = function(o) {
442
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
443
+ var ar = [];
444
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
445
+ return ar;
446
+ };
447
+ return ownKeys(o);
448
+ };
449
+ return function(mod) {
450
+ if (mod && mod.__esModule) return mod;
451
+ var result = {};
452
+ if (mod != null) {
453
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
454
+ }
455
+ __setModuleDefault(result, mod);
456
+ return result;
457
+ };
458
+ }();
459
+ Object.defineProperty(exports, "__esModule", { value: true });
460
+ exports.EVENT_LOG_ENV_VAR = void 0;
461
+ exports.expandUserPath = expandUserPath;
462
+ exports.resolveEventLogPath = resolveEventLogPath2;
463
+ exports.appendEventLog = appendEventLog2;
464
+ var fs2 = __importStar(__require("fs"));
465
+ var os = __importStar(__require("os"));
466
+ var path = __importStar(__require("path"));
467
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
468
+ var MAX_BYTES = 5 * 1024 * 1024;
469
+ function expandUserPath(configured) {
470
+ const value = configured?.trim();
471
+ if (!value)
472
+ return void 0;
473
+ if (value === "~")
474
+ return os.homedir();
475
+ if (value.startsWith("~/"))
476
+ return path.join(os.homedir(), value.slice(2));
477
+ return path.resolve(value);
478
+ }
479
+ function resolveEventLogPath2() {
480
+ return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
481
+ }
482
+ function appendEventLog2(logFilePath, entry) {
483
+ try {
484
+ rotateIfLarge(logFilePath);
485
+ const dir = path.dirname(logFilePath);
486
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
487
+ fs2.appendFileSync(logFilePath, `${JSON.stringify(entry)}
488
+ `, { encoding: "utf8", mode: 384 });
489
+ if (process.platform !== "win32")
490
+ fs2.chmodSync(logFilePath, 384);
491
+ } catch {
492
+ }
493
+ }
494
+ function rotateIfLarge(logFilePath) {
495
+ try {
496
+ if (fs2.statSync(logFilePath).size < MAX_BYTES)
497
+ return;
498
+ fs2.renameSync(logFilePath, `${logFilePath}.1`);
499
+ } catch {
500
+ }
501
+ }
502
+ }
503
+ });
504
+
418
505
  // ../packages/tool-kit/out/http.js
419
506
  var require_http = __commonJS({
420
507
  "../packages/tool-kit/out/http.js"(exports) {
@@ -424,6 +511,7 @@ var require_http = __commonJS({
424
511
  exports.createPairingSession = createPairingSession2;
425
512
  exports.getPairingStatus = getPairingStatus2;
426
513
  exports.renewToolToken = renewToolToken;
514
+ exports.isRetryableStatus = isRetryableStatus;
427
515
  exports.postToolEvent = postToolEvent;
428
516
  exports.postToolEventsBatch = postToolEventsBatch;
429
517
  exports.parseIngestResponse = parseIngestResponse;
@@ -469,26 +557,34 @@ var require_http = __commonJS({
469
557
  throw new AscendaApiError2(response.status, void 0, await response.text());
470
558
  return await response.json();
471
559
  }
560
+ function isRetryableStatus(status) {
561
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
562
+ }
472
563
  async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
473
- const response = await fetch(`${apiBaseUrl}/v1/tool-events`, {
474
- method: "POST",
475
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
476
- body: JSON.stringify(payload),
477
- signal
478
- });
479
- return parseIngestResponse(response);
564
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
480
565
  }
481
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads) {
482
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/batch`, {
483
- method: "POST",
484
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
485
- body: JSON.stringify({ events: payloads })
486
- });
487
- return parseIngestResponse(response);
566
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
567
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
568
+ }
569
+ async function sendIngest(url, eventWriteToken, body, signal) {
570
+ try {
571
+ const response = await fetch(url, {
572
+ method: "POST",
573
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
574
+ body,
575
+ signal
576
+ });
577
+ return parseIngestResponse(response);
578
+ } catch (error) {
579
+ return {
580
+ result: "transport_error",
581
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
582
+ };
583
+ }
488
584
  }
489
585
  async function parseIngestResponse(response) {
490
586
  if (response.ok)
491
- return "accepted";
587
+ return { result: "accepted", httpStatus: response.status };
492
588
  const body = await response.text();
493
589
  let errorCode;
494
590
  try {
@@ -496,13 +592,14 @@ var require_http = __commonJS({
496
592
  } catch {
497
593
  errorCode = void 0;
498
594
  }
595
+ const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
499
596
  if (response.status === 401)
500
- return "auth_failed";
597
+ return { ...base, result: "auth_failed" };
501
598
  if (response.status === 403 && errorCode === "consent_missing_or_expired")
502
- return "consent_missing";
599
+ return { ...base, result: "consent_missing" };
503
600
  if (response.status === 400 || response.status === 422)
504
- return "validation_failed";
505
- throw new AscendaApiError2(response.status, errorCode, body);
601
+ return { ...base, result: "validation_failed" };
602
+ return { ...base, result: "transport_error" };
506
603
  }
507
604
  }
508
605
  });
@@ -552,7 +649,8 @@ var require_tokenStore = __commonJS({
552
649
  exports.defaultTokenFilePath = defaultTokenFilePath3;
553
650
  exports.persistEventWriteToken = persistEventWriteToken3;
554
651
  exports.readTokenFile = readTokenFile2;
555
- var fs = __importStar(__require("fs"));
652
+ exports.sanitizeFilePart = sanitizeFilePart;
653
+ var fs2 = __importStar(__require("fs"));
556
654
  var os = __importStar(__require("os"));
557
655
  var path = __importStar(__require("path"));
558
656
  function defaultTokenFilePath3(toolInstallationId) {
@@ -560,18 +658,18 @@ var require_tokenStore = __commonJS({
560
658
  }
561
659
  function persistEventWriteToken3(tokenFilePath, token) {
562
660
  const dir = path.dirname(tokenFilePath);
563
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
564
- fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
661
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
662
+ fs2.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
565
663
  if (process.platform !== "win32") {
566
- fs.chmodSync(dir, 448);
567
- fs.chmodSync(tokenFilePath, 384);
664
+ fs2.chmodSync(dir, 448);
665
+ fs2.chmodSync(tokenFilePath, 384);
568
666
  }
569
667
  }
570
668
  function readTokenFile2(tokenFilePath) {
571
669
  try {
572
- if (!fs.existsSync(tokenFilePath))
670
+ if (!fs2.existsSync(tokenFilePath))
573
671
  return void 0;
574
- const value = fs.readFileSync(tokenFilePath, "utf8").trim();
672
+ const value = fs2.readFileSync(tokenFilePath, "utf8").trim();
575
673
  return value || void 0;
576
674
  } catch {
577
675
  return void 0;
@@ -583,15 +681,144 @@ var require_tokenStore = __commonJS({
583
681
  }
584
682
  });
585
683
 
684
+ // ../packages/tool-kit/out/stateStore.js
685
+ var require_stateStore = __commonJS({
686
+ "../packages/tool-kit/out/stateStore.js"(exports) {
687
+ "use strict";
688
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
689
+ if (k2 === void 0) k2 = k;
690
+ var desc = Object.getOwnPropertyDescriptor(m, k);
691
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
692
+ desc = { enumerable: true, get: function() {
693
+ return m[k];
694
+ } };
695
+ }
696
+ Object.defineProperty(o, k2, desc);
697
+ } : function(o, m, k, k2) {
698
+ if (k2 === void 0) k2 = k;
699
+ o[k2] = m[k];
700
+ });
701
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
702
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
703
+ } : function(o, v) {
704
+ o["default"] = v;
705
+ });
706
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
707
+ var ownKeys = function(o) {
708
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
709
+ var ar = [];
710
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
711
+ return ar;
712
+ };
713
+ return ownKeys(o);
714
+ };
715
+ return function(mod) {
716
+ if (mod && mod.__esModule) return mod;
717
+ var result = {};
718
+ if (mod != null) {
719
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
720
+ }
721
+ __setModuleDefault(result, mod);
722
+ return result;
723
+ };
724
+ }();
725
+ Object.defineProperty(exports, "__esModule", { value: true });
726
+ exports.defaultStateFilePath = defaultStateFilePath2;
727
+ exports.readCollectorState = readCollectorState2;
728
+ exports.recordSendOutcome = recordSendOutcome;
729
+ exports.shouldAnnounceFailure = shouldAnnounceFailure2;
730
+ exports.markFailureNotified = markFailureNotified2;
731
+ var fs2 = __importStar(__require("fs"));
732
+ var os = __importStar(__require("os"));
733
+ var path = __importStar(__require("path"));
734
+ var tokenStore_1 = require_tokenStore();
735
+ function defaultStateFilePath2(toolInstallationId) {
736
+ return path.join(os.homedir(), ".ascenda", "state", `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
737
+ }
738
+ function readCollectorState2(stateFilePath) {
739
+ try {
740
+ if (!fs2.existsSync(stateFilePath))
741
+ return void 0;
742
+ const raw = fs2.readFileSync(stateFilePath, "utf8").trim();
743
+ if (!raw)
744
+ return void 0;
745
+ const parsed = JSON.parse(raw);
746
+ if (!parsed || typeof parsed !== "object")
747
+ return void 0;
748
+ return parsed;
749
+ } catch {
750
+ return void 0;
751
+ }
752
+ }
753
+ function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
754
+ const now = (/* @__PURE__ */ new Date()).toISOString();
755
+ const previous = readCollectorState2(stateFilePath);
756
+ const accepted = outcome === "accepted";
757
+ const next = {
758
+ toolInstallationId,
759
+ lastAttemptAt: now,
760
+ lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
761
+ lastOutcome: outcome,
762
+ consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
763
+ ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
764
+ ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
765
+ ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
766
+ // A success closes the episode; a failure either opens one or continues
767
+ // the one already open. Carrying `notifiedFailingSince` across a
768
+ // continuing episode is what keeps the notice to once per outage.
769
+ ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
770
+ ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {}
771
+ };
772
+ writeStateFile(stateFilePath, next);
773
+ return next;
774
+ }
775
+ function shouldAnnounceFailure2(state) {
776
+ if (!state || state.consecutiveFailures === 0 || !state.failingSince)
777
+ return false;
778
+ return state.notifiedFailingSince !== state.failingSince;
779
+ }
780
+ function markFailureNotified2(stateFilePath, state) {
781
+ if (!state.failingSince)
782
+ return;
783
+ writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
784
+ }
785
+ function writeStateFile(stateFilePath, state) {
786
+ const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
787
+ try {
788
+ const dir = path.dirname(stateFilePath);
789
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
790
+ fs2.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
791
+ `, { encoding: "utf8", mode: 384 });
792
+ fs2.renameSync(temporaryPath, stateFilePath);
793
+ if (process.platform !== "win32")
794
+ fs2.chmodSync(stateFilePath, 384);
795
+ } catch {
796
+ try {
797
+ if (fs2.existsSync(temporaryPath))
798
+ fs2.unlinkSync(temporaryPath);
799
+ } catch {
800
+ }
801
+ }
802
+ }
803
+ function truncate(value) {
804
+ const collapsed = value.replace(/\s+/g, " ").trim();
805
+ return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
806
+ }
807
+ }
808
+ });
809
+
586
810
  // ../packages/tool-kit/out/eventSender.js
587
811
  var require_eventSender = __commonJS({
588
812
  "../packages/tool-kit/out/eventSender.js"(exports) {
589
813
  "use strict";
590
814
  Object.defineProperty(exports, "__esModule", { value: true });
591
815
  exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
816
+ exports.buildEventPayload = buildEventPayload2;
592
817
  var tool_contract_1 = require_out();
818
+ var eventLog_1 = require_eventLog();
593
819
  var http_1 = require_http();
594
820
  var tokenStore_1 = require_tokenStore();
821
+ var stateStore_1 = require_stateStore();
595
822
  var AscendaSemanticEventError = class extends Error {
596
823
  constructor(message) {
597
824
  super(message);
@@ -599,27 +826,32 @@ var require_eventSender = __commonJS({
599
826
  }
600
827
  };
601
828
  exports.AscendaSemanticEventError = AscendaSemanticEventError;
829
+ function buildEventPayload2(identity, mapped) {
830
+ return {
831
+ toolInstallationId: identity.toolInstallationId,
832
+ source: identity.source,
833
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
834
+ sessionId: identity.sessionId ?? void 0,
835
+ workspaceHash: identity.workspaceHash ?? void 0,
836
+ consentScope: tool_contract_1.ASCENDA_CONSENT_SCOPE,
837
+ provenance: tool_contract_1.ASCENDA_PROVENANCE,
838
+ privacyMode: "metadata_only",
839
+ ...mapped,
840
+ metadata: mapped.metadata ?? {}
841
+ };
842
+ }
843
+ var DEFAULT_TIMEOUT_MS = 5e3;
844
+ var RETRY_DELAY_MS = 250;
602
845
  var AscendaEventSender2 = class {
603
846
  config;
604
847
  eventWriteToken;
848
+ lastState;
605
849
  constructor(config) {
606
850
  this.config = config;
607
851
  this.eventWriteToken = config.eventWriteToken;
608
852
  }
609
853
  async send(mapped) {
610
- const payload = {
611
- toolInstallationId: this.config.toolInstallationId,
612
- source: this.config.source,
613
- occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
614
- sessionId: this.config.sessionId ?? void 0,
615
- workspaceHash: this.config.workspaceHash ?? void 0,
616
- consentScope: tool_contract_1.ASCENDA_CONSENT_SCOPE,
617
- provenance: tool_contract_1.ASCENDA_PROVENANCE,
618
- privacyMode: "metadata_only",
619
- ...mapped,
620
- metadata: mapped.metadata ?? {}
621
- };
622
- return this.post(payload);
854
+ return this.post(buildEventPayload2(this.config, mapped));
623
855
  }
624
856
  /**
625
857
  * Sends one of the six agent-observed types (dark-flow-gap-analysis §2.1).
@@ -690,32 +922,263 @@ var require_eventSender = __commonJS({
690
922
  };
691
923
  return this.post(payload);
692
924
  }
925
+ /**
926
+ * The single choke point every event passes through, and therefore the only
927
+ * honest place to journal one. Recording here rather than in each adapter is
928
+ * deliberate: Claude Code, Codex, the GitHub collector and the MCP server all
929
+ * send through this method, and the defect being fixed showed up in three
930
+ * separate components because each was left to notice its own failures.
931
+ */
693
932
  async post(payload) {
694
- let result = await (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
695
- if (result === "auth_failed") {
696
- const renewed = await this.renewEventToken();
697
- if (!renewed)
698
- return "auth_failed";
699
- result = await (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
933
+ const outcome = await this.attempt(payload);
934
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, outcome.result, {
935
+ httpStatus: outcome.httpStatus,
936
+ errorCode: outcome.errorCode,
937
+ detail: outcome.detail
938
+ });
939
+ this.log(payload, outcome.result);
940
+ return outcome.result;
941
+ }
942
+ /**
943
+ * Two recoveries, each tried once. A rejected token gets a renewal and one
944
+ * replay — rotation is expected and should heal unattended. A transport
945
+ * error gets one retry, because the common cases (a restarting instance, a
946
+ * proxy blip, a 429) clear in well under a second and the alternative is
947
+ * losing the event outright.
948
+ */
949
+ async attempt(payload) {
950
+ const outcome = await (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
951
+ if (outcome.result === "auth_failed") {
952
+ if (!await this.renewEventToken())
953
+ return outcome;
954
+ return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
700
955
  }
701
- return result;
956
+ if (outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus))) {
957
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
958
+ return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
959
+ }
960
+ return outcome;
961
+ }
962
+ /**
963
+ * The state written by the most recent send, so a caller can decide whether
964
+ * to surface a one-time notice without re-reading the journal it just wrote.
965
+ */
966
+ get state() {
967
+ return this.lastState;
968
+ }
969
+ stateFilePath() {
970
+ return this.config.stateFilePath ?? (0, stateStore_1.defaultStateFilePath)(this.config.toolInstallationId);
971
+ }
972
+ /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
973
+ /**
974
+ * Every send path funnels through {@link post}, so semantic and
975
+ * collaboration signals are logged on the same terms as host events — the
976
+ * log would be misleading as an audit of what left the machine otherwise.
977
+ *
978
+ * An unreachable backend used to be logged as `other` from a catch block.
979
+ * It is now `transport_error` through the ordinary path, because the
980
+ * transport returns that outcome instead of throwing.
981
+ */
982
+ log(payload, delivery) {
983
+ const logFile = this.config.eventLogFile === void 0 ? (0, eventLog_1.resolveEventLogPath)() : this.config.eventLogFile;
984
+ if (!logFile)
985
+ return;
986
+ (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload });
702
987
  }
703
988
  async renewEventToken() {
704
- const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
705
- if (!renewed)
989
+ try {
990
+ const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
991
+ if (!renewed)
992
+ return false;
993
+ this.eventWriteToken = renewed.eventWriteToken;
994
+ (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken);
995
+ return true;
996
+ } catch {
706
997
  return false;
707
- this.eventWriteToken = renewed.eventWriteToken;
708
- (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken);
709
- return true;
998
+ }
710
999
  }
711
1000
  signal() {
712
- return this.config.timeoutMs ? AbortSignal.timeout(this.config.timeoutMs) : void 0;
1001
+ return AbortSignal.timeout(this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS);
713
1002
  }
714
1003
  };
715
1004
  exports.AscendaEventSender = AscendaEventSender2;
716
1005
  }
717
1006
  });
718
1007
 
1008
+ // ../packages/tool-kit/out/hookAdapter.js
1009
+ var require_hookAdapter = __commonJS({
1010
+ "../packages/tool-kit/out/hookAdapter.js"(exports) {
1011
+ "use strict";
1012
+ Object.defineProperty(exports, "__esModule", { value: true });
1013
+ exports.DEFAULT_API_BASE_URL = void 0;
1014
+ exports.loadCliAgentConfig = loadCliAgentConfig;
1015
+ exports.deliverHookEvents = deliverHookEvents;
1016
+ var eventLog_1 = require_eventLog();
1017
+ var eventSender_1 = require_eventSender();
1018
+ var tokenStore_1 = require_tokenStore();
1019
+ exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
1020
+ function loadCliAgentConfig(toolType, sessionIdFromHook) {
1021
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
1022
+ const toolInstallationIdRaw = process.env.ASCENDA_TOOL_INSTALLATION_ID;
1023
+ if (!toolInstallationIdRaw)
1024
+ throw new Error("Missing ASCENDA_TOOL_INSTALLATION_ID");
1025
+ const toolInstallationId = toolInstallationIdRaw.trim().includes(":") ? toolInstallationIdRaw.trim() : `${toolType}:${toolInstallationIdRaw.trim()}`;
1026
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId);
1027
+ const fileToken = (0, tokenStore_1.readTokenFile)(tokenFilePath);
1028
+ const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
1029
+ if (!eventWriteToken)
1030
+ throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
1031
+ if (!fileToken)
1032
+ (0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
1033
+ return {
1034
+ apiBaseUrl,
1035
+ toolInstallationId,
1036
+ eventWriteToken,
1037
+ tokenFilePath,
1038
+ sessionId: process.env.ASCENDA_SESSION_ID ?? sessionIdFromHook ?? null,
1039
+ workspaceHash: process.env.ASCENDA_WORKSPACE_HASH ?? null,
1040
+ // Agents await command hooks; fail fast rather than stall the user's turn.
1041
+ timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
1042
+ };
1043
+ }
1044
+ async function deliverHookEvents(events, options) {
1045
+ if (events.length === 0)
1046
+ return;
1047
+ const notice = options.onNotice ?? ((message) => console.error(message));
1048
+ let config;
1049
+ try {
1050
+ config = loadCliAgentConfig(options.toolType, options.sessionId);
1051
+ } catch (error) {
1052
+ const logFile = (0, eventLog_1.resolveEventLogPath)();
1053
+ if (!logFile)
1054
+ throw error;
1055
+ for (const event of events) {
1056
+ (0, eventLog_1.appendEventLog)(logFile, {
1057
+ loggedAt: (/* @__PURE__ */ new Date()).toISOString(),
1058
+ delivery: "not_sent",
1059
+ payload: (0, eventSender_1.buildEventPayload)({
1060
+ toolInstallationId: `${options.toolType}:unpaired`,
1061
+ source: options.source,
1062
+ sessionId: options.sessionId ?? null,
1063
+ workspaceHash: process.env.ASCENDA_WORKSPACE_HASH ?? null
1064
+ }, event)
1065
+ });
1066
+ }
1067
+ return;
1068
+ }
1069
+ const sender = new eventSender_1.AscendaEventSender({
1070
+ apiBaseUrl: config.apiBaseUrl,
1071
+ toolInstallationId: config.toolInstallationId,
1072
+ source: options.source,
1073
+ eventWriteToken: config.eventWriteToken,
1074
+ tokenFilePath: config.tokenFilePath,
1075
+ sessionId: config.sessionId,
1076
+ workspaceHash: config.workspaceHash,
1077
+ timeoutMs: config.timeoutMs
1078
+ });
1079
+ for (const event of events) {
1080
+ const result = await sender.send(event);
1081
+ if (result === "accepted")
1082
+ continue;
1083
+ if (result === "consent_missing") {
1084
+ notice("Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.");
1085
+ } else if (result === "auth_failed") {
1086
+ notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
1087
+ } else if (result === "transport_error") {
1088
+ notice("Ascenda telemetry paused: the ingest endpoint could not be reached. Your work is unaffected.");
1089
+ } else {
1090
+ notice(`Ascenda telemetry rejected: ${result}`);
1091
+ }
1092
+ return;
1093
+ }
1094
+ }
1095
+ function parsePositiveInt(value) {
1096
+ const n = Number(value);
1097
+ return Number.isInteger(n) && n > 0 ? n : void 0;
1098
+ }
1099
+ }
1100
+ });
1101
+
1102
+ // ../packages/tool-kit/out/turnState.js
1103
+ var require_turnState = __commonJS({
1104
+ "../packages/tool-kit/out/turnState.js"(exports) {
1105
+ "use strict";
1106
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1107
+ if (k2 === void 0) k2 = k;
1108
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1109
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1110
+ desc = { enumerable: true, get: function() {
1111
+ return m[k];
1112
+ } };
1113
+ }
1114
+ Object.defineProperty(o, k2, desc);
1115
+ } : function(o, m, k, k2) {
1116
+ if (k2 === void 0) k2 = k;
1117
+ o[k2] = m[k];
1118
+ });
1119
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1120
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1121
+ } : function(o, v) {
1122
+ o["default"] = v;
1123
+ });
1124
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1125
+ var ownKeys = function(o) {
1126
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1127
+ var ar = [];
1128
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1129
+ return ar;
1130
+ };
1131
+ return ownKeys(o);
1132
+ };
1133
+ return function(mod) {
1134
+ if (mod && mod.__esModule) return mod;
1135
+ var result = {};
1136
+ if (mod != null) {
1137
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1138
+ }
1139
+ __setModuleDefault(result, mod);
1140
+ return result;
1141
+ };
1142
+ }();
1143
+ Object.defineProperty(exports, "__esModule", { value: true });
1144
+ exports.recordTurnStart = recordTurnStart;
1145
+ exports.consumeTurnDurationMs = consumeTurnDurationMs;
1146
+ var fs2 = __importStar(__require("fs"));
1147
+ var os = __importStar(__require("os"));
1148
+ var path = __importStar(__require("path"));
1149
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join(os.homedir(), ".ascenda", "state");
1150
+ function turnFile(agent, sessionId) {
1151
+ return path.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
1152
+ }
1153
+ function sanitize(value) {
1154
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_");
1155
+ }
1156
+ function recordTurnStart(agent, sessionId, now = Date.now()) {
1157
+ if (!sessionId)
1158
+ return;
1159
+ try {
1160
+ fs2.mkdirSync(stateDir(), { recursive: true });
1161
+ fs2.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
1162
+ } catch {
1163
+ }
1164
+ }
1165
+ function consumeTurnDurationMs(agent, sessionId, now = Date.now()) {
1166
+ if (!sessionId)
1167
+ return void 0;
1168
+ const file = turnFile(agent, sessionId);
1169
+ try {
1170
+ const started = Number(fs2.readFileSync(file, "utf8").trim());
1171
+ fs2.rmSync(file, { force: true });
1172
+ if (!Number.isFinite(started) || started <= 0 || started > now)
1173
+ return void 0;
1174
+ return now - started;
1175
+ } catch {
1176
+ return void 0;
1177
+ }
1178
+ }
1179
+ }
1180
+ });
1181
+
719
1182
  // ../packages/tool-kit/out/salt.js
720
1183
  var require_salt = __commonJS({
721
1184
  "../packages/tool-kit/out/salt.js"(exports) {
@@ -762,7 +1225,7 @@ var require_salt = __commonJS({
762
1225
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
763
1226
  exports.hashWithMachineSalt = hashWithMachineSalt;
764
1227
  var crypto = __importStar(__require("crypto"));
765
- var fs = __importStar(__require("fs"));
1228
+ var fs2 = __importStar(__require("fs"));
766
1229
  var os = __importStar(__require("os"));
767
1230
  var path = __importStar(__require("path"));
768
1231
  function machineSaltFilePath() {
@@ -774,19 +1237,19 @@ var require_salt = __commonJS({
774
1237
  if (hit)
775
1238
  return hit;
776
1239
  const dir = path.dirname(saltFilePath);
777
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1240
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
778
1241
  let salt;
779
1242
  try {
780
1243
  salt = crypto.randomBytes(32).toString("hex");
781
- fs.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
1244
+ fs2.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
782
1245
  } catch (error) {
783
1246
  if (error.code !== "EEXIST")
784
1247
  throw error;
785
- salt = fs.readFileSync(saltFilePath, "utf8").trim();
1248
+ salt = fs2.readFileSync(saltFilePath, "utf8").trim();
786
1249
  }
787
1250
  if (process.platform !== "win32") {
788
- fs.chmodSync(dir, 448);
789
- fs.chmodSync(saltFilePath, 384);
1251
+ fs2.chmodSync(dir, 448);
1252
+ fs2.chmodSync(saltFilePath, 384);
790
1253
  }
791
1254
  cache.set(saltFilePath, salt);
792
1255
  return salt;
@@ -845,7 +1308,7 @@ var require_liveBus = __commonJS({
845
1308
  exports.liveBusSocketPath = liveBusSocketPath;
846
1309
  exports.bucketPromptSize = bucketPromptSize2;
847
1310
  exports.emitLiveSignal = emitLiveSignal2;
848
- var fs = __importStar(__require("fs"));
1311
+ var fs2 = __importStar(__require("fs"));
849
1312
  var net = __importStar(__require("net"));
850
1313
  var os = __importStar(__require("os"));
851
1314
  var path = __importStar(__require("path"));
@@ -865,7 +1328,7 @@ var require_liveBus = __commonJS({
865
1328
  const candidates = liveBusSocketCandidates();
866
1329
  for (const candidate of candidates) {
867
1330
  try {
868
- if (fs.statSync(candidate).isSocket())
1331
+ if (fs2.statSync(candidate).isSocket())
869
1332
  return candidate;
870
1333
  } catch {
871
1334
  }
@@ -930,7 +1393,8 @@ var require_out2 = __commonJS({
930
1393
  "../packages/tool-kit/out/index.js"(exports) {
931
1394
  "use strict";
932
1395
  Object.defineProperty(exports, "__esModule", { value: true });
933
- exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.defaultTokenFilePath = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
1396
+ exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = 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.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.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
1397
+ exports.isRetryableStatus = exports.parseIngestResponse = void 0;
934
1398
  var commandClassifier_1 = require_commandClassifier();
935
1399
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
936
1400
  return commandClassifier_1.classifyCommand;
@@ -995,6 +1459,39 @@ var require_out2 = __commonJS({
995
1459
  Object.defineProperty(exports, "AscendaSemanticEventError", { enumerable: true, get: function() {
996
1460
  return eventSender_1.AscendaSemanticEventError;
997
1461
  } });
1462
+ Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
1463
+ return eventSender_1.buildEventPayload;
1464
+ } });
1465
+ var eventLog_1 = require_eventLog();
1466
+ Object.defineProperty(exports, "EVENT_LOG_ENV_VAR", { enumerable: true, get: function() {
1467
+ return eventLog_1.EVENT_LOG_ENV_VAR;
1468
+ } });
1469
+ Object.defineProperty(exports, "appendEventLog", { enumerable: true, get: function() {
1470
+ return eventLog_1.appendEventLog;
1471
+ } });
1472
+ Object.defineProperty(exports, "expandUserPath", { enumerable: true, get: function() {
1473
+ return eventLog_1.expandUserPath;
1474
+ } });
1475
+ Object.defineProperty(exports, "resolveEventLogPath", { enumerable: true, get: function() {
1476
+ return eventLog_1.resolveEventLogPath;
1477
+ } });
1478
+ var hookAdapter_1 = require_hookAdapter();
1479
+ Object.defineProperty(exports, "DEFAULT_API_BASE_URL", { enumerable: true, get: function() {
1480
+ return hookAdapter_1.DEFAULT_API_BASE_URL;
1481
+ } });
1482
+ Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
1483
+ return hookAdapter_1.deliverHookEvents;
1484
+ } });
1485
+ Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
1486
+ return hookAdapter_1.loadCliAgentConfig;
1487
+ } });
1488
+ var turnState_1 = require_turnState();
1489
+ Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
1490
+ return turnState_1.consumeTurnDurationMs;
1491
+ } });
1492
+ Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
1493
+ return turnState_1.recordTurnStart;
1494
+ } });
998
1495
  var tokenStore_1 = require_tokenStore();
999
1496
  Object.defineProperty(exports, "defaultTokenFilePath", { enumerable: true, get: function() {
1000
1497
  return tokenStore_1.defaultTokenFilePath;
@@ -1005,6 +1502,22 @@ var require_out2 = __commonJS({
1005
1502
  Object.defineProperty(exports, "readTokenFile", { enumerable: true, get: function() {
1006
1503
  return tokenStore_1.readTokenFile;
1007
1504
  } });
1505
+ var stateStore_1 = require_stateStore();
1506
+ Object.defineProperty(exports, "defaultStateFilePath", { enumerable: true, get: function() {
1507
+ return stateStore_1.defaultStateFilePath;
1508
+ } });
1509
+ Object.defineProperty(exports, "readCollectorState", { enumerable: true, get: function() {
1510
+ return stateStore_1.readCollectorState;
1511
+ } });
1512
+ Object.defineProperty(exports, "recordSendOutcome", { enumerable: true, get: function() {
1513
+ return stateStore_1.recordSendOutcome;
1514
+ } });
1515
+ Object.defineProperty(exports, "shouldAnnounceFailure", { enumerable: true, get: function() {
1516
+ return stateStore_1.shouldAnnounceFailure;
1517
+ } });
1518
+ Object.defineProperty(exports, "markFailureNotified", { enumerable: true, get: function() {
1519
+ return stateStore_1.markFailureNotified;
1520
+ } });
1008
1521
  var salt_1 = require_salt();
1009
1522
  Object.defineProperty(exports, "machineSaltFilePath", { enumerable: true, get: function() {
1010
1523
  return salt_1.machineSaltFilePath;
@@ -1050,12 +1563,16 @@ var require_out2 = __commonJS({
1050
1563
  Object.defineProperty(exports, "parseIngestResponse", { enumerable: true, get: function() {
1051
1564
  return http_1.parseIngestResponse;
1052
1565
  } });
1566
+ Object.defineProperty(exports, "isRetryableStatus", { enumerable: true, get: function() {
1567
+ return http_1.isRetryableStatus;
1568
+ } });
1053
1569
  }
1054
1570
  });
1055
1571
 
1056
1572
  // src/cli.ts
1057
1573
  var import_tool_kit6 = __toESM(require_out2(), 1);
1058
1574
  import { randomUUID } from "node:crypto";
1575
+ import * as fs from "node:fs";
1059
1576
 
1060
1577
  // src/ascendaClient.ts
1061
1578
  var import_tool_kit = __toESM(require_out2(), 1);
@@ -1069,10 +1586,15 @@ var AscendaClient = class {
1069
1586
  source: "claude_code",
1070
1587
  eventWriteToken: config.eventWriteToken,
1071
1588
  tokenFilePath: config.tokenFilePath,
1589
+ stateFilePath: config.stateFilePath,
1072
1590
  sessionId: config.sessionId,
1073
1591
  workspaceHash: config.workspaceHash
1074
1592
  });
1075
1593
  }
1594
+ /** The journal entry written by the most recent {@link send}. */
1595
+ get state() {
1596
+ return this.sender.state;
1597
+ }
1076
1598
  async send(mapped) {
1077
1599
  return this.sender.send(mapped);
1078
1600
  }
@@ -1086,9 +1608,27 @@ var import_tool_kit3 = __toESM(require_out2(), 1);
1086
1608
 
1087
1609
  // src/types.ts
1088
1610
  var import_tool_contract = __toESM(require_out(), 1);
1611
+ var CLAUDE_HOOK_EVENT_NAMES = [
1612
+ "SessionStart",
1613
+ "UserPromptSubmit",
1614
+ "PreToolUse",
1615
+ "PostToolUse",
1616
+ "PostToolUseFailure",
1617
+ "PreCompact",
1618
+ "PostCompact",
1619
+ "Stop",
1620
+ "Notification"
1621
+ ];
1622
+ function isClaudeHookEventName(value) {
1623
+ return CLAUDE_HOOK_EVENT_NAMES.includes(value);
1624
+ }
1089
1625
  var ASCENDA_TOOL_TYPE = "claude_code";
1626
+ var CLAUDE_HOST = "claude_code";
1090
1627
 
1091
1628
  // src/config.ts
1629
+ function resolveStateFilePath(toolInstallationId) {
1630
+ return process.env.ASCENDA_STATE_FILE ?? (0, import_tool_kit3.defaultStateFilePath)(toolInstallationId);
1631
+ }
1092
1632
  function loadConfigFromEnv() {
1093
1633
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
1094
1634
  const toolInstallationIdRaw = process.env.ASCENDA_TOOL_INSTALLATION_ID;
@@ -1104,6 +1644,7 @@ function loadConfigFromEnv() {
1104
1644
  toolInstallationId,
1105
1645
  eventWriteToken,
1106
1646
  tokenFilePath,
1647
+ stateFilePath: resolveStateFilePath(toolInstallationId),
1107
1648
  sessionId: process.env.ASCENDA_SESSION_ID ?? null,
1108
1649
  workspaceHash: process.env.ASCENDA_WORKSPACE_HASH ?? null
1109
1650
  };
@@ -1123,6 +1664,12 @@ var import_tool_kit4 = __toESM(require_out2(), 1);
1123
1664
 
1124
1665
  // src/mapClaudeEvent.ts
1125
1666
  function mapClaudeEvent(hookName, input) {
1667
+ return mapEvent(hookName, input).map((event) => ({
1668
+ ...event,
1669
+ metadata: { host: CLAUDE_HOST, ...event.metadata }
1670
+ }));
1671
+ }
1672
+ function mapEvent(hookName, input) {
1126
1673
  switch (hookName) {
1127
1674
  case "SessionStart":
1128
1675
  return mapSessionStart(input);
@@ -1308,7 +1855,7 @@ async function runPair() {
1308
1855
  const toolInstallationId = existing && existing.includes(":") ? existing : `${toolType}:${randomUUID()}`;
1309
1856
  const session = await (0, import_tool_kit6.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
1310
1857
  const code = session.deviceCode ?? session.code;
1311
- process.stdout.write(
1858
+ await writeStdout(
1312
1859
  `
1313
1860
  Pairing code: ${code}
1314
1861
 
@@ -1338,7 +1885,7 @@ Waiting for confirmation (expires ${session.expiresAt})...
1338
1885
  }
1339
1886
  const tokenFilePath = (0, import_tool_kit6.defaultTokenFilePath)(pairedId);
1340
1887
  (0, import_tool_kit6.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
1341
- process.stdout.write(
1888
+ await writeStdout(
1342
1889
  `Paired. Write token saved to ${tokenFilePath}
1343
1890
 
1344
1891
  One step left \u2014 add this to your shell profile (~/.zshrc), then restart Claude Code:
@@ -1353,48 +1900,69 @@ One step left \u2014 add this to your shell profile (~/.zshrc), then restart Cla
1353
1900
  process.exitCode = 1;
1354
1901
  }
1355
1902
  async function main() {
1356
- const hookName = process.argv[2];
1357
- if (!hookName) throw new Error("Usage: ascenda-claude-hook <ClaudeHookEventName> | pair");
1358
- if (hookName === "pair") {
1903
+ const command = process.argv[2];
1904
+ if (!command) throw new Error("Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | doctor");
1905
+ if (command === "pair") {
1359
1906
  await runPair();
1360
1907
  return;
1361
1908
  }
1909
+ if (command === "doctor") {
1910
+ await runDoctor();
1911
+ return;
1912
+ }
1913
+ if (!isClaudeHookEventName(command)) {
1914
+ throw new Error(`Unknown command "${command}". Expected a Claude Code hook name, "pair" or "doctor".`);
1915
+ }
1916
+ const hookName = command;
1362
1917
  const input = await readJsonFromStdin();
1918
+ const contextParts = [];
1363
1919
  if (hookName === "SessionStart" && isNewSessionStart(input) && process.env.ASCENDA_DISABLE_INTENTION_INVITE !== "true") {
1364
- process.stdout.write(JSON.stringify({
1365
- hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: INTENTION_INVITE }
1366
- }));
1920
+ contextParts.push(INTENTION_INVITE);
1367
1921
  }
1368
1922
  if (hookName === "PostToolUse" && milestoneInviting(input) && process.env.ASCENDA_DISABLE_MILESTONE_DEBRIEF !== "true") {
1369
- process.stdout.write(JSON.stringify({
1370
- hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: MILESTONE_DEBRIEF_INVITE }
1923
+ contextParts.push(MILESTONE_DEBRIEF_INVITE);
1924
+ }
1925
+ const pending = pendingFailureNotice(hookName);
1926
+ if (pending) contextParts.push(pending.text);
1927
+ if (contextParts.length > 0) {
1928
+ await writeStdout(JSON.stringify({
1929
+ hookSpecificOutput: { hookEventName: hookName, additionalContext: contextParts.join("\n\n") }
1371
1930
  }));
1931
+ if (pending) (0, import_tool_kit6.markFailureNotified)(pending.stateFilePath, pending.state);
1372
1932
  }
1373
1933
  await emitLive(hookName, input);
1374
- const config = loadConfigFromEnv();
1375
- const client = new AscendaClient(config);
1376
1934
  const mappedEvents = mapClaudeEvent(hookName, input);
1935
+ if (!mappedEvents.length) return;
1936
+ let config;
1937
+ try {
1938
+ config = loadConfigFromEnv();
1939
+ } catch (error) {
1940
+ const logFile = (0, import_tool_kit6.resolveEventLogPath)();
1941
+ if (!logFile) throw error;
1942
+ for (const event of mappedEvents) logUnsent(logFile, event);
1943
+ return;
1944
+ }
1945
+ const client = new AscendaClient(config);
1377
1946
  for (const event of mappedEvents) {
1378
1947
  const result = await client.send(event);
1379
- if (result === "consent_missing") {
1380
- console.error("Ascenda telemetry rejected: renew IDE telemetry consent in the Ascenda app.");
1381
- return;
1382
- }
1383
- if (result === "auth_failed") {
1384
- console.error("Ascenda telemetry rejected: event write token invalid or revoked. Re-pair via the VS Code/Cursor extension.");
1385
- return;
1386
- }
1387
- if (result !== "accepted") {
1388
- console.error(`Ascenda telemetry rejected: ${result}`);
1389
- return;
1390
- }
1948
+ if (result === "accepted") continue;
1949
+ console.error(explainRejection(result));
1950
+ return;
1391
1951
  }
1392
1952
  }
1953
+ function explainRejection(result) {
1954
+ if (result === "consent_missing") return "Ascenda telemetry rejected: renew IDE telemetry consent in the Ascenda app.";
1955
+ if (result === "auth_failed") return "Ascenda telemetry rejected: event write token invalid or revoked. Re-pair with `npx @ascenda-one/claude-code-hooks pair`.";
1956
+ if (result === "transport_error") return "Ascenda telemetry not delivered: the ingest endpoint could not be reached.";
1957
+ return `Ascenda telemetry rejected: ${result}`;
1958
+ }
1393
1959
  async function emitLive(hookName, input) {
1394
1960
  const event = hookName === "UserPromptSubmit" ? "prompt_submitted" : hookName === "PreToolUse" ? "tool_call" : hookName === "PreCompact" ? "compaction" : hookName === "PostToolUseFailure" ? "tool_failure" : hookName === "Stop" ? "stop" : void 0;
1395
1961
  if (!event) return;
1396
1962
  try {
1397
1963
  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;
1964
+ const promptSource = event === "prompt_submitted" ? (0, import_tool_kit6.getString)(input, ["promptSource", "prompt_source"]) : void 0;
1965
+ const queued = promptSource === void 0 ? void 0 : promptSource === "queued";
1398
1966
  await (0, import_tool_kit6.emitLiveSignal)({
1399
1967
  tool: process.env.ASCENDA_TOOL_TYPE ?? "claude_code",
1400
1968
  // Concurrent sessions must count as separate streams for the X gauge.
@@ -1403,11 +1971,114 @@ async function emitLive(hookName, input) {
1403
1971
  // Code spawns hooks from the session process.
1404
1972
  session: (0, import_tool_kit6.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
1405
1973
  event,
1406
- ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit6.bucketPromptSize)(prompt) } : {}
1974
+ ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit6.bucketPromptSize)(prompt) } : {},
1975
+ ...queued !== void 0 ? { queued } : {}
1407
1976
  });
1408
1977
  } catch {
1409
1978
  }
1410
1979
  }
1980
+ function pendingFailureNotice(hookName) {
1981
+ if (hookName !== "SessionStart" && hookName !== "PostToolUse") return void 0;
1982
+ if (process.env.ASCENDA_DISABLE_FAILURE_NOTICE === "true") return void 0;
1983
+ const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
1984
+ if (!rawId) return void 0;
1985
+ const stateFilePath = resolveStateFilePath(normalizeToolInstallationId(rawId));
1986
+ const state = (0, import_tool_kit6.readCollectorState)(stateFilePath);
1987
+ if (!(0, import_tool_kit6.shouldAnnounceFailure)(state) || !state) return void 0;
1988
+ const since = state.lastSuccessAt ? `since ${state.lastSuccessAt}` : "and has never succeeded on this machine";
1989
+ return {
1990
+ 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.`,
1991
+ state,
1992
+ stateFilePath
1993
+ };
1994
+ }
1995
+ function describeOutcome(state) {
1996
+ const status = state.httpStatus ? `, HTTP ${state.httpStatus}` : "";
1997
+ switch (state.lastOutcome) {
1998
+ case "auth_failed":
1999
+ return `the write token was rejected${status}`;
2000
+ case "consent_missing":
2001
+ return `the telemetry consent lease has lapsed${status}`;
2002
+ case "validation_failed":
2003
+ return `the events were refused as invalid${status}`;
2004
+ case "transport_error":
2005
+ return `the ingest endpoint could not be reached${status}`;
2006
+ default:
2007
+ return `last outcome ${state.lastOutcome}${status}`;
2008
+ }
2009
+ }
2010
+ function writeStdout(text) {
2011
+ return new Promise((resolve) => {
2012
+ process.stdout.write(text, () => resolve());
2013
+ });
2014
+ }
2015
+ async function runDoctor() {
2016
+ const lines = ["Ascenda collector doctor", ""];
2017
+ const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2018
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
2019
+ lines.push(` API base URL ${apiBaseUrl}`);
2020
+ lines.push(` Installation id ${rawId || "(unset \u2014 ASCENDA_TOOL_INSTALLATION_ID is empty)"}`);
2021
+ if (!rawId) {
2022
+ lines.push("", " Not paired on this machine. Run:", " npx @ascenda-one/claude-code-hooks pair");
2023
+ await writeStdout(`${lines.join("\n")}
2024
+ `);
2025
+ return;
2026
+ }
2027
+ const toolInstallationId = normalizeToolInstallationId(rawId);
2028
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit6.defaultTokenFilePath)(toolInstallationId);
2029
+ lines.push(` Token file ${tokenFilePath}`);
2030
+ lines.push(` Token ${describeToken(tokenFilePath)}`);
2031
+ const stateFilePath = resolveStateFilePath(toolInstallationId);
2032
+ lines.push(` Journal ${stateFilePath}`);
2033
+ const state = (0, import_tool_kit6.readCollectorState)(stateFilePath);
2034
+ if (!state) {
2035
+ lines.push(" Last outcome (no journal yet \u2014 no send attempted since this version was installed)");
2036
+ } else {
2037
+ lines.push(` Last attempt ${state.lastAttemptAt}`);
2038
+ lines.push(` Last success ${state.lastSuccessAt ?? "never"}`);
2039
+ lines.push(` Last outcome ${state.lastOutcome}${state.httpStatus ? ` (HTTP ${state.httpStatus})` : ""}`);
2040
+ if (state.errorCode) lines.push(` Error code ${state.errorCode}`);
2041
+ if (state.detail) lines.push(` Detail ${state.detail}`);
2042
+ lines.push(` Consecutive failures ${state.consecutiveFailures}`);
2043
+ if (state.failingSince) lines.push(` Failing since ${state.failingSince}`);
2044
+ }
2045
+ lines.push("", " Live round trip...");
2046
+ lines.push(` ${await liveRoundTrip()}`);
2047
+ await writeStdout(`${lines.join("\n")}
2048
+ `);
2049
+ }
2050
+ async function liveRoundTrip() {
2051
+ let config;
2052
+ try {
2053
+ config = loadConfigFromEnv();
2054
+ } catch (error) {
2055
+ return `skipped \u2014 ${error instanceof Error ? error.message : String(error)}`;
2056
+ }
2057
+ const result = await new AscendaClient(config).send({ eventType: "editor_activity", severity: "low", metadata: {} });
2058
+ if (result === "accepted") return "OK \u2014 event accepted by the ingest endpoint.";
2059
+ return `FAILED \u2014 ${explainRejection(result)}`;
2060
+ }
2061
+ function describeToken(tokenFilePath) {
2062
+ try {
2063
+ if (!fs.existsSync(tokenFilePath)) {
2064
+ return process.env.ASCENDA_EVENT_WRITE_TOKEN ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : "MISSING \u2014 run `pair`";
2065
+ }
2066
+ const stat = fs.statSync(tokenFilePath);
2067
+ const ageDays = Math.floor((Date.now() - stat.mtimeMs) / 864e5);
2068
+ return `present, last written ${stat.mtime.toISOString()} (${ageDays}d ago)`;
2069
+ } catch (error) {
2070
+ return `unreadable \u2014 ${error instanceof Error ? error.message : String(error)}`;
2071
+ }
2072
+ }
2073
+ function logUnsent(logFile, event) {
2074
+ const payload = (0, import_tool_kit6.buildEventPayload)({
2075
+ toolInstallationId: `${ASCENDA_TOOL_TYPE}:unpaired`,
2076
+ source: "claude_code",
2077
+ sessionId: process.env.ASCENDA_SESSION_ID ?? null,
2078
+ workspaceHash: process.env.ASCENDA_WORKSPACE_HASH ?? null
2079
+ }, event);
2080
+ (0, import_tool_kit6.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery: "not_sent", payload });
2081
+ }
1411
2082
  async function readJsonFromStdin() {
1412
2083
  const chunks = [];
1413
2084
  for await (const chunk of process.stdin) {
@@ -1421,4 +2092,4 @@ async function readJsonFromStdin() {
1421
2092
  }
1422
2093
  main().catch((error) => {
1423
2094
  console.error(error instanceof Error ? error.message : String(error));
1424
- }).finally(() => process.exit(0));
2095
+ }).finally(() => process.exit(process.exitCode ?? 0));