olakai-cli 0.6.7 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,20 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ TOOL_IDS,
4
+ formatRegistryTable,
5
+ getCodexConfigPath,
6
+ getCodexHomeDir,
7
+ getPlugin,
8
+ getToolSource,
9
+ isInteractive,
10
+ isToolId,
11
+ listPlugins,
12
+ promptUser,
13
+ readRegistry,
14
+ reconcileCurrentWorkspace,
15
+ removeEntry,
16
+ runMonitorInstall
17
+ } from "./chunk-E33XD5CO.js";
2
18
  import {
3
19
  createAgent,
4
20
  createCustomDataConfig,
@@ -24,40 +40,24 @@ import {
24
40
  listSessions,
25
41
  listWorkflows,
26
42
  pollForToken,
27
- regenerateAgentApiKey,
28
43
  requestDeviceCode,
29
44
  updateAgent,
30
45
  updateCustomDataConfig,
31
46
  updateKpi,
32
47
  updateWorkflow,
33
48
  validateKpiFormula
34
- } from "./chunk-43E2A3O2.js";
49
+ } from "./chunk-KNGRF4XU.js";
35
50
  import {
36
- CLAUDE_DIR,
37
- OLAKAI_DIR,
38
- OLAKAI_HOOK_MARKER,
39
- SETTINGS_FILE,
40
- deleteClaudeCodeConfig,
41
51
  findConfiguredWorkspace,
42
- getClaudeCodeConfigPath,
43
- getClaudeCodeStatus,
44
- getClaudeDir,
45
52
  getLegacyClaudeMonitorConfigPath,
46
- getMonitorConfigPath,
47
- getSettingsPath,
48
- loadClaudeCodeConfig,
49
- mergeHooksSettings,
50
- readJsonFile,
51
- writeClaudeCodeConfig,
52
- writeJsonFile
53
- } from "./chunk-2Q7JYGCK.js";
53
+ getMonitorConfigPath
54
+ } from "./chunk-KY6OHQZW.js";
54
55
  import {
55
56
  HOSTS,
56
57
  clearToken,
57
58
  getBaseUrl,
58
59
  getEnvironment,
59
60
  getValidEnvironments,
60
- getValidToken,
61
61
  isTokenValid,
62
62
  isValidEnvironment,
63
63
  loadToken,
@@ -294,2393 +294,115 @@ async function postHandshakeJson(url, body, options = {}) {
294
294
  return {
295
295
  kind: "error",
296
296
  code: "unknown_error",
297
- message: err instanceof Error ? err.message : "Failed to parse response",
298
- status: response.status
299
- };
300
- }
301
- return { kind: "ok", data };
302
- }
303
- let errBody = {};
304
- try {
305
- errBody = await response.json();
306
- } catch {
307
- }
308
- const code = mapErrorCode(response.status, errBody);
309
- let fallbackPath = "";
310
- try {
311
- fallbackPath = new URL(url).pathname;
312
- } catch {
313
- fallbackPath = url;
314
- }
315
- const message = errBody.message || errBody.error || `Request to ${fallbackPath} failed with status ${response.status}`;
316
- const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
317
- const envelope = {
318
- kind: "error",
319
- code,
320
- message,
321
- status: response.status,
322
- ...retryAfter !== void 0 ? { retryAfter } : {}
323
- };
324
- if (options.captureDetail && typeof errBody.attemptsRemaining === "number") {
325
- envelope.detail = { attemptsRemaining: errBody.attemptsRemaining };
326
- }
327
- return envelope;
328
- }
329
- function mapErrorCode(status, body) {
330
- const known = [
331
- "validation_error",
332
- "invalid_code",
333
- "invalid_consent",
334
- "user_unavailable",
335
- "blocked",
336
- "no_code",
337
- "expired",
338
- "locked",
339
- "rate_limited",
340
- "service_unavailable"
341
- ];
342
- if (typeof body.code === "string" && known.includes(body.code)) {
343
- return body.code;
344
- }
345
- if (typeof body.error === "string" && known.includes(body.error)) {
346
- return body.error;
347
- }
348
- switch (status) {
349
- case 400:
350
- return "validation_error";
351
- case 401:
352
- return "invalid_consent";
353
- case 403:
354
- return "blocked";
355
- case 404:
356
- return "no_code";
357
- case 410:
358
- return "expired";
359
- case 429:
360
- return "rate_limited";
361
- case 503:
362
- return "service_unavailable";
363
- default:
364
- return "unknown_error";
365
- }
366
- }
367
- function buildNetworkError(err) {
368
- const base = err instanceof Error ? err.message : "Network request failed";
369
- let causeCode;
370
- let causeMessage;
371
- if (err instanceof Error && err.cause && typeof err.cause === "object") {
372
- const c = err.cause;
373
- if (typeof c.code === "string" && c.code.length > 0) {
374
- causeCode = c.code;
375
- }
376
- if (typeof c.message === "string" && c.message.length > 0) {
377
- causeMessage = c.message;
378
- }
379
- }
380
- const message = causeMessage && causeMessage !== base ? `${base}: ${causeMessage}` : base;
381
- return {
382
- kind: "error",
383
- code: "network_error",
384
- message,
385
- status: 0,
386
- ...causeCode ? { causeCode } : {}
387
- };
388
- }
389
- function parseRetryAfter(header) {
390
- if (!header) return void 0;
391
- const asNumber2 = Number(header);
392
- if (Number.isFinite(asNumber2) && asNumber2 > 0) {
393
- return Math.floor(asNumber2);
394
- }
395
- const asDate = Date.parse(header);
396
- if (Number.isFinite(asDate)) {
397
- const seconds = Math.floor((asDate - Date.now()) / 1e3);
398
- return seconds > 0 ? seconds : void 0;
399
- }
400
- return void 0;
401
- }
402
-
403
- // src/monitor/prompt.ts
404
- import * as readline from "readline";
405
- function promptUser(question) {
406
- const rl = readline.createInterface({
407
- input: process.stdin,
408
- output: process.stdout
409
- });
410
- return new Promise((resolve) => {
411
- rl.question(question, (answer) => {
412
- rl.close();
413
- resolve(answer.trim());
414
- });
415
- });
416
- }
417
- function isInteractive() {
418
- return Boolean(process.stdin.isTTY && process.stdout.isTTY);
419
- }
420
-
421
- // src/monitor/detect-all.ts
422
- import * as fs15 from "fs";
423
- import * as path14 from "path";
424
-
425
- // src/monitor/plugins/codex/paths.ts
426
- import * as os from "os";
427
- import * as path from "path";
428
- var CODEX_HOME_DIRNAME = ".codex";
429
- var CODEX_CONFIG_FILENAME = "config.toml";
430
- var CODEX_SESSIONS_DIRNAME = "sessions";
431
- function getCodexHomeDir() {
432
- return path.join(os.homedir(), CODEX_HOME_DIRNAME);
433
- }
434
- function getCodexConfigPath() {
435
- return path.join(getCodexHomeDir(), CODEX_CONFIG_FILENAME);
436
- }
437
- function getCodexSessionsDir() {
438
- return path.join(getCodexHomeDir(), CODEX_SESSIONS_DIRNAME);
439
- }
440
-
441
- // src/monitor/plugins/claude-code/index.ts
442
- import * as fs4 from "fs";
443
- import { spawnSync as spawnSync2 } from "child_process";
444
-
445
- // src/monitor/plugin.ts
446
- var TOOL_IDS = [
447
- "claude-code",
448
- "codex",
449
- "cursor"
450
- ];
451
- var registry = /* @__PURE__ */ new Map();
452
- function registerPlugin(plugin) {
453
- registry.set(plugin.id, plugin);
454
- }
455
- function getPlugin(id) {
456
- if (!isToolId(id)) {
457
- throw new Error(
458
- `Unknown tool: "${id}". Supported tools: ${TOOL_IDS.join(", ")}`
459
- );
460
- }
461
- const plugin = registry.get(id);
462
- if (!plugin) {
463
- throw new Error(
464
- `Tool "${id}" is not registered. This is a CLI bug \u2014 please report it.`
465
- );
466
- }
467
- return plugin;
468
- }
469
- function listPlugins() {
470
- return Array.from(registry.values());
471
- }
472
- function isToolId(value) {
473
- return TOOL_IDS.includes(value);
474
- }
475
-
476
- // src/commands/monitor-state.ts
477
- import * as fs from "fs";
478
- import * as os2 from "os";
479
- import * as path2 from "path";
480
- var STATE_DIR_SEGMENTS = [".olakai", "monitor-state"];
481
- function getStateDir(homeDir) {
482
- return path2.join(homeDir, ...STATE_DIR_SEGMENTS);
483
- }
484
- function getStateFile(sessionId, homeDir) {
485
- return path2.join(getStateDir(homeDir), `${sessionId}.json`);
486
- }
487
- var debugLogger = null;
488
- function setDebugLogger(logger) {
489
- debugLogger = logger;
490
- }
491
- function log(label, data) {
492
- if (debugLogger) {
493
- try {
494
- debugLogger(label, data);
495
- } catch {
496
- }
497
- }
498
- }
499
- function loadSessionState(sessionId, homeDir = os2.homedir()) {
500
- if (!sessionId) return null;
501
- const filePath = getStateFile(sessionId, homeDir);
502
- try {
503
- if (!fs.existsSync(filePath)) return null;
504
- const raw = fs.readFileSync(filePath, "utf-8");
505
- const parsed = JSON.parse(raw);
506
- if (typeof parsed?.lastUserTimestamp !== "string" || typeof parsed?.lastReportedAt !== "string" || typeof parsed?.numTurnsAtLastReport !== "number") {
507
- return null;
508
- }
509
- return {
510
- lastUserTimestamp: parsed.lastUserTimestamp,
511
- lastReportedAt: parsed.lastReportedAt,
512
- numTurnsAtLastReport: parsed.numTurnsAtLastReport
513
- };
514
- } catch (err) {
515
- log("state-load-failed", {
516
- sessionId,
517
- error: err.message
518
- });
519
- return null;
520
- }
521
- }
522
- function saveSessionState(sessionId, state, homeDir = os2.homedir()) {
523
- if (!sessionId) return;
524
- const dir = getStateDir(homeDir);
525
- const filePath = getStateFile(sessionId, homeDir);
526
- try {
527
- if (!fs.existsSync(dir)) {
528
- fs.mkdirSync(dir, { recursive: true });
529
- }
530
- fs.writeFileSync(filePath, JSON.stringify(state, null, 2) + "\n", "utf-8");
531
- } catch (err) {
532
- log("state-save-failed", {
533
- sessionId,
534
- error: err.message
535
- });
536
- }
537
- }
538
- function shouldReportTurn(existing, currentUserTimestamp) {
539
- if (!currentUserTimestamp) return true;
540
- if (!existing) return true;
541
- return existing.lastUserTimestamp !== currentUserTimestamp;
542
- }
543
-
544
- // src/monitor/plugins/claude-code/install.ts
545
- import * as fs2 from "fs";
546
-
547
- // src/monitor/self-monitor-provision.ts
548
- import path3 from "path";
549
-
550
- // src/lib/git.ts
551
- import { spawnSync } from "child_process";
552
- function getGitConfigEmail() {
553
- let result;
554
- try {
555
- result = spawnSync("git", ["config", "--global", "user.email"], {
556
- encoding: "utf8",
557
- // Cap stdout. A normal `user.email` value is well under 320 bytes
558
- // (RFC 5321 max email length); 64KB leaves headroom for git config
559
- // wrappers that print a banner without ever truncating real
560
- // values. spawnSync sets `result.error` (ENOBUFS) on overflow
561
- // rather than truncating silently — we check it below.
562
- maxBuffer: 65536,
563
- // Don't pipe stderr to our process; we treat any error as "no email".
564
- stdio: ["ignore", "pipe", "ignore"]
565
- });
566
- } catch {
567
- return null;
568
- }
569
- if (result.error) return null;
570
- if (result.status !== 0) return null;
571
- const raw = (result.stdout || "").toString().trim();
572
- if (!raw) return null;
573
- const EMAIL_RE = /^[^\s@.]+(?:\.[^\s@.]+)*@[^\s@.]+(?:\.[^\s@.]+)*\.[a-zA-Z]{2,}$/;
574
- if (!EMAIL_RE.test(raw)) return null;
575
- if (raw.length > 320) return null;
576
- return raw;
577
- }
578
-
579
- // src/monitor/self-monitor-provision.ts
580
- async function provisionSelfMonitorAgent(opts) {
581
- const me = await getCurrentUser();
582
- const localPart = (me.email.split("@")[0] ?? "user").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
583
- const workspaceName = path3.basename(opts.projectRoot).toLowerCase();
584
- const defaultName = `${workspaceName}-${localPart}`;
585
- let existing = [];
586
- try {
587
- existing = await listMyAgents({
588
- source: opts.source,
589
- name: defaultName
590
- });
591
- } catch (err) {
592
- const message = err instanceof Error ? err.message : String(err);
593
- if (!message.includes("Failed to list your agents")) {
594
- }
595
- }
596
- if (existing.length > 0) {
597
- const found = existing[0];
598
- console.log(
599
- `
600
- Found your existing ${opts.displayName} agent "${found.name}".`
601
- );
602
- console.log(
603
- "Re-using it requires rotating its API key. Any other workspace currently using this agent will start failing on the next monitor request until it re-runs 'olakai monitor init'."
604
- );
605
- const ack = await promptUser("Rotate the API key and reuse? [y/N]: ");
606
- if (ack.trim().toLowerCase() !== "y") {
607
- console.error(
608
- "Cancelled. To use this workspace without affecting the other workspace, run 'olakai monitor init' again and pick a different agent name when prompted."
609
- );
610
- process.exit(1);
611
- }
612
- const rotated = await regenerateAgentApiKey(found.id);
613
- return {
614
- id: found.id,
615
- name: found.name,
616
- description: found.description,
617
- role: found.role,
618
- // `source` on the listMyAgents response is the AgentSource enum
619
- // string; the Agent type narrows it more loosely. Cast through
620
- // the shared union.
621
- source: found.source,
622
- apiKey: {
623
- id: rotated.id,
624
- key: rotated.key,
625
- keyMasked: rotated.keyMasked,
626
- isActive: rotated.isActive
627
- },
628
- workflowId: null,
629
- category: opts.category
630
- };
631
- }
632
- const nameInput = await promptUser(
633
- `Enter a descriptive name for this agent or accept the recommended name [${defaultName}]: `
634
- );
635
- const agentName = nameInput.trim() || defaultName;
636
- const vcsEmailHint = getGitConfigEmail() ?? void 0;
637
- try {
638
- return await createAgent({
639
- name: agentName,
640
- description: `${opts.displayName} local agent for ${agentName}`,
641
- role: "WORKER",
642
- createApiKey: true,
643
- source: opts.source,
644
- ...vcsEmailHint ? { vcsEmailHint } : {}
645
- });
646
- } catch (err) {
647
- const message = err instanceof Error ? err.message : String(err);
648
- if (message.toLowerCase().includes("already exists") || message.toLowerCase().includes("conflict")) {
649
- console.log(
650
- `
651
- An agent named "${agentName}" already exists on this account (created by someone else or an admin).`
652
- );
653
- const retry = await promptUser("Try a different name: ");
654
- if (!retry.trim()) {
655
- console.error("No name provided. Aborting.");
656
- process.exit(1);
657
- }
658
- return createAgent({
659
- name: retry.trim(),
660
- description: `${opts.displayName} local agent for ${retry.trim()}`,
661
- role: "WORKER",
662
- createApiKey: true,
663
- source: opts.source,
664
- ...vcsEmailHint ? { vcsEmailHint } : {}
665
- });
666
- }
667
- throw err;
668
- }
669
- }
670
-
671
- // src/monitor/plugins/claude-code/install.ts
672
- import path4 from "path";
673
- var CLAUDE_CODE_SOURCE = "claude-code";
674
- var CLAUDE_CODE_AGENT_SOURCE = "CLAUDE_CODE";
675
- var CLAUDE_CODE_AGENT_CATEGORY = "CODING";
676
- async function installClaudeCode(opts) {
677
- const projectRoot = opts.projectRoot ?? process.cwd();
678
- const token = getValidToken();
679
- if (!token) {
680
- console.error("Not logged in. Run 'olakai login' first.");
681
- process.exit(1);
682
- }
683
- console.log("Setting up Claude Code monitoring for this workspace...\n");
684
- const agent = await provisionSelfMonitorAgent({
685
- projectRoot,
686
- source: CLAUDE_CODE_AGENT_SOURCE,
687
- displayName: "Claude Code",
688
- category: CLAUDE_CODE_AGENT_CATEGORY
689
- });
690
- const monitoringEndpoint = `${getBaseUrl()}/api/monitoring/prompt`;
691
- const apiKey = agent.apiKey?.key;
692
- if (!apiKey) {
693
- console.error(
694
- "Internal error: agent provisioned but no API key returned. Please re-run 'olakai monitor init'."
695
- );
696
- process.exit(1);
697
- }
698
- const claudeDir = getClaudeDir(projectRoot);
699
- if (!fs2.existsSync(claudeDir)) {
700
- fs2.mkdirSync(claudeDir, { recursive: true });
701
- }
702
- const settingsPath = getSettingsPath(projectRoot);
703
- const existingSettings = readJsonFile(settingsPath) ?? {};
704
- const mergedHooks = mergeHooksSettings(existingSettings.hooks);
705
- const updatedSettings = {
706
- ...existingSettings,
707
- hooks: mergedHooks
708
- };
709
- writeJsonFile(settingsPath, updatedSettings);
710
- const monitorConfig = {
711
- agentId: agent.id,
712
- apiKey,
713
- agentName: agent.name,
714
- source: CLAUDE_CODE_SOURCE,
715
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
716
- monitoringEndpoint
717
- };
718
- writeClaudeCodeConfig(projectRoot, monitorConfig);
719
- const configPath = getClaudeCodeConfigPath(projectRoot);
720
- const configRel = path4.relative(projectRoot, configPath);
721
- console.log("");
722
- console.log(`\u2713 Agent "${agent.name}" configured (ID: ${agent.id})`);
723
- if (agent.apiKey?.key) {
724
- console.log("\u2713 API key generated");
725
- }
726
- console.log(
727
- `\u2713 Claude Code hooks configured in ${CLAUDE_DIR}/${SETTINGS_FILE}`
728
- );
729
- console.log(`\u2713 Monitor config saved to ${configRel}`);
730
- console.log("");
731
- console.log(
732
- "Congrats! Monitoring is now active. Claude Code will report activity to Olakai"
733
- );
734
- console.log(`on each turn.`);
735
- console.log("");
736
- console.log(
737
- `\u26A0 Ensure ${OLAKAI_DIR}/ is in your .gitignore (it contains your API key)`
738
- );
739
- console.log("");
740
- console.log("To check status: olakai monitor status --tool claude-code");
741
- console.log("To disable: olakai monitor disable --tool claude-code");
742
- return {
743
- agentId: agent.id,
744
- agentName: agent.name,
745
- source: CLAUDE_CODE_SOURCE,
746
- monitoringEndpoint
747
- };
748
- }
749
- async function uninstallClaudeCode(opts) {
750
- const projectRoot = opts.projectRoot ?? process.cwd();
751
- const settingsPath = getSettingsPath(projectRoot);
752
- const settings = readJsonFile(settingsPath);
753
- if (settings?.hooks) {
754
- const cleanedHooks = {};
755
- for (const [event, entries] of Object.entries(settings.hooks)) {
756
- const filtered = entries.filter(
757
- (e) => !e.hooks.some((h) => h.command.includes(OLAKAI_HOOK_MARKER))
758
- );
759
- if (filtered.length > 0) {
760
- cleanedHooks[event] = filtered;
761
- }
762
- }
763
- if (Object.keys(cleanedHooks).length > 0) {
764
- settings.hooks = cleanedHooks;
765
- } else {
766
- delete settings.hooks;
767
- }
768
- writeJsonFile(settingsPath, settings);
769
- console.log(`\u2713 Olakai hooks removed from ${CLAUDE_DIR}/${SETTINGS_FILE}`);
770
- } else {
771
- console.log("No hooks found in settings.json.");
772
- }
773
- if (!opts.keepConfig) {
774
- const configPath = getClaudeCodeConfigPath(projectRoot);
775
- const configRel = path4.relative(projectRoot, configPath);
776
- if (deleteClaudeCodeConfig(projectRoot)) {
777
- console.log(`\u2713 Monitor config removed (${configRel})`);
778
- }
779
- } else {
780
- const configPath = getClaudeCodeConfigPath(projectRoot);
781
- const configRel = path4.relative(projectRoot, configPath);
782
- console.log(`Monitor config retained at ${configRel}`);
783
- }
784
- console.log("");
785
- console.log(
786
- "Monitoring disabled. Run 'olakai monitor init --tool claude-code' to re-enable."
787
- );
788
- }
789
-
790
- // src/monitor/plugins/claude-code/hook.ts
791
- import * as fs3 from "fs";
792
-
793
- // src/commands/monitor-transcript.ts
794
- var FILE_EDITING_TOOL_NAMES = /* @__PURE__ */ new Set([
795
- "Edit",
796
- "Write",
797
- "MultiEdit"
798
- ]);
799
- var BASH_TOOL_NAME = "Bash";
800
- var SKILL_REGEX = /^\/([\w-]+)(?:\s|$)/;
801
- function detectSkill(userMessage) {
802
- if (typeof userMessage !== "string") return void 0;
803
- const trimmed = userMessage.trimStart();
804
- if (!trimmed) return void 0;
805
- const match = SKILL_REGEX.exec(trimmed);
806
- if (!match) return void 0;
807
- return match[1];
808
- }
809
- function extractTextContent(content) {
810
- if (typeof content === "string") return content;
811
- if (!Array.isArray(content)) return "";
812
- const parts = [];
813
- for (const block of content) {
814
- if (block?.type === "text" && typeof block.text === "string") {
815
- parts.push(block.text);
816
- }
817
- }
818
- return parts.join("\n").trim();
819
- }
820
- function isMetaUserMessage(line, text) {
821
- if (line.isMeta === true) return true;
822
- if (!text) return true;
823
- return text.includes("<command-name>") || text.includes("<local-command-caveat>") || text.includes("<command-message>");
824
- }
825
- function parseTimestamp(ts) {
826
- if (typeof ts !== "string" || !ts) return NaN;
827
- return Date.parse(ts);
828
- }
829
- function isCompactionEntry(line) {
830
- if (line.type !== "system") return false;
831
- const subtype = line.subtype ?? "";
832
- return subtype === "compact_boundary" || subtype === "pre_compact" || subtype === "post_compact" || /compact/i.test(subtype);
833
- }
834
- function parseTranscript(raw) {
835
- const empty = {
836
- prompt: "",
837
- response: "",
838
- tokens: 0,
839
- inputTokens: 0,
840
- outputTokens: 0,
841
- modelName: null,
842
- numTurns: 0,
843
- toolCallCount: 0,
844
- filesEditedCount: 0,
845
- bashCommandCount: 0
846
- };
847
- if (!raw) return empty;
848
- const lines = raw.split("\n");
849
- let lastUserText = "";
850
- let lastUserTimestamp = NaN;
851
- let lastUserTimestampRaw;
852
- let lastAssistantText = "";
853
- let lastAssistantTimestamp = NaN;
854
- let lastAssistantModel = null;
855
- let lastAssistantInputTokens = 0;
856
- let lastAssistantOutputTokens = 0;
857
- let numTurns = 0;
858
- let currentTurnUserTimestamp = NaN;
859
- let toolCallCount = 0;
860
- let bashCommandCount = 0;
861
- let editedFilePaths = /* @__PURE__ */ new Set();
862
- for (const rawLine of lines) {
863
- if (!rawLine) continue;
864
- let parsed;
865
- try {
866
- parsed = JSON.parse(rawLine);
867
- } catch {
868
- continue;
869
- }
870
- if (isCompactionEntry(parsed)) continue;
871
- if (parsed.isSidechain === true) continue;
872
- if (parsed.type === "user" && parsed.message) {
873
- const text = extractTextContent(parsed.message.content);
874
- if (isMetaUserMessage(parsed, text)) continue;
875
- lastUserText = text;
876
- lastUserTimestamp = parseTimestamp(parsed.timestamp);
877
- currentTurnUserTimestamp = lastUserTimestamp;
878
- toolCallCount = 0;
879
- bashCommandCount = 0;
880
- editedFilePaths = /* @__PURE__ */ new Set();
881
- lastUserTimestampRaw = typeof parsed.timestamp === "string" && parsed.timestamp ? parsed.timestamp : void 0;
882
- } else if (parsed.type === "assistant" && parsed.message) {
883
- const text = extractTextContent(parsed.message.content);
884
- numTurns += 1;
885
- if (text) lastAssistantText = text;
886
- if (typeof parsed.message.model === "string") {
887
- lastAssistantModel = parsed.message.model;
888
- }
889
- const content = parsed.message.content;
890
- if (Array.isArray(content)) {
891
- for (const block of content) {
892
- try {
893
- if (!block || block.type !== "tool_use") continue;
894
- toolCallCount += 1;
895
- const name = typeof block.name === "string" ? block.name : "";
896
- if (name === BASH_TOOL_NAME) {
897
- bashCommandCount += 1;
898
- continue;
899
- }
900
- if (FILE_EDITING_TOOL_NAMES.has(name)) {
901
- const input = block.input;
902
- if (input !== null && typeof input === "object" && "file_path" in input) {
903
- const filePath = input.file_path;
904
- if (typeof filePath === "string" && filePath) {
905
- editedFilePaths.add(filePath);
906
- }
907
- }
908
- }
909
- } catch {
910
- }
911
- }
912
- }
913
- const usage = parsed.message.usage;
914
- if (usage) {
915
- const input = (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0);
916
- const output = usage.output_tokens ?? 0;
917
- lastAssistantInputTokens = input;
918
- lastAssistantOutputTokens = output;
919
- }
920
- const ts = parseTimestamp(parsed.timestamp);
921
- if (!Number.isNaN(ts)) {
922
- lastAssistantTimestamp = ts;
923
- }
924
- }
925
- }
926
- const result = {
927
- prompt: lastUserText,
928
- response: lastAssistantText,
929
- tokens: lastAssistantInputTokens + lastAssistantOutputTokens,
930
- inputTokens: lastAssistantInputTokens,
931
- outputTokens: lastAssistantOutputTokens,
932
- modelName: lastAssistantModel,
933
- numTurns,
934
- toolCallCount,
935
- filesEditedCount: editedFilePaths.size,
936
- bashCommandCount
937
- };
938
- if (!Number.isNaN(currentTurnUserTimestamp) && !Number.isNaN(lastAssistantTimestamp) && lastAssistantTimestamp >= currentTurnUserTimestamp) {
939
- result.latencyMs = Math.round(
940
- lastAssistantTimestamp - currentTurnUserTimestamp
941
- );
942
- }
943
- const skill = detectSkill(lastUserText);
944
- if (skill) {
945
- result.skill = skill;
946
- }
947
- if (lastUserTimestampRaw) {
948
- result.userTurnTimestamp = lastUserTimestampRaw;
949
- }
950
- return result;
951
- }
952
-
953
- // src/monitor/plugins/claude-code/hook.ts
954
- var noopDebug = () => {
955
- };
956
- function extractFromTranscript(transcriptPath, debugLog4 = noopDebug) {
957
- const empty = {
958
- prompt: "",
959
- response: "",
960
- tokens: 0,
961
- inputTokens: 0,
962
- outputTokens: 0,
963
- modelName: null,
964
- numTurns: 0,
965
- toolCallCount: 0,
966
- filesEditedCount: 0,
967
- bashCommandCount: 0
968
- };
969
- if (!transcriptPath) return empty;
970
- let raw;
971
- try {
972
- raw = fs3.readFileSync(transcriptPath, "utf-8");
973
- } catch (err) {
974
- debugLog4("transcript-read-failed", {
975
- transcriptPath,
976
- error: err.message
977
- });
978
- return empty;
979
- }
980
- return parseTranscript(raw);
981
- }
982
- function extractSubagentName(event) {
983
- const candidates = [
984
- event.agent_name,
985
- event.subagent_type,
986
- event.agent_type,
987
- event.tool_input?.subagent_type
988
- ];
989
- for (const value of candidates) {
990
- if (typeof value === "string" && value.trim()) {
991
- return value.trim();
992
- }
993
- }
994
- return void 0;
995
- }
996
- function buildClaudeCodePayload(event, eventData, config) {
997
- const sessionId = eventData.session_id ?? `claude-code-${Date.now()}`;
998
- switch (event) {
999
- case "stop":
1000
- case "subagent-stop": {
1001
- const extracted = extractFromTranscript(eventData.transcript_path);
1002
- const isSubagent = event === "subagent-stop";
1003
- const customData = {
1004
- hookEvent: eventData.hook_event_name ?? (isSubagent ? "SubagentStop" : "Stop"),
1005
- sessionId,
1006
- transcriptPath: eventData.transcript_path ?? "",
1007
- cwd: eventData.cwd ?? "",
1008
- stopHookActive: eventData.stop_hook_active ?? false,
1009
- inputTokens: extracted.inputTokens,
1010
- outputTokens: extracted.outputTokens,
1011
- numTurns: extracted.numTurns,
1012
- // Per-turn work signals for the Claude Code classifier (D-027).
1013
- // Always emitted as JSON numbers — the backend classifier and
1014
- // KPI formulas must see numeric 0, not missing keys or strings.
1015
- toolCallCount: extracted.toolCallCount,
1016
- filesEditedCount: extracted.filesEditedCount,
1017
- bashCommandCount: extracted.bashCommandCount
1018
- };
1019
- if (typeof extracted.latencyMs === "number") {
1020
- customData.latencyMs = extracted.latencyMs;
1021
- }
1022
- if (isSubagent) {
1023
- const subagent = extractSubagentName(eventData);
1024
- if (subagent) {
1025
- customData.subagent = subagent;
1026
- }
1027
- } else if (extracted.skill) {
1028
- customData.skill = extracted.skill;
1029
- }
1030
- const payloadAssistant = eventData.last_assistant_message;
1031
- const response = typeof payloadAssistant === "string" && payloadAssistant.trim() ? payloadAssistant : extracted.response;
1032
- return {
1033
- prompt: extracted.prompt,
1034
- response,
1035
- chatId: sessionId,
1036
- source: config.source,
1037
- modelName: extracted.modelName ?? void 0,
1038
- tokens: extracted.tokens,
1039
- customData
1040
- };
1041
- }
1042
- default:
1043
- return null;
1044
- }
1045
- }
1046
-
1047
- // src/monitor/plugins/claude-code/index.ts
1048
- var TOOL_ID = "claude-code";
1049
- var SUPPORTED_HOOK_EVENTS = /* @__PURE__ */ new Set(["stop", "subagent-stop"]);
1050
- function debugLog(label, data) {
1051
- if (process.env.OLAKAI_MONITOR_DEBUG !== "1") return;
1052
- try {
1053
- const logPath = `/tmp/olakai-monitor-debug-${process.pid}.log`;
1054
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${label}: ${typeof data === "string" ? data : JSON.stringify(data, null, 2)}
1055
- `;
1056
- fs4.appendFileSync(logPath, line, "utf-8");
1057
- } catch {
1058
- }
1059
- }
1060
- function resolveProjectRootFromPayload(eventData, fallbackCwd) {
1061
- const payloadCwd = typeof eventData.cwd === "string" && eventData.cwd.trim() ? eventData.cwd : fallbackCwd;
1062
- return findConfiguredWorkspace(payloadCwd, [TOOL_ID]);
1063
- }
1064
- var claudeCodePlugin = {
1065
- id: TOOL_ID,
1066
- displayName: "Claude Code",
1067
- install(opts) {
1068
- return installClaudeCode(opts);
1069
- },
1070
- uninstall(opts) {
1071
- return uninstallClaudeCode(opts);
1072
- },
1073
- status(opts) {
1074
- return getClaudeCodeStatus(opts);
1075
- },
1076
- async handleHook(eventName, payloadJson) {
1077
- setDebugLogger(debugLog);
1078
- const event = eventName.trim();
1079
- if (!SUPPORTED_HOOK_EVENTS.has(event)) {
1080
- debugLog("hook-unknown-event", event);
1081
- return null;
1082
- }
1083
- const eventData = payloadJson ?? {};
1084
- debugLog("event-parsed", { event, eventData });
1085
- const projectRoot = resolveProjectRootFromPayload(
1086
- eventData,
1087
- process.cwd()
1088
- );
1089
- if (!projectRoot) {
1090
- debugLog("config-not-found", {
1091
- startDir: typeof eventData.cwd === "string" && eventData.cwd.trim() ? eventData.cwd : process.cwd()
1092
- });
1093
- return null;
1094
- }
1095
- const config = loadClaudeCodeConfig(projectRoot, () => {
1096
- });
1097
- if (!config) {
1098
- debugLog("config-load-failed", { projectRoot });
1099
- return null;
1100
- }
1101
- const payload = buildClaudeCodePayload(event, eventData, config);
1102
- if (!payload) return null;
1103
- debugLog("payload-built", payload);
1104
- const sessionId = typeof eventData.session_id === "string" && eventData.session_id || void 0;
1105
- const extracted = extractFromTranscript(
1106
- eventData.transcript_path,
1107
- debugLog
1108
- );
1109
- const userTurnTimestamp = extracted.userTurnTimestamp;
1110
- if (extracted.prompt.trim() === "" && extracted.response.trim() === "" && extracted.numTurns === 0) {
1111
- debugLog("empty-parse-skip", {
1112
- event,
1113
- sessionId,
1114
- transcriptPath: eventData.transcript_path
1115
- });
1116
- return null;
1117
- }
1118
- if (sessionId) {
1119
- const existingState = loadSessionState(sessionId);
1120
- if (!shouldReportTurn(existingState, userTurnTimestamp)) {
1121
- debugLog("turn-dedup-skip", { sessionId, userTurnTimestamp });
1122
- return null;
1123
- }
1124
- }
1125
- if (sessionId && userTurnTimestamp) {
1126
- saveSessionState(sessionId, {
1127
- lastUserTimestamp: userTurnTimestamp,
1128
- lastReportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1129
- numTurnsAtLastReport: extracted.numTurns
1130
- });
1131
- debugLog("state-saved", {
1132
- sessionId,
1133
- userTurnTimestamp,
1134
- numTurns: extracted.numTurns
1135
- });
1136
- }
1137
- return {
1138
- payload,
1139
- transport: {
1140
- endpoint: config.monitoringEndpoint,
1141
- apiKey: config.apiKey,
1142
- projectRoot
1143
- }
1144
- };
1145
- },
1146
- async detectInstalled(opts) {
1147
- const projectRoot = opts?.projectRoot ?? process.cwd();
1148
- try {
1149
- if (fs4.existsSync(getMonitorConfigPath(projectRoot, TOOL_ID))) {
1150
- return true;
1151
- }
1152
- if (fs4.existsSync(getLegacyClaudeMonitorConfigPath(projectRoot))) {
1153
- return true;
1154
- }
1155
- } catch {
1156
- }
1157
- return detectClaudeBinaryOnPath();
1158
- }
1159
- };
1160
- function detectClaudeBinaryOnPath() {
1161
- try {
1162
- const probe = spawnSync2(
1163
- process.platform === "win32" ? "where" : "which",
1164
- ["claude"],
1165
- {
1166
- stdio: ["ignore", "pipe", "ignore"],
1167
- timeout: 1e3
1168
- }
1169
- );
1170
- if (probe.status === 0 && probe.stdout && probe.stdout.toString().trim()) {
1171
- return true;
1172
- }
1173
- } catch {
1174
- }
1175
- return false;
1176
- }
1177
- registerPlugin(claudeCodePlugin);
1178
-
1179
- // src/monitor/plugins/codex/index.ts
1180
- import * as fs9 from "fs";
1181
- import { spawnSync as spawnSync3 } from "child_process";
1182
-
1183
- // src/monitor/plugins/codex/install.ts
1184
- import * as fs6 from "fs";
1185
- import * as path6 from "path";
1186
- import * as TOML from "@iarna/toml";
1187
-
1188
- // src/monitor/plugins/codex/hooks.ts
1189
- var OLAKAI_HOOK_MARKER2 = "olakai monitor hook";
1190
- var CODEX_HOOK_TIMEOUT_SECONDS = 5;
1191
- var SUPPORTED_HOOK_EVENT_NAMES = ["Stop"];
1192
- function buildOlakaiHookGroup(event) {
1193
- return {
1194
- hooks: [
1195
- {
1196
- type: "command",
1197
- command: `olakai monitor hook --tool codex ${event}`,
1198
- timeout: CODEX_HOOK_TIMEOUT_SECONDS
1199
- }
1200
- ]
1201
- };
1202
- }
1203
- function isOlakaiHandler(handler) {
1204
- return typeof handler.command === "string" && handler.command.includes(OLAKAI_HOOK_MARKER2);
1205
- }
1206
- function groupContainsOlakaiHandler(group) {
1207
- if (!Array.isArray(group.hooks)) return false;
1208
- return group.hooks.some(isOlakaiHandler);
1209
- }
1210
- function mergeCodexHooks(existing, events = SUPPORTED_HOOK_EVENT_NAMES) {
1211
- const merged = { ...existing ?? {} };
1212
- for (const event of events) {
1213
- const existingGroups = merged[event] ?? [];
1214
- const hasOlakaiHook = existingGroups.some(groupContainsOlakaiHandler);
1215
- if (hasOlakaiHook) {
1216
- merged[event] = existingGroups;
1217
- } else {
1218
- merged[event] = [...existingGroups, buildOlakaiHookGroup(event)];
1219
- }
1220
- }
1221
- return merged;
1222
- }
1223
- function stripOlakaiHooks(existing) {
1224
- if (!existing) return void 0;
1225
- const cleaned = {};
1226
- for (const [event, groups] of Object.entries(existing)) {
1227
- if (!Array.isArray(groups)) continue;
1228
- const filteredGroups = [];
1229
- for (const group of groups) {
1230
- const handlers = Array.isArray(group.hooks) ? group.hooks : [];
1231
- const remaining = handlers.filter((h) => !isOlakaiHandler(h));
1232
- if (remaining.length === 0 && handlers.length > 0) {
1233
- continue;
1234
- }
1235
- if (remaining.length === handlers.length) {
1236
- filteredGroups.push(group);
1237
- } else {
1238
- filteredGroups.push({ ...group, hooks: remaining });
1239
- }
1240
- }
1241
- if (filteredGroups.length > 0) {
1242
- cleaned[event] = filteredGroups;
1243
- }
1244
- }
1245
- return Object.keys(cleaned).length > 0 ? cleaned : void 0;
1246
- }
1247
- function hasOlakaiHooksInstalled(parsed) {
1248
- const hooks = parsed.hooks;
1249
- if (!hooks) return false;
1250
- for (const groups of Object.values(hooks)) {
1251
- if (!Array.isArray(groups)) continue;
1252
- for (const group of groups) {
1253
- if (groupContainsOlakaiHandler(group)) return true;
1254
- }
1255
- }
1256
- return false;
1257
- }
1258
-
1259
- // src/monitor/plugins/codex/config.ts
1260
- import * as fs5 from "fs";
1261
- import * as path5 from "path";
1262
- function getCodexConfigPath2(projectRoot) {
1263
- return getMonitorConfigPath(projectRoot, "codex");
1264
- }
1265
- function loadCodexConfig(projectRoot) {
1266
- const filePath = getCodexConfigPath2(projectRoot);
1267
- try {
1268
- if (!fs5.existsSync(filePath)) return null;
1269
- const raw = fs5.readFileSync(filePath, "utf-8");
1270
- return JSON.parse(raw);
1271
- } catch {
1272
- return null;
1273
- }
1274
- }
1275
- function writeCodexConfig(projectRoot, config) {
1276
- const filePath = getCodexConfigPath2(projectRoot);
1277
- const dir = path5.dirname(filePath);
1278
- if (!fs5.existsSync(dir)) {
1279
- fs5.mkdirSync(dir, { recursive: true });
1280
- }
1281
- fs5.writeFileSync(filePath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1282
- try {
1283
- fs5.chmodSync(filePath, 384);
1284
- } catch {
1285
- }
1286
- }
1287
- function deleteCodexConfig(projectRoot) {
1288
- const filePath = getCodexConfigPath2(projectRoot);
1289
- if (!fs5.existsSync(filePath)) return false;
1290
- try {
1291
- fs5.unlinkSync(filePath);
1292
- return true;
1293
- } catch {
1294
- return false;
1295
- }
1296
- }
1297
-
1298
- // src/monitor/plugins/codex/install.ts
1299
- var CODEX_SOURCE = "codex";
1300
- var CODEX_AGENT_SOURCE = "CODEX";
1301
- var CODEX_AGENT_CATEGORY = "CODING";
1302
- async function installCodex(opts) {
1303
- const projectRoot = opts.projectRoot ?? process.cwd();
1304
- const token = getValidToken();
1305
- if (!token) {
1306
- console.error("Not logged in. Run 'olakai login' first.");
1307
- process.exit(1);
1308
- }
1309
- console.log("Setting up Codex CLI monitoring for this workspace...\n");
1310
- const agent = await provisionSelfMonitorAgent({
1311
- projectRoot,
1312
- source: CODEX_AGENT_SOURCE,
1313
- displayName: "Codex CLI",
1314
- category: CODEX_AGENT_CATEGORY
1315
- });
1316
- const monitoringEndpoint = `${getBaseUrl()}/api/monitoring/prompt`;
1317
- const apiKey = agent.apiKey?.key;
1318
- if (!apiKey) {
1319
- console.error(
1320
- "Internal error: agent provisioned but no API key returned. Please re-run 'olakai monitor init'."
1321
- );
1322
- process.exit(1);
1323
- }
1324
- const { configExisted: codexConfigExisted } = installCodexHooksConfig();
1325
- const monitorConfig = {
1326
- agentId: agent.id,
1327
- apiKey,
1328
- agentName: agent.name,
1329
- source: CODEX_SOURCE,
1330
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1331
- monitoringEndpoint
1332
- };
1333
- writeCodexConfig(projectRoot, monitorConfig);
1334
- const configPath = getCodexConfigPath2(projectRoot);
1335
- const configRel = path6.relative(projectRoot, configPath);
1336
- console.log("");
1337
- console.log(`\u2713 Agent "${agent.name}" configured (ID: ${agent.id})`);
1338
- if (agent.apiKey?.key) {
1339
- console.log("\u2713 API key generated");
1340
- }
1341
- console.log(
1342
- `\u2713 Codex hooks configured in ~/${CODEX_HOME_DIRNAME}/${CODEX_CONFIG_FILENAME}`
1343
- );
1344
- console.log(`\u2713 Monitor config saved to ${configRel}`);
1345
- console.log("");
1346
- console.log(
1347
- "Congrats! Monitoring is now active. Codex CLI will report activity to Olakai"
1348
- );
1349
- console.log(`on each turn.`);
1350
- console.log("");
1351
- console.log(
1352
- `\u26A0 Ensure ${OLAKAI_DIR}/ is in your .gitignore (it contains your API key).`
1353
- );
1354
- console.log(
1355
- `\u26A0 Codex hooks require codex >= 0.124.0. Earlier versions silently skip them.`
1356
- );
1357
- if (codexConfigExisted) {
1358
- console.log(
1359
- `\u26A0 Existing comments in ~/${CODEX_HOME_DIRNAME}/${CODEX_CONFIG_FILENAME} were not preserved (TOML serializer limitation).`
1360
- );
1361
- }
1362
- console.log("");
1363
- console.log("To check status: olakai monitor status --tool codex");
1364
- console.log("To disable: olakai monitor disable --tool codex");
1365
- return {
1366
- agentId: agent.id,
1367
- agentName: agent.name,
1368
- source: CODEX_SOURCE,
1369
- monitoringEndpoint
1370
- };
1371
- }
1372
- function installCodexHooksConfig() {
1373
- const homeDir = getCodexHomeDir();
1374
- const configPath = getCodexConfigPath();
1375
- if (!fs6.existsSync(homeDir)) {
1376
- fs6.mkdirSync(homeDir, { recursive: true });
1377
- }
1378
- const configExisted = fs6.existsSync(configPath);
1379
- const parsed = readCodexConfigToml(configPath);
1380
- const merged = {
1381
- ...parsed,
1382
- hooks: mergeCodexHooks(parsed.hooks, SUPPORTED_HOOK_EVENT_NAMES)
1383
- };
1384
- writeCodexConfigToml(configPath, merged);
1385
- return { configExisted };
1386
- }
1387
- async function uninstallCodex(opts) {
1388
- const projectRoot = opts.projectRoot ?? process.cwd();
1389
- const removedHooks = stripCodexHooksConfig();
1390
- if (removedHooks) {
1391
- console.log(
1392
- `\u2713 Olakai hooks removed from ~/${CODEX_HOME_DIRNAME}/${CODEX_CONFIG_FILENAME}`
1393
- );
1394
- } else {
1395
- console.log("No Olakai hooks found in Codex config.");
1396
- }
1397
- if (!opts.keepConfig) {
1398
- const configPath = getCodexConfigPath2(projectRoot);
1399
- const configRel = path6.relative(projectRoot, configPath);
1400
- if (deleteCodexConfig(projectRoot)) {
1401
- console.log(`\u2713 Monitor config removed (${configRel})`);
1402
- }
1403
- } else {
1404
- const configPath = getCodexConfigPath2(projectRoot);
1405
- const configRel = path6.relative(projectRoot, configPath);
1406
- console.log(`Monitor config retained at ${configRel}`);
1407
- }
1408
- console.log("");
1409
- console.log(
1410
- "Monitoring disabled. Run 'olakai monitor init --tool codex' to re-enable."
1411
- );
1412
- }
1413
- function applyOlakaiStripToConfig(parsed) {
1414
- const cleaned = stripOlakaiHooks(parsed.hooks);
1415
- const next = { ...parsed };
1416
- if (cleaned === void 0) {
1417
- delete next.hooks;
1418
- } else {
1419
- next.hooks = cleaned;
1420
- }
1421
- return next;
1422
- }
1423
- function stripCodexHooksConfig() {
1424
- const configPath = getCodexConfigPath();
1425
- if (!fs6.existsSync(configPath)) return false;
1426
- const parsed = readCodexConfigToml(configPath);
1427
- if (!hasOlakaiHooksInstalled(parsed)) return false;
1428
- const next = applyOlakaiStripToConfig(parsed);
1429
- writeCodexConfigToml(configPath, next);
1430
- return true;
1431
- }
1432
- function readCodexConfigToml(configPath) {
1433
- try {
1434
- if (!fs6.existsSync(configPath)) return {};
1435
- const raw = fs6.readFileSync(configPath, "utf-8");
1436
- if (!raw.trim()) return {};
1437
- return TOML.parse(raw);
1438
- } catch {
1439
- return {};
1440
- }
1441
- }
1442
- function writeCodexConfigToml(configPath, data) {
1443
- const dir = path6.dirname(configPath);
1444
- if (!fs6.existsSync(dir)) {
1445
- fs6.mkdirSync(dir, { recursive: true });
1446
- }
1447
- const serialized = TOML.stringify(data);
1448
- fs6.writeFileSync(configPath, serialized, "utf-8");
1449
- }
1450
-
1451
- // src/monitor/plugins/codex/status.ts
1452
- import path7 from "path";
1453
- import * as fs7 from "fs";
1454
- async function getCodexStatus(opts) {
1455
- const projectRoot = opts?.projectRoot ?? process.cwd();
1456
- const configPath = getCodexConfigPath2(projectRoot);
1457
- const config = loadCodexConfig(projectRoot);
1458
- const hooksConfigured = isHooksBlockInstalled();
1459
- if (!config) {
1460
- return {
1461
- toolId: "codex",
1462
- configured: false,
1463
- hooksConfigured,
1464
- configPath,
1465
- notes: hooksConfigured ? [
1466
- `Codex hooks present in ~/${CODEX_HOME_DIRNAME}/${CODEX_CONFIG_FILENAME} but no monitor config in this workspace \u2014 re-run init.`
1467
- ] : []
1468
- };
1469
- }
1470
- return {
1471
- toolId: "codex",
1472
- configured: true,
1473
- hooksConfigured,
1474
- agentId: config.agentId,
1475
- agentName: config.agentName,
1476
- source: config.source,
1477
- apiKeyMasked: config.apiKey.slice(0, 12) + "...",
1478
- monitoringEndpoint: config.monitoringEndpoint,
1479
- configuredAt: config.createdAt,
1480
- configPath
1481
- };
1482
- }
1483
- function isHooksBlockInstalled() {
1484
- const homeConfig = getCodexConfigPath();
1485
- if (!fs7.existsSync(homeConfig)) return false;
1486
- const parsed = readCodexConfigToml(homeConfig);
1487
- return hasOlakaiHooksInstalled(parsed);
1488
- }
1489
-
1490
- // src/monitor/plugins/codex/transcript.ts
1491
- import * as fs8 from "fs";
1492
- import * as path8 from "path";
1493
- function emptyRollout() {
1494
- return {
1495
- prompt: "",
1496
- response: "",
1497
- modelName: null,
1498
- inputTokens: 0,
1499
- outputTokens: 0,
1500
- cachedInputTokens: 0,
1501
- reasoningOutputTokens: 0,
1502
- tokens: 0,
1503
- numTurns: 0
1504
- };
1505
- }
1506
- var noopDebug2 = () => {
1507
- };
1508
- var DEFAULT_LIMITS = {
1509
- maxDirs: 200,
1510
- maxFiles: 5e3
1511
- };
1512
- function findRolloutPathForSession(sessionId, sessionsDir = getCodexSessionsDir(), limits = {}) {
1513
- const merged = { ...DEFAULT_LIMITS, ...limits };
1514
- if (!sessionId) return null;
1515
- if (!fs8.existsSync(sessionsDir)) return null;
1516
- const suffix = `-${sessionId}.jsonl`;
1517
- const matches = [];
1518
- let dirsScanned = 0;
1519
- let filesScanned = 0;
1520
- const queue = [sessionsDir];
1521
- while (queue.length > 0) {
1522
- const dir = queue.shift();
1523
- if (dirsScanned++ > merged.maxDirs) break;
1524
- let entries;
1525
- try {
1526
- entries = fs8.readdirSync(dir, { withFileTypes: true });
1527
- } catch {
1528
- continue;
1529
- }
1530
- for (const entry of entries) {
1531
- if (filesScanned++ > merged.maxFiles) break;
1532
- const full = path8.join(dir, entry.name);
1533
- if (entry.isDirectory()) {
1534
- queue.push(full);
1535
- continue;
1536
- }
1537
- if (!entry.isFile()) continue;
1538
- if (!entry.name.endsWith(suffix)) continue;
1539
- if (!entry.name.startsWith("rollout-")) continue;
1540
- try {
1541
- const stat = fs8.statSync(full);
1542
- matches.push({ path: full, mtimeMs: stat.mtimeMs });
1543
- } catch {
1544
- }
1545
- }
1546
- }
1547
- if (matches.length === 0) return null;
1548
- matches.sort((a, b) => b.mtimeMs - a.mtimeMs);
1549
- return matches[0].path;
1550
- }
1551
- function parseRolloutContent(raw, debugLog4 = noopDebug2) {
1552
- const result = emptyRollout();
1553
- if (!raw) return result;
1554
- const lines = raw.split("\n");
1555
- let lastUserMessage = "";
1556
- let lastAssistantMessage = "";
1557
- let lastTokenUsage = null;
1558
- let totalTokenUsage = null;
1559
- let modelName = null;
1560
- let userTurnCount = 0;
1561
- for (const line of lines) {
1562
- const trimmed = line.trim();
1563
- if (!trimmed) continue;
1564
- let parsed;
1565
- try {
1566
- parsed = JSON.parse(trimmed);
1567
- } catch (err) {
1568
- debugLog4("rollout-line-parse-failed", {
1569
- line: trimmed.slice(0, 120),
1570
- error: err.message
1571
- });
1572
- continue;
1573
- }
1574
- const type = parsed.type;
1575
- const payload = parsed.payload;
1576
- if (!type || !payload) continue;
1577
- if (type === "session_meta") {
1578
- continue;
1579
- }
1580
- if (type === "event_msg") {
1581
- const ev = payload;
1582
- const evType = ev.type;
1583
- if (evType === "user_message" && typeof ev.message === "string") {
1584
- lastUserMessage = ev.message;
1585
- userTurnCount += 1;
1586
- } else if (evType === "agent_message" && typeof ev.message === "string") {
1587
- lastAssistantMessage = ev.message;
1588
- } else if (evType === "token_count" && ev.info) {
1589
- if (ev.info.last_token_usage) {
1590
- lastTokenUsage = ev.info.last_token_usage;
1591
- }
1592
- if (ev.info.total_token_usage) {
1593
- totalTokenUsage = ev.info.total_token_usage;
1594
- }
1595
- } else if (evType === "session_configured" && typeof ev.model === "string" && ev.model) {
1596
- modelName = ev.model;
1597
- }
1598
- continue;
1599
- }
1600
- if (type === "response_item") {
1601
- const ri = payload;
1602
- if (ri.type === "message" && Array.isArray(ri.content)) {
1603
- const text = extractTextFromContent(ri.content);
1604
- if (!text) continue;
1605
- if (ri.role === "user") {
1606
- lastUserMessage = text;
1607
- userTurnCount += 1;
1608
- } else if (ri.role === "assistant") {
1609
- lastAssistantMessage = text;
1610
- }
1611
- }
1612
- continue;
1613
- }
1614
- }
1615
- result.prompt = lastUserMessage;
1616
- result.response = lastAssistantMessage;
1617
- result.modelName = modelName;
1618
- result.numTurns = userTurnCount;
1619
- const tokenSource = lastTokenUsage ?? totalTokenUsage;
1620
- if (tokenSource) {
1621
- result.inputTokens = numberOrZero(tokenSource.input_tokens);
1622
- result.outputTokens = numberOrZero(tokenSource.output_tokens);
1623
- result.cachedInputTokens = numberOrZero(tokenSource.cached_input_tokens);
1624
- result.reasoningOutputTokens = numberOrZero(
1625
- tokenSource.reasoning_output_tokens
1626
- );
1627
- result.tokens = numberOrZero(tokenSource.total_tokens) || result.inputTokens + result.outputTokens;
1628
- }
1629
- return result;
1630
- }
1631
- function extractTextFromContent(content) {
1632
- const parts = [];
1633
- for (const block of content) {
1634
- if (typeof block.text !== "string") continue;
1635
- if (block.type === "output_text" || block.type === "input_text" || block.type === "text") {
1636
- parts.push(block.text);
1637
- }
1638
- }
1639
- return parts.join("\n").trim();
1640
- }
1641
- function numberOrZero(value) {
1642
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
1643
- }
1644
- function loadRolloutForSession(sessionId, options = {}) {
1645
- const debugLog4 = options.debugLog ?? noopDebug2;
1646
- const sessionsDir = options.sessionsDir ?? getCodexSessionsDir();
1647
- const result = emptyRollout();
1648
- const rolloutPath = findRolloutPathForSession(sessionId, sessionsDir);
1649
- if (!rolloutPath) {
1650
- debugLog4("rollout-not-found", {
1651
- sessionId,
1652
- sessionsDir
1653
- });
1654
- return result;
1655
- }
1656
- let raw;
1657
- try {
1658
- raw = fs8.readFileSync(rolloutPath, "utf-8");
1659
- } catch (err) {
1660
- debugLog4("rollout-read-failed", {
1661
- rolloutPath,
1662
- error: err.message
1663
- });
1664
- return result;
1665
- }
1666
- const parsed = parseRolloutContent(raw, debugLog4);
1667
- parsed.rolloutPath = rolloutPath;
1668
- return parsed;
1669
- }
1670
-
1671
- // src/monitor/plugins/codex/hook.ts
1672
- var noopDebug3 = () => {
1673
- };
1674
- var SUPPORTED_EVENTS = /* @__PURE__ */ new Set(["Stop", "UserPromptSubmit"]);
1675
- function isSupportedCodexEvent(eventName) {
1676
- return SUPPORTED_EVENTS.has(eventName);
1677
- }
1678
- function buildCodexPayload(eventName, eventData, config, rollout = emptyRollout()) {
1679
- if (!isSupportedCodexEvent(eventName)) return null;
1680
- if (eventName === "UserPromptSubmit") return null;
1681
- const sessionId = typeof eventData.session_id === "string" && eventData.session_id ? eventData.session_id : `codex-${Date.now()}`;
1682
- const cwd = typeof eventData.cwd === "string" ? eventData.cwd : "";
1683
- const turnId = typeof eventData.turn_id === "string" ? eventData.turn_id : "";
1684
- const permissionMode = typeof eventData.permission_mode === "string" ? eventData.permission_mode : "";
1685
- const transcriptPath = typeof eventData.transcript_path === "string" ? eventData.transcript_path : "";
1686
- const modelName = (typeof eventData.model === "string" && eventData.model.trim() ? eventData.model : null) ?? rollout.modelName;
1687
- const customData = {
1688
- hookEvent: eventData.hook_event_name ?? eventName,
1689
- sessionId,
1690
- cwd,
1691
- turnId,
1692
- permissionMode,
1693
- transcriptPath,
1694
- inputTokens: rollout.inputTokens,
1695
- outputTokens: rollout.outputTokens,
1696
- cachedInputTokens: rollout.cachedInputTokens,
1697
- reasoningOutputTokens: rollout.reasoningOutputTokens,
1698
- numTurns: rollout.numTurns
1699
- };
1700
- if (rollout.rolloutPath) {
1701
- customData.rolloutPath = rollout.rolloutPath;
1702
- }
1703
- if (typeof eventData.stop_hook_active === "boolean") {
1704
- customData.stopHookActive = eventData.stop_hook_active;
1705
- }
1706
- const inlineAssistant = typeof eventData.last_assistant_message === "string" && eventData.last_assistant_message.trim() ? eventData.last_assistant_message : "";
1707
- const response = inlineAssistant || rollout.response;
1708
- return {
1709
- prompt: rollout.prompt,
1710
- response,
1711
- chatId: sessionId,
1712
- source: config.source,
1713
- modelName: modelName ?? void 0,
1714
- tokens: rollout.tokens,
1715
- customData
1716
- };
1717
- }
1718
- function handleCodexHook(eventName, payloadJson, config, options = {}) {
1719
- const debugLog4 = options.debugLog ?? noopDebug3;
1720
- if (!isSupportedCodexEvent(eventName)) {
1721
- debugLog4("hook-unknown-event", eventName);
1722
- return null;
1723
- }
1724
- if (eventName === "UserPromptSubmit") {
1725
- debugLog4("user-prompt-submit-dropped", { eventName });
1726
- return null;
1727
- }
1728
- const eventData = payloadJson ?? {};
1729
- debugLog4("event-parsed", { eventName, eventData });
1730
- const sessionId = typeof eventData.session_id === "string" ? eventData.session_id : "";
1731
- let rollout = emptyRollout();
1732
- if (eventName === "Stop" && sessionId) {
1733
- rollout = loadRolloutForSession(sessionId, {
1734
- debugLog: debugLog4,
1735
- sessionsDir: options.sessionsDir
1736
- });
1737
- }
1738
- const payload = buildCodexPayload(eventName, eventData, config, rollout);
1739
- if (!payload) return null;
1740
- if (!payload.prompt && !payload.response) {
1741
- debugLog4("payload-empty", { eventName, sessionId });
1742
- return null;
1743
- }
1744
- debugLog4("payload-built", payload);
1745
- return payload;
1746
- }
1747
-
1748
- // src/monitor/plugins/codex/index.ts
1749
- var TOOL_ID2 = "codex";
1750
- function debugLog2(label, data) {
1751
- if (process.env.OLAKAI_MONITOR_DEBUG !== "1") return;
1752
- try {
1753
- const logPath = `/tmp/olakai-monitor-debug-${process.pid}.log`;
1754
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] codex/${label}: ${typeof data === "string" ? data : JSON.stringify(data, null, 2)}
1755
- `;
1756
- fs9.appendFileSync(logPath, line, "utf-8");
1757
- } catch {
1758
- }
1759
- }
1760
- function resolveCodexProjectRoot(eventData, fallbackCwd) {
1761
- const payloadCwd = typeof eventData.cwd === "string" && eventData.cwd.trim() ? eventData.cwd : fallbackCwd;
1762
- return findConfiguredWorkspace(payloadCwd, [TOOL_ID2]);
1763
- }
1764
- var codexPlugin = {
1765
- id: TOOL_ID2,
1766
- displayName: "OpenAI Codex CLI",
1767
- install(opts) {
1768
- return installCodex(opts);
1769
- },
1770
- uninstall(opts) {
1771
- return uninstallCodex(opts);
1772
- },
1773
- status(opts) {
1774
- return getCodexStatus(opts);
1775
- },
1776
- async handleHook(eventName, payloadJson) {
1777
- const eventData = payloadJson ?? {};
1778
- debugLog2("hook-fired", { eventName, hasPayload: payloadJson != null });
1779
- const projectRoot = resolveCodexProjectRoot(eventData, process.cwd());
1780
- if (!projectRoot) {
1781
- debugLog2("config-not-found", {
1782
- startDir: typeof eventData.cwd === "string" && eventData.cwd.trim() ? eventData.cwd : process.cwd()
1783
- });
1784
- return null;
1785
- }
1786
- const config = loadCodexConfig(projectRoot);
1787
- if (!config) {
1788
- debugLog2("monitor-config-missing", { projectRoot });
1789
- return null;
1790
- }
1791
- const payload = handleCodexHook(eventName, eventData, config, {
1792
- debugLog: debugLog2
1793
- });
1794
- if (!payload) return null;
1795
- return {
1796
- payload,
1797
- transport: {
1798
- endpoint: config.monitoringEndpoint,
1799
- apiKey: config.apiKey,
1800
- projectRoot
1801
- }
1802
- };
1803
- },
1804
- async detectInstalled(opts) {
1805
- const projectRoot = opts?.projectRoot ?? process.cwd();
1806
- try {
1807
- if (fs9.existsSync(getCodexConfigPath2(projectRoot))) {
1808
- return true;
1809
- }
1810
- } catch {
1811
- }
1812
- try {
1813
- if (fs9.existsSync(getCodexConfigPath())) {
1814
- return true;
1815
- }
1816
- if (fs9.existsSync(getCodexHomeDir())) {
1817
- return true;
1818
- }
1819
- } catch {
1820
- }
1821
- return detectCodexBinaryOnPath();
1822
- }
1823
- };
1824
- function detectCodexBinaryOnPath() {
1825
- try {
1826
- const probe = spawnSync3(
1827
- process.platform === "win32" ? "where" : "which",
1828
- ["codex"],
1829
- {
1830
- stdio: ["ignore", "pipe", "ignore"],
1831
- timeout: 1e3
1832
- }
1833
- );
1834
- if (probe.status === 0 && probe.stdout && probe.stdout.toString().trim()) {
1835
- return true;
1836
- }
1837
- } catch {
1838
- }
1839
- return false;
1840
- }
1841
- registerPlugin(codexPlugin);
1842
-
1843
- // src/monitor/plugins/cursor/index.ts
1844
- import * as fs14 from "fs";
1845
- import * as os7 from "os";
1846
-
1847
- // src/monitor/plugins/cursor/install.ts
1848
- import * as fs11 from "fs";
1849
- import * as os4 from "os";
1850
- import * as path11 from "path";
1851
-
1852
- // src/monitor/plugins/cursor/config.ts
1853
- import * as fs10 from "fs";
1854
- import * as path9 from "path";
1855
- function getCursorConfigPath(projectRoot) {
1856
- return getMonitorConfigPath(projectRoot, "cursor");
1857
- }
1858
- function loadCursorConfig(projectRoot) {
1859
- const filePath = getCursorConfigPath(projectRoot);
1860
- try {
1861
- if (!fs10.existsSync(filePath)) return null;
1862
- const raw = fs10.readFileSync(filePath, "utf-8");
1863
- return JSON.parse(raw);
1864
- } catch {
1865
- return null;
1866
- }
1867
- }
1868
- function writeCursorConfig(projectRoot, config) {
1869
- const filePath = getCursorConfigPath(projectRoot);
1870
- const dir = path9.dirname(filePath);
1871
- if (!fs10.existsSync(dir)) {
1872
- fs10.mkdirSync(dir, { recursive: true });
1873
- }
1874
- fs10.writeFileSync(filePath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1875
- try {
1876
- fs10.chmodSync(filePath, 384);
1877
- } catch {
1878
- }
1879
- }
1880
- function deleteCursorConfig(projectRoot) {
1881
- const filePath = getCursorConfigPath(projectRoot);
1882
- if (!fs10.existsSync(filePath)) return false;
1883
- try {
1884
- fs10.unlinkSync(filePath);
1885
- return true;
1886
- } catch {
1887
- return false;
1888
- }
1889
- }
1890
-
1891
- // src/monitor/plugins/cursor/paths.ts
1892
- import * as os3 from "os";
1893
- import * as path10 from "path";
1894
- var CURSOR_DIR_NAME = ".cursor";
1895
- var CURSOR_HOOKS_FILE = "hooks.json";
1896
- function getCursorUserDir(homeDir = os3.homedir()) {
1897
- return path10.join(homeDir, CURSOR_DIR_NAME);
1898
- }
1899
- function getCursorHooksPath(homeDir = os3.homedir()) {
1900
- return path10.join(getCursorUserDir(homeDir), CURSOR_HOOKS_FILE);
1901
- }
1902
-
1903
- // src/monitor/plugins/cursor/hooks-config.ts
1904
- var OLAKAI_HOOK_MARKER3 = "olakai monitor hook --tool cursor";
1905
- var CURSOR_HOOK_DEFINITIONS = {
1906
- beforeSubmitPrompt: [
1907
- {
1908
- command: "olakai monitor hook --tool cursor beforeSubmitPrompt",
1909
- timeout: 5
1910
- }
1911
- ],
1912
- afterAgentResponse: [
1913
- {
1914
- command: "olakai monitor hook --tool cursor afterAgentResponse",
1915
- timeout: 5
1916
- }
1917
- ],
1918
- sessionEnd: [
1919
- {
1920
- command: "olakai monitor hook --tool cursor sessionEnd",
1921
- timeout: 5
1922
- }
1923
- ],
1924
- stop: [
1925
- {
1926
- command: "olakai monitor hook --tool cursor stop",
1927
- timeout: 5
1928
- }
1929
- ]
1930
- };
1931
- var CURSOR_HOOKS_VERSION = 1;
1932
- function mergeCursorHooks(existing, definitions = CURSOR_HOOK_DEFINITIONS) {
1933
- const base = existing ? { ...existing } : {};
1934
- if (typeof base.version !== "number") {
1935
- base.version = CURSOR_HOOKS_VERSION;
1936
- }
1937
- const mergedHooks = {
1938
- ...base.hooks ?? {}
1939
- };
1940
- for (const [event, defaultEntries] of Object.entries(definitions)) {
1941
- const existingEntries = mergedHooks[event] ?? [];
1942
- const hasOlakaiEntry = existingEntries.some(
1943
- (e) => typeof e?.command === "string" && e.command.includes(OLAKAI_HOOK_MARKER3)
1944
- );
1945
- if (hasOlakaiEntry) {
1946
- mergedHooks[event] = existingEntries;
1947
- } else {
1948
- mergedHooks[event] = [...existingEntries, ...defaultEntries];
1949
- }
1950
- }
1951
- return {
1952
- ...base,
1953
- hooks: mergedHooks
1954
- };
1955
- }
1956
- function removeOlakaiCursorHooks(existing) {
1957
- const base = existing ? { ...existing } : {};
1958
- const sourceHooks = base.hooks ?? {};
1959
- const cleaned = {};
1960
- for (const [event, entries] of Object.entries(sourceHooks)) {
1961
- const filtered = entries.filter(
1962
- (e) => typeof e?.command !== "string" || !e.command.includes(OLAKAI_HOOK_MARKER3)
1963
- );
1964
- if (filtered.length > 0) {
1965
- cleaned[event] = filtered;
1966
- }
1967
- }
1968
- if (Object.keys(cleaned).length > 0) {
1969
- base.hooks = cleaned;
1970
- } else {
1971
- delete base.hooks;
1972
- }
1973
- return base;
1974
- }
1975
- function hasOlakaiCursorHooks(config) {
1976
- if (!config?.hooks) return false;
1977
- return Object.values(config.hooks).some(
1978
- (entries) => entries.some(
1979
- (e) => typeof e?.command === "string" && e.command.includes(OLAKAI_HOOK_MARKER3)
1980
- )
1981
- );
1982
- }
1983
-
1984
- // src/monitor/plugins/cursor/install.ts
1985
- var CURSOR_SOURCE = "cursor";
1986
- var CURSOR_AGENT_SOURCE = "CURSOR";
1987
- var CURSOR_AGENT_CATEGORY = "CODING";
1988
- function readJsonFileTolerant(filePath) {
1989
- try {
1990
- if (!fs11.existsSync(filePath)) return null;
1991
- const raw = fs11.readFileSync(filePath, "utf-8");
1992
- return JSON.parse(raw);
1993
- } catch {
1994
- return null;
1995
- }
1996
- }
1997
- function writeJsonFileWithDir(filePath, data) {
1998
- const dir = path11.dirname(filePath);
1999
- if (!fs11.existsSync(dir)) {
2000
- fs11.mkdirSync(dir, { recursive: true });
2001
- }
2002
- fs11.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n", "utf-8");
2003
- }
2004
- async function installCursor(opts) {
2005
- const projectRoot = opts.projectRoot ?? process.cwd();
2006
- const homeDir = opts.homeDir ?? os4.homedir();
2007
- const token = getValidToken();
2008
- if (!token) {
2009
- console.error("Not logged in. Run 'olakai login' first.");
2010
- process.exit(1);
2011
- }
2012
- console.log("Setting up Cursor monitoring for this workspace...\n");
2013
- console.log(
2014
- "Note: Cursor hooks are installed globally per user (~/.cursor/hooks.json)."
2015
- );
2016
- console.log(
2017
- `Activity from this workspace (${projectRoot}) will be associated with`
2018
- );
2019
- console.log("the agent you select below.\n");
2020
- const agent = await provisionSelfMonitorAgent({
2021
- projectRoot,
2022
- source: CURSOR_AGENT_SOURCE,
2023
- displayName: "Cursor",
2024
- category: CURSOR_AGENT_CATEGORY
2025
- });
2026
- const monitoringEndpoint = `${getBaseUrl()}/api/monitoring/prompt`;
2027
- const apiKey = agent.apiKey?.key;
2028
- if (!apiKey) {
2029
- console.error(
2030
- "Internal error: agent provisioned but no API key returned. Please re-run 'olakai monitor init'."
2031
- );
2032
- process.exit(1);
2033
- }
2034
- const cursorDir = getCursorUserDir(homeDir);
2035
- if (!fs11.existsSync(cursorDir)) {
2036
- fs11.mkdirSync(cursorDir, { recursive: true });
2037
- }
2038
- const hooksPath = getCursorHooksPath(homeDir);
2039
- const existingHooks = readJsonFileTolerant(hooksPath);
2040
- const mergedHooks = mergeCursorHooks(existingHooks);
2041
- writeJsonFileWithDir(hooksPath, mergedHooks);
2042
- const monitorConfig = {
2043
- agentId: agent.id,
2044
- apiKey,
2045
- agentName: agent.name,
2046
- source: CURSOR_SOURCE,
2047
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2048
- monitoringEndpoint
2049
- };
2050
- writeCursorConfig(projectRoot, monitorConfig);
2051
- const configPath = getCursorConfigPath(projectRoot);
2052
- const configRel = path11.relative(projectRoot, configPath);
2053
- const hooksDisplay = `~/${path11.join(CURSOR_DIR_NAME, CURSOR_HOOKS_FILE)}`;
2054
- console.log("");
2055
- console.log(`\u2713 Agent "${agent.name}" configured (ID: ${agent.id})`);
2056
- if (agent.apiKey?.key) {
2057
- console.log("\u2713 API key generated");
2058
- }
2059
- console.log(`\u2713 Cursor hooks installed at ${hooksDisplay}`);
2060
- console.log(`\u2713 Monitor config saved to ${configRel}`);
2061
- console.log("");
2062
- console.log(
2063
- "Congrats! Monitoring is now active. Restart Cursor for the new hooks to take effect."
2064
- );
2065
- console.log("");
2066
- console.log(
2067
- `\u26A0 Ensure ${OLAKAI_DIR}/ is in your .gitignore (it contains your API key)`
2068
- );
2069
- console.log("");
2070
- console.log("To check status: olakai monitor status --tool cursor");
2071
- console.log("To disable: olakai monitor disable --tool cursor");
2072
- return {
2073
- agentId: agent.id,
2074
- agentName: agent.name,
2075
- source: CURSOR_SOURCE,
2076
- monitoringEndpoint
2077
- };
2078
- }
2079
- async function uninstallCursor(opts) {
2080
- const projectRoot = opts.projectRoot ?? process.cwd();
2081
- const homeDir = opts.homeDir ?? os4.homedir();
2082
- const hooksPath = getCursorHooksPath(homeDir);
2083
- const existingHooks = readJsonFileTolerant(hooksPath);
2084
- if (existingHooks) {
2085
- const cleaned = removeOlakaiCursorHooks(existingHooks);
2086
- if (!cleaned.hooks || Object.keys(cleaned.hooks).length === 0) {
2087
- const otherKeys = Object.keys(cleaned).filter(
2088
- (k) => k !== "hooks" && k !== "version"
2089
- );
2090
- const onlyDefaults = otherKeys.length === 0 && (cleaned.version === 1 || cleaned.version === void 0);
2091
- if (onlyDefaults) {
2092
- try {
2093
- fs11.unlinkSync(hooksPath);
2094
- } catch {
2095
- }
2096
- } else {
2097
- writeJsonFileWithDir(hooksPath, cleaned);
2098
- }
2099
- } else {
2100
- writeJsonFileWithDir(hooksPath, cleaned);
2101
- }
2102
- console.log(
2103
- `\u2713 Olakai hooks removed from ~/${path11.join(CURSOR_DIR_NAME, CURSOR_HOOKS_FILE)}`
2104
- );
2105
- } else {
2106
- console.log("No Cursor hooks file found.");
2107
- }
2108
- if (!opts.keepConfig) {
2109
- const configPath = getCursorConfigPath(projectRoot);
2110
- const configRel = path11.relative(projectRoot, configPath);
2111
- if (deleteCursorConfig(projectRoot)) {
2112
- console.log(`\u2713 Monitor config removed (${configRel})`);
2113
- }
2114
- } else {
2115
- const configPath = getCursorConfigPath(projectRoot);
2116
- const configRel = path11.relative(projectRoot, configPath);
2117
- console.log(`Monitor config retained at ${configRel}`);
2118
- }
2119
- console.log("");
2120
- console.log(
2121
- "Monitoring disabled. Run 'olakai monitor init --tool cursor' to re-enable."
2122
- );
2123
- console.log("Restart Cursor for the change to take effect.");
2124
- }
2125
-
2126
- // src/monitor/plugins/cursor/status.ts
2127
- import * as fs12 from "fs";
2128
- import * as os5 from "os";
2129
- import * as path12 from "path";
2130
- async function getCursorStatus(opts) {
2131
- const projectRoot = opts?.projectRoot ?? process.cwd();
2132
- const homeDir = opts?.homeDir ?? os5.homedir();
2133
- const configPath = getCursorConfigPath(projectRoot);
2134
- const config = loadCursorConfig(projectRoot);
2135
- let hooksConfigured = false;
2136
- const hooksPath = getCursorHooksPath(homeDir);
2137
- if (fs12.existsSync(hooksPath)) {
2138
- try {
2139
- const raw = fs12.readFileSync(hooksPath, "utf-8");
2140
- const parsed = JSON.parse(raw);
2141
- hooksConfigured = hasOlakaiCursorHooks(parsed);
2142
- } catch {
2143
- }
2144
- }
2145
- if (!config) {
2146
- return {
2147
- toolId: "cursor",
2148
- configured: false,
2149
- hooksConfigured,
2150
- configPath,
2151
- notes: hooksConfigured ? [
2152
- "Cursor hooks installed but no monitor config in this workspace \u2014 run 'olakai monitor init --tool cursor' to associate it with an agent."
2153
- ] : []
2154
- };
2155
- }
2156
- return {
2157
- toolId: "cursor",
2158
- configured: true,
2159
- hooksConfigured,
2160
- agentId: config.agentId,
2161
- agentName: config.agentName,
2162
- source: config.source,
2163
- apiKeyMasked: config.apiKey.slice(0, 12) + "...",
2164
- monitoringEndpoint: config.monitoringEndpoint,
2165
- configuredAt: config.createdAt,
2166
- configPath
2167
- };
2168
- }
2169
-
2170
- // src/monitor/plugins/cursor/hook.ts
2171
- var SUPPORTED_CURSOR_EVENTS = /* @__PURE__ */ new Set([
2172
- "beforeSubmitPrompt",
2173
- "afterAgentResponse",
2174
- "sessionEnd",
2175
- "stop"
2176
- ]);
2177
- function asString(value) {
2178
- return typeof value === "string" && value.trim() ? value : void 0;
2179
- }
2180
- function asNumber(value) {
2181
- if (typeof value !== "number") return 0;
2182
- if (!Number.isFinite(value)) return 0;
2183
- return value;
2184
- }
2185
- function extractCursorTokens(payload) {
2186
- return {
2187
- inputTokens: asNumber(payload.input_tokens),
2188
- outputTokens: asNumber(payload.output_tokens),
2189
- cacheReadTokens: asNumber(payload.cache_read_tokens),
2190
- cacheWriteTokens: asNumber(payload.cache_write_tokens)
2191
- };
2192
- }
2193
- function asStringArray(value) {
2194
- if (!Array.isArray(value)) return void 0;
2195
- const out = [];
2196
- for (const item of value) {
2197
- if (typeof item === "string" && item.trim()) out.push(item);
2198
- }
2199
- return out.length > 0 ? out : void 0;
2200
- }
2201
- function extractPromptText(payload) {
2202
- if (typeof payload.prompt === "string") return payload.prompt;
2203
- if (payload.prompt && typeof payload.prompt === "object" && typeof payload.prompt.text === "string") {
2204
- return payload.prompt.text;
2205
- }
2206
- return "";
2207
- }
2208
- function extractResponseText(payload) {
2209
- if (typeof payload.response === "string") return payload.response;
2210
- if (payload.response && typeof payload.response === "object" && typeof payload.response.text === "string") {
2211
- return payload.response.text;
2212
- }
2213
- if (typeof payload.text === "string") return payload.text;
2214
- return "";
2215
- }
2216
- function extractAttachments(payload) {
2217
- if (Array.isArray(payload.attachments)) return payload.attachments;
2218
- if (payload.prompt && typeof payload.prompt === "object" && Array.isArray(payload.prompt.attachments)) {
2219
- return payload.prompt.attachments;
2220
- }
2221
- return void 0;
2222
- }
2223
- function buildPairedPayload(inputs, config) {
2224
- const customData = {
2225
- hookEvent: "afterAgentResponse",
2226
- conversationId: inputs.conversationId
2227
- };
2228
- if (inputs.generationId) customData.generationId = inputs.generationId;
2229
- if (inputs.cursorVersion) customData.cursorVersion = inputs.cursorVersion;
2230
- if (inputs.workspaceRoots) customData.workspaceRoots = inputs.workspaceRoots;
2231
- if (inputs.transcriptPath) customData.transcriptPath = inputs.transcriptPath;
2232
- if (inputs.attachments && inputs.attachments.length > 0) {
2233
- customData.attachmentCount = inputs.attachments.length;
2234
- }
2235
- if (inputs.userEmail) customData.userEmail = inputs.userEmail;
2236
- const inputTokens = asNumber(inputs.inputTokens);
2237
- const outputTokens = asNumber(inputs.outputTokens);
2238
- const cacheReadTokens = asNumber(inputs.cacheReadTokens);
2239
- const cacheWriteTokens = asNumber(inputs.cacheWriteTokens);
2240
- customData.inputTokens = inputTokens;
2241
- customData.outputTokens = outputTokens;
2242
- customData.cacheReadTokens = cacheReadTokens;
2243
- customData.cacheWriteTokens = cacheWriteTokens;
2244
- if (inputs.unknownFields && Object.keys(inputs.unknownFields).length > 0) {
2245
- customData.unknownPayloadFields = inputs.unknownFields;
2246
- }
2247
- return {
2248
- prompt: inputs.prompt,
2249
- response: inputs.response,
2250
- chatId: inputs.conversationId,
2251
- source: config.source,
2252
- modelName: inputs.model,
2253
- tokens: inputTokens + outputTokens,
2254
- customData
2255
- };
2256
- }
2257
- function buildOrphanPayload(inputs, config, reason = "orphan-prompt") {
2258
- const base = buildPairedPayload({ ...inputs, response: "" }, config);
2259
- return {
2260
- ...base,
2261
- customData: {
2262
- ...base.customData,
2263
- hookEvent: "sessionEnd",
2264
- partial: true,
2265
- partialReason: reason
2266
- }
2267
- };
2268
- }
2269
- var KNOWN_PAYLOAD_KEYS = /* @__PURE__ */ new Set([
2270
- "event",
2271
- "conversation_id",
2272
- "generation_id",
2273
- "model",
2274
- "cursor_version",
2275
- "workspace_roots",
2276
- "user_email",
2277
- "transcript_path",
2278
- "prompt",
2279
- "response",
2280
- "text",
2281
- "attachments",
2282
- "input_tokens",
2283
- "output_tokens",
2284
- "cache_read_tokens",
2285
- "cache_write_tokens"
2286
- ]);
2287
- function collectUnknownFields(payload) {
2288
- const out = {};
2289
- for (const key of Object.keys(payload)) {
2290
- if (!KNOWN_PAYLOAD_KEYS.has(key)) {
2291
- out[key] = payload[key];
2292
- }
2293
- }
2294
- return Object.keys(out).length > 0 ? out : void 0;
2295
- }
2296
- function normalizeEventName(event) {
2297
- const lower = event.trim();
2298
- if (!lower) return null;
2299
- const exact = lower;
2300
- if (SUPPORTED_CURSOR_EVENTS.has(exact)) return exact;
2301
- for (const known of SUPPORTED_CURSOR_EVENTS) {
2302
- if (known.toLowerCase() === lower.toLowerCase()) return known;
2303
- }
2304
- return null;
2305
- }
2306
- function extractCursorMeta(payload) {
2307
- return {
2308
- conversationId: asString(payload.conversation_id),
2309
- generationId: asString(payload.generation_id),
2310
- model: asString(payload.model),
2311
- cursorVersion: asString(payload.cursor_version),
2312
- workspaceRoots: asStringArray(payload.workspace_roots),
2313
- userEmail: asString(payload.user_email),
2314
- transcriptPath: asString(payload.transcript_path)
2315
- };
2316
- }
2317
-
2318
- // src/monitor/plugins/cursor/pairing-state.ts
2319
- import * as fs13 from "fs";
2320
- import * as os6 from "os";
2321
- import * as path13 from "path";
2322
- var STATE_DIR_SEGMENTS2 = [".olakai", "cursor-pairings"];
2323
- function getPairingsDir(homeDir) {
2324
- return path13.join(homeDir, ...STATE_DIR_SEGMENTS2);
2325
- }
2326
- function sanitizeKeyFragment(value) {
2327
- return value.replace(/[^A-Za-z0-9._-]/g, "_");
2328
- }
2329
- function getPairingKey(conversationId, generationId) {
2330
- const conv = sanitizeKeyFragment(conversationId);
2331
- if (!generationId) return conv;
2332
- return `${conv}__${sanitizeKeyFragment(generationId)}`;
2333
- }
2334
- function getPairingFile(conversationId, generationId, homeDir) {
2335
- return path13.join(
2336
- getPairingsDir(homeDir),
2337
- `${getPairingKey(conversationId, generationId)}.json`
2338
- );
2339
- }
2340
- function stashPendingPrompt(pending, homeDir = os6.homedir()) {
2341
- if (!pending.conversationId) return;
2342
- const dir = getPairingsDir(homeDir);
2343
- try {
2344
- if (!fs13.existsSync(dir)) {
2345
- fs13.mkdirSync(dir, { recursive: true });
2346
- }
2347
- const filePath = getPairingFile(
2348
- pending.conversationId,
2349
- pending.generationId,
2350
- homeDir
2351
- );
2352
- fs13.writeFileSync(
2353
- filePath,
2354
- JSON.stringify(pending, null, 2) + "\n",
2355
- "utf-8"
2356
- );
2357
- } catch {
2358
- }
2359
- }
2360
- function takePendingPrompt(conversationId, generationId, homeDir = os6.homedir()) {
2361
- if (!conversationId) return null;
2362
- const candidates = [];
2363
- if (generationId) {
2364
- candidates.push(getPairingFile(conversationId, generationId, homeDir));
2365
- }
2366
- candidates.push(getPairingFile(conversationId, void 0, homeDir));
2367
- for (const filePath of candidates) {
2368
- let raw;
2369
- try {
2370
- if (!fs13.existsSync(filePath)) continue;
2371
- raw = fs13.readFileSync(filePath, "utf-8");
2372
- } catch {
2373
- continue;
2374
- }
2375
- try {
2376
- fs13.unlinkSync(filePath);
2377
- } catch {
2378
- }
2379
- try {
2380
- const parsed = JSON.parse(raw);
2381
- if (parsed && typeof parsed.conversationId === "string") {
2382
- return parsed;
2383
- }
2384
- } catch {
297
+ message: err instanceof Error ? err.message : "Failed to parse response",
298
+ status: response.status
299
+ };
2385
300
  }
301
+ return { kind: "ok", data };
2386
302
  }
2387
- return null;
2388
- }
2389
- function listPendingPrompts(homeDir = os6.homedir()) {
2390
- const dir = getPairingsDir(homeDir);
2391
- if (!fs13.existsSync(dir)) return [];
2392
- let files;
303
+ let errBody = {};
2393
304
  try {
2394
- files = fs13.readdirSync(dir);
305
+ errBody = await response.json();
2395
306
  } catch {
2396
- return [];
2397
- }
2398
- const result = [];
2399
- for (const name of files) {
2400
- if (!name.endsWith(".json")) continue;
2401
- const filePath = path13.join(dir, name);
2402
- try {
2403
- const raw = fs13.readFileSync(filePath, "utf-8");
2404
- const parsed = JSON.parse(raw);
2405
- if (parsed && typeof parsed.conversationId === "string") {
2406
- result.push(parsed);
2407
- }
2408
- } catch {
2409
- }
2410
- }
2411
- return result;
2412
- }
2413
- function clearPendingPrompt(conversationId, generationId, homeDir = os6.homedir()) {
2414
- if (!conversationId) return;
2415
- const candidates = [];
2416
- if (generationId) {
2417
- candidates.push(getPairingFile(conversationId, generationId, homeDir));
2418
- }
2419
- candidates.push(getPairingFile(conversationId, void 0, homeDir));
2420
- for (const filePath of candidates) {
2421
- try {
2422
- if (fs13.existsSync(filePath)) {
2423
- fs13.unlinkSync(filePath);
2424
- }
2425
- } catch {
2426
- }
2427
307
  }
2428
- }
2429
-
2430
- // src/monitor/plugins/cursor/index.ts
2431
- var TOOL_ID3 = "cursor";
2432
- function debugLog3(label, data) {
2433
- if (process.env.OLAKAI_MONITOR_DEBUG !== "1") return;
308
+ const code = mapErrorCode(response.status, errBody);
309
+ let fallbackPath = "";
2434
310
  try {
2435
- const logPath = `/tmp/olakai-monitor-debug-${process.pid}.log`;
2436
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] cursor:${label}: ${typeof data === "string" ? data : JSON.stringify(data, null, 2)}
2437
- `;
2438
- fs14.appendFileSync(logPath, line, "utf-8");
311
+ fallbackPath = new URL(url).pathname;
2439
312
  } catch {
313
+ fallbackPath = url;
2440
314
  }
315
+ const message = errBody.message || errBody.error || `Request to ${fallbackPath} failed with status ${response.status}`;
316
+ const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
317
+ const envelope = {
318
+ kind: "error",
319
+ code,
320
+ message,
321
+ status: response.status,
322
+ ...retryAfter !== void 0 ? { retryAfter } : {}
323
+ };
324
+ if (options.captureDetail && typeof errBody.attemptsRemaining === "number") {
325
+ envelope.detail = { attemptsRemaining: errBody.attemptsRemaining };
326
+ }
327
+ return envelope;
2441
328
  }
2442
- function resolveCursorProjectRoot(payload, fallbackCwd = process.cwd()) {
2443
- const roots = Array.isArray(payload.workspace_roots) ? payload.workspace_roots.filter(
2444
- (r) => typeof r === "string" && r.trim().length > 0
2445
- ) : [];
2446
- const candidates = roots.length > 0 ? roots : [fallbackCwd];
2447
- for (const candidate of candidates) {
2448
- const found = findConfiguredWorkspace(candidate, [TOOL_ID3]);
2449
- if (found) return found;
2450
- }
2451
- return null;
2452
- }
2453
- async function handleCursorHook(eventName, payloadJson, opts = {}) {
2454
- const event = normalizeEventName(eventName);
2455
- if (!event) {
2456
- debugLog3("hook-unknown-event", eventName);
2457
- return null;
329
+ function mapErrorCode(status, body) {
330
+ const known = [
331
+ "validation_error",
332
+ "invalid_code",
333
+ "invalid_consent",
334
+ "user_unavailable",
335
+ "blocked",
336
+ "no_code",
337
+ "expired",
338
+ "locked",
339
+ "rate_limited",
340
+ "service_unavailable"
341
+ ];
342
+ if (typeof body.code === "string" && known.includes(body.code)) {
343
+ return body.code;
2458
344
  }
2459
- const payload = payloadJson && typeof payloadJson === "object" ? payloadJson : {};
2460
- debugLog3("event-parsed", { event, payload });
2461
- const meta = extractCursorMeta(payload);
2462
- const homeDir = opts.homeDir ?? os7.homedir();
2463
- switch (event) {
2464
- case "beforeSubmitPrompt": {
2465
- if (!meta.conversationId) {
2466
- debugLog3("missing-conversation-id", { event });
2467
- return null;
2468
- }
2469
- stashPendingPrompt(
2470
- {
2471
- prompt: extractPromptText(payload),
2472
- userEmail: meta.userEmail,
2473
- model: meta.model,
2474
- cursorVersion: meta.cursorVersion,
2475
- conversationId: meta.conversationId,
2476
- generationId: meta.generationId,
2477
- workspaceRoots: meta.workspaceRoots,
2478
- transcriptPath: meta.transcriptPath,
2479
- attachments: extractAttachments(payload),
2480
- stashedAt: (/* @__PURE__ */ new Date()).toISOString(),
2481
- extra: collectUnknownFields(payload)
2482
- },
2483
- homeDir
2484
- );
2485
- return null;
2486
- }
2487
- case "afterAgentResponse": {
2488
- if (!meta.conversationId) {
2489
- debugLog3("missing-conversation-id", { event });
2490
- return null;
2491
- }
2492
- const projectRoot = resolveCursorProjectRoot(
2493
- payload,
2494
- opts.projectRoot ?? process.cwd()
2495
- );
2496
- if (!projectRoot) {
2497
- debugLog3("config-not-found", {
2498
- workspaceRoots: meta.workspaceRoots,
2499
- fallbackCwd: opts.projectRoot ?? process.cwd()
2500
- });
2501
- takePendingPrompt(meta.conversationId, meta.generationId, homeDir);
2502
- return null;
2503
- }
2504
- const config = loadCursorConfig(projectRoot);
2505
- if (!config) {
2506
- debugLog3("config-load-failed", { projectRoot });
2507
- takePendingPrompt(meta.conversationId, meta.generationId, homeDir);
2508
- return null;
2509
- }
2510
- const stashed = takePendingPrompt(
2511
- meta.conversationId,
2512
- meta.generationId,
2513
- homeDir
2514
- );
2515
- const responseText = extractResponseText(payload);
2516
- const promptText = stashed?.prompt ?? extractPromptText(payload);
2517
- const userEmail = meta.userEmail ?? stashed?.userEmail;
2518
- const model = meta.model ?? stashed?.model;
2519
- const cursorVersion = meta.cursorVersion ?? stashed?.cursorVersion;
2520
- const workspaceRoots = meta.workspaceRoots ?? stashed?.workspaceRoots;
2521
- const transcriptPath = meta.transcriptPath ?? stashed?.transcriptPath;
2522
- const attachments = extractAttachments(payload) ?? stashed?.attachments;
2523
- const tokens = extractCursorTokens(payload);
2524
- const unknownFields = mergeUnknownFields(
2525
- collectUnknownFields(payload),
2526
- stashed?.extra
2527
- );
2528
- const built = buildPairedPayload(
2529
- {
2530
- conversationId: meta.conversationId,
2531
- generationId: meta.generationId ?? stashed?.generationId,
2532
- prompt: promptText,
2533
- response: responseText,
2534
- userEmail,
2535
- model,
2536
- cursorVersion,
2537
- workspaceRoots,
2538
- transcriptPath,
2539
- attachments,
2540
- inputTokens: tokens.inputTokens,
2541
- outputTokens: tokens.outputTokens,
2542
- cacheReadTokens: tokens.cacheReadTokens,
2543
- cacheWriteTokens: tokens.cacheWriteTokens,
2544
- unknownFields
2545
- },
2546
- config
2547
- );
2548
- const finalPayload = userEmail ? { ...built, email: userEmail } : built;
2549
- debugLog3("payload-built", finalPayload);
2550
- return {
2551
- payload: finalPayload,
2552
- transport: {
2553
- endpoint: config.monitoringEndpoint,
2554
- apiKey: config.apiKey,
2555
- projectRoot
2556
- }
2557
- };
345
+ if (typeof body.error === "string" && known.includes(body.error)) {
346
+ return body.error;
347
+ }
348
+ switch (status) {
349
+ case 400:
350
+ return "validation_error";
351
+ case 401:
352
+ return "invalid_consent";
353
+ case 403:
354
+ return "blocked";
355
+ case 404:
356
+ return "no_code";
357
+ case 410:
358
+ return "expired";
359
+ case 429:
360
+ return "rate_limited";
361
+ case 503:
362
+ return "service_unavailable";
363
+ default:
364
+ return "unknown_error";
365
+ }
366
+ }
367
+ function buildNetworkError(err) {
368
+ const base = err instanceof Error ? err.message : "Network request failed";
369
+ let causeCode;
370
+ let causeMessage;
371
+ if (err instanceof Error && err.cause && typeof err.cause === "object") {
372
+ const c = err.cause;
373
+ if (typeof c.code === "string" && c.code.length > 0) {
374
+ causeCode = c.code;
2558
375
  }
2559
- case "sessionEnd":
2560
- case "stop": {
2561
- const orphan = pickOrphanForFlush(meta.conversationId, homeDir);
2562
- if (!orphan) return null;
2563
- const projectRoot = resolveCursorProjectRoot(
2564
- // Synthesize a payload-like for resolution — orphan carries
2565
- // the workspace_roots from the stashed beforeSubmitPrompt.
2566
- {
2567
- workspace_roots: orphan.workspaceRoots
2568
- },
2569
- opts.projectRoot ?? process.cwd()
2570
- );
2571
- if (!projectRoot) {
2572
- debugLog3("orphan-config-not-found", {
2573
- conversationId: orphan.conversationId
2574
- });
2575
- clearPendingPrompt(
2576
- orphan.conversationId,
2577
- orphan.generationId,
2578
- homeDir
2579
- );
2580
- return null;
2581
- }
2582
- const config = loadCursorConfig(projectRoot);
2583
- if (!config) {
2584
- debugLog3("orphan-config-load-failed", { projectRoot });
2585
- clearPendingPrompt(
2586
- orphan.conversationId,
2587
- orphan.generationId,
2588
- homeDir
2589
- );
2590
- return null;
2591
- }
2592
- clearPendingPrompt(
2593
- orphan.conversationId,
2594
- orphan.generationId,
2595
- homeDir
2596
- );
2597
- const built = buildOrphanPayload(
2598
- {
2599
- conversationId: orphan.conversationId,
2600
- generationId: orphan.generationId,
2601
- prompt: orphan.prompt,
2602
- response: "",
2603
- userEmail: orphan.userEmail,
2604
- model: orphan.model,
2605
- cursorVersion: orphan.cursorVersion,
2606
- workspaceRoots: orphan.workspaceRoots,
2607
- transcriptPath: orphan.transcriptPath,
2608
- attachments: orphan.attachments,
2609
- unknownFields: orphan.extra
2610
- },
2611
- config,
2612
- event === "sessionEnd" ? "session-end" : "orphan-prompt"
2613
- );
2614
- const finalPayload = orphan.userEmail ? { ...built, email: orphan.userEmail } : built;
2615
- return {
2616
- payload: finalPayload,
2617
- transport: {
2618
- endpoint: config.monitoringEndpoint,
2619
- apiKey: config.apiKey,
2620
- projectRoot
2621
- }
2622
- };
376
+ if (typeof c.message === "string" && c.message.length > 0) {
377
+ causeMessage = c.message;
2623
378
  }
2624
379
  }
380
+ const message = causeMessage && causeMessage !== base ? `${base}: ${causeMessage}` : base;
381
+ return {
382
+ kind: "error",
383
+ code: "network_error",
384
+ message,
385
+ status: 0,
386
+ ...causeCode ? { causeCode } : {}
387
+ };
2625
388
  }
2626
- function mergeUnknownFields(primary, fallback) {
2627
- if (!primary && !fallback) return void 0;
2628
- return { ...fallback ?? {}, ...primary ?? {} };
2629
- }
2630
- function pickOrphanForFlush(conversationId, homeDir) {
2631
- const pending = listPendingPrompts(homeDir);
2632
- if (pending.length === 0) return null;
2633
- if (conversationId) {
2634
- const match = pending.find((p) => p.conversationId === conversationId);
2635
- if (match) return match;
2636
- }
2637
- return pending.sort(
2638
- (a, b) => (a.stashedAt || "").localeCompare(b.stashedAt || "")
2639
- )[0];
2640
- }
2641
- var cursorPlugin = {
2642
- id: TOOL_ID3,
2643
- displayName: "Cursor",
2644
- install(opts) {
2645
- return installCursor(opts);
2646
- },
2647
- uninstall(opts) {
2648
- return uninstallCursor(opts);
2649
- },
2650
- status(opts) {
2651
- return getCursorStatus(opts);
2652
- },
2653
- handleHook(eventName, payloadJson, opts) {
2654
- return handleCursorHook(eventName, payloadJson, opts);
2655
- },
2656
- async detectInstalled() {
2657
- try {
2658
- if (fs14.existsSync(getCursorUserDir())) return true;
2659
- return whichCursorOnPath();
2660
- } catch {
2661
- return false;
2662
- }
389
+ function parseRetryAfter(header) {
390
+ if (!header) return void 0;
391
+ const asNumber = Number(header);
392
+ if (Number.isFinite(asNumber) && asNumber > 0) {
393
+ return Math.floor(asNumber);
2663
394
  }
2664
- };
2665
- function whichCursorOnPath() {
2666
- const pathEnv = process.env.PATH;
2667
- if (!pathEnv) return false;
2668
- const sep = process.platform === "win32" ? ";" : ":";
2669
- const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
2670
- for (const dir of pathEnv.split(sep)) {
2671
- for (const ext of exts) {
2672
- const candidate = `${dir}/cursor${ext.toLowerCase()}`;
2673
- try {
2674
- if (fs14.existsSync(candidate)) return true;
2675
- } catch {
2676
- }
2677
- }
395
+ const asDate = Date.parse(header);
396
+ if (Number.isFinite(asDate)) {
397
+ const seconds = Math.floor((asDate - Date.now()) / 1e3);
398
+ return seconds > 0 ? seconds : void 0;
2678
399
  }
2679
- return false;
400
+ return void 0;
2680
401
  }
2681
- registerPlugin(cursorPlugin);
2682
402
 
2683
403
  // src/monitor/detect-all.ts
404
+ import * as fs from "fs";
405
+ import * as path from "path";
2684
406
  async function detectInstalledTools(projectRoot = process.cwd()) {
2685
407
  const detected = [];
2686
408
  for (const plugin of listPlugins()) {
@@ -2700,7 +422,7 @@ async function detectInstalledTools(projectRoot = process.cwd()) {
2700
422
  }
2701
423
  function describeDetection(plugin, projectRoot) {
2702
424
  try {
2703
- if (fs15.existsSync(getMonitorConfigPath(projectRoot, plugin.id))) {
425
+ if (fs.existsSync(getMonitorConfigPath(projectRoot, plugin.id))) {
2704
426
  return `existing config at .olakai/monitor-${plugin.id}.json`;
2705
427
  }
2706
428
  } catch {
@@ -2708,14 +430,14 @@ function describeDetection(plugin, projectRoot) {
2708
430
  switch (plugin.id) {
2709
431
  case "claude-code": {
2710
432
  try {
2711
- if (fs15.existsSync(getLegacyClaudeMonitorConfigPath(projectRoot))) {
433
+ if (fs.existsSync(getLegacyClaudeMonitorConfigPath(projectRoot))) {
2712
434
  return "legacy config at .claude/olakai-monitor.json";
2713
435
  }
2714
436
  } catch {
2715
437
  }
2716
438
  try {
2717
- const settings = path14.join(projectRoot, ".claude", "settings.json");
2718
- if (fs15.existsSync(settings)) {
439
+ const settings = path.join(projectRoot, ".claude", "settings.json");
440
+ if (fs.existsSync(settings)) {
2719
441
  return "found .claude/settings.json";
2720
442
  }
2721
443
  } catch {
@@ -2724,10 +446,10 @@ function describeDetection(plugin, projectRoot) {
2724
446
  }
2725
447
  case "codex": {
2726
448
  try {
2727
- if (fs15.existsSync(getCodexConfigPath())) {
449
+ if (fs.existsSync(getCodexConfigPath())) {
2728
450
  return "found ~/.codex/config.toml";
2729
451
  }
2730
- if (fs15.existsSync(getCodexHomeDir())) {
452
+ if (fs.existsSync(getCodexHomeDir())) {
2731
453
  return "found ~/.codex/";
2732
454
  }
2733
455
  } catch {
@@ -2737,6 +459,38 @@ function describeDetection(plugin, projectRoot) {
2737
459
  case "cursor": {
2738
460
  return "Cursor installed for this user";
2739
461
  }
462
+ case "gemini-cli": {
463
+ try {
464
+ const homeSettings = path.join(
465
+ process.env.HOME ?? "",
466
+ ".gemini",
467
+ "settings.json"
468
+ );
469
+ if (process.env.HOME && fs.existsSync(homeSettings)) {
470
+ return "found ~/.gemini/settings.json";
471
+ }
472
+ const homeDir = path.join(process.env.HOME ?? "", ".gemini");
473
+ if (process.env.HOME && fs.existsSync(homeDir)) {
474
+ return "found ~/.gemini/";
475
+ }
476
+ } catch {
477
+ }
478
+ return "Gemini CLI on PATH";
479
+ }
480
+ case "antigravity": {
481
+ try {
482
+ const cliDir = path.join(
483
+ process.env.HOME ?? "",
484
+ ".gemini",
485
+ "antigravity-cli"
486
+ );
487
+ if (process.env.HOME && fs.existsSync(cliDir)) {
488
+ return "found ~/.gemini/antigravity-cli/";
489
+ }
490
+ } catch {
491
+ }
492
+ return "Antigravity (agy) on PATH";
493
+ }
2740
494
  default: {
2741
495
  const _exhaustive = plugin.id;
2742
496
  void _exhaustive;
@@ -2745,15 +499,6 @@ function describeDetection(plugin, projectRoot) {
2745
499
  }
2746
500
  }
2747
501
 
2748
- // src/monitor/install.ts
2749
- async function runMonitorInstall(toolId, opts = {}) {
2750
- const plugin = getPlugin(toolId);
2751
- return plugin.install({
2752
- projectRoot: opts.projectRoot ?? process.cwd(),
2753
- interactive: opts.interactive ?? true
2754
- });
2755
- }
2756
-
2757
502
  // src/lib/branding.ts
2758
503
  var RESET = "\x1B[0m";
2759
504
  var CYAN = "\x1B[36m";
@@ -3282,6 +1027,28 @@ function formatAgentDetail(agent) {
3282
1027
  }
3283
1028
  }
3284
1029
  }
1030
+ function formatMineTable(agents) {
1031
+ if (agents.length === 0) {
1032
+ console.log("You haven't created any agents.");
1033
+ return;
1034
+ }
1035
+ const headers = ["NAME", "SOURCE", "AGENT ID", "CREATED", "API KEY"];
1036
+ const rows = agents.map((agent) => [
1037
+ agent.name.slice(0, 30),
1038
+ agent.source,
1039
+ agent.id.slice(0, 12) + "...",
1040
+ agent.createdAt ? agent.createdAt.slice(0, 10) : "-",
1041
+ agent.apiKey ? agent.apiKey.isActive ? "Active" : "Inactive" : "None"
1042
+ ]);
1043
+ const widths = headers.map(
1044
+ (h, i) => Math.max(h.length, ...rows.map((r) => r[i].length))
1045
+ );
1046
+ console.log(headers.map((h, i) => h.padEnd(widths[i])).join(" "));
1047
+ console.log(widths.map((w) => "-".repeat(w)).join(" "));
1048
+ for (const row of rows) {
1049
+ console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(" "));
1050
+ }
1051
+ }
3285
1052
  async function listCommand(options) {
3286
1053
  try {
3287
1054
  const agents = await listAgents({ includeKpis: options.includeKpis });
@@ -3391,13 +1158,85 @@ async function deleteCommand(id, options) {
3391
1158
  process.exit(1);
3392
1159
  }
3393
1160
  }
1161
+ async function mineCommand(options) {
1162
+ try {
1163
+ let source;
1164
+ if (options.source !== void 0) {
1165
+ if (!isToolId(options.source)) {
1166
+ console.error(
1167
+ `Unknown --source "${options.source}". Supported coding-agent sources: ${TOOL_IDS.join(", ")}`
1168
+ );
1169
+ process.exit(1);
1170
+ }
1171
+ source = getToolSource(options.source);
1172
+ }
1173
+ const agents = await listMyAgents(source ? { source } : void 0);
1174
+ if (options.json) {
1175
+ console.log(JSON.stringify(agents, null, 2));
1176
+ } else {
1177
+ formatMineTable(agents);
1178
+ }
1179
+ } catch (error) {
1180
+ console.error(
1181
+ `Error: ${error instanceof Error ? error.message : "Unknown error"}`
1182
+ );
1183
+ process.exit(1);
1184
+ }
1185
+ }
1186
+ async function archiveCommand(id, options) {
1187
+ try {
1188
+ const archived = !options.unarchive;
1189
+ const agent = await updateAgent(id, { archived });
1190
+ if (options.json) {
1191
+ console.log(JSON.stringify(agent, null, 2));
1192
+ } else {
1193
+ console.log(
1194
+ archived ? `Agent ${id} archived.` : `Agent ${id} unarchived.`
1195
+ );
1196
+ }
1197
+ } catch (error) {
1198
+ console.error(
1199
+ `Error: ${error instanceof Error ? error.message : "Unknown error"}`
1200
+ );
1201
+ process.exit(1);
1202
+ }
1203
+ }
1204
+ async function renameCommand(id, name, options) {
1205
+ try {
1206
+ if (!name || !name.trim()) {
1207
+ console.error("Error: a non-empty <name> is required");
1208
+ process.exit(1);
1209
+ }
1210
+ const agent = await updateAgent(id, { name: name.trim() });
1211
+ if (options.json) {
1212
+ console.log(JSON.stringify(agent, null, 2));
1213
+ } else {
1214
+ console.log(`Agent ${id} renamed to "${agent.name}".`);
1215
+ }
1216
+ } catch (error) {
1217
+ console.error(
1218
+ `Error: ${error instanceof Error ? error.message : "Unknown error"}`
1219
+ );
1220
+ process.exit(1);
1221
+ }
1222
+ }
3394
1223
  function registerAgentsCommand(program2) {
3395
1224
  const agents = program2.command("agents").description("Manage agents");
3396
1225
  agents.command("list").description("List all agents").option("--json", "Output as JSON").option("--include-kpis", "Include KPI definitions").action(listCommand);
3397
1226
  agents.command("get <id>").description("Get agent details").option("--json", "Output as JSON").action(getCommand);
3398
1227
  agents.command("create").description("Create a new agent").requiredOption("--name <name>", "Agent name").option("--description <description>", "Agent description").option("--role <role>", "Agent role (WORKER or COORDINATOR)", "WORKER").option("--workflow <id>", "Workflow ID to assign").option("--with-api-key", "Create an API key for this agent").option("--category <category>", "Agent category").option("--json", "Output as JSON").action(createCommand);
3399
1228
  agents.command("update <id>").description("Update an agent").option("--name <name>", "Agent name").option("--description <description>", "Agent description").option("--role <role>", "Agent role (WORKER or COORDINATOR)").option("--workflow <id>", "Workflow ID to assign").option("--category <category>", "Agent category").option("--json", "Output as JSON").action(updateCommand);
3400
- agents.command("delete <id>").description("Delete an agent").option("--force", "Skip confirmation").action(deleteCommand);
1229
+ agents.command("delete <id>").description(
1230
+ "Delete an agent (account-wide). Owner or ADMIN only \u2014 non-owners get a permission error."
1231
+ ).option("--force", "Skip confirmation").action(deleteCommand);
1232
+ agents.command("mine").description(
1233
+ "List agents you created across your whole account (the account lens, cross-machine). For what's installed on THIS machine, use 'olakai monitor list'."
1234
+ ).option(
1235
+ "--source <source>",
1236
+ `Filter to a coding-agent source (${TOOL_IDS.join("|")})`
1237
+ ).option("--json", "Output as JSON").action(mineCommand);
1238
+ agents.command("archive <id>").description("Archive an agent account-wide (soft delete). Owner or ADMIN only.").option("--unarchive", "Restore an archived agent instead").option("--json", "Output as JSON").action(archiveCommand);
1239
+ agents.command("rename <id> <name>").description("Rename an agent account-wide. Owner or ADMIN only.").option("--json", "Output as JSON").action(renameCommand);
3401
1240
  }
3402
1241
 
3403
1242
  // src/commands/workflows.ts
@@ -4485,7 +2324,7 @@ function registerActivityCommand(program2) {
4485
2324
  }
4486
2325
 
4487
2326
  // src/commands/monitor.ts
4488
- import * as fs16 from "fs";
2327
+ import * as fs2 from "fs";
4489
2328
  function readStdin(timeoutMs = 3e3) {
4490
2329
  return new Promise((resolve) => {
4491
2330
  if (process.stdin.isTTY) {
@@ -4573,7 +2412,7 @@ async function statusCommand(options) {
4573
2412
  return;
4574
2413
  }
4575
2414
  if (plugin.id === "claude-code") {
4576
- const { printClaudeCodeStatus } = await import("./status-USHUUHK6.js");
2415
+ const { printClaudeCodeStatus } = await import("./status-IZCIMES2.js");
4577
2416
  await printClaudeCodeStatus({ projectRoot: process.cwd() });
4578
2417
  return;
4579
2418
  }
@@ -4607,6 +2446,7 @@ async function disableCommand(options) {
4607
2446
  );
4608
2447
  }
4609
2448
  }
2449
+ const registryRoot = findConfiguredWorkspace(process.cwd(), TOOL_IDS);
4610
2450
  await runPluginAction(
4611
2451
  plugin,
4612
2452
  () => plugin.uninstall({
@@ -4614,8 +2454,14 @@ async function disableCommand(options) {
4614
2454
  keepConfig: options.keepConfig
4615
2455
  })
4616
2456
  );
2457
+ if (registryRoot && !options.keepConfig) {
2458
+ try {
2459
+ removeEntry(registryRoot, toolId);
2460
+ } catch {
2461
+ }
2462
+ }
4617
2463
  if (agentIdToDelete) {
4618
- const { deleteAgent: deleteAgent2 } = await import("./api-OAWRQIZM.js");
2464
+ const { deleteAgent: deleteAgent2 } = await import("./api-JBVSHCKY.js");
4619
2465
  try {
4620
2466
  await deleteAgent2(agentIdToDelete);
4621
2467
  console.log(`\u2713 Remote agent ${agentIdToDelete} deleted.`);
@@ -4631,6 +2477,49 @@ async function disableCommand(options) {
4631
2477
  }
4632
2478
  }
4633
2479
  }
2480
+ async function listCommand6(options) {
2481
+ try {
2482
+ reconcileCurrentWorkspace(process.cwd());
2483
+ } catch {
2484
+ }
2485
+ const registry = readRegistry();
2486
+ if (options.json) {
2487
+ console.log(JSON.stringify(registry.workspaces, null, 2));
2488
+ return;
2489
+ }
2490
+ console.log(formatRegistryTable(registry));
2491
+ }
2492
+ async function doctorCommand(options) {
2493
+ const { runDoctor, printDoctorResult, exitCodeForStatus } = await import("./doctor-TIVMQBE3.js");
2494
+ let tool;
2495
+ if (!options.all) {
2496
+ tool = await resolveToolFromOptions(options.tool, "status");
2497
+ }
2498
+ const result = await runDoctor({
2499
+ tool,
2500
+ all: options.all,
2501
+ fix: options.fix,
2502
+ json: options.json,
2503
+ recreateMissing: options.recreateMissing,
2504
+ interactive: isInteractive()
2505
+ });
2506
+ printDoctorResult(result, Boolean(options.json));
2507
+ process.exitCode = exitCodeForStatus(result.report.overall);
2508
+ }
2509
+ async function repairCommand(options) {
2510
+ const tool = await resolveToolFromOptions(options.tool, "init");
2511
+ const { runRepair, formatRepairResult, exitCodeForRepair } = await import("./repair-JYRH2ES4.js");
2512
+ const result = await runRepair({
2513
+ tool,
2514
+ interactive: isInteractive()
2515
+ });
2516
+ if (options.json) {
2517
+ console.log(JSON.stringify(result, null, 2));
2518
+ } else {
2519
+ console.log(formatRepairResult(result));
2520
+ }
2521
+ process.exitCode = exitCodeForRepair(result);
2522
+ }
4634
2523
  async function runPluginAction(plugin, fn) {
4635
2524
  try {
4636
2525
  return await fn();
@@ -4679,7 +2568,7 @@ function debugInvalidToolFlag(value, event) {
4679
2568
  { event, tool: value ?? null }
4680
2569
  )}
4681
2570
  `;
4682
- fs16.appendFileSync(logPath, line, "utf-8");
2571
+ fs2.appendFileSync(logPath, line, "utf-8");
4683
2572
  } catch {
4684
2573
  }
4685
2574
  }
@@ -4688,10 +2577,10 @@ async function postMonitoringPayload(result) {
4688
2577
  const timeoutId = setTimeout(() => controller.abort(), 5e3);
4689
2578
  const debug = process.env.OLAKAI_MONITOR_DEBUG === "1";
4690
2579
  const logPath = `/tmp/olakai-monitor-debug-${process.pid}.log`;
4691
- const log2 = (event, data) => {
2580
+ const log = (event, data) => {
4692
2581
  if (!debug) return;
4693
2582
  try {
4694
- fs16.appendFileSync(
2583
+ fs2.appendFileSync(
4695
2584
  logPath,
4696
2585
  `[${(/* @__PURE__ */ new Date()).toISOString()}] dispatcher/${event}: ${JSON.stringify(data)}
4697
2586
  `,
@@ -4701,7 +2590,7 @@ async function postMonitoringPayload(result) {
4701
2590
  }
4702
2591
  };
4703
2592
  try {
4704
- log2("posting", {
2593
+ log("posting", {
4705
2594
  endpoint: result.transport.endpoint,
4706
2595
  apiKeyPresent: Boolean(result.transport.apiKey),
4707
2596
  apiKeyPrefix: result.transport.apiKey ? result.transport.apiKey.slice(0, 8) + "..." : null,
@@ -4721,9 +2610,9 @@ async function postMonitoringPayload(result) {
4721
2610
  bodyPreview = (await response.text()).slice(0, 500);
4722
2611
  } catch {
4723
2612
  }
4724
- log2("posted", { status: response.status, bodyPreview });
2613
+ log("posted", { status: response.status, bodyPreview });
4725
2614
  } catch (err) {
4726
- log2("post-error", {
2615
+ log("post-error", {
4727
2616
  name: err instanceof Error ? err.name : "unknown",
4728
2617
  message: err instanceof Error ? err.message : String(err)
4729
2618
  });
@@ -4748,6 +2637,27 @@ function registerMonitorCommand(program2) {
4748
2637
  "--tool <tool>",
4749
2638
  `Tool to inspect (${TOOL_IDS.join("|")}). Prompts when omitted in interactive mode.`
4750
2639
  ).option("--json", "Output as JSON").action(statusCommand);
2640
+ monitor.command("list").description(
2641
+ "List every workspace monitored on this machine (the machine lens)"
2642
+ ).option("--json", "Output the raw registry entries as JSON").action(listCommand6);
2643
+ monitor.command("doctor").description(
2644
+ "Diagnose (and optionally repair) monitoring health for this workspace or the whole machine"
2645
+ ).option(
2646
+ "--tool <tool>",
2647
+ `Tool to diagnose (${TOOL_IDS.join("|")}). Prompts when omitted in interactive mode. Ignored with --all.`
2648
+ ).option(
2649
+ "--all",
2650
+ "Diagnose every workspace monitored on this machine (the machine lens), not just the current one"
2651
+ ).option("--fix", "Attempt to repair fixable failures (idempotent, best-effort)").option(
2652
+ "--recreate-missing",
2653
+ "With --fix, also recreate a self-monitor agent that no longer exists on the backend (provisions a NEW agent). Off by default; 'olakai monitor repair' is the heavier alternative."
2654
+ ).option("--json", "Output the structured diagnostic results as JSON").action(doctorCommand);
2655
+ monitor.command("repair").description(
2656
+ "Forcefully re-initialize monitoring for this workspace (re-merge hooks, re-link/recreate the agent if needed) while preserving agent linkage"
2657
+ ).option(
2658
+ "--tool <tool>",
2659
+ `Tool to repair (${TOOL_IDS.join("|")}). Prompts when omitted in interactive mode.`
2660
+ ).option("--json", "Output the structured repair result as JSON").action(repairCommand);
4751
2661
  monitor.command("disable").description("Remove Olakai monitoring from this workspace").option(
4752
2662
  "--tool <tool>",
4753
2663
  `Tool to disable (${TOOL_IDS.join("|")}). Prompts when omitted in interactive mode.`