@ascenda-one/claude-code-hooks 0.1.14 → 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/README.md +56 -8
- package/dist/cli.js +781 -222
- package/dist/cli.js.map +1 -1
- package/dist/config.js +13 -4
- package/dist/config.js.map +1 -1
- package/dist/paths.js +36 -0
- package/dist/paths.js.map +1 -0
- package/dist/setup.js +375 -0
- package/dist/setup.js.map +1 -0
- package/package.json +1 -1
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,
|
|
333
|
+
function getNested2(input, path3) {
|
|
327
334
|
let current = input;
|
|
328
|
-
for (const segment of
|
|
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
|
|
337
|
-
const value = getNested2(input,
|
|
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
|
|
345
|
-
const value = getNested2(input,
|
|
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
|
|
494
|
-
var
|
|
495
|
-
var
|
|
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
|
|
660
|
+
return os2.homedir();
|
|
504
661
|
if (value.startsWith("~/"))
|
|
505
|
-
return
|
|
506
|
-
return
|
|
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 =
|
|
515
|
-
|
|
516
|
-
|
|
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
|
-
|
|
676
|
+
fs4.chmodSync(logFilePath, 384);
|
|
520
677
|
} catch {
|
|
521
678
|
}
|
|
522
679
|
}
|
|
523
680
|
function rotateIfLarge(logFilePath) {
|
|
524
681
|
try {
|
|
525
|
-
if (
|
|
682
|
+
if (fs4.statSync(logFilePath).size < MAX_BYTES)
|
|
526
683
|
return;
|
|
527
|
-
|
|
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 =
|
|
541
|
-
exports.getPairingStatus =
|
|
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
|
|
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
|
|
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.
|
|
679
|
-
exports.
|
|
680
|
-
exports.
|
|
835
|
+
exports.ascendaHome = ascendaHome3;
|
|
836
|
+
exports.defaultTokenFilePath = defaultTokenFilePath4;
|
|
837
|
+
exports.persistEventWriteToken = persistEventWriteToken4;
|
|
838
|
+
exports.readTokenFile = readTokenFile3;
|
|
681
839
|
exports.sanitizeFilePart = sanitizeFilePart;
|
|
682
|
-
var
|
|
683
|
-
var
|
|
684
|
-
var
|
|
685
|
-
function
|
|
686
|
-
return
|
|
687
|
-
}
|
|
688
|
-
function
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
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
|
-
|
|
694
|
-
|
|
854
|
+
fs4.chmodSync(dir, 448);
|
|
855
|
+
fs4.chmodSync(tokenFilePath, 384);
|
|
695
856
|
}
|
|
696
857
|
}
|
|
697
|
-
function
|
|
858
|
+
function readTokenFile3(tokenFilePath) {
|
|
698
859
|
try {
|
|
699
|
-
if (!
|
|
860
|
+
if (!fs4.existsSync(tokenFilePath))
|
|
700
861
|
return void 0;
|
|
701
|
-
const value =
|
|
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
|
|
761
|
-
var
|
|
762
|
-
var
|
|
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 :
|
|
767
|
-
return
|
|
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 (!
|
|
932
|
+
if (!fs4.existsSync(stateFilePath))
|
|
772
933
|
return void 0;
|
|
773
|
-
const raw =
|
|
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 =
|
|
820
|
-
|
|
821
|
-
|
|
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
|
-
|
|
984
|
+
fs4.renameSync(temporaryPath, stateFilePath);
|
|
824
985
|
if (process.platform !== "win32")
|
|
825
|
-
|
|
986
|
+
fs4.chmodSync(stateFilePath, 384);
|
|
826
987
|
} catch {
|
|
827
988
|
try {
|
|
828
|
-
if (
|
|
829
|
-
|
|
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((
|
|
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
|
|
1093
|
-
var
|
|
1094
|
-
var
|
|
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
|
|
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(
|
|
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 =
|
|
1178
|
-
|
|
1338
|
+
const dir = path3.dirname(registryFilePath);
|
|
1339
|
+
fs4.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1179
1340
|
const tmp = `${registryFilePath}.${process.pid}.tmp`;
|
|
1180
|
-
|
|
1341
|
+
fs4.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
|
|
1181
1342
|
`, { encoding: "utf8", mode: 384 });
|
|
1182
|
-
|
|
1343
|
+
fs4.renameSync(tmp, registryFilePath);
|
|
1183
1344
|
if (process.platform !== "win32") {
|
|
1184
|
-
|
|
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
|
|
1236
|
-
var
|
|
1237
|
-
var
|
|
1238
|
-
var
|
|
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
|
|
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 =
|
|
1248
|
-
|
|
1408
|
+
const dir = path3.dirname(saltFilePath);
|
|
1409
|
+
fs4.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1249
1410
|
let salt;
|
|
1250
1411
|
try {
|
|
1251
|
-
salt =
|
|
1252
|
-
|
|
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 =
|
|
1417
|
+
salt = fs4.readFileSync(saltFilePath, "utf8").trim();
|
|
1257
1418
|
}
|
|
1258
1419
|
if (process.platform !== "win32") {
|
|
1259
|
-
|
|
1260
|
-
|
|
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
|
|
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
|
|
1317
|
-
var
|
|
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 (!
|
|
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 =
|
|
1511
|
+
const dotGit = path3.join(dir, ".git");
|
|
1351
1512
|
let stat = null;
|
|
1352
1513
|
try {
|
|
1353
|
-
stat =
|
|
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 =
|
|
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(
|
|
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 =
|
|
1379
|
-
const marker = `${
|
|
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
|
|
1558
|
-
var
|
|
1559
|
-
var
|
|
1560
|
-
var stateDir = () => process.env.ASCENDA_STATE_DIR ??
|
|
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
|
|
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
|
-
|
|
1572
|
-
|
|
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(
|
|
1582
|
-
|
|
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,10 +1797,10 @@ var require_liveBus = __commonJS({
|
|
|
1636
1797
|
exports.liveBusSocketPath = liveBusSocketPath;
|
|
1637
1798
|
exports.bucketPromptSize = bucketPromptSize2;
|
|
1638
1799
|
exports.emitLiveSignal = emitLiveSignal2;
|
|
1639
|
-
var
|
|
1800
|
+
var fs4 = __importStar(__require("fs"));
|
|
1640
1801
|
var net = __importStar(__require("net"));
|
|
1641
|
-
var
|
|
1642
|
-
var
|
|
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";
|
|
1645
1806
|
var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
|
|
@@ -1647,18 +1808,18 @@ var require_liveBus = __commonJS({
|
|
|
1647
1808
|
const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
|
|
1648
1809
|
if (override)
|
|
1649
1810
|
return [override];
|
|
1650
|
-
const home =
|
|
1811
|
+
const home = os2.homedir();
|
|
1651
1812
|
return [
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
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")
|
|
1655
1816
|
];
|
|
1656
1817
|
}
|
|
1657
1818
|
function liveBusSocketPath() {
|
|
1658
1819
|
const candidates = liveBusSocketCandidates();
|
|
1659
1820
|
for (const candidate of candidates) {
|
|
1660
1821
|
try {
|
|
1661
|
-
if (
|
|
1822
|
+
if (fs4.statSync(candidate).isSocket())
|
|
1662
1823
|
return candidate;
|
|
1663
1824
|
} catch {
|
|
1664
1825
|
}
|
|
@@ -1676,7 +1837,7 @@ var require_liveBus = __commonJS({
|
|
|
1676
1837
|
return "xl";
|
|
1677
1838
|
}
|
|
1678
1839
|
function emitLiveSignal2(signal) {
|
|
1679
|
-
return new Promise((
|
|
1840
|
+
return new Promise((resolve2) => {
|
|
1680
1841
|
let settled = false;
|
|
1681
1842
|
const done = () => {
|
|
1682
1843
|
if (settled)
|
|
@@ -1686,13 +1847,13 @@ var require_liveBus = __commonJS({
|
|
|
1686
1847
|
socket.destroy();
|
|
1687
1848
|
} catch {
|
|
1688
1849
|
}
|
|
1689
|
-
|
|
1850
|
+
resolve2();
|
|
1690
1851
|
};
|
|
1691
1852
|
let socket;
|
|
1692
1853
|
try {
|
|
1693
1854
|
socket = net.createConnection(liveBusSocketPath());
|
|
1694
1855
|
} catch {
|
|
1695
|
-
|
|
1856
|
+
resolve2();
|
|
1696
1857
|
return;
|
|
1697
1858
|
}
|
|
1698
1859
|
const timer = setTimeout(done, WRITE_TIMEOUT_MS);
|
|
@@ -1723,8 +1884,8 @@ var require_out2 = __commonJS({
|
|
|
1723
1884
|
"../packages/tool-kit/out/index.js"(exports) {
|
|
1724
1885
|
"use strict";
|
|
1725
1886
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1726
|
-
exports.
|
|
1727
|
-
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;
|
|
1728
1889
|
var commandClassifier_1 = require_commandClassifier();
|
|
1729
1890
|
Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
|
|
1730
1891
|
return commandClassifier_1.classifyCommand;
|
|
@@ -1838,6 +1999,9 @@ var require_out2 = __commonJS({
|
|
|
1838
1999
|
return turnState_1.recordTurnStart;
|
|
1839
2000
|
} });
|
|
1840
2001
|
var tokenStore_1 = require_tokenStore();
|
|
2002
|
+
Object.defineProperty(exports, "ascendaHome", { enumerable: true, get: function() {
|
|
2003
|
+
return tokenStore_1.ascendaHome;
|
|
2004
|
+
} });
|
|
1841
2005
|
Object.defineProperty(exports, "defaultTokenFilePath", { enumerable: true, get: function() {
|
|
1842
2006
|
return tokenStore_1.defaultTokenFilePath;
|
|
1843
2007
|
} });
|
|
@@ -1931,77 +2095,86 @@ var require_out2 = __commonJS({
|
|
|
1931
2095
|
}
|
|
1932
2096
|
});
|
|
1933
2097
|
|
|
1934
|
-
// src/
|
|
1935
|
-
|
|
1936
|
-
import
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
sessionId: config.sessionId,
|
|
1953
|
-
workspaceHash: config.workspaceHash,
|
|
1954
|
-
projectHash: config.projectHash
|
|
1955
|
-
});
|
|
1956
|
-
}
|
|
1957
|
-
/** The journal entry written by the most recent {@link send}. */
|
|
1958
|
-
get state() {
|
|
1959
|
-
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;
|
|
1960
2116
|
}
|
|
1961
|
-
|
|
1962
|
-
|
|
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);
|
|
1963
2126
|
}
|
|
1964
|
-
|
|
1965
|
-
|
|
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);
|
|
1966
2133
|
}
|
|
1967
|
-
};
|
|
1968
|
-
|
|
1969
|
-
// src/config.ts
|
|
1970
|
-
var import_tool_kit3 = __toESM(require_out2(), 1);
|
|
2134
|
+
});
|
|
1971
2135
|
|
|
1972
2136
|
// src/types.ts
|
|
1973
|
-
var import_tool_contract = __toESM(require_out(), 1);
|
|
1974
|
-
var CLAUDE_HOOK_EVENT_NAMES = [
|
|
1975
|
-
"SessionStart",
|
|
1976
|
-
"UserPromptSubmit",
|
|
1977
|
-
"PreToolUse",
|
|
1978
|
-
"PostToolUse",
|
|
1979
|
-
"PostToolUseFailure",
|
|
1980
|
-
"PreCompact",
|
|
1981
|
-
"PostCompact",
|
|
1982
|
-
"Stop",
|
|
1983
|
-
"Notification"
|
|
1984
|
-
];
|
|
1985
2137
|
function isClaudeHookEventName(value) {
|
|
1986
2138
|
return CLAUDE_HOOK_EVENT_NAMES.includes(value);
|
|
1987
2139
|
}
|
|
1988
|
-
var ASCENDA_TOOL_TYPE
|
|
1989
|
-
var
|
|
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
|
+
});
|
|
1990
2160
|
|
|
1991
2161
|
// src/config.ts
|
|
1992
2162
|
function resolveStateFilePath(toolInstallationId) {
|
|
1993
|
-
return process.env.ASCENDA_STATE_FILE ?? (0,
|
|
2163
|
+
return process.env.ASCENDA_STATE_FILE ?? (0, import_tool_kit4.defaultStateFilePath)(toolInstallationId);
|
|
1994
2164
|
}
|
|
1995
2165
|
function loadConfigFromEnv() {
|
|
1996
|
-
const
|
|
1997
|
-
const
|
|
1998
|
-
|
|
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
|
+
}
|
|
1999
2172
|
const toolInstallationId = normalizeToolInstallationId(toolInstallationIdRaw);
|
|
2000
|
-
const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0,
|
|
2001
|
-
const fileToken = (0,
|
|
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);
|
|
2002
2175
|
const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
|
|
2003
2176
|
if (!eventWriteToken) throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
|
|
2004
|
-
if (!fileToken) (0,
|
|
2177
|
+
if (!fileToken) (0, import_tool_kit4.persistEventWriteToken)(tokenFilePath, eventWriteToken);
|
|
2005
2178
|
return {
|
|
2006
2179
|
apiBaseUrl,
|
|
2007
2180
|
toolInstallationId,
|
|
@@ -2026,12 +2199,384 @@ function normalizeToolInstallationId(value) {
|
|
|
2026
2199
|
if (trimmed.startsWith("claude_tool_")) return `${ASCENDA_TOOL_TYPE}:${trimmed.slice("claude_tool_".length)}`;
|
|
2027
2200
|
return `${ASCENDA_TOOL_TYPE}:${trimmed}`;
|
|
2028
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();
|
|
2029
2573
|
|
|
2030
2574
|
// src/mapClaudeEvent.ts
|
|
2031
|
-
var
|
|
2575
|
+
var import_tool_kit6 = __toESM(require_out2(), 1);
|
|
2576
|
+
init_types();
|
|
2032
2577
|
|
|
2033
2578
|
// src/safeExtract.ts
|
|
2034
|
-
var
|
|
2579
|
+
var import_tool_kit5 = __toESM(require_out2(), 1);
|
|
2035
2580
|
|
|
2036
2581
|
// src/mapClaudeEvent.ts
|
|
2037
2582
|
function mapClaudeEvent(hookName, input) {
|
|
@@ -2069,22 +2614,22 @@ function mapEvent(hookName, input) {
|
|
|
2069
2614
|
}
|
|
2070
2615
|
}
|
|
2071
2616
|
function isNewSessionStart(input) {
|
|
2072
|
-
const source = (0,
|
|
2617
|
+
const source = (0, import_tool_kit5.getString)(input, ["source"]);
|
|
2073
2618
|
return !source || source === "startup" || source === "resume";
|
|
2074
2619
|
}
|
|
2075
2620
|
function milestoneInviting(input) {
|
|
2076
|
-
if ((0,
|
|
2077
|
-
const command = (0,
|
|
2078
|
-
return (0,
|
|
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));
|
|
2079
2624
|
}
|
|
2080
2625
|
function mapSessionStart(input) {
|
|
2081
2626
|
if (!isNewSessionStart(input)) return [];
|
|
2082
2627
|
return [{ eventType: "create_focus_session", severity: "low", metadata: { activity: "session_started" } }];
|
|
2083
2628
|
}
|
|
2084
2629
|
function mapUserPromptSubmit(input) {
|
|
2085
|
-
const prompt = (0,
|
|
2630
|
+
const prompt = (0, import_tool_kit5.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit5.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
|
|
2086
2631
|
const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown" } }];
|
|
2087
|
-
if ((0,
|
|
2632
|
+
if ((0, import_tool_kit5.looksLikeCorrection)(prompt)) {
|
|
2088
2633
|
events.push({ eventType: "ai_correction_prompt", severity: "medium", metadata: { reason: "repeated_reprompting", trigger: "inferred" } });
|
|
2089
2634
|
}
|
|
2090
2635
|
return events;
|
|
@@ -2095,20 +2640,20 @@ function mapPreToolUse(input) {
|
|
|
2095
2640
|
function mapPostToolUse(hookName, input) {
|
|
2096
2641
|
const toolName = getToolName(input);
|
|
2097
2642
|
const safeToolName = sanitiseToolName(toolName);
|
|
2098
|
-
const outcome = (0,
|
|
2099
|
-
const durationMs = (0,
|
|
2100
|
-
const command = (0,
|
|
2101
|
-
const commandClass = (0,
|
|
2102
|
-
const gitAction = outcome === "success" ? (0,
|
|
2103
|
-
const milestoneKind = outcome === "success" ? (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;
|
|
2104
2649
|
if (outcome === "cancelled") {
|
|
2105
|
-
return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0,
|
|
2650
|
+
return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "manual_interrupt" } }];
|
|
2106
2651
|
}
|
|
2107
2652
|
if (outcome === "failure") {
|
|
2108
|
-
if (toolName?.toLowerCase() === "bash" && (0,
|
|
2109
|
-
return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0,
|
|
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" } }];
|
|
2110
2655
|
}
|
|
2111
|
-
return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0,
|
|
2656
|
+
return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "tool_failure" } }];
|
|
2112
2657
|
}
|
|
2113
2658
|
if (isWriteTool(toolName)) {
|
|
2114
2659
|
const linesChanged = computeLinesChanged(toolName, input);
|
|
@@ -2118,18 +2663,18 @@ function mapPostToolUse(hookName, input) {
|
|
|
2118
2663
|
metadata: {
|
|
2119
2664
|
toolName: safeToolName,
|
|
2120
2665
|
outcome,
|
|
2121
|
-
durationBucket: (0,
|
|
2666
|
+
durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs),
|
|
2122
2667
|
// The boundary C2/the macOS work-self-report card triggers on: at
|
|
2123
2668
|
// "200+" this is the "substantial accepted change" moment. No
|
|
2124
2669
|
// second event type exists for this — the bucket on the existing
|
|
2125
2670
|
// creation event *is* the boundary, deliberately, since the write
|
|
2126
2671
|
// already happened; there is nothing else to mark.
|
|
2127
|
-
...linesChanged !== void 0 ? { linesChangedBucket: (0,
|
|
2672
|
+
...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit5.bucketLinesChanged)(linesChanged) } : {}
|
|
2128
2673
|
}
|
|
2129
2674
|
}];
|
|
2130
2675
|
}
|
|
2131
|
-
if (toolName?.toLowerCase() === "bash" && (0,
|
|
2132
|
-
return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0,
|
|
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" } }];
|
|
2133
2678
|
}
|
|
2134
2679
|
return [{
|
|
2135
2680
|
eventType: "ai_tool_call_completed",
|
|
@@ -2138,13 +2683,13 @@ function mapPostToolUse(hookName, input) {
|
|
|
2138
2683
|
toolName: safeToolName,
|
|
2139
2684
|
commandClass,
|
|
2140
2685
|
outcome,
|
|
2141
|
-
durationBucket: (0,
|
|
2686
|
+
durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs),
|
|
2142
2687
|
// The boundary and rework signal both ride this existing event rather
|
|
2143
2688
|
// than minting a type: the backend already reads `gitAction` off any
|
|
2144
2689
|
// event, and a commit is not a different *kind* of thing happening, it
|
|
2145
2690
|
// is a fact about the tool call that just happened.
|
|
2146
2691
|
...gitAction !== void 0 ? { gitAction } : {},
|
|
2147
|
-
...(0,
|
|
2692
|
+
...(0, import_tool_kit6.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
|
|
2148
2693
|
// Same reasoning as `gitAction` above, one grain coarser: a milestone is
|
|
2149
2694
|
// a fact about the tool call that just happened, not a different kind of
|
|
2150
2695
|
// event. It rides here so the record carries the work's own rhythm —
|
|
@@ -2154,23 +2699,23 @@ function mapPostToolUse(hookName, input) {
|
|
|
2154
2699
|
}];
|
|
2155
2700
|
}
|
|
2156
2701
|
function mapPreCompact(input) {
|
|
2157
|
-
const trigger = (0,
|
|
2702
|
+
const trigger = (0, import_tool_kit5.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit5.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
|
|
2158
2703
|
const isManual = trigger?.toLowerCase().includes("manual") ?? false;
|
|
2159
2704
|
return [{ eventType: isManual ? "context_compression_manual" : "context_compression_auto", severity: isManual ? "medium" : "high", metadata: { trigger: isManual ? "manual" : "auto", reason: "context_limit" } }];
|
|
2160
2705
|
}
|
|
2161
2706
|
function mapStop(input) {
|
|
2162
|
-
const durationMs = (0,
|
|
2163
|
-
const durationBucket = (0,
|
|
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);
|
|
2164
2709
|
if (durationBucket === "30-60m" || durationBucket === "60m+") {
|
|
2165
2710
|
return [{ eventType: "agent_loop_long", severity: durationBucket === "60m+" ? "high" : "medium", metadata: { durationBucket, reason: "long_session", trigger: "inferred" } }];
|
|
2166
2711
|
}
|
|
2167
2712
|
return [];
|
|
2168
2713
|
}
|
|
2169
2714
|
function getToolName(input) {
|
|
2170
|
-
return (0,
|
|
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"]]);
|
|
2171
2716
|
}
|
|
2172
2717
|
function computeLinesChanged(toolName, input) {
|
|
2173
|
-
const toolInput = (0,
|
|
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"]);
|
|
2174
2719
|
if (!toolInput || typeof toolInput !== "object") return void 0;
|
|
2175
2720
|
const record = toolInput;
|
|
2176
2721
|
switch (toolName?.toLowerCase()) {
|
|
@@ -2216,6 +2761,7 @@ function sanitiseToolName(toolName) {
|
|
|
2216
2761
|
}
|
|
2217
2762
|
|
|
2218
2763
|
// src/cli.ts
|
|
2764
|
+
init_types();
|
|
2219
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.";
|
|
2220
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.";
|
|
2221
2767
|
async function runPair() {
|
|
@@ -2223,8 +2769,8 @@ async function runPair() {
|
|
|
2223
2769
|
const flagIndex = process.argv.indexOf("--tool-type");
|
|
2224
2770
|
const toolType = flagIndex !== -1 ? (process.argv[flagIndex + 1] ?? "").trim() || ASCENDA_TOOL_TYPE : ASCENDA_TOOL_TYPE;
|
|
2225
2771
|
const existing = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
|
|
2226
|
-
const toolInstallationId = existing && existing.includes(":") ? existing : `${toolType}:${
|
|
2227
|
-
const session = await (0,
|
|
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);
|
|
2228
2774
|
const code = session.deviceCode ?? session.code;
|
|
2229
2775
|
await writeStdout(
|
|
2230
2776
|
`
|
|
@@ -2237,8 +2783,8 @@ Waiting for confirmation (expires ${session.expiresAt})...
|
|
|
2237
2783
|
);
|
|
2238
2784
|
const deadline = Date.now() + 11 * 60 * 1e3;
|
|
2239
2785
|
while (Date.now() < deadline) {
|
|
2240
|
-
await new Promise((
|
|
2241
|
-
const status = await (0,
|
|
2786
|
+
await new Promise((resolve2) => setTimeout(resolve2, 3e3));
|
|
2787
|
+
const status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
|
|
2242
2788
|
if (status.status === "pending") continue;
|
|
2243
2789
|
if (status.status !== "paired") {
|
|
2244
2790
|
process.stderr.write(`Pairing ${status.status}. Run the command again for a fresh code.
|
|
@@ -2254,8 +2800,8 @@ Waiting for confirmation (expires ${session.expiresAt})...
|
|
|
2254
2800
|
process.exitCode = 1;
|
|
2255
2801
|
return;
|
|
2256
2802
|
}
|
|
2257
|
-
const tokenFilePath = (0,
|
|
2258
|
-
(0,
|
|
2803
|
+
const tokenFilePath = (0, import_tool_kit8.defaultTokenFilePath)(pairedId);
|
|
2804
|
+
(0, import_tool_kit8.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
|
|
2259
2805
|
await writeStdout(
|
|
2260
2806
|
`Paired. Write token saved to ${tokenFilePath}
|
|
2261
2807
|
|
|
@@ -2270,9 +2816,14 @@ One step left \u2014 add this to your shell profile (~/.zshrc), then restart Cla
|
|
|
2270
2816
|
process.stderr.write("Timed out waiting for confirmation. Run the command again for a fresh code.\n");
|
|
2271
2817
|
process.exitCode = 1;
|
|
2272
2818
|
}
|
|
2819
|
+
var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
|
|
2273
2820
|
async function main() {
|
|
2274
2821
|
const command = process.argv[2];
|
|
2275
|
-
if (!command)
|
|
2822
|
+
if (!command) {
|
|
2823
|
+
throw new Error(
|
|
2824
|
+
"Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | doctor | setup | status | uninstall"
|
|
2825
|
+
);
|
|
2826
|
+
}
|
|
2276
2827
|
if (command === "pair") {
|
|
2277
2828
|
await runPair();
|
|
2278
2829
|
return;
|
|
@@ -2281,8 +2832,15 @@ async function main() {
|
|
|
2281
2832
|
await runDoctor();
|
|
2282
2833
|
return;
|
|
2283
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
|
+
}
|
|
2284
2840
|
if (!isClaudeHookEventName(command)) {
|
|
2285
|
-
throw new Error(
|
|
2841
|
+
throw new Error(
|
|
2842
|
+
`Unknown command "${command}". Expected a Claude Code hook name, "pair", "doctor", "setup", "status" or "uninstall".`
|
|
2843
|
+
);
|
|
2286
2844
|
}
|
|
2287
2845
|
const hookName = command;
|
|
2288
2846
|
const input = await readJsonFromStdin();
|
|
@@ -2299,18 +2857,18 @@ async function main() {
|
|
|
2299
2857
|
await writeStdout(JSON.stringify({
|
|
2300
2858
|
hookSpecificOutput: { hookEventName: hookName, additionalContext: contextParts.join("\n\n") }
|
|
2301
2859
|
}));
|
|
2302
|
-
if (pending) (0,
|
|
2860
|
+
if (pending) (0, import_tool_kit8.markFailureNotified)(pending.stateFilePath, pending.state);
|
|
2303
2861
|
}
|
|
2304
2862
|
await emitLive(hookName, input);
|
|
2305
2863
|
const mappedEvents = mapClaudeEvent(hookName, input);
|
|
2306
2864
|
if (!mappedEvents.length) return;
|
|
2307
|
-
const workContext = (0,
|
|
2308
|
-
if (workContext) (0,
|
|
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);
|
|
2309
2867
|
let config;
|
|
2310
2868
|
try {
|
|
2311
2869
|
config = loadConfigFromEnv();
|
|
2312
2870
|
} catch (error) {
|
|
2313
|
-
const logFile = (0,
|
|
2871
|
+
const logFile = (0, import_tool_kit8.resolveEventLogPath)();
|
|
2314
2872
|
if (!logFile) throw error;
|
|
2315
2873
|
for (const event of mappedEvents) logUnsent(logFile, event, workContext);
|
|
2316
2874
|
return;
|
|
@@ -2335,18 +2893,18 @@ async function emitLive(hookName, input) {
|
|
|
2335
2893
|
const event = hookName === "UserPromptSubmit" ? "prompt_submitted" : hookName === "PreToolUse" ? "tool_call" : hookName === "PreCompact" ? "compaction" : hookName === "PostToolUseFailure" ? "tool_failure" : hookName === "Stop" ? "stop" : void 0;
|
|
2336
2894
|
if (!event) return;
|
|
2337
2895
|
try {
|
|
2338
|
-
const prompt = event === "prompt_submitted" ? (0,
|
|
2339
|
-
const promptSource = event === "prompt_submitted" ? (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;
|
|
2340
2898
|
const queued = promptSource === void 0 ? void 0 : promptSource === "queued";
|
|
2341
|
-
await (0,
|
|
2899
|
+
await (0, import_tool_kit8.emitLiveSignal)({
|
|
2342
2900
|
tool: process.env.ASCENDA_TOOL_TYPE ?? "claude_code",
|
|
2343
2901
|
// Concurrent sessions must count as separate streams for the X gauge.
|
|
2344
2902
|
// Without a session id every window collapses into one, so fall back to
|
|
2345
2903
|
// this process's parent — still per-session in practice, since Claude
|
|
2346
2904
|
// Code spawns hooks from the session process.
|
|
2347
|
-
session: (0,
|
|
2905
|
+
session: (0, import_tool_kit8.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
|
|
2348
2906
|
event,
|
|
2349
|
-
...prompt !== void 0 ? { sizeBucket: (0,
|
|
2907
|
+
...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit8.bucketPromptSize)(prompt) } : {},
|
|
2350
2908
|
...queued !== void 0 ? { queued } : {}
|
|
2351
2909
|
});
|
|
2352
2910
|
} catch {
|
|
@@ -2358,8 +2916,8 @@ function pendingFailureNotice(hookName) {
|
|
|
2358
2916
|
const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
|
|
2359
2917
|
if (!rawId) return void 0;
|
|
2360
2918
|
const stateFilePath = resolveStateFilePath(normalizeToolInstallationId(rawId));
|
|
2361
|
-
const state = (0,
|
|
2362
|
-
if (!(0,
|
|
2919
|
+
const state = (0, import_tool_kit8.readCollectorState)(stateFilePath);
|
|
2920
|
+
if (!(0, import_tool_kit8.shouldAnnounceFailure)(state) || !state) return void 0;
|
|
2363
2921
|
const since = state.lastSuccessAt ? `since ${state.lastSuccessAt}` : "and has never succeeded on this machine";
|
|
2364
2922
|
return {
|
|
2365
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.`,
|
|
@@ -2383,8 +2941,8 @@ function describeOutcome(state) {
|
|
|
2383
2941
|
}
|
|
2384
2942
|
}
|
|
2385
2943
|
function writeStdout(text) {
|
|
2386
|
-
return new Promise((
|
|
2387
|
-
process.stdout.write(text, () =>
|
|
2944
|
+
return new Promise((resolve2) => {
|
|
2945
|
+
process.stdout.write(text, () => resolve2());
|
|
2388
2946
|
});
|
|
2389
2947
|
}
|
|
2390
2948
|
async function runDoctor() {
|
|
@@ -2400,12 +2958,12 @@ async function runDoctor() {
|
|
|
2400
2958
|
return;
|
|
2401
2959
|
}
|
|
2402
2960
|
const toolInstallationId = normalizeToolInstallationId(rawId);
|
|
2403
|
-
const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0,
|
|
2961
|
+
const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId);
|
|
2404
2962
|
lines.push(` Token file ${tokenFilePath}`);
|
|
2405
2963
|
lines.push(` Token ${describeToken(tokenFilePath)}`);
|
|
2406
2964
|
const stateFilePath = resolveStateFilePath(toolInstallationId);
|
|
2407
2965
|
lines.push(` Journal ${stateFilePath}`);
|
|
2408
|
-
const state = (0,
|
|
2966
|
+
const state = (0, import_tool_kit8.readCollectorState)(stateFilePath);
|
|
2409
2967
|
if (!state) {
|
|
2410
2968
|
lines.push(" Last outcome (no journal yet \u2014 no send attempted since this version was installed)");
|
|
2411
2969
|
} else {
|
|
@@ -2435,10 +2993,10 @@ async function liveRoundTrip() {
|
|
|
2435
2993
|
}
|
|
2436
2994
|
function describeToken(tokenFilePath) {
|
|
2437
2995
|
try {
|
|
2438
|
-
if (!
|
|
2996
|
+
if (!fs3.existsSync(tokenFilePath)) {
|
|
2439
2997
|
return process.env.ASCENDA_EVENT_WRITE_TOKEN ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : "MISSING \u2014 run `pair`";
|
|
2440
2998
|
}
|
|
2441
|
-
const stat =
|
|
2999
|
+
const stat = fs3.statSync(tokenFilePath);
|
|
2442
3000
|
const ageDays = Math.floor((Date.now() - stat.mtimeMs) / 864e5);
|
|
2443
3001
|
return `present, last written ${stat.mtime.toISOString()} (${ageDays}d ago)`;
|
|
2444
3002
|
} catch (error) {
|
|
@@ -2446,14 +3004,14 @@ function describeToken(tokenFilePath) {
|
|
|
2446
3004
|
}
|
|
2447
3005
|
}
|
|
2448
3006
|
function logUnsent(logFile, event, workContext) {
|
|
2449
|
-
const payload = (0,
|
|
3007
|
+
const payload = (0, import_tool_kit8.buildEventPayload)({
|
|
2450
3008
|
toolInstallationId: `${ASCENDA_TOOL_TYPE}:unpaired`,
|
|
2451
3009
|
source: "claude_code",
|
|
2452
3010
|
sessionId: process.env.ASCENDA_SESSION_ID ?? null,
|
|
2453
3011
|
workspaceHash: envHashOverride("ASCENDA_WORKSPACE_HASH") ?? workContext?.workspaceHash ?? null,
|
|
2454
3012
|
projectHash: envHashOverride("ASCENDA_PROJECT_HASH") ?? workContext?.projectHash ?? null
|
|
2455
3013
|
}, event);
|
|
2456
|
-
(0,
|
|
3014
|
+
(0, import_tool_kit8.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery: "not_sent", payload });
|
|
2457
3015
|
}
|
|
2458
3016
|
async function readJsonFromStdin() {
|
|
2459
3017
|
const chunks = [];
|
|
@@ -2466,6 +3024,7 @@ async function readJsonFromStdin() {
|
|
|
2466
3024
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
|
2467
3025
|
return parsed;
|
|
2468
3026
|
}
|
|
3027
|
+
var setupExitCode;
|
|
2469
3028
|
main().catch((error) => {
|
|
2470
3029
|
console.error(error instanceof Error ? error.message : String(error));
|
|
2471
|
-
}).finally(() => process.exit(process.exitCode ?? 0));
|
|
3030
|
+
}).finally(() => process.exit(setupExitCode ?? process.exitCode ?? 0));
|