kontexta 6.1.0 → 6.1.1
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/bundle/standalone/CHANGELOG.md +12 -0
- package/bundle/standalone/apps/web/.next/BUILD_ID +1 -1
- package/bundle/standalone/apps/web/.next/app-build-manifest.json +46 -46
- package/bundle/standalone/apps/web/.next/app-path-routes-manifest.json +10 -10
- package/bundle/standalone/apps/web/.next/build-manifest.json +2 -2
- package/bundle/standalone/apps/web/.next/prerender-manifest.json +16 -16
- package/bundle/standalone/apps/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/_not-found.html +1 -1
- package/bundle/standalone/apps/web/.next/server/app/_not-found.rsc +4 -4
- package/bundle/standalone/apps/web/.next/server/app/api/about/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/agents/[id]/hooks/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/agents/[id]/mcp/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/agents/[id]/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/agents/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/auth/login/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/auth/logout/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/auth/setup/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/auth/status/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/auth/token/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/calendar/conflicts/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/calendar/entities/[id]/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/calendar/entities/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/calendar/events/[id]/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/calendar/events/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/calendar/ics/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/calendar/links/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/calendar/settings/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/clip/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/docker-config/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/export/zip/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/backlinks/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/download/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/export-html/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/export-pdf/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/history/restore/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/history/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/move/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/files/upload/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/folders/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/git/remote/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/git/sync-all/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/hands/test-pattern/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/hands/validate/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/health/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/install-snippets/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/mcp-tools/route.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/mcp-tools/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/profile/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/hands-config/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/journal-config/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/journal-status/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/onboard/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/refresh/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/sync/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/onboard/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/projects/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/publish/html/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/publish/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/refresh/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/reindex/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/reports/resources/[name]/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/search/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/tags/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/version-check/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/welcome/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/api/ws-config/route_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/calendar/page_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/page.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/page_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/preview/motifs/page_client-reference-manifest.js +1 -1
- package/bundle/standalone/apps/web/.next/server/app/preview/motifs.html +2 -2
- package/bundle/standalone/apps/web/.next/server/app/preview/motifs.rsc +4 -4
- package/bundle/standalone/apps/web/.next/server/app-paths-manifest.json +10 -10
- package/bundle/standalone/apps/web/.next/server/chunks/3668.js +2 -2
- package/bundle/standalone/apps/web/.next/server/pages/404.html +1 -1
- package/bundle/standalone/apps/web/.next/server/pages/500.html +1 -1
- package/bundle/standalone/apps/web/.next/server/server-reference-manifest.json +1 -1
- package/bundle/standalone/apps/web/.next/static/chunks/app/{layout-da10917c290d5da7.js → layout-b3fc3a7cf96952bd.js} +1 -1
- package/bundle/standalone/apps/web/.next/static/chunks/app/{page-86e385abedf10ccd.js → page-df588fddee22c453.js} +1 -1
- package/bundle/standalone/apps/web/.next/static/css/{d6e83b3f51ebdda3.css → c9d10f1f97d629ff.css} +1 -1
- package/bundle/standalone/apps/web/package.json +4 -4
- package/bundle/standalone/apps/web/src/lib/mcp-tools.json +1 -1
- package/bundle/standalone/node_modules/kontexta-mcp/dist/index.js +25 -5
- package/bundle/standalone/node_modules/kontexta-mcp/dist/index.js.map +1 -1
- package/bundle/standalone/node_modules/kontexta-mcp/package.json +1 -1
- package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.d.ts +3 -0
- package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.d.ts.map +1 -1
- package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.js +4 -0
- package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.js.map +1 -1
- package/bundle/standalone/node_modules/kxta-core/dist/index.d.ts +1 -1
- package/bundle/standalone/node_modules/kxta-core/dist/index.d.ts.map +1 -1
- package/bundle/standalone/node_modules/kxta-core/dist/index.js +1 -1
- package/bundle/standalone/node_modules/kxta-core/dist/index.js.map +1 -1
- package/bundle/standalone/node_modules/kxta-core/package.json +1 -1
- package/bundle/standalone/node_modules/kxta-publish/package.json +2 -2
- package/bundle/standalone/package.json +1 -1
- package/dist/index.js +5 -0
- package/dist/skill-GG5D7ZPL.js +90 -0
- package/package.json +2 -1
- package/skills/kontexta/README.md +71 -0
- package/skills/kontexta/SKILL.md +51 -0
- package/skills/kontexta/scripts/kxta.py +450 -0
- package/skills/kontexta/tests/test_rules.py +82 -0
- /package/bundle/standalone/apps/web/.next/static/{0ZL7PJwYf_7ZTTXE_AM0S → Q-gj-xAe-1yQapG2yO_2G}/_buildManifest.js +0 -0
- /package/bundle/standalone/apps/web/.next/static/{0ZL7PJwYf_7ZTTXE_AM0S → Q-gj-xAe-1yQapG2yO_2G}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Stdio MCP client for the Kontexta (kxta) server, via a persistent per-cwd daemon."""
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import secrets
|
|
9
|
+
import shlex
|
|
10
|
+
import shutil
|
|
11
|
+
import socket
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
IS_WINDOWS = os.name == "nt"
|
|
18
|
+
if IS_WINDOWS:
|
|
19
|
+
import msvcrt
|
|
20
|
+
else:
|
|
21
|
+
import fcntl
|
|
22
|
+
|
|
23
|
+
# KXTA_SERVER: a .js entrypoint (run with node) or a full command line; defaults to the published CLI.
|
|
24
|
+
SERVER = os.environ.get("KXTA_SERVER", "npx -y --package=kontexta@latest kontexta mcp")
|
|
25
|
+
IDLE_SECONDS = int(os.environ.get("KXTA_IDLE_SECONDS", "1800"))
|
|
26
|
+
RUN_DIR = os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~/.cache"), "kxta")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def server_argv():
|
|
30
|
+
path = os.path.abspath(os.path.expanduser(SERVER))
|
|
31
|
+
if path.endswith((".js", ".mjs")) and os.path.isfile(path):
|
|
32
|
+
return ["node", path]
|
|
33
|
+
if IS_WINDOWS:
|
|
34
|
+
# Non-POSIX split keeps backslashes in paths but leaves the quotes on, so strip them.
|
|
35
|
+
return [a[1:-1] if len(a) > 1 and a[0] == a[-1] == '"' else a for a in shlex.split(SERVER, posix=False)]
|
|
36
|
+
return shlex.split(SERVER)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def spawnable(argv):
|
|
40
|
+
# Windows can't exec npx.cmd-style shims directly; resolve via PATH/PATHEXT and route through cmd.
|
|
41
|
+
exe = shutil.which(argv[0]) or argv[0]
|
|
42
|
+
if IS_WINDOWS and exe.lower().endswith((".cmd", ".bat")):
|
|
43
|
+
return ["cmd.exe", "/c", exe, *argv[1:]]
|
|
44
|
+
return [exe, *argv[1:]]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def state_path(cwd):
|
|
48
|
+
key = os.path.normcase(os.path.abspath(cwd))
|
|
49
|
+
return os.path.join(RUN_DIR, hashlib.sha1(key.encode()).hexdigest()[:12] + ".json")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class FileLock:
|
|
53
|
+
def __init__(self, path):
|
|
54
|
+
self.f = open(path, "a+")
|
|
55
|
+
|
|
56
|
+
def __enter__(self):
|
|
57
|
+
if IS_WINDOWS:
|
|
58
|
+
while True:
|
|
59
|
+
try:
|
|
60
|
+
self.f.seek(0)
|
|
61
|
+
msvcrt.locking(self.f.fileno(), msvcrt.LK_LOCK, 1)
|
|
62
|
+
return self
|
|
63
|
+
except OSError:
|
|
64
|
+
time.sleep(0.1)
|
|
65
|
+
fcntl.flock(self.f, fcntl.LOCK_EX)
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
def __exit__(self, *exc):
|
|
69
|
+
try:
|
|
70
|
+
if IS_WINDOWS:
|
|
71
|
+
self.f.seek(0)
|
|
72
|
+
msvcrt.locking(self.f.fileno(), msvcrt.LK_UNLCK, 1)
|
|
73
|
+
else:
|
|
74
|
+
fcntl.flock(self.f, fcntl.LOCK_UN)
|
|
75
|
+
finally:
|
|
76
|
+
self.f.close()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def write_line(stream, obj):
|
|
80
|
+
stream.write((json.dumps(obj) + "\n").encode("utf-8"))
|
|
81
|
+
stream.flush()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class McpClient:
|
|
85
|
+
def __init__(self, cwd):
|
|
86
|
+
env = dict(os.environ)
|
|
87
|
+
env.setdefault("KONTEXTA_AGENT", "claude-code")
|
|
88
|
+
argv = json.loads(env.pop("KXTA_SERVER_ARGV")) if "KXTA_SERVER_ARGV" in env else server_argv()
|
|
89
|
+
self.proc = subprocess.Popen(
|
|
90
|
+
spawnable(argv),
|
|
91
|
+
cwd=cwd,
|
|
92
|
+
env=env,
|
|
93
|
+
stdin=subprocess.PIPE,
|
|
94
|
+
stdout=subprocess.PIPE,
|
|
95
|
+
stderr=subprocess.DEVNULL,
|
|
96
|
+
creationflags=subprocess.CREATE_NO_WINDOW if IS_WINDOWS else 0,
|
|
97
|
+
)
|
|
98
|
+
self.next_id = 0
|
|
99
|
+
self.lock = threading.Lock()
|
|
100
|
+
self.init = self.request("initialize", {
|
|
101
|
+
"protocolVersion": "2024-11-05",
|
|
102
|
+
"capabilities": {},
|
|
103
|
+
"clientInfo": {"name": "kxta-skill", "version": "2.0"},
|
|
104
|
+
})
|
|
105
|
+
write_line(self.proc.stdin, {"jsonrpc": "2.0", "method": "notifications/initialized"})
|
|
106
|
+
|
|
107
|
+
def request(self, method, params):
|
|
108
|
+
with self.lock:
|
|
109
|
+
self.next_id += 1
|
|
110
|
+
rid = self.next_id
|
|
111
|
+
write_line(self.proc.stdin, {"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
|
|
112
|
+
for line in self.proc.stdout:
|
|
113
|
+
try:
|
|
114
|
+
msg = json.loads(line.decode("utf-8"))
|
|
115
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
116
|
+
continue
|
|
117
|
+
# Server-initiated requests (ping, roots/list) must be answered or the server stalls.
|
|
118
|
+
if "method" in msg and "id" in msg:
|
|
119
|
+
if msg["method"] == "ping":
|
|
120
|
+
write_line(self.proc.stdin, {"jsonrpc": "2.0", "id": msg["id"], "result": {}})
|
|
121
|
+
else:
|
|
122
|
+
write_line(self.proc.stdin, {"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32601, "message": "unsupported"}})
|
|
123
|
+
continue
|
|
124
|
+
if msg.get("id") != rid:
|
|
125
|
+
continue
|
|
126
|
+
if "error" in msg:
|
|
127
|
+
raise RuntimeError(f"MCP error {msg['error'].get('code')}: {msg['error'].get('message')}")
|
|
128
|
+
return msg["result"]
|
|
129
|
+
raise RuntimeError("kxta server exited without responding")
|
|
130
|
+
|
|
131
|
+
def alive(self):
|
|
132
|
+
return self.proc.poll() is None
|
|
133
|
+
|
|
134
|
+
def close(self):
|
|
135
|
+
try:
|
|
136
|
+
self.proc.stdin.close()
|
|
137
|
+
self.proc.wait(timeout=5)
|
|
138
|
+
except Exception:
|
|
139
|
+
self.proc.kill()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def dispatch(client, req):
|
|
143
|
+
op = req["op"]
|
|
144
|
+
if op == "context":
|
|
145
|
+
return {"text": client.init.get("instructions", "")}
|
|
146
|
+
if op == "tools":
|
|
147
|
+
return {"tools": client.request("tools/list", {})["tools"]}
|
|
148
|
+
if op == "call":
|
|
149
|
+
return {"result": client.request("tools/call", {"name": req["tool"], "arguments": req.get("args") or {}})}
|
|
150
|
+
raise RuntimeError(f"unknown op: {op}")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def serve(cwd):
|
|
154
|
+
path = state_path(cwd)
|
|
155
|
+
client = McpClient(cwd)
|
|
156
|
+
token = secrets.token_hex(16)
|
|
157
|
+
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
158
|
+
srv.bind(("127.0.0.1", 0))
|
|
159
|
+
srv.listen(16)
|
|
160
|
+
srv.settimeout(0.5)
|
|
161
|
+
tmp = path + ".tmp"
|
|
162
|
+
with open(tmp, "w") as f:
|
|
163
|
+
json.dump({"port": srv.getsockname()[1], "token": token, "pid": os.getpid()}, f)
|
|
164
|
+
if not IS_WINDOWS:
|
|
165
|
+
os.chmod(tmp, 0o600)
|
|
166
|
+
os.replace(tmp, path)
|
|
167
|
+
last = [time.time()]
|
|
168
|
+
stop = threading.Event()
|
|
169
|
+
|
|
170
|
+
def handle(conn):
|
|
171
|
+
with conn, conn.makefile("rwb") as f:
|
|
172
|
+
for line in f:
|
|
173
|
+
last[0] = time.time()
|
|
174
|
+
try:
|
|
175
|
+
req = json.loads(line.decode("utf-8"))
|
|
176
|
+
if not hmac.compare_digest(str(req.get("token", "")), token):
|
|
177
|
+
resp = {"ok": False, "error": "bad token"}
|
|
178
|
+
elif req.get("op") == "stop":
|
|
179
|
+
stop.set()
|
|
180
|
+
resp = {"ok": True}
|
|
181
|
+
else:
|
|
182
|
+
resp = {"ok": True, **dispatch(client, req)}
|
|
183
|
+
except Exception as e:
|
|
184
|
+
resp = {"ok": False, "error": str(e)}
|
|
185
|
+
write_line(f, resp)
|
|
186
|
+
last[0] = time.time()
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
while not stop.is_set() and client.alive() and time.time() - last[0] < IDLE_SECONDS:
|
|
190
|
+
try:
|
|
191
|
+
conn, _ = srv.accept()
|
|
192
|
+
except socket.timeout:
|
|
193
|
+
continue
|
|
194
|
+
conn.settimeout(None)
|
|
195
|
+
threading.Thread(target=handle, args=(conn,), daemon=True).start()
|
|
196
|
+
finally:
|
|
197
|
+
srv.close()
|
|
198
|
+
try:
|
|
199
|
+
os.remove(path)
|
|
200
|
+
except OSError:
|
|
201
|
+
pass
|
|
202
|
+
client.close()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def connect(cwd):
|
|
206
|
+
with open(state_path(cwd)) as f:
|
|
207
|
+
state = json.load(f)
|
|
208
|
+
s = socket.create_connection(("127.0.0.1", state["port"]), timeout=5)
|
|
209
|
+
s.settimeout(None)
|
|
210
|
+
return s, state["token"]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def spawn_daemon(cwd):
|
|
214
|
+
kwargs = {}
|
|
215
|
+
if IS_WINDOWS:
|
|
216
|
+
kwargs["creationflags"] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
|
|
217
|
+
else:
|
|
218
|
+
kwargs["start_new_session"] = True
|
|
219
|
+
return subprocess.Popen(
|
|
220
|
+
[sys.executable, os.path.abspath(__file__), "_serve", cwd],
|
|
221
|
+
env={**os.environ, "KXTA_SERVER_ARGV": json.dumps(server_argv())},
|
|
222
|
+
stdin=subprocess.DEVNULL,
|
|
223
|
+
stdout=subprocess.DEVNULL,
|
|
224
|
+
stderr=subprocess.DEVNULL,
|
|
225
|
+
**kwargs,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def ensure_daemon(cwd):
|
|
230
|
+
try:
|
|
231
|
+
return connect(cwd)
|
|
232
|
+
except (OSError, ValueError):
|
|
233
|
+
pass
|
|
234
|
+
os.makedirs(RUN_DIR, exist_ok=True)
|
|
235
|
+
# Serialize spawns so parallel callers don't start duplicate daemons.
|
|
236
|
+
with FileLock(state_path(cwd) + ".lock"):
|
|
237
|
+
try:
|
|
238
|
+
return connect(cwd)
|
|
239
|
+
except (OSError, ValueError):
|
|
240
|
+
try:
|
|
241
|
+
os.remove(state_path(cwd))
|
|
242
|
+
except OSError:
|
|
243
|
+
pass
|
|
244
|
+
daemon = spawn_daemon(cwd)
|
|
245
|
+
# First npx run may download the package.
|
|
246
|
+
deadline = time.time() + 120
|
|
247
|
+
while time.time() < deadline and daemon.poll() is None:
|
|
248
|
+
try:
|
|
249
|
+
return connect(cwd)
|
|
250
|
+
except (OSError, ValueError):
|
|
251
|
+
time.sleep(0.1)
|
|
252
|
+
raise RuntimeError(f"kxta server failed to start: {' '.join(server_argv())} (check Node 22+ or set KXTA_SERVER)")
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
class Session:
|
|
256
|
+
def __init__(self, cwd):
|
|
257
|
+
self.sock, self.token = ensure_daemon(cwd)
|
|
258
|
+
self.f = self.sock.makefile("rwb")
|
|
259
|
+
|
|
260
|
+
def ask(self, req):
|
|
261
|
+
write_line(self.f, {**req, "token": self.token})
|
|
262
|
+
line = self.f.readline()
|
|
263
|
+
if not line:
|
|
264
|
+
raise RuntimeError("kxta daemon closed the connection")
|
|
265
|
+
resp = json.loads(line.decode("utf-8"))
|
|
266
|
+
if not resp.get("ok"):
|
|
267
|
+
raise RuntimeError(resp.get("error"))
|
|
268
|
+
return resp
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
# Same fence the server's rules block uses, so the staleness check and nudges cover this block too.
|
|
272
|
+
RULES_BEGIN_RE = re.compile(r"<!--\s*BEGIN\s+kontexta:rules\s+v(\d+\.\d+\.\d+)\s*-->")
|
|
273
|
+
RULES_END_RE = re.compile(r"<!--\s*END\s+kontexta:rules(?:\s+v\d+\.\d+\.\d+)?\s*-->")
|
|
274
|
+
FLAVOR_TAG = "<!-- kontexta:flavor skill-bridge -->"
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def short_desc(desc, limit=140):
|
|
278
|
+
text = " ".join((desc or "").split())
|
|
279
|
+
m = re.search(r"[.!?](?:\s|$)", text)
|
|
280
|
+
if m and m.end() <= limit:
|
|
281
|
+
return text[:m.end()].strip()
|
|
282
|
+
if len(text) <= limit:
|
|
283
|
+
return text
|
|
284
|
+
return text[:limit].rsplit(" ", 1)[0].rstrip(",;:(") + "..."
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def bridge_command():
|
|
288
|
+
script = os.path.abspath(__file__)
|
|
289
|
+
home = os.path.expanduser("~")
|
|
290
|
+
if script.startswith(home + os.sep):
|
|
291
|
+
script = "~" + script[len(home):].replace(os.sep, "/")
|
|
292
|
+
return f"{'python' if IS_WINDOWS else 'python3'} {script}"
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def render_rules_block(version, tools, cmd):
|
|
296
|
+
lines = [
|
|
297
|
+
f"<!-- BEGIN kontexta:rules v{version} -->",
|
|
298
|
+
FLAVOR_TAG,
|
|
299
|
+
"## kxta tools (via skill bridge)",
|
|
300
|
+
"",
|
|
301
|
+
"To call any tool below, run:",
|
|
302
|
+
f"`{cmd} call <tool> '<json-args>'`",
|
|
303
|
+
"",
|
|
304
|
+
f"Inspect inputs with `{cmd} schema <tool>`.",
|
|
305
|
+
"",
|
|
306
|
+
"Tools:",
|
|
307
|
+
]
|
|
308
|
+
lines += [f"- `{t['name']}` · {short_desc(t.get('description'), 120)}" for t in tools]
|
|
309
|
+
lines += ["", f"<!-- END kontexta:rules v{version} -->"]
|
|
310
|
+
return "\n".join(lines) + "\n"
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def apply_rules_block(content, block):
|
|
314
|
+
"""Insert or replace the fenced block. Returns (action, new_content); action is created, updated or unchanged."""
|
|
315
|
+
begins = list(RULES_BEGIN_RE.finditer(content))
|
|
316
|
+
if not begins:
|
|
317
|
+
sep = "" if not content or content.endswith("\n\n") else "\n" if content.endswith("\n") else "\n\n"
|
|
318
|
+
return "created", content + sep + block
|
|
319
|
+
if len(begins) > 1:
|
|
320
|
+
raise RuntimeError("duplicate kontexta rules marker found; fix the file by hand")
|
|
321
|
+
begin = begins[0]
|
|
322
|
+
end = RULES_END_RE.search(content, begin.end())
|
|
323
|
+
if not end:
|
|
324
|
+
raise RuntimeError("kontexta rules marker is malformed (BEGIN with no matching END)")
|
|
325
|
+
if content[begin.start():end.end()] == block.rstrip("\n"):
|
|
326
|
+
return "unchanged", content
|
|
327
|
+
return "updated", content[:begin.start()] + block.rstrip("\n") + content[end.end():]
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def rules_version(sess):
|
|
331
|
+
projects = json.loads(result_text(sess.ask({"op": "call", "tool": "projects_list", "args": {}})["result"]))
|
|
332
|
+
for p in projects:
|
|
333
|
+
v = (p.get("agent_rules") or {}).get("latest_version")
|
|
334
|
+
if v:
|
|
335
|
+
return v
|
|
336
|
+
raise RuntimeError("could not read the rules version from the server (projects_list returned no projects)")
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def write_rules(path, block):
|
|
340
|
+
if os.path.islink(path):
|
|
341
|
+
raise RuntimeError(f"refusing to write through symlink: {path}")
|
|
342
|
+
content = ""
|
|
343
|
+
if os.path.exists(path):
|
|
344
|
+
with open(path, encoding="utf-8", newline="") as f:
|
|
345
|
+
content = f.read()
|
|
346
|
+
action, new = apply_rules_block(content, block)
|
|
347
|
+
if action != "unchanged":
|
|
348
|
+
tmp = f"{path}.tmp.{os.getpid()}"
|
|
349
|
+
with open(tmp, "w", encoding="utf-8", newline="") as f:
|
|
350
|
+
f.write(new)
|
|
351
|
+
os.replace(tmp, path)
|
|
352
|
+
return action
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def result_text(result):
|
|
356
|
+
out = []
|
|
357
|
+
for item in result.get("content", []):
|
|
358
|
+
out.append(item["text"] if item.get("type") == "text" else json.dumps(item))
|
|
359
|
+
return "\n".join(out)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def main():
|
|
363
|
+
# Windows consoles default to a legacy code page; kxta output contains emoji and non-ASCII text.
|
|
364
|
+
for stream in (sys.stdin, sys.stdout, sys.stderr):
|
|
365
|
+
if hasattr(stream, "reconfigure"):
|
|
366
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
367
|
+
args = sys.argv[1:]
|
|
368
|
+
if args and args[0] == "_serve":
|
|
369
|
+
serve(args[1])
|
|
370
|
+
return
|
|
371
|
+
if not args or args[0] in ("-h", "--help"):
|
|
372
|
+
print("usage: kxta.py context | list | rules [--write [file]] | schema <tool> | call <tool> [json-args | -] | batch | stop")
|
|
373
|
+
return
|
|
374
|
+
cwd = os.environ.get("KXTA_CWD", os.getcwd())
|
|
375
|
+
cmd = args[0]
|
|
376
|
+
if cmd == "stop":
|
|
377
|
+
try:
|
|
378
|
+
sock, token = connect(cwd)
|
|
379
|
+
except (OSError, ValueError):
|
|
380
|
+
print("no daemon running")
|
|
381
|
+
return
|
|
382
|
+
with sock, sock.makefile("rwb") as f:
|
|
383
|
+
write_line(f, {"op": "stop", "token": token})
|
|
384
|
+
f.readline()
|
|
385
|
+
deadline = time.time() + 10
|
|
386
|
+
while os.path.exists(state_path(cwd)) and time.time() < deadline:
|
|
387
|
+
time.sleep(0.1)
|
|
388
|
+
print("stopped")
|
|
389
|
+
return
|
|
390
|
+
try:
|
|
391
|
+
sess = Session(cwd)
|
|
392
|
+
if cmd == "context":
|
|
393
|
+
print(sess.ask({"op": "context"})["text"])
|
|
394
|
+
elif cmd == "list":
|
|
395
|
+
for t in sess.ask({"op": "tools"})["tools"]:
|
|
396
|
+
desc = " ".join((t.get("description") or "").split())
|
|
397
|
+
print(f"{t['name']}: {desc[:140]}")
|
|
398
|
+
elif cmd == "rules":
|
|
399
|
+
# Versioned, minimal CLAUDE.md block (bridge prefix + tool list); lighter than admin_onboard_agent's.
|
|
400
|
+
opts = args[1:]
|
|
401
|
+
write = "--write" in opts
|
|
402
|
+
rest = [a for a in opts if a != "--write"]
|
|
403
|
+
if any(a.startswith("-") for a in rest) or len(rest) > 1 or (rest and not write):
|
|
404
|
+
sys.exit("usage: kxta.py rules [--write [file]] (default file: CLAUDE.md in the current directory)")
|
|
405
|
+
block = render_rules_block(rules_version(sess), sess.ask({"op": "tools"})["tools"], bridge_command())
|
|
406
|
+
if not write:
|
|
407
|
+
sys.stdout.write(block)
|
|
408
|
+
else:
|
|
409
|
+
path = os.path.join(cwd, rest[0] if rest else "CLAUDE.md")
|
|
410
|
+
print(f"{os.path.relpath(path, cwd)}: {write_rules(path, block)}")
|
|
411
|
+
elif cmd == "schema":
|
|
412
|
+
tools = {t["name"]: t for t in sess.ask({"op": "tools"})["tools"]}
|
|
413
|
+
tool = tools.get(args[1]) if len(args) > 1 else None
|
|
414
|
+
if not tool:
|
|
415
|
+
sys.exit(f"unknown tool: {args[1] if len(args) > 1 else ''}")
|
|
416
|
+
print(json.dumps(tool, indent=2))
|
|
417
|
+
elif cmd == "call":
|
|
418
|
+
if len(args) < 2:
|
|
419
|
+
sys.exit("call needs a tool name")
|
|
420
|
+
raw = args[2] if len(args) > 2 else "{}"
|
|
421
|
+
if raw == "-":
|
|
422
|
+
raw = sys.stdin.read()
|
|
423
|
+
result = sess.ask({"op": "call", "tool": args[1], "args": json.loads(raw)})["result"]
|
|
424
|
+
print(result_text(result))
|
|
425
|
+
if result.get("isError"):
|
|
426
|
+
sys.exit(1)
|
|
427
|
+
elif cmd == "batch":
|
|
428
|
+
# stdin: one {"tool": ..., "args": {...}} per line; stdout: one {"tool", "isError", "text"} per line
|
|
429
|
+
failed = False
|
|
430
|
+
for line in sys.stdin:
|
|
431
|
+
if not line.strip():
|
|
432
|
+
continue
|
|
433
|
+
item = json.loads(line)
|
|
434
|
+
try:
|
|
435
|
+
result = sess.ask({"op": "call", "tool": item["tool"], "args": item.get("args")})["result"]
|
|
436
|
+
out = {"tool": item["tool"], "isError": bool(result.get("isError")), "text": result_text(result)}
|
|
437
|
+
except RuntimeError as e:
|
|
438
|
+
out = {"tool": item["tool"], "isError": True, "text": str(e)}
|
|
439
|
+
failed = failed or out["isError"]
|
|
440
|
+
print(json.dumps(out), flush=True)
|
|
441
|
+
if failed:
|
|
442
|
+
sys.exit(1)
|
|
443
|
+
else:
|
|
444
|
+
sys.exit(f"unknown command: {cmd}")
|
|
445
|
+
except RuntimeError as e:
|
|
446
|
+
sys.exit(str(e))
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
if __name__ == "__main__":
|
|
450
|
+
main()
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import os
|
|
3
|
+
import tempfile
|
|
4
|
+
import unittest
|
|
5
|
+
|
|
6
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
7
|
+
spec = importlib.util.spec_from_file_location("kxta", os.path.join(HERE, "..", "scripts", "kxta.py"))
|
|
8
|
+
kxta = importlib.util.module_from_spec(spec)
|
|
9
|
+
spec.loader.exec_module(kxta)
|
|
10
|
+
|
|
11
|
+
TOOLS = [
|
|
12
|
+
{"name": "files_search", "description": "Full-text keyword search. Returns ranked matches with excerpts."},
|
|
13
|
+
{"name": "journal_write", "description": "Write one event to the journal."},
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def block(version="3.2.0", tools=TOOLS):
|
|
18
|
+
return kxta.render_rules_block(version, tools, "python3 ~/.claude/skills/kontexta/scripts/kxta.py")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RulesBlock(unittest.TestCase):
|
|
22
|
+
def test_block_uses_server_marker_so_staleness_check_sees_it(self):
|
|
23
|
+
b = block("3.2.0")
|
|
24
|
+
self.assertTrue(kxta.RULES_BEGIN_RE.search(b))
|
|
25
|
+
self.assertEqual(kxta.RULES_BEGIN_RE.search(b).group(1), "3.2.0")
|
|
26
|
+
self.assertTrue(kxta.RULES_END_RE.search(b))
|
|
27
|
+
self.assertIn(kxta.FLAVOR_TAG, b)
|
|
28
|
+
|
|
29
|
+
def test_short_desc_cuts_at_sentence_not_mid_word(self):
|
|
30
|
+
self.assertEqual(kxta.short_desc("Full-text search. More detail here."), "Full-text search.")
|
|
31
|
+
long = "word " * 80
|
|
32
|
+
out = kxta.short_desc(long, 40)
|
|
33
|
+
self.assertTrue(out.endswith("..."))
|
|
34
|
+
self.assertLessEqual(len(out), 43)
|
|
35
|
+
|
|
36
|
+
def test_append_then_rerun_is_idempotent(self):
|
|
37
|
+
action, once = kxta.apply_rules_block("# Project\n", block())
|
|
38
|
+
self.assertEqual(action, "created")
|
|
39
|
+
action, twice = kxta.apply_rules_block(once, block())
|
|
40
|
+
self.assertEqual(action, "unchanged")
|
|
41
|
+
self.assertEqual(once, twice)
|
|
42
|
+
self.assertEqual(once.count("BEGIN kontexta:rules"), 1)
|
|
43
|
+
|
|
44
|
+
def test_version_bump_replaces_in_place_and_keeps_surrounding_content(self):
|
|
45
|
+
_, old = kxta.apply_rules_block("# Project\n", block("3.2.0"))
|
|
46
|
+
content = old + "\n## Mine\nkeep me\n"
|
|
47
|
+
action, new = kxta.apply_rules_block(content, block("3.3.0"))
|
|
48
|
+
self.assertEqual(action, "updated")
|
|
49
|
+
self.assertIn("BEGIN kontexta:rules v3.3.0", new)
|
|
50
|
+
self.assertNotIn("v3.2.0", new)
|
|
51
|
+
self.assertIn("# Project", new)
|
|
52
|
+
self.assertIn("keep me", new)
|
|
53
|
+
|
|
54
|
+
def test_tool_list_change_at_same_version_still_updates(self):
|
|
55
|
+
_, old = kxta.apply_rules_block("", block("3.2.0", TOOLS[:1]))
|
|
56
|
+
action, _ = kxta.apply_rules_block(old, block("3.2.0", TOOLS))
|
|
57
|
+
self.assertEqual(action, "updated")
|
|
58
|
+
|
|
59
|
+
def test_duplicate_and_malformed_markers_are_refused(self):
|
|
60
|
+
with self.assertRaises(RuntimeError):
|
|
61
|
+
kxta.apply_rules_block(block() + "\n" + block(), block())
|
|
62
|
+
with self.assertRaises(RuntimeError):
|
|
63
|
+
kxta.apply_rules_block("<!-- BEGIN kontexta:rules v3.2.0 -->\nno end", block())
|
|
64
|
+
|
|
65
|
+
def test_write_rules_refuses_symlink_and_writes_utf8(self):
|
|
66
|
+
with tempfile.TemporaryDirectory() as d:
|
|
67
|
+
target = os.path.join(d, "real.md")
|
|
68
|
+
open(target, "w").close()
|
|
69
|
+
link = os.path.join(d, "CLAUDE.md")
|
|
70
|
+
try:
|
|
71
|
+
os.symlink(target, link)
|
|
72
|
+
except (OSError, NotImplementedError):
|
|
73
|
+
self.skipTest("symlinks unavailable")
|
|
74
|
+
with self.assertRaises(RuntimeError):
|
|
75
|
+
kxta.write_rules(link, block())
|
|
76
|
+
plain = os.path.join(d, "AGENTS.md")
|
|
77
|
+
self.assertEqual(kxta.write_rules(plain, block()), "created")
|
|
78
|
+
self.assertEqual(kxta.write_rules(plain, block()), "unchanged")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == "__main__":
|
|
82
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|