@ascenda-one/codex-hooks 0.1.18 → 0.1.20

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 CHANGED
@@ -27,48 +27,74 @@ Codex **awaits** command hooks and treats **exit code 2 as blocking** the user's
27
27
 
28
28
  - [Codex CLI](https://developers.openai.com/codex) with hooks support (v0.117+)
29
29
  - Node.js **20+**
30
- - A pairing to reuse (see [Pair first](#pair-first) below)
31
30
 
32
- ### 1. Run the published CLI
31
+ ### 1. Set up
33
32
 
34
- No clone, no build — the package is on npm:
33
+ One command pairs Codex, installs the hook binary, and registers the hooks:
35
34
 
36
35
  ```bash
37
- npx @ascenda-one/codex-hooks --help
36
+ npx -y @ascenda-one/codex-hooks setup --scope user
38
37
  ```
39
38
 
40
- ### 2. Pair first
39
+ It prints a 6-digit code — confirm it in the Ascenda app under
40
+ **Connections → Ingest telemetry** — then writes:
41
+
42
+ - the write token to `~/.ascenda/tokens/`
43
+ - the pairing to `tools.codex` in `~/.ascenda/credentials.json`
44
+ - the hook entries to `~/.codex/hooks.json`
45
+
46
+ **There is no shell profile line to add.** Codex reads its identity from the
47
+ credentials file, which is per agent — so pairing Codex cannot disturb a
48
+ Claude Code or Cursor pairing on the same machine, and a Codex hook launched
49
+ from the Dock with an empty environment still names itself correctly.
50
+
51
+ `--scope user` registers machine-wide. Omit it and hooks land in
52
+ `<cwd>/.codex/hooks.json`, instrumenting that project only — which is the
53
+ default, so pass the flag unless you mean one repo.
54
+
55
+ ### 2. Check it
41
56
 
42
57
  ```bash
43
- npx -y @ascenda-one/claude-code-hooks pair --tool-type cli_agent
58
+ npx @ascenda-one/codex-hooks status --scope user
44
59
  ```
45
60
 
46
- It prints a 6-digit code — confirm it in the Ascenda app under
47
- **Connections → Ingest telemetry** — then saves the write token to
48
- `~/.ascenda/tokens/` and prints the export line:
61
+ Names the pairing, the binary and how many of the 7 events are registered.
62
+ Exits non-zero when something is missing, so it can gate a CI step.
63
+
64
+ To undo everything it wrote:
49
65
 
50
66
  ```bash
51
- export ASCENDA_TOOL_INSTALLATION_ID="cli_agent:<uuid>" # printed by `pair`
67
+ npx @ascenda-one/codex-hooks uninstall --scope user
52
68
  ```
53
69
 
54
- Add it to your shell profile. **Without this variable every hook invocation
55
- exits with `Missing ASCENDA_TOOL_INSTALLATION_ID`.**
70
+ ### 3. Restart Codex and review hooks
71
+
72
+ Open `/hooks` in the Codex CLI and review and trust the Ascenda commands.
73
+ Codex skips untrusted hooks; registration and workspace trust alone do not
74
+ authorize them. Changes to a hook definition require review again. See the
75
+ [Codex hook trust reference](https://learn.chatgpt.com/docs/hooks).
76
+
77
+ The setup command registers hooks but does not write Codex trust hashes or
78
+ bypass review. A successful `status` checks installation, not runtime trust
79
+ or accepted delivery.
56
80
 
57
- On a Dev backend with no phone:
81
+ ### On a Dev backend with no phone
82
+
83
+ `setup --local` points at the [dev server](../ascenda-dev-server), which
84
+ auto-confirms the pairing:
58
85
 
59
86
  ```bash
60
- cd ../ascenda-pairing-sim && npm run build
61
- node dist/cli.js e2e --tool-type cli_agent --name "Codex CLI"
87
+ node ../ascenda-dev-server/dist/cli.js # in another terminal
88
+ npx @ascenda-one/codex-hooks setup --local --scope user
62
89
  ```
63
90
 
64
- `ASCENDA_API_BASE_URL` defaults to `https://api.ascenda.one`; set it to
65
- `http://localhost:5002` or the Azure Dev host for development.
91
+ `--api-base-url` takes any other host; the default is `https://api.ascenda.one`.
66
92
 
67
- ### 3. Register hooks in Codex
93
+ ### Registering hooks by hand
68
94
 
69
- Merge [`examples/hooks.json`](./examples/hooks.json) into `~/.codex/hooks.json`
70
- (machine-wide) or `<repo>/.codex/hooks.json` (per project). Inline `config.toml`
71
- form works too:
95
+ `setup` is the supported path. [`examples/hooks.json`](./examples/hooks.json)
96
+ is the same content for anyone who would rather merge it themselves, or who
97
+ needs the inline `config.toml` form:
72
98
 
73
99
  ```toml
74
100
  [[hooks.UserPromptSubmit]]
@@ -78,10 +104,25 @@ command = "npx -y @ascenda-one/codex-hooks UserPromptSubmit"
78
104
  timeout = 10
79
105
  ```
80
106
 
81
- ### 4. Verify
82
-
83
- Run a Codex session and confirm events arrive on the backend — or simply that
84
- the hook exits `0`, which it always does (see the safety contract above).
107
+ A hand-merged file still needs a pairing — run `setup` for that, or export
108
+ `ASCENDA_TOOL_INSTALLATION_ID` yourself. A matching `cli_agent:` id or an unqualified id overrides the credentials
109
+ file. An id qualified for another tool type, such as `claude_code:`, is ignored
110
+ so a shell-wide setting cannot redirect Codex events to that pairing. Multiple
111
+ agents using `cli_agent` should use per-host credentials instead of a shared
112
+ environment override.
113
+
114
+ ### Verify
115
+
116
+ Run a Codex session, then read the send journal at
117
+ `~/.ascenda/state/<installationId>.json`. Look for `lastOutcome: "accepted"` and a fresh attempt timestamp. The journal
118
+ records delivery attempts under the resolved installation id, not hook process
119
+ starts. An absent expected journal can also mean a different identity was
120
+ selected, input processing failed before delivery, or the hook mapped to no
121
+ event. Check the local event log for `metadata.host: "codex"` and confirm its
122
+ `toolInstallationId` matches `tools.codex` in the credentials file. The hook
123
+ always exits `0`, so its exit code alone cannot prove delivery.
124
+
125
+ Set `ASCENDA_EVENT_LOG_FILE` to also log each payload locally.
85
126
 
86
127
  ## Build from source
87
128
 
package/dist/cli.js CHANGED
@@ -583,7 +583,61 @@ var require_out = __commonJS({
583
583
  "../packages/tool-contract/out/index.js"(exports) {
584
584
  "use strict";
585
585
  Object.defineProperty(exports, "__esModule", { value: true });
586
- 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.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.EVENT_METADATA_FIELDS = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = void 0;
586
+ 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.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.EVENT_METADATA_FIELDS = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
587
+ exports.combineDisjointHalves = combineDisjointHalves;
588
+ exports.requireComparableQuantities = requireComparableQuantities;
589
+ exports.ASCENDA_TELEMETRY_SOURCES = [
590
+ "vscode_extension",
591
+ "cursor_mcp",
592
+ "claude_code",
593
+ "copilot_otel",
594
+ "cli_agent",
595
+ "mcp_server",
596
+ "activity_signals",
597
+ "code_forge"
598
+ ];
599
+ exports.ASCENDA_TOOL_TYPES = [
600
+ "vscode_extension",
601
+ "cursor_mcp",
602
+ "claude_code",
603
+ "copilot_otel",
604
+ "cli_agent",
605
+ "mcp_server",
606
+ "github_collector",
607
+ "other"
608
+ ];
609
+ exports.ASCENDA_ACTIVE_TIME_QUANTITIES = [
610
+ "coverage",
611
+ "hands_on",
612
+ "supervising",
613
+ "block_coverage",
614
+ "hands_on_agent_hours",
615
+ "supervising_agent_hours"
616
+ ];
617
+ exports.ASCENDA_ELAPSED_QUANTITIES = {
618
+ coverage: true,
619
+ hands_on: true,
620
+ supervising: true,
621
+ block_coverage: true,
622
+ hands_on_agent_hours: false,
623
+ supervising_agent_hours: false
624
+ };
625
+ var DISJOINT_HALVES = [
626
+ ["hands_on", "supervising", "coverage"],
627
+ ["supervising", "hands_on", "coverage"]
628
+ ];
629
+ function combineDisjointHalves(left, leftQuantity, right, rightQuantity) {
630
+ const pair = DISJOINT_HALVES.find(([a, b]) => a === leftQuantity && b === rightQuantity);
631
+ if (!pair) {
632
+ throw new Error(`'combine-disjoint' combines active-time quantities '${leftQuantity}' and '${rightQuantity}', which do not partition a common whole.`);
633
+ }
634
+ return { total: left + right, quantity: pair[2] };
635
+ }
636
+ function requireComparableQuantities(left, right, operation) {
637
+ if (left !== right) {
638
+ throw new Error(`'${operation}' combines active-time quantities '${left}' and '${right}', which measure different things. See docs/ACTIVE_TIME.md, 'The quantity is the label, not the gap'.`);
639
+ }
640
+ }
587
641
  exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = [
588
642
  "approach_churn_detected",
589
643
  "goal_drift_detected",
@@ -723,9 +777,9 @@ var require_payload = __commonJS({
723
777
  }
724
778
  return void 0;
725
779
  }
726
- function getNested2(input, path) {
780
+ function getNested2(input, path2) {
727
781
  let current = input;
728
- for (const segment of path) {
782
+ for (const segment of path2) {
729
783
  if (!current || typeof current !== "object")
730
784
  return void 0;
731
785
  current = current[segment];
@@ -733,16 +787,16 @@ var require_payload = __commonJS({
733
787
  return current;
734
788
  }
735
789
  function getNestedString2(input, paths) {
736
- for (const path of paths) {
737
- const value = getNested2(input, path);
790
+ for (const path2 of paths) {
791
+ const value = getNested2(input, path2);
738
792
  if (typeof value === "string" && value.trim())
739
793
  return value;
740
794
  }
741
795
  return void 0;
742
796
  }
743
797
  function getNestedNumber(input, paths) {
744
- for (const path of paths) {
745
- const value = getNested2(input, path);
798
+ for (const path2 of paths) {
799
+ const value = getNested2(input, path2);
746
800
  if (typeof value === "number" && Number.isFinite(value))
747
801
  return value;
748
802
  }
@@ -824,8 +878,8 @@ var require_eventLog = __commonJS({
824
878
  exports.resolveEventLogPath = resolveEventLogPath;
825
879
  exports.appendEventLog = appendEventLog;
826
880
  var fs = __importStar(__require("fs"));
827
- var os = __importStar(__require("os"));
828
- var path = __importStar(__require("path"));
881
+ var os2 = __importStar(__require("os"));
882
+ var path2 = __importStar(__require("path"));
829
883
  exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
830
884
  var MAX_BYTES = 5 * 1024 * 1024;
831
885
  function expandUserPath(configured) {
@@ -833,10 +887,10 @@ var require_eventLog = __commonJS({
833
887
  if (!value)
834
888
  return void 0;
835
889
  if (value === "~")
836
- return os.homedir();
890
+ return os2.homedir();
837
891
  if (value.startsWith("~/"))
838
- return path.join(os.homedir(), value.slice(2));
839
- return path.resolve(value);
892
+ return path2.join(os2.homedir(), value.slice(2));
893
+ return path2.resolve(value);
840
894
  }
841
895
  function resolveEventLogPath() {
842
896
  return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
@@ -844,7 +898,7 @@ var require_eventLog = __commonJS({
844
898
  function appendEventLog(logFilePath, entry) {
845
899
  try {
846
900
  rotateIfLarge(logFilePath);
847
- const dir = path.dirname(logFilePath);
901
+ const dir = path2.dirname(logFilePath);
848
902
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
849
903
  fs.appendFileSync(logFilePath, `${JSON.stringify(entry)}
850
904
  `, { encoding: "utf8", mode: 384 });
@@ -1057,16 +1111,16 @@ var require_tokenStore = __commonJS({
1057
1111
  exports.readTokenFile = readTokenFile;
1058
1112
  exports.sanitizeFilePart = sanitizeFilePart;
1059
1113
  var fs = __importStar(__require("fs"));
1060
- var os = __importStar(__require("os"));
1061
- var path = __importStar(__require("path"));
1114
+ var os2 = __importStar(__require("os"));
1115
+ var path2 = __importStar(__require("path"));
1062
1116
  function ascendaHome() {
1063
- return process.env.ASCENDA_HOME ?? path.join(os.homedir(), ".ascenda");
1117
+ return process.env.ASCENDA_HOME ?? path2.join(os2.homedir(), ".ascenda");
1064
1118
  }
1065
1119
  function defaultTokenFilePath(toolInstallationId) {
1066
- return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1120
+ return path2.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1067
1121
  }
1068
1122
  function persistEventWriteToken(tokenFilePath, token) {
1069
- const dir = path.dirname(tokenFilePath);
1123
+ const dir = path2.dirname(tokenFilePath);
1070
1124
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1071
1125
  fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1072
1126
  if (process.platform !== "win32") {
@@ -1076,7 +1130,7 @@ var require_tokenStore = __commonJS({
1076
1130
  }
1077
1131
  function listPersistedToolInstallationIds(toolType) {
1078
1132
  const prefix = `${sanitizeFilePart(toolType)}_`;
1079
- const dir = path.join(ascendaHome(), "tokens");
1133
+ const dir = path2.join(ascendaHome(), "tokens");
1080
1134
  let names;
1081
1135
  try {
1082
1136
  names = fs.readdirSync(dir);
@@ -1087,7 +1141,7 @@ var require_tokenStore = __commonJS({
1087
1141
  for (const name of names.sort()) {
1088
1142
  if (!name.startsWith(prefix) || name.length === prefix.length)
1089
1143
  continue;
1090
- const file = path.join(dir, name);
1144
+ const file = path2.join(dir, name);
1091
1145
  try {
1092
1146
  if (!fs.statSync(file).isFile())
1093
1147
  continue;
@@ -1167,13 +1221,12 @@ var require_stateStore = __commonJS({
1167
1221
  exports.shouldAnnounceFailure = shouldAnnounceFailure;
1168
1222
  exports.markFailureNotified = markFailureNotified;
1169
1223
  var fs = __importStar(__require("fs"));
1170
- var os = __importStar(__require("os"));
1171
- var path = __importStar(__require("path"));
1224
+ var path2 = __importStar(__require("path"));
1172
1225
  var tokenStore_1 = require_tokenStore();
1173
1226
  function defaultStateFilePath(toolInstallationId) {
1174
1227
  const dir = process.env.ASCENDA_STATE_DIR?.trim();
1175
- const base = dir ? dir : path.join(os.homedir(), ".ascenda", "state");
1176
- return path.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1228
+ const base = dir ? dir : path2.join((0, tokenStore_1.ascendaHome)(), "state");
1229
+ return path2.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1177
1230
  }
1178
1231
  function unresolvedToolInstallationId(toolType) {
1179
1232
  return `${toolType}:unresolved`;
@@ -1252,7 +1305,7 @@ var require_stateStore = __commonJS({
1252
1305
  function writeStateFile(stateFilePath, state) {
1253
1306
  const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1254
1307
  try {
1255
- const dir = path.dirname(stateFilePath);
1308
+ const dir = path2.dirname(stateFilePath);
1256
1309
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1257
1310
  fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1258
1311
  `, { encoding: "utf8", mode: 384 });
@@ -1324,7 +1377,7 @@ var require_outbox = __commonJS({
1324
1377
  exports.claimOutbox = claimOutbox;
1325
1378
  exports.enforceOutboxBounds = enforceOutboxBounds;
1326
1379
  var fs = __importStar(__require("fs"));
1327
- var path = __importStar(__require("path"));
1380
+ var path2 = __importStar(__require("path"));
1328
1381
  var stateStore_1 = require_stateStore();
1329
1382
  var tokenStore_1 = require_tokenStore();
1330
1383
  exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
@@ -1338,12 +1391,12 @@ var require_outbox = __commonJS({
1338
1391
  return value === "1" || value === "true" || value === "yes" || value === "on";
1339
1392
  }
1340
1393
  function defaultOutboxFilePath(toolInstallationId) {
1341
- const dir = path.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1342
- return path.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1394
+ const dir = path2.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1395
+ return path2.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1343
1396
  }
1344
1397
  function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1345
1398
  try {
1346
- const dir = path.dirname(outboxFilePath);
1399
+ const dir = path2.dirname(outboxFilePath);
1347
1400
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1348
1401
  const entry = { queuedAt: now.toISOString(), payload };
1349
1402
  fs.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
@@ -1414,7 +1467,7 @@ var require_outbox = __commonJS({
1414
1467
  released = true;
1415
1468
  if (remainder.length > 0) {
1416
1469
  try {
1417
- fs.mkdirSync(path.dirname(outboxFilePath), { recursive: true, mode: 448 });
1470
+ fs.mkdirSync(path2.dirname(outboxFilePath), { recursive: true, mode: 448 });
1418
1471
  fs.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1419
1472
  `).join(""), { encoding: "utf8", mode: 384 });
1420
1473
  if (process.platform !== "win32")
@@ -1458,10 +1511,10 @@ var require_outbox = __commonJS({
1458
1511
  return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1459
1512
  }
1460
1513
  function listClaimFiles(outboxFilePath) {
1461
- const dir = path.dirname(outboxFilePath);
1462
- const prefix = `${path.basename(outboxFilePath)}.`;
1514
+ const dir = path2.dirname(outboxFilePath);
1515
+ const prefix = `${path2.basename(outboxFilePath)}.`;
1463
1516
  try {
1464
- return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
1517
+ return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path2.join(dir, name)).sort();
1465
1518
  } catch {
1466
1519
  return [];
1467
1520
  }
@@ -1494,6 +1547,25 @@ var require_outbox = __commonJS({
1494
1547
  }
1495
1548
  });
1496
1549
 
1550
+ // ../packages/tool-kit/out/timeProvider.js
1551
+ var require_timeProvider = __commonJS({
1552
+ "../packages/tool-kit/out/timeProvider.js"(exports) {
1553
+ "use strict";
1554
+ Object.defineProperty(exports, "__esModule", { value: true });
1555
+ exports.systemTimeProvider = void 0;
1556
+ exports.fixedTimeProvider = fixedTimeProvider;
1557
+ exports.systemTimeProvider = {
1558
+ now: () => Date.now()
1559
+ };
1560
+ function fixedTimeProvider(instant) {
1561
+ const ms = typeof instant === "number" ? instant : new Date(instant).valueOf();
1562
+ if (!Number.isFinite(ms))
1563
+ throw new TypeError(`fixedTimeProvider: not a usable instant: ${String(instant)}`);
1564
+ return { now: () => ms };
1565
+ }
1566
+ }
1567
+ });
1568
+
1497
1569
  // ../packages/tool-kit/out/eventSender.js
1498
1570
  var require_eventSender = __commonJS({
1499
1571
  "../packages/tool-kit/out/eventSender.js"(exports) {
@@ -1506,6 +1578,7 @@ var require_eventSender = __commonJS({
1506
1578
  var eventLog_1 = require_eventLog();
1507
1579
  var http_1 = require_http();
1508
1580
  var outbox_1 = require_outbox();
1581
+ var timeProvider_1 = require_timeProvider();
1509
1582
  var tokenStore_1 = require_tokenStore();
1510
1583
  var stateStore_1 = require_stateStore();
1511
1584
  var payload_1 = require_payload();
@@ -1542,9 +1615,12 @@ var require_eventSender = __commonJS({
1542
1615
  lastDrain;
1543
1616
  /** One outbox pass per sender, i.e. per hook process. The hook is on the user's critical path. */
1544
1617
  outboxServiced = false;
1618
+ /** Resolved once, so every clock read in one pass sees the same instant. */
1619
+ time;
1545
1620
  constructor(config) {
1546
1621
  this.config = config;
1547
1622
  this.eventWriteToken = config.eventWriteToken;
1623
+ this.time = config.timeProvider ?? timeProvider_1.systemTimeProvider;
1548
1624
  }
1549
1625
  async send(mapped) {
1550
1626
  return this.post(buildEventPayload(this.config, mapped));
@@ -1695,7 +1771,7 @@ var require_eventSender = __commonJS({
1695
1771
  * journal's detail says so instead of implying it was kept.
1696
1772
  */
1697
1773
  enqueue(payload) {
1698
- return (0, outbox_1.appendToOutbox)(this.outboxFilePath(), payload);
1774
+ return (0, outbox_1.appendToOutbox)(this.outboxFilePath(), payload, new Date(this.time.now()));
1699
1775
  }
1700
1776
  /**
1701
1777
  * One pass over the outbox: claim it, apply the bounds, and — when sending
@@ -1718,7 +1794,7 @@ var require_eventSender = __commonJS({
1718
1794
  return void 0;
1719
1795
  this.outboxServiced = true;
1720
1796
  const sendEnabled = this.config.outboxDrain ?? (0, outbox_1.outboxDrainEnabled)();
1721
- const claimed = (0, outbox_1.claimOutbox)(this.outboxFilePath());
1797
+ const claimed = (0, outbox_1.claimOutbox)(this.outboxFilePath(), this.time.now());
1722
1798
  if (!claimed) {
1723
1799
  this.lastDrain = { found: 0, discarded: 0, delivered: 0, remaining: 0, sendEnabled };
1724
1800
  return void 0;
@@ -1727,7 +1803,7 @@ var require_eventSender = __commonJS({
1727
1803
  const { kept, discarded } = (0, outbox_1.enforceOutboxBounds)(claimed.entries, {
1728
1804
  maxEntries: this.config.outboxMaxEntries ?? outbox_1.DEFAULT_OUTBOX_MAX_ENTRIES,
1729
1805
  maxAgeMs: this.config.outboxMaxAgeMs ?? outbox_1.DEFAULT_OUTBOX_MAX_AGE_MS
1730
- });
1806
+ }, this.time.now());
1731
1807
  if (claimed.unreadable > 0) {
1732
1808
  discarded.count += claimed.unreadable;
1733
1809
  discarded.reasons.unreadable = claimed.unreadable;
@@ -1914,11 +1990,11 @@ var require_contextRegistry = __commonJS({
1914
1990
  exports.recordWorkContext = recordWorkContext;
1915
1991
  exports.recordWorkContextAlias = recordWorkContextAlias;
1916
1992
  var fs = __importStar(__require("fs"));
1917
- var os = __importStar(__require("os"));
1918
- var path = __importStar(__require("path"));
1993
+ var os2 = __importStar(__require("os"));
1994
+ var path2 = __importStar(__require("path"));
1919
1995
  var MAX_PATHS_PER_ENTRY = 8;
1920
1996
  function workContextRegistryFilePath() {
1921
- return path.join(os.homedir(), ".ascenda", "work-contexts.json");
1997
+ return path2.join(os2.homedir(), ".ascenda", "work-contexts.json");
1922
1998
  }
1923
1999
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
1924
2000
  try {
@@ -1998,7 +2074,7 @@ var require_contextRegistry = __commonJS({
1998
2074
  return iso.slice(0, 10);
1999
2075
  }
2000
2076
  function writeRegistry(registryFilePath, registry) {
2001
- const dir = path.dirname(registryFilePath);
2077
+ const dir = path2.dirname(registryFilePath);
2002
2078
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
2003
2079
  const tmp = `${registryFilePath}.${process.pid}.tmp`;
2004
2080
  fs.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
@@ -2061,10 +2137,10 @@ var require_credentials = __commonJS({
2061
2137
  exports.writeHostCredentials = writeHostCredentials;
2062
2138
  exports.removeHostCredentials = removeHostCredentials;
2063
2139
  var fs = __importStar(__require("fs"));
2064
- var path = __importStar(__require("path"));
2140
+ var path2 = __importStar(__require("path"));
2065
2141
  var tokenStore_1 = require_tokenStore();
2066
2142
  function credentialsFilePath() {
2067
- return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2143
+ return path2.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2068
2144
  }
2069
2145
  function readMachineCredentials() {
2070
2146
  try {
@@ -2081,11 +2157,11 @@ var require_credentials = __commonJS({
2081
2157
  }
2082
2158
  function writeMachineCredentials(credentials) {
2083
2159
  const file = credentialsFilePath();
2084
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2160
+ fs.mkdirSync(path2.dirname(file), { recursive: true, mode: 448 });
2085
2161
  fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2086
2162
  `, { encoding: "utf8", mode: 384 });
2087
2163
  if (process.platform !== "win32") {
2088
- fs.chmodSync(path.dirname(file), 448);
2164
+ fs.chmodSync(path2.dirname(file), 448);
2089
2165
  fs.chmodSync(file, 384);
2090
2166
  }
2091
2167
  }
@@ -2167,7 +2243,7 @@ var require_forgeProject = __commonJS({
2167
2243
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
2168
2244
  exports.recordForgeProjectAlias = recordForgeProjectAlias;
2169
2245
  var fs = __importStar(__require("fs"));
2170
- var path = __importStar(__require("path"));
2246
+ var path2 = __importStar(__require("path"));
2171
2247
  var contextRegistry_1 = require_contextRegistry();
2172
2248
  function forgeProjectHash(value) {
2173
2249
  let h = 2166136261;
@@ -2213,7 +2289,7 @@ var require_forgeProject = __commonJS({
2213
2289
  return null;
2214
2290
  let config;
2215
2291
  try {
2216
- config = fs.readFileSync(path.join(repositoryRoot, ".git", "config"), "utf8");
2292
+ config = fs.readFileSync(path2.join(repositoryRoot, ".git", "config"), "utf8");
2217
2293
  } catch {
2218
2294
  return null;
2219
2295
  }
@@ -2321,17 +2397,17 @@ var require_salt = __commonJS({
2321
2397
  exports.hashWithMachineSalt = hashWithMachineSalt;
2322
2398
  var crypto = __importStar(__require("crypto"));
2323
2399
  var fs = __importStar(__require("fs"));
2324
- var os = __importStar(__require("os"));
2325
- var path = __importStar(__require("path"));
2400
+ var os2 = __importStar(__require("os"));
2401
+ var path2 = __importStar(__require("path"));
2326
2402
  function machineSaltFilePath() {
2327
- return path.join(os.homedir(), ".ascenda", "salt");
2403
+ return path2.join(os2.homedir(), ".ascenda", "salt");
2328
2404
  }
2329
2405
  var cache = /* @__PURE__ */ new Map();
2330
2406
  function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
2331
2407
  const hit = cache.get(saltFilePath);
2332
2408
  if (hit)
2333
2409
  return hit;
2334
- const dir = path.dirname(saltFilePath);
2410
+ const dir = path2.dirname(saltFilePath);
2335
2411
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
2336
2412
  let salt;
2337
2413
  try {
@@ -2405,7 +2481,7 @@ var require_workContext = __commonJS({
2405
2481
  exports.readBranchName = readBranchName;
2406
2482
  exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
2407
2483
  var fs = __importStar(__require("fs"));
2408
- var path = __importStar(__require("path"));
2484
+ var path2 = __importStar(__require("path"));
2409
2485
  var salt_1 = require_salt();
2410
2486
  var MAX_WALK_DEPTH = 64;
2411
2487
  function deriveWorkContext(cwd, saltFilePath) {
@@ -2440,7 +2516,7 @@ var require_workContext = __commonJS({
2440
2516
  return null;
2441
2517
  let dir = startDir;
2442
2518
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
2443
- const dotGit = path.join(dir, ".git");
2519
+ const dotGit = path2.join(dir, ".git");
2444
2520
  let stat = null;
2445
2521
  try {
2446
2522
  stat = fs.statSync(dotGit);
@@ -2454,7 +2530,7 @@ var require_workContext = __commonJS({
2454
2530
  const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
2455
2531
  return { checkoutRoot: dir, canonicalRoot, gitDir };
2456
2532
  }
2457
- const parent = path.dirname(dir);
2533
+ const parent = path2.dirname(dir);
2458
2534
  if (parent === dir)
2459
2535
  return null;
2460
2536
  dir = parent;
@@ -2466,13 +2542,13 @@ var require_workContext = __commonJS({
2466
2542
  const match = /^gitdir:\s*(.+)\s*$/m.exec(fs.readFileSync(dotGitFile, "utf8"));
2467
2543
  if (!match)
2468
2544
  return null;
2469
- return path.resolve(containingDir, match[1].trim());
2545
+ return path2.resolve(containingDir, match[1].trim());
2470
2546
  } catch {
2471
2547
  return null;
2472
2548
  }
2473
2549
  }
2474
2550
  function worktreeParentRoot(resolvedGitDir) {
2475
- const marker = `${path.sep}.git${path.sep}worktrees${path.sep}`;
2551
+ const marker = `${path2.sep}.git${path2.sep}worktrees${path2.sep}`;
2476
2552
  const idx = resolvedGitDir.indexOf(marker);
2477
2553
  if (idx === -1)
2478
2554
  return null;
@@ -2482,12 +2558,12 @@ var require_workContext = __commonJS({
2482
2558
  const sep = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
2483
2559
  const leading = /^[\\/]/.test(startPath) ? sep : "";
2484
2560
  const segments = startPath.split(/[\\/]/).filter(Boolean);
2485
- const join = (count) => leading + segments.slice(0, count).join(sep);
2561
+ const join2 = (count) => leading + segments.slice(0, count).join(sep);
2486
2562
  for (let i = 0; i + 2 < segments.length; i++) {
2487
2563
  if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
2488
2564
  if (i === 0)
2489
2565
  return null;
2490
- return { checkoutRoot: join(i + 3), canonicalRoot: join(i), gitDir: null };
2566
+ return { checkoutRoot: join2(i + 3), canonicalRoot: join2(i), gitDir: null };
2491
2567
  }
2492
2568
  }
2493
2569
  for (let i = 0; i + 1 < segments.length; i++) {
@@ -2497,7 +2573,7 @@ var require_workContext = __commonJS({
2497
2573
  continue;
2498
2574
  const repoName = folder.slice(0, -suffix.length);
2499
2575
  const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep);
2500
- return { checkoutRoot: join(i + 2), canonicalRoot, gitDir: null };
2576
+ return { checkoutRoot: join2(i + 2), canonicalRoot, gitDir: null };
2501
2577
  }
2502
2578
  return null;
2503
2579
  }
@@ -2545,7 +2621,7 @@ var require_workContext = __commonJS({
2545
2621
  return null;
2546
2622
  let head;
2547
2623
  try {
2548
- head = fs.readFileSync(path.join(gitDir, "HEAD"), "utf8").trim();
2624
+ head = fs.readFileSync(path2.join(gitDir, "HEAD"), "utf8").trim();
2549
2625
  } catch {
2550
2626
  return null;
2551
2627
  }
@@ -2596,10 +2672,10 @@ var require_hookAdapter = __commonJS({
2596
2672
  exports.MissingInstallationIdError = MissingInstallationIdError;
2597
2673
  function resolveCliAgentInstallationId(toolType, identity = {}) {
2598
2674
  const fromEnv = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2599
- if (fromEnv)
2675
+ if (fromEnv && belongsToToolType(toolType, fromEnv))
2600
2676
  return { toolInstallationId: qualify(toolType, fromEnv), source: "env" };
2601
2677
  const fromCredentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host)?.toolInstallationId?.trim() : void 0;
2602
- if (fromCredentials)
2678
+ if (fromCredentials && belongsToToolType(toolType, fromCredentials))
2603
2679
  return { toolInstallationId: qualify(toolType, fromCredentials), source: "credentials" };
2604
2680
  const candidates = (0, tokenStore_1.listPersistedToolInstallationIds)(toolType);
2605
2681
  if (candidates.length === 1)
@@ -2609,6 +2685,9 @@ var require_hookAdapter = __commonJS({
2609
2685
  function defaultSetupCommand(host) {
2610
2686
  return host ? `npx @ascenda-one/${host.replace(/_cli$/, "")}-hooks setup` : "the agent's setup command";
2611
2687
  }
2688
+ function belongsToToolType(toolType, value) {
2689
+ return !value.includes(":") || value.startsWith(`${toolType}:`);
2690
+ }
2612
2691
  function qualify(toolType, value) {
2613
2692
  return value.includes(":") ? value : `${toolType}:${value}`;
2614
2693
  }
@@ -2765,25 +2844,25 @@ var require_cliAgentSetup = __commonJS({
2765
2844
  };
2766
2845
  }();
2767
2846
  Object.defineProperty(exports, "__esModule", { value: true });
2768
- exports.isCliAgentManagementCommand = isCliAgentManagementCommand;
2847
+ exports.isCliAgentManagementCommand = isCliAgentManagementCommand2;
2769
2848
  exports.cliAgentHookBinPath = cliAgentHookBinPath;
2770
- exports.runCliAgentSetup = runCliAgentSetup;
2849
+ exports.runCliAgentSetup = runCliAgentSetup2;
2771
2850
  exports.writeHookSettings = writeHookSettings;
2772
2851
  exports.findStaleHookCommands = findStaleHookCommands;
2773
2852
  var crypto = __importStar(__require("crypto"));
2774
2853
  var fs = __importStar(__require("fs"));
2775
- var os = __importStar(__require("os"));
2776
- var path = __importStar(__require("path"));
2854
+ var os2 = __importStar(__require("os"));
2855
+ var path2 = __importStar(__require("path"));
2777
2856
  var credentials_1 = require_credentials();
2778
2857
  var hookAdapter_1 = require_hookAdapter();
2779
2858
  var http_1 = require_http();
2780
2859
  var tokenStore_1 = require_tokenStore();
2781
2860
  var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
2782
- function isCliAgentManagementCommand(argument) {
2861
+ function isCliAgentManagementCommand2(argument) {
2783
2862
  return argument !== void 0 && MANAGEMENT_COMMANDS.has(argument);
2784
2863
  }
2785
2864
  function cliAgentHookBinPath(binaryName) {
2786
- return path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
2865
+ return path2.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
2787
2866
  }
2788
2867
  function usage(spec) {
2789
2868
  return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
@@ -2803,7 +2882,7 @@ Options
2803
2882
  -h, --help
2804
2883
  `;
2805
2884
  }
2806
- async function runCliAgentSetup(argv, spec) {
2885
+ async function runCliAgentSetup2(argv, spec) {
2807
2886
  let options;
2808
2887
  try {
2809
2888
  options = parseArgs(argv, spec);
@@ -2894,7 +2973,7 @@ Done. ${spec.restartHint}`);
2894
2973
  break;
2895
2974
  }
2896
2975
  case "--project-dir":
2897
- options.projectDir = path.resolve(next());
2976
+ options.projectDir = path2.resolve(next());
2898
2977
  break;
2899
2978
  case "--dry-run":
2900
2979
  options.dryRun = true;
@@ -2927,7 +3006,7 @@ ${usage(spec)}`);
2927
3006
  const toolInstallationId = existingId ?? `${spec.toolType}:${crypto.randomUUID()}`;
2928
3007
  let session;
2929
3008
  try {
2930
- session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os.hostname()}`);
3009
+ session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os2.hostname()}`);
2931
3010
  } catch (error) {
2932
3011
  console.error(`
2933
3012
  Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
@@ -2968,8 +3047,8 @@ Pairing ${status.status}. Run setup again.`);
2968
3047
  if (dryRun)
2969
3048
  return target;
2970
3049
  const source = process.argv[1];
2971
- fs.mkdirSync(path.dirname(target), { recursive: true });
2972
- if (path.resolve(source) !== path.resolve(target)) {
3050
+ fs.mkdirSync(path2.dirname(target), { recursive: true });
3051
+ if (path2.resolve(source) !== path2.resolve(target)) {
2973
3052
  fs.copyFileSync(source, target);
2974
3053
  }
2975
3054
  if (process.platform !== "win32")
@@ -3010,7 +3089,7 @@ ${serialised}`);
3010
3089
  }
3011
3090
  if (exists)
3012
3091
  fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3013
- fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
3092
+ fs.mkdirSync(path2.dirname(settingsFile), { recursive: true });
3014
3093
  fs.writeFileSync(settingsFile, serialised, "utf8");
3015
3094
  return true;
3016
3095
  }
@@ -3098,7 +3177,7 @@ ${serialised}`);
3098
3177
  (0, credentials_1.removeHostCredentials)(spec.host);
3099
3178
  console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
3100
3179
  }
3101
- console.log(`tokens left in ${path.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
3180
+ console.log(`tokens left in ${path2.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
3102
3181
  return 0;
3103
3182
  }
3104
3183
  }
@@ -3149,11 +3228,11 @@ var require_turnState = __commonJS({
3149
3228
  exports.recordTurnStart = recordTurnStart2;
3150
3229
  exports.consumeTurnDurationMs = consumeTurnDurationMs2;
3151
3230
  var fs = __importStar(__require("fs"));
3152
- var os = __importStar(__require("os"));
3153
- var path = __importStar(__require("path"));
3154
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join(os.homedir(), ".ascenda", "state");
3231
+ var path2 = __importStar(__require("path"));
3232
+ var tokenStore_1 = require_tokenStore();
3233
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path2.join((0, tokenStore_1.ascendaHome)(), "state");
3155
3234
  function turnFile(agent, sessionId) {
3156
- return path.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
3235
+ return path2.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
3157
3236
  }
3158
3237
  function sanitize(value) {
3159
3238
  return value.replace(/[^a-zA-Z0-9._-]/g, "_");
@@ -3232,8 +3311,8 @@ var require_liveBus = __commonJS({
3232
3311
  exports.emitLiveSignal = emitLiveSignal;
3233
3312
  var fs = __importStar(__require("fs"));
3234
3313
  var net = __importStar(__require("net"));
3235
- var os = __importStar(__require("os"));
3236
- var path = __importStar(__require("path"));
3314
+ var os2 = __importStar(__require("os"));
3315
+ var path2 = __importStar(__require("path"));
3237
3316
  var WRITE_TIMEOUT_MS = 50;
3238
3317
  var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
3239
3318
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
@@ -3241,11 +3320,11 @@ var require_liveBus = __commonJS({
3241
3320
  const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
3242
3321
  if (override)
3243
3322
  return [override];
3244
- const home = os.homedir();
3323
+ const home = os2.homedir();
3245
3324
  return [
3246
- path.join(home, ".ascenda", "live.sock"),
3247
- path.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
3248
- path.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
3325
+ path2.join(home, ".ascenda", "live.sock"),
3326
+ path2.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
3327
+ path2.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
3249
3328
  ];
3250
3329
  }
3251
3330
  function liveBusSocketPath() {
@@ -3318,8 +3397,8 @@ var require_out2 = __commonJS({
3318
3397
  "use strict";
3319
3398
  Object.defineProperty(exports, "__esModule", { value: true });
3320
3399
  exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.credentialsFilePath = exports.writeHookSettings = exports.runCliAgentSetup = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
3321
- exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.recordTurnStart = void 0;
3322
- exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = void 0;
3400
+ exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.recordTurnStart = void 0;
3401
+ exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = void 0;
3323
3402
  var commandClassifier_1 = require_commandClassifier();
3324
3403
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
3325
3404
  return commandClassifier_1.classifyCommand;
@@ -3559,6 +3638,13 @@ var require_out2 = __commonJS({
3559
3638
  Object.defineProperty(exports, "enforceOutboxBounds", { enumerable: true, get: function() {
3560
3639
  return outbox_1.enforceOutboxBounds;
3561
3640
  } });
3641
+ var timeProvider_1 = require_timeProvider();
3642
+ Object.defineProperty(exports, "systemTimeProvider", { enumerable: true, get: function() {
3643
+ return timeProvider_1.systemTimeProvider;
3644
+ } });
3645
+ Object.defineProperty(exports, "fixedTimeProvider", { enumerable: true, get: function() {
3646
+ return timeProvider_1.fixedTimeProvider;
3647
+ } });
3562
3648
  var salt_1 = require_salt();
3563
3649
  Object.defineProperty(exports, "machineSaltFilePath", { enumerable: true, get: function() {
3564
3650
  return salt_1.machineSaltFilePath;
@@ -3790,11 +3876,51 @@ function withHost(metadata) {
3790
3876
  return { host: CODEX_HOST, ...metadata };
3791
3877
  }
3792
3878
 
3879
+ // src/setup.ts
3880
+ import * as os from "os";
3881
+ import * as path from "path";
3882
+ var HOOK_EVENTS = [
3883
+ "SessionStart",
3884
+ "UserPromptSubmit",
3885
+ "PreToolUse",
3886
+ "PostToolUse",
3887
+ "PreCompact",
3888
+ "PostCompact",
3889
+ "Stop"
3890
+ ];
3891
+ var HOOK_TIMEOUT_SECONDS = 10;
3892
+ var SETUP = {
3893
+ host: CODEX_HOST,
3894
+ displayName: "Codex CLI",
3895
+ toolType: ASCENDA_TOOL_TYPE,
3896
+ packageName: "@ascenda-one/codex-hooks",
3897
+ binaryName: "ascenda-codex-hook",
3898
+ hookEvents: HOOK_EVENTS,
3899
+ restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not enable execution. After a session, verify the cli_agent send journal and metadata.host: codex in the event log.",
3900
+ settings: {
3901
+ settingsPath: (scope, projectDir) => scope === "user" ? path.join(os.homedir(), ".codex", "hooks.json") : path.join(projectDir, ".codex", "hooks.json"),
3902
+ // Codex nests as Gemini does — each event maps to an array of
3903
+ // { hooks: [{ type, command }] } — but reads the event from argv rather
3904
+ // than stdin, so unlike Gemini the name has to be on the command line.
3905
+ entry: (command, event) => ({ hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }),
3906
+ commandOf: (entry) => {
3907
+ const group = entry;
3908
+ const command = group?.hooks?.find((hook) => typeof hook?.command === "string")?.command;
3909
+ return typeof command === "string" ? command : void 0;
3910
+ }
3911
+ }
3912
+ };
3913
+
3793
3914
  // src/cli.ts
3794
3915
  async function main() {
3795
- const hookName = process.argv[2];
3916
+ const command = process.argv[2];
3917
+ if ((0, import_tool_kit2.isCliAgentManagementCommand)(command)) {
3918
+ managementExitCode = await (0, import_tool_kit2.runCliAgentSetup)(process.argv.slice(2), SETUP);
3919
+ return;
3920
+ }
3921
+ const hookName = command;
3796
3922
  if (!hookName) {
3797
- console.error("Usage: ascenda-codex-hook <CodexHookEventName>");
3923
+ console.error("Usage: ascenda-codex-hook <CodexHookEventName> | setup | status | uninstall");
3798
3924
  return;
3799
3925
  }
3800
3926
  const input = await readJsonFromStdin();
@@ -3805,11 +3931,13 @@ async function main() {
3805
3931
  await (0, import_tool_kit2.deliverHookEvents)(mapCodexEvent(hookName, input, turnDurationMs), {
3806
3932
  toolType: ASCENDA_TOOL_TYPE,
3807
3933
  host: CODEX_HOST,
3934
+ setupCommand: `npx ${SETUP.packageName} setup`,
3808
3935
  source: "cli_agent",
3809
3936
  sessionId,
3810
3937
  onNotice: emitSystemMessage
3811
3938
  });
3812
3939
  }
3940
+ var managementExitCode;
3813
3941
  function emitSystemMessage(message) {
3814
3942
  console.log(JSON.stringify({ continue: true, systemMessage: message, suppressOutput: true }));
3815
3943
  }
@@ -3830,4 +3958,4 @@ async function readJsonFromStdin() {
3830
3958
  }
3831
3959
  main().catch((error) => {
3832
3960
  console.error(error instanceof Error ? error.message : String(error));
3833
- }).finally(() => process.exit(0));
3961
+ }).finally(() => process.exit(managementExitCode ?? 0));
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAClG,OAAO,EAAE,aAAa,EAAE,MAA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qE;IACrE,uEAAuE;IACvE,2DAA2D;IAC3D,OAAO,CAAC,KAAK,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACxE,CAAC,CAAC;KACD,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,kBAAkB,IAAI,CAAC,CAAC,CAAC,CAAC"}
package/dist/setup.js ADDED
@@ -0,0 +1,44 @@
1
+ import * as os from "os";
2
+ import * as path from "path";
3
+ import { ASCENDA_TOOL_TYPE, CODEX_HOST } from "./types.js";
4
+ /**
5
+ * Only the hooks that map to a catalog event. `PermissionRequest` and the
6
+ * subagent lifecycle pair map to nothing, so registering them would spend a
7
+ * process per approval to send an empty list.
8
+ */
9
+ export const HOOK_EVENTS = [
10
+ "SessionStart",
11
+ "UserPromptSubmit",
12
+ "PreToolUse", "PostToolUse",
13
+ "PreCompact", "PostCompact",
14
+ "Stop"
15
+ ];
16
+ /**
17
+ * Matches the timeout in `examples/hooks.json`, so a hand-merged file and a
18
+ * `setup`-written one do not disagree. Generous on purpose: the adapter caps
19
+ * its own HTTP at 3 s (ASCENDA_HTTP_TIMEOUT_MS), so this ceiling is only ever
20
+ * reached by a wedged process, and Codex awaits command hooks.
21
+ */
22
+ const HOOK_TIMEOUT_SECONDS = 10;
23
+ export const SETUP = {
24
+ host: CODEX_HOST,
25
+ displayName: "Codex CLI",
26
+ toolType: ASCENDA_TOOL_TYPE,
27
+ packageName: "@ascenda-one/codex-hooks",
28
+ binaryName: "ascenda-codex-hook",
29
+ hookEvents: HOOK_EVENTS,
30
+ restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not enable execution. After a session, verify the cli_agent send journal and metadata.host: codex in the event log.",
31
+ settings: {
32
+ settingsPath: (scope, projectDir) => scope === "user" ? path.join(os.homedir(), ".codex", "hooks.json") : path.join(projectDir, ".codex", "hooks.json"),
33
+ // Codex nests as Gemini does — each event maps to an array of
34
+ // { hooks: [{ type, command }] } — but reads the event from argv rather
35
+ // than stdin, so unlike Gemini the name has to be on the command line.
36
+ entry: (command, event) => ({ hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }),
37
+ commandOf: (entry) => {
38
+ const group = entry;
39
+ const command = group?.hooks?.find((hook) => typeof hook?.command === "string")?.command;
40
+ return typeof command === "string" ? command : undefined;
41
+ }
42
+ }
43
+ };
44
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE3D;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,cAAc;IACd,kBAAkB;IAClB,YAAY,EAAE,aAAa;IAC3B,YAAY,EAAE,aAAa;IAC3B,MAAM;CACE,CAAC;AAEX;;;;;GAKG;AACH,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAIhC,MAAM,CAAC,MAAM,KAAK,GAAsB;IACtC,IAAI,EAAE,UAAU;IAChB,WAAW,EAAE,WAAW;IACxB,QAAQ,EAAE,iBAAiB;IAC3B,WAAW,EAAE,0BAA0B;IACvC,UAAU,EAAE,oBAAoB;IAChC,UAAU,EAAE,WAAW;IACvB,WAAW,EAAE,oNAAoN;IACjO,QAAQ,EAAE;QACR,YAAY,EAAE,CAAC,KAAK,EAAE,UAAU,EAAE,EAAE,CAClC,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,YAAY,CAAC;QACpH,8DAA8D;QAC9D,wEAAwE;QACxE,uEAAuE;QACvE,KAAK,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,OAAO,IAAI,KAAK,EAAE,EAAE,OAAO,EAAE,oBAAoB,EAAE,CAAC,EAAE,CAAC;QAC5H,SAAS,EAAE,CAAC,KAAK,EAAE,EAAE;YACnB,MAAM,KAAK,GAAG,KAAmC,CAAC;YAClD,MAAM,OAAO,GAAG,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,EAAE,OAAO,KAAK,QAAQ,CAAC,EAAE,OAAO,CAAC;YACzF,OAAO,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;QAC3D,CAAC;KACF;CACF,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "publishConfig": { "access": "public" },
3
3
  "name": "@ascenda-one/codex-hooks",
4
- "version": "0.1.18",
4
+ "version": "0.1.20",
5
5
  "description": "OpenAI Codex hooks adapter for Ascenda AI workload telemetry",
6
6
  "repository": {
7
7
  "type": "git",