@triflux/remote 10.31.0 → 10.33.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.
@@ -0,0 +1,94 @@
1
+ import { execFile } from "node:child_process";
2
+
3
+ export const FOCUS_SCRIPT_TIMEOUT_MS = 5_000;
4
+
5
+ const DEFAULT_FOCUS_CANDIDATES = [
6
+ "iTerm2",
7
+ "Terminal",
8
+ "Codex",
9
+ "Claude",
10
+ "Antigravity",
11
+ "Code",
12
+ ];
13
+
14
+ function normalizeAgentId(value) {
15
+ const id = String(value || "")
16
+ .trim()
17
+ .toLowerCase();
18
+ if (id === "agy" || id === "anti") return "antigravity";
19
+ return id;
20
+ }
21
+
22
+ export function getFocusCandidates({ agentId } = {}) {
23
+ switch (normalizeAgentId(agentId)) {
24
+ case "codex":
25
+ return ["Codex", "iTerm2", "Terminal", "Code"];
26
+ case "claude":
27
+ return ["Claude", "iTerm2", "Terminal"];
28
+ case "antigravity":
29
+ return ["Antigravity", "iTerm2", "Terminal"];
30
+ default:
31
+ return [...DEFAULT_FOCUS_CANDIDATES];
32
+ }
33
+ }
34
+
35
+ function appleScriptList(values) {
36
+ return `{${values.map((value) => JSON.stringify(String(value))).join(", ")}}`;
37
+ }
38
+
39
+ export function buildFocusScript({ agentId, appCandidates } = {}) {
40
+ const candidates = Array.isArray(appCandidates)
41
+ ? appCandidates.map(String).filter(Boolean)
42
+ : getFocusCandidates({ agentId });
43
+ return `
44
+ set appCandidates to ${appleScriptList(candidates)}
45
+ tell application "System Events"
46
+ set runningNames to name of every process
47
+ end tell
48
+ repeat with appName in appCandidates
49
+ set appText to appName as text
50
+ if runningNames contains appText then
51
+ tell application appText to activate
52
+ return "activated " & appText
53
+ end if
54
+ end repeat
55
+ return "no focus candidate running"
56
+ `;
57
+ }
58
+
59
+ export function focusSessionOnMac(target = {}, maybeUdsId = null) {
60
+ const normalizedTarget =
61
+ target && typeof target === "object"
62
+ ? target
63
+ : { sessionId: target, udsId: maybeUdsId };
64
+ const script = buildFocusScript({ agentId: normalizedTarget.agentId });
65
+ return new Promise((resolve) => {
66
+ execFile(
67
+ "osascript",
68
+ ["-e", script],
69
+ { timeout: FOCUS_SCRIPT_TIMEOUT_MS },
70
+ (err, stdout = "", stderr = "") => {
71
+ const output = String(stdout || stderr || "").trim();
72
+ if (err) {
73
+ console.error("mac-focus error:", err?.message || err);
74
+ resolve({
75
+ ok: false,
76
+ sessionId: normalizedTarget.sessionId || null,
77
+ pid: Number(normalizedTarget.pid) || null,
78
+ agentId: normalizedTarget.agentId || null,
79
+ error: err?.message || String(err),
80
+ output,
81
+ });
82
+ return;
83
+ }
84
+ resolve({
85
+ ok: true,
86
+ sessionId: normalizedTarget.sessionId || null,
87
+ pid: Number(normalizedTarget.pid) || null,
88
+ agentId: normalizedTarget.agentId || null,
89
+ output,
90
+ });
91
+ },
92
+ );
93
+ });
94
+ }
@@ -0,0 +1,133 @@
1
+ import Cocoa
2
+ import WebKit
3
+
4
+ class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate {
5
+ var statusItem: NSStatusItem!
6
+ var popover: NSPopover!
7
+ var webVC: WebViewController!
8
+ var port: String = "27888"
9
+
10
+ func applicationDidFinishLaunching(_ aNotification: Notification) {
11
+ if CommandLine.arguments.count > 1 {
12
+ port = CommandLine.arguments[1]
13
+ }
14
+
15
+ statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
16
+ if let button = statusItem.button {
17
+ button.title = "T"
18
+ button.target = self
19
+ button.action = #selector(togglePopover(_:))
20
+ }
21
+
22
+ webVC = WebViewController()
23
+ webVC.port = port
24
+ webVC.onFocusComplete = { [weak self] in
25
+ self?.popover.performClose(nil)
26
+ }
27
+
28
+ popover = NSPopover()
29
+ popover.contentViewController = webVC
30
+ popover.behavior = .transient
31
+ popover.animates = false
32
+ popover.delegate = self
33
+ }
34
+
35
+ @objc func togglePopover(_ sender: Any?) {
36
+ if popover.isShown {
37
+ popover.performClose(sender)
38
+ } else {
39
+ if let button = statusItem.button {
40
+ webVC.reloadForPopover()
41
+ popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ class WebViewController: NSViewController, WKNavigationDelegate, WKScriptMessageHandler {
48
+ var webView: WKWebView!
49
+ var port: String = "27888"
50
+ var retryWorkItem: DispatchWorkItem?
51
+ var onFocusComplete: (() -> Void)?
52
+
53
+ func logError(_ msg: String) {
54
+ let path = "/tmp/mac-tray.log"
55
+ if let outputStream = OutputStream(toFileAtPath: path, append: true) {
56
+ outputStream.open()
57
+ let text = "\(Date()): \(msg)\n"
58
+ let bytesWritten = outputStream.write(text, maxLength: text.utf8.count)
59
+ outputStream.close()
60
+ }
61
+ }
62
+
63
+ override func loadView() {
64
+ let webConfiguration = WKWebViewConfiguration()
65
+ webConfiguration.userContentController.add(self, name: "tray")
66
+ let initialFrame = NSRect(x: 0, y: 0, width: 320, height: 520)
67
+ webView = WKWebView(frame: initialFrame, configuration: webConfiguration)
68
+
69
+ // Transparent background for Glassmorphism
70
+ webView.setValue(false, forKey: "drawsBackground")
71
+
72
+ self.view = NSView(frame: initialFrame)
73
+ webView.frame = self.view.bounds
74
+ webView.autoresizingMask = [.width, .height]
75
+ self.view.addSubview(webView)
76
+
77
+ self.preferredContentSize = initialFrame.size
78
+ }
79
+
80
+ override func viewDidLoad() {
81
+ super.viewDidLoad()
82
+ webView.navigationDelegate = self
83
+ loadTray()
84
+ }
85
+
86
+ func loadTray() {
87
+ retryWorkItem?.cancel()
88
+ if let url = URL(string: "http://127.0.0.1:\(port)/tray.html?t=\(Date().timeIntervalSince1970)") {
89
+ let request = URLRequest(url: url)
90
+ webView.load(request)
91
+ } else {
92
+ logError("Invalid URL")
93
+ }
94
+ }
95
+
96
+ func reloadForPopover() {
97
+ if isViewLoaded {
98
+ loadTray()
99
+ }
100
+ }
101
+
102
+ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
103
+ logError("Failed to load: \(error.localizedDescription)")
104
+ let retry = DispatchWorkItem { [weak self] in
105
+ self?.loadTray()
106
+ }
107
+ retryWorkItem = retry
108
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: retry)
109
+ }
110
+
111
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
112
+ retryWorkItem?.cancel()
113
+ retryWorkItem = nil
114
+ logError("Successfully loaded URL")
115
+ }
116
+
117
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
118
+ guard message.name == "tray" else { return }
119
+ if let body = message.body as? [String: Any],
120
+ let type = body["type"] as? String,
121
+ type == "focus-complete" {
122
+ DispatchQueue.main.async { [weak self] in
123
+ self?.onFocusComplete?()
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ let app = NSApplication.shared
130
+ let delegate = AppDelegate()
131
+ app.delegate = delegate
132
+ app.setActivationPolicy(.accessory)
133
+ app.run()
@@ -0,0 +1,138 @@
1
+ // hub/promote-penalties.mjs — pending-penalties.jsonl → store adaptive_rules 승격
2
+ //
3
+ // 흐름:
4
+ // 1. safety-guard BLOCK → error-context.mjs → pending-penalties.jsonl 기록
5
+ // 2. 이 스크립트가 penalties를 읽어 store.addAdaptiveRule()로 승격
6
+ // 3. 승격 완료된 penalty는 파일에서 제거
7
+ //
8
+ // 호출 시점:
9
+ // - Hub 시작 시 (server.mjs에서 import)
10
+ // - 수동: node hub/promote-penalties.mjs
11
+
12
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { adaptiveRuleFromError, promoteRule } from "@triflux/core/hub/reflexion.mjs";
15
+
16
+ const HOME = process.env.HOME || process.env.USERPROFILE || "";
17
+ const PENALTY_DIR = join(HOME, ".triflux", "reflexion");
18
+ const PENALTY_FILE = join(PENALTY_DIR, "pending-penalties.jsonl");
19
+
20
+ function loadPenalties() {
21
+ if (!existsSync(PENALTY_FILE)) return [];
22
+ try {
23
+ return readFileSync(PENALTY_FILE, "utf8")
24
+ .split("\n")
25
+ .filter(Boolean)
26
+ .map((line) => {
27
+ try {
28
+ return JSON.parse(line);
29
+ } catch {
30
+ return null;
31
+ }
32
+ })
33
+ .filter(Boolean);
34
+ } catch {
35
+ return [];
36
+ }
37
+ }
38
+
39
+ function clearPenalties() {
40
+ try {
41
+ writeFileSync(PENALTY_FILE, "", "utf8");
42
+ } catch {
43
+ /* ignore */
44
+ }
45
+ }
46
+
47
+ /**
48
+ * pending penalties를 adaptive rules로 승격한다.
49
+ *
50
+ * @param {object} store — store-adapter 인스턴스 (addAdaptiveRule 필요)
51
+ * @param {object} [options]
52
+ * @param {string} [options.projectSlug] — 프로젝트 식별자
53
+ * @param {number} [options.sessionCount] — 현재 세션 번호
54
+ * @returns {{ promoted: number, skipped: number, total: number }}
55
+ */
56
+ export function promotePenalties(store, options = {}) {
57
+ const penalties = loadPenalties();
58
+ if (penalties.length === 0) return { promoted: 0, skipped: 0, total: 0 };
59
+
60
+ const projectSlug = options.projectSlug || "triflux";
61
+ const sessionCount = options.sessionCount || 1;
62
+ let promoted = 0;
63
+ let skipped = 0;
64
+
65
+ for (const penalty of penalties) {
66
+ const errorContext = {
67
+ errorText: penalty.error_pattern || "",
68
+ errorMessage: `[${penalty.source}] ${penalty.error_pattern || "guard block"}`,
69
+ command: penalty.command_preview || "",
70
+ projectSlug,
71
+ sessionCount,
72
+ tool: penalty.tool || "Bash",
73
+ };
74
+
75
+ const rule = adaptiveRuleFromError(errorContext);
76
+ if (!rule) {
77
+ skipped++;
78
+ continue;
79
+ }
80
+
81
+ try {
82
+ if (store.addAdaptiveRule) {
83
+ const existing = store.findAdaptiveRule?.(
84
+ projectSlug,
85
+ rule.error_pattern,
86
+ );
87
+ if (existing) {
88
+ // 기존 규칙 → confidence 승격
89
+ promoteRule(store, projectSlug, rule.error_pattern);
90
+ } else {
91
+ // 새 규칙 → 추가
92
+ store.addAdaptiveRule({
93
+ project_slug: projectSlug,
94
+ pattern: rule.error_pattern,
95
+ error_message: rule.error_message,
96
+ solution: rule.solution,
97
+ context:
98
+ typeof rule.context === "string"
99
+ ? rule.context
100
+ : JSON.stringify(rule.context),
101
+ confidence: rule.confidence,
102
+ hit_count: rule.hit_count,
103
+ last_seen_ms: Date.now(),
104
+ });
105
+ }
106
+ promoted++;
107
+ } else {
108
+ skipped++;
109
+ }
110
+ } catch {
111
+ skipped++;
112
+ }
113
+ }
114
+
115
+ // 승격 완료된 penalties 제거
116
+ if (promoted > 0) clearPenalties();
117
+
118
+ return { promoted, skipped, total: penalties.length };
119
+ }
120
+
121
+ /**
122
+ * store 없이 standalone 실행 — penalties 요약만 출력
123
+ */
124
+ export function dryRun() {
125
+ const penalties = loadPenalties();
126
+ console.log(`[promote-penalties] ${penalties.length} pending penalties`);
127
+ for (const p of penalties) {
128
+ console.log(
129
+ ` ${p.ts?.slice(0, 19)} [${p.source}] ${p.error_pattern?.slice(0, 80)}`,
130
+ );
131
+ }
132
+ return penalties;
133
+ }
134
+
135
+ // CLI 직접 실행
136
+ if (process.argv[1]?.endsWith("promote-penalties.mjs")) {
137
+ dryRun();
138
+ }