@phyzess/kitto 0.0.0-stage → 0.2.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/CHANGELOG.md +42 -0
- package/README.md +32 -2
- package/bin/kitto.mjs +35 -0
- package/bin/maintain.mjs +9 -0
- package/integration/cordis.patch.yml +3 -0
- package/integration/dsh.mjs +21 -0
- package/integration/pi.mjs +14 -0
- package/integration/plugin.json +6 -0
- package/integration/scoped-codex/session-start.mjs +59 -0
- package/integration/scoped-dsh/index.mjs +124 -0
- package/integration/scoped-dsh/native.mjs +8 -0
- package/integration/scoped-pi/index.mjs +62 -0
- package/integration/skills/kitto/SKILL.md +39 -0
- package/lib/dependencies.mjs +178 -0
- package/lib/environment-setup.mjs +43 -0
- package/lib/host-config.mjs +70 -0
- package/lib/kitto.mjs +616 -0
- package/lib/pi_config.py +330 -0
- package/lib/scope-codex.mjs +76 -0
- package/lib/scope-dsh.mjs +92 -0
- package/lib/scope-pi.mjs +41 -0
- package/lib/scope-service.mjs +261 -0
- package/lib/scope-setup.mjs +140 -0
- package/lib/scopes.mjs +51 -0
- package/lib/setup-wizard.mjs +241 -0
- package/lib/update-notice.mjs +26 -0
- package/lib/versions.mjs +139 -0
- package/package.json +16 -4
- package/sync.sh +480 -0
package/lib/pi_config.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Structural merge helpers for pi-config sync.
|
|
3
|
+
|
|
4
|
+
Three responsibilities, each exposed as a subcommand so sync.sh can stay in bash:
|
|
5
|
+
|
|
6
|
+
merge-settings repo settings + machine settings + machine-only packages -> machine settings
|
|
7
|
+
sanitize-settings machine settings -> repo settings (drops volatile keys)
|
|
8
|
+
merge-mcp repo + platform + machine local + machine -> machine mcp.json
|
|
9
|
+
|
|
10
|
+
Shared definitions are updated while machine overrides and runtime switches
|
|
11
|
+
stay local. Preview helpers write only their explicit output path.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
import tempfile
|
|
20
|
+
|
|
21
|
+
VOLATILE_KEYS = ("lastChangelogVersion", "extensionChangelogVersions")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# ---------------------------------------------------------------- helpers
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load(path: str, default=None):
|
|
28
|
+
if not path or not os.path.exists(path):
|
|
29
|
+
return default
|
|
30
|
+
with open(path, encoding="utf-8") as fh:
|
|
31
|
+
try:
|
|
32
|
+
return json.load(fh)
|
|
33
|
+
except json.JSONDecodeError as exc:
|
|
34
|
+
sys.exit(f"invalid JSON in {path}: {exc}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def dump(path: str, data) -> bool:
|
|
38
|
+
"""Write JSON atomically. Returns True when the file changed."""
|
|
39
|
+
text = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
|
|
40
|
+
old = None
|
|
41
|
+
if os.path.exists(path):
|
|
42
|
+
with open(path, encoding="utf-8") as fh:
|
|
43
|
+
old = fh.read()
|
|
44
|
+
if old == text:
|
|
45
|
+
return False
|
|
46
|
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
47
|
+
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or ".", prefix=".kitto-")
|
|
48
|
+
try:
|
|
49
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
50
|
+
fh.write(text)
|
|
51
|
+
os.replace(tmp, path)
|
|
52
|
+
finally:
|
|
53
|
+
if os.path.exists(tmp):
|
|
54
|
+
os.unlink(tmp)
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def dump_semantic(path: str, data) -> bool:
|
|
59
|
+
"""Like dump(), but leaves the file byte-identical when the JSON means the
|
|
60
|
+
same thing. Keeps the repo's own formatting until a real change lands."""
|
|
61
|
+
if os.path.exists(path) and load(path) == data:
|
|
62
|
+
return False
|
|
63
|
+
return dump(path, data)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def read_list(path: str) -> list[str]:
|
|
67
|
+
if not os.path.exists(path):
|
|
68
|
+
return []
|
|
69
|
+
out = []
|
|
70
|
+
with open(path, encoding="utf-8") as fh:
|
|
71
|
+
for raw in fh:
|
|
72
|
+
value = raw.strip()
|
|
73
|
+
if value.startswith("#"):
|
|
74
|
+
continue
|
|
75
|
+
if value:
|
|
76
|
+
out.append(value)
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def write_list(path: str, values: list[str]) -> None:
|
|
81
|
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
82
|
+
body = "\n".join(values)
|
|
83
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
84
|
+
fh.write(f"# generated by sync.sh pull — machine-only pi packages\n{body}\n" if body else
|
|
85
|
+
"# generated by sync.sh pull — machine-only pi packages\n")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def deep_merge(base, over):
|
|
89
|
+
"""Dicts merge recursively, everything else is replaced by `over`."""
|
|
90
|
+
if isinstance(base, dict) and isinstance(over, dict):
|
|
91
|
+
out = dict(base)
|
|
92
|
+
for key, value in over.items():
|
|
93
|
+
out[key] = deep_merge(out[key], value) if key in out else value
|
|
94
|
+
return out
|
|
95
|
+
return over
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def unique(seq):
|
|
99
|
+
seen = set()
|
|
100
|
+
out = []
|
|
101
|
+
for item in seq:
|
|
102
|
+
key = json.dumps(item, sort_keys=True)
|
|
103
|
+
if key not in seen:
|
|
104
|
+
seen.add(key)
|
|
105
|
+
out.append(item)
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------- commands
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def package_key(package):
|
|
113
|
+
source = package if isinstance(package, str) else package.get("source", "")
|
|
114
|
+
if source.startswith("npm:"):
|
|
115
|
+
spec = source.removeprefix("npm:")
|
|
116
|
+
if spec.rfind("@") > 0:
|
|
117
|
+
source = "npm:" + spec.rsplit("@", 1)[0]
|
|
118
|
+
elif source.startswith(("git:github.com/", "https://github.com/")):
|
|
119
|
+
repo = source.split("github.com/", 1)[1].split("@", 1)[0].removesuffix(".git")
|
|
120
|
+
source = "github.com/" + repo
|
|
121
|
+
return source
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cmd_list_shared_packages(argv: list[str]) -> int:
|
|
125
|
+
repo_path, skip_path = argv
|
|
126
|
+
skip = {package_key(item) for item in read_list(skip_path)}
|
|
127
|
+
for package in load(repo_path)["packages"]:
|
|
128
|
+
if package_key(package) not in skip:
|
|
129
|
+
print(package if isinstance(package, str) else package["source"])
|
|
130
|
+
return 0
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def cmd_merge_settings(argv: list[str]) -> int:
|
|
134
|
+
repo_path, machine_path, local_dir, out_path = argv
|
|
135
|
+
repo_cfg = load(repo_path, {}) or {}
|
|
136
|
+
machine_cfg = load(machine_path, {}) or {}
|
|
137
|
+
for key in VOLATILE_KEYS:
|
|
138
|
+
repo_cfg.pop(key, None)
|
|
139
|
+
|
|
140
|
+
extra_path = os.path.join(local_dir, "packages.txt")
|
|
141
|
+
skip = {package_key(item) for item in read_list(os.path.join(local_dir, "packages.skip.txt"))}
|
|
142
|
+
|
|
143
|
+
extra = read_list(extra_path)
|
|
144
|
+
previous = load(os.path.join(local_dir, "managed-packages.json"), []) or []
|
|
145
|
+
# Unknown packages remain local. Previously managed entries can be removed
|
|
146
|
+
# by deleting them from the shared source. No source mutation during preview.
|
|
147
|
+
repo_pkgs = repo_cfg.get("packages", [])
|
|
148
|
+
extra = unique(extra + [p for p in machine_cfg.get("packages", [])
|
|
149
|
+
if p not in repo_pkgs and p not in previous])
|
|
150
|
+
|
|
151
|
+
overrides = load(os.path.join(local_dir, "settings.json"), {}) or {}
|
|
152
|
+
|
|
153
|
+
# Start from what the machine already has (keeps runtime keys), let the repo
|
|
154
|
+
# own the keys it declares, then apply this machine's overrides.
|
|
155
|
+
result = dict(machine_cfg)
|
|
156
|
+
for key, value in repo_cfg.items():
|
|
157
|
+
result[key] = value
|
|
158
|
+
result = deep_merge(result, overrides)
|
|
159
|
+
|
|
160
|
+
before = list(machine_cfg.get("packages", []))
|
|
161
|
+
packages = unique(
|
|
162
|
+
[p for p in (repo_pkgs + extra)
|
|
163
|
+
if package_key(p) not in skip]
|
|
164
|
+
)
|
|
165
|
+
result["packages"] = packages
|
|
166
|
+
|
|
167
|
+
changed = dump(out_path, result)
|
|
168
|
+
added = [p for p in packages if p not in before]
|
|
169
|
+
removed = [p for p in before if p not in packages]
|
|
170
|
+
print(f"settings: {'updated' if changed else 'unchanged'}")
|
|
171
|
+
if added:
|
|
172
|
+
print(" packages added: " + ", ".join(map(str, added)))
|
|
173
|
+
if removed:
|
|
174
|
+
print(" packages dropped: " + ", ".join(map(str, removed)))
|
|
175
|
+
if extra:
|
|
176
|
+
print(" machine-only packages kept: " + ", ".join(map(str, extra)))
|
|
177
|
+
return 0
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def cmd_record_settings(argv: list[str]) -> int:
|
|
181
|
+
"""Record ownership only after a successful real settings deployment."""
|
|
182
|
+
repo_path, machine_path, local_dir = argv
|
|
183
|
+
repo = load(repo_path, {}).get("packages", [])
|
|
184
|
+
machine = load(machine_path, {}).get("packages", [])
|
|
185
|
+
extra_path = os.path.join(local_dir, "packages.txt")
|
|
186
|
+
extra = unique(read_list(extra_path) + [p for p in machine if p not in repo])
|
|
187
|
+
# Pi object-form package entries are preserved in settings but not flattened
|
|
188
|
+
# into a text list. The ownership record still supports them.
|
|
189
|
+
write_list(extra_path, [p for p in extra if isinstance(p, str)])
|
|
190
|
+
dump(os.path.join(local_dir, "managed-packages.json"), repo)
|
|
191
|
+
return 0
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def restore_overrides(out, repo, overrides):
|
|
195
|
+
"""Remove machine-owned values from export, restoring shared defaults."""
|
|
196
|
+
result = dict(out)
|
|
197
|
+
for key, value in overrides.items():
|
|
198
|
+
if isinstance(value, dict) and isinstance(result.get(key), dict):
|
|
199
|
+
result[key] = restore_overrides(result[key], repo.get(key, {})
|
|
200
|
+
if isinstance(repo.get(key), dict) else {}, value)
|
|
201
|
+
if not result[key] and key not in repo:
|
|
202
|
+
result.pop(key)
|
|
203
|
+
elif key in repo:
|
|
204
|
+
result[key] = repo[key]
|
|
205
|
+
else:
|
|
206
|
+
result.pop(key, None)
|
|
207
|
+
return result
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def cmd_sanitize_settings(argv: list[str]) -> int:
|
|
211
|
+
machine_path, repo_path, local_dir, out_path = argv
|
|
212
|
+
machine = load(machine_path, {}) or {}
|
|
213
|
+
repo = load(repo_path, {}) or {}
|
|
214
|
+
extra = read_list(os.path.join(local_dir, "packages.txt"))
|
|
215
|
+
skip = read_list(os.path.join(local_dir, "packages.skip.txt"))
|
|
216
|
+
|
|
217
|
+
# Repo owns the key order so pushes stay diff-quiet; machine values win so
|
|
218
|
+
# local edits (theme, defaults, …) still travel upstream.
|
|
219
|
+
repo_pkgs = list(repo.get("packages", []))
|
|
220
|
+
mach_pkgs = list(machine.get("packages", []))
|
|
221
|
+
dropped = [p for p in mach_pkgs if p in extra or p in skip]
|
|
222
|
+
additions = [p for p in mach_pkgs if p not in repo_pkgs and p not in extra and p not in skip]
|
|
223
|
+
packages = unique(repo_pkgs + additions)
|
|
224
|
+
|
|
225
|
+
out: dict = {}
|
|
226
|
+
for key in repo:
|
|
227
|
+
if key in VOLATILE_KEYS:
|
|
228
|
+
continue
|
|
229
|
+
out[key] = packages if key == "packages" else machine.get(key, repo[key])
|
|
230
|
+
if "packages" not in out:
|
|
231
|
+
out["packages"] = packages
|
|
232
|
+
for key, value in machine.items():
|
|
233
|
+
if key in out or key in VOLATILE_KEYS:
|
|
234
|
+
continue
|
|
235
|
+
out[key] = value
|
|
236
|
+
|
|
237
|
+
overrides = load(os.path.join(local_dir, "settings.json"), {}) or {}
|
|
238
|
+
out = restore_overrides(out, repo, overrides)
|
|
239
|
+
changed = dump_semantic(out_path, out)
|
|
240
|
+
print(f"settings: {'exported' if changed else 'unchanged'}")
|
|
241
|
+
if dropped:
|
|
242
|
+
print(" machine-only packages left out: " + ", ".join(map(str, dropped)))
|
|
243
|
+
if additions:
|
|
244
|
+
print(" new packages taken upstream: " + ", ".join(map(str, additions)))
|
|
245
|
+
return 0
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def cmd_merge_mcp(argv: list[str]) -> int:
|
|
249
|
+
repo_path, platform_path, local_path, machine_path, out_path = argv
|
|
250
|
+
sources = [("machine", machine_path), ("repo", repo_path),
|
|
251
|
+
("platform", platform_path), ("local", local_path)]
|
|
252
|
+
merged: dict[str, dict] = {}
|
|
253
|
+
for _, path in sources:
|
|
254
|
+
cfg = load(path, {}) or {}
|
|
255
|
+
for name, entry in (cfg.get("mcpServers") or {}).items():
|
|
256
|
+
if name.startswith("_") or not isinstance(entry, dict):
|
|
257
|
+
continue
|
|
258
|
+
merged[name] = deep_merge(merged.get(name, {}), entry)
|
|
259
|
+
machine = load(machine_path, {}) or {}
|
|
260
|
+
local = (load(local_path, {}) or {}).get("mcpServers", {})
|
|
261
|
+
for name, entry in machine.get("mcpServers", {}).items():
|
|
262
|
+
if name not in merged or not isinstance(entry, dict):
|
|
263
|
+
continue
|
|
264
|
+
for key in ("enabled", "exposure", "toolExposure"):
|
|
265
|
+
if key in entry and key not in local.get(name, {}):
|
|
266
|
+
merged[name][key] = entry[key]
|
|
267
|
+
changed = dump(out_path, {**machine, "mcpServers": merged})
|
|
268
|
+
enabled = [n for n, e in merged.items() if e.get("enabled", True)]
|
|
269
|
+
disabled = [n for n, e in merged.items() if not e.get("enabled", True)]
|
|
270
|
+
print(f"mcp: {'updated' if changed else 'unchanged'} ({len(merged)} servers)")
|
|
271
|
+
if enabled:
|
|
272
|
+
print(" enabled: " + ", ".join(enabled))
|
|
273
|
+
if disabled:
|
|
274
|
+
print(" disabled: " + ", ".join(disabled))
|
|
275
|
+
return 0
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def cmd_export_mcp(argv: list[str]) -> int:
|
|
279
|
+
repo_path, machine_path, platform_path, local_path, private_path, out_path = argv
|
|
280
|
+
repo = (load(repo_path, {}) or {}).get("mcpServers") or {}
|
|
281
|
+
machine = (load(machine_path, {}) or {}).get("mcpServers") or {}
|
|
282
|
+
platform = (load(platform_path, {}) or {}).get("mcpServers") or {}
|
|
283
|
+
local = (load(local_path, {}) or {}).get("mcpServers") or {}
|
|
284
|
+
private = (load(private_path, {}) or {}).get("mcpServers") or {}
|
|
285
|
+
|
|
286
|
+
out: dict[str, dict] = {}
|
|
287
|
+
replaced: list[str] = []
|
|
288
|
+
dropped: list[str] = []
|
|
289
|
+
for name, entry in machine.items():
|
|
290
|
+
if name in local or name in private:
|
|
291
|
+
if name in repo:
|
|
292
|
+
out[name] = repo[name]
|
|
293
|
+
dropped.append(name)
|
|
294
|
+
continue
|
|
295
|
+
if name in platform:
|
|
296
|
+
if name in repo:
|
|
297
|
+
out[name] = repo[name] # platform override is machine-specific
|
|
298
|
+
replaced.append(name)
|
|
299
|
+
else:
|
|
300
|
+
dropped.append(name) # platform-only server never ships
|
|
301
|
+
continue
|
|
302
|
+
out[name] = entry
|
|
303
|
+
|
|
304
|
+
changed = dump_semantic(out_path, {"mcpServers": out})
|
|
305
|
+
print(f"mcp: {'exported' if changed else 'unchanged'} ({len(out)} servers)")
|
|
306
|
+
if dropped:
|
|
307
|
+
print(" left out (local/platform/private): " + ", ".join(sorted(dropped)))
|
|
308
|
+
if replaced:
|
|
309
|
+
print(" repo entry kept instead of machine override: " + ", ".join(sorted(replaced)))
|
|
310
|
+
return 0
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
COMMANDS = {
|
|
314
|
+
"list-shared-packages": cmd_list_shared_packages,
|
|
315
|
+
"record-settings": cmd_record_settings,
|
|
316
|
+
"merge-settings": cmd_merge_settings,
|
|
317
|
+
"sanitize-settings": cmd_sanitize_settings,
|
|
318
|
+
"merge-mcp": cmd_merge_mcp,
|
|
319
|
+
"export-mcp": cmd_export_mcp,
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def main(argv: list[str]) -> int:
|
|
324
|
+
if len(argv) < 2 or argv[1] not in COMMANDS:
|
|
325
|
+
sys.exit("usage: pi_config.py {merge-settings|sanitize-settings|merge-mcp|export-mcp} ...")
|
|
326
|
+
return COMMANDS[argv[1]](argv[2:])
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
if __name__ == "__main__":
|
|
330
|
+
sys.exit(main(sys.argv))
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { lstat, mkdir, mkdtemp, readFile, readlink, rename, rm, symlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const packageDir = fileURLToPath(new URL('../', import.meta.url));
|
|
7
|
+
const shellQuote = value => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
8
|
+
const missing = error => error.code === 'ENOENT';
|
|
9
|
+
const existing = async path => lstat(path).catch(error => {
|
|
10
|
+
if (!missing(error)) throw error;
|
|
11
|
+
return null;
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
async function inspectHooks(path) {
|
|
15
|
+
const info = await existing(path);
|
|
16
|
+
if (info && !info.isFile()) throw new Error(`Codex hooks path is not a regular file: ${path}`);
|
|
17
|
+
return { info, text: info ? await readFile(path, 'utf8') : null };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function isObject(value) {
|
|
21
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function installCodexScope({ dryRun = false, home = homedir(), root, global, runtime = packageDir } = {}) {
|
|
25
|
+
const path = join(resolve(process.env.CODEX_HOME || join(home, '.codex')), 'hooks.json');
|
|
26
|
+
const { info, text } = await inspectHooks(path);
|
|
27
|
+
const config = text === null ? {} : JSON.parse(text);
|
|
28
|
+
if (!isObject(config) || (config.hooks !== undefined && !isObject(config.hooks))) {
|
|
29
|
+
throw new Error(`Invalid Codex hooks file: ${path}`);
|
|
30
|
+
}
|
|
31
|
+
config.hooks ??= {};
|
|
32
|
+
const groups = config.hooks.SessionStart ?? [];
|
|
33
|
+
if (!Array.isArray(groups)) throw new Error(`Invalid SessionStart hooks in ${path}`);
|
|
34
|
+
|
|
35
|
+
const adapter = join(runtime, 'integration/scoped-codex/session-start.mjs');
|
|
36
|
+
const command = [process.execPath, adapter].map(shellQuote).join(' ');
|
|
37
|
+
const needsHook = !groups.some(group => Array.isArray(group?.hooks) &&
|
|
38
|
+
group.hooks.some(handler => handler?.type === 'command' && handler.command === command));
|
|
39
|
+
|
|
40
|
+
const skillsPath = global ? join(home, '.agents/skills/kitto-shared') : null;
|
|
41
|
+
const skillsSource = global ? join(root, '.agents/skills') : null;
|
|
42
|
+
async function needsLink() {
|
|
43
|
+
if (!skillsPath) return false;
|
|
44
|
+
const entry = await existing(skillsPath);
|
|
45
|
+
if (!entry) return true;
|
|
46
|
+
if (entry.isSymbolicLink() && resolve(dirname(skillsPath), await readlink(skillsPath)) === skillsSource) return false;
|
|
47
|
+
throw new Error(`Codex shared skills path is already occupied: ${skillsPath}`);
|
|
48
|
+
}
|
|
49
|
+
const link = await needsLink();
|
|
50
|
+
if (!dryRun && needsHook) {
|
|
51
|
+
config.hooks.SessionStart = [...groups, {
|
|
52
|
+
hooks: [{ type: 'command', command, statusMessage: 'Loading Kitto scopes' }],
|
|
53
|
+
}];
|
|
54
|
+
await mkdir(dirname(path), { recursive: true });
|
|
55
|
+
const staging = await mkdtemp(join(dirname(path), '.kitto-hooks-'));
|
|
56
|
+
try {
|
|
57
|
+
const next = join(staging, 'hooks.json');
|
|
58
|
+
await writeFile(next, JSON.stringify(config, null, 2) + '\n', { mode: info ? info.mode & 0o777 : 0o600 });
|
|
59
|
+
if ((await inspectHooks(path)).text !== text) throw new Error(`Codex hooks changed during setup: ${path}`);
|
|
60
|
+
await rename(next, path);
|
|
61
|
+
} finally {
|
|
62
|
+
await rm(staging, { recursive: true, force: true });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (!dryRun && link) {
|
|
66
|
+
await mkdir(dirname(skillsPath), { recursive: true });
|
|
67
|
+
try {
|
|
68
|
+
await symlink(skillsSource, skillsPath, 'dir');
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error.code !== 'EEXIST' || await needsLink()) throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (dryRun) console.log(`Codex scoped configuration: ${path}`);
|
|
74
|
+
else if (needsHook) console.log('In Codex, review and trust the Kitto SessionStart hook with /hooks. Start a new session afterward.');
|
|
75
|
+
return { path, changed: needsHook || link, skillsPath };
|
|
76
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { access, lstat, mkdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { delimiter, dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { importFromDsh } from '../integration/scoped-dsh/native.mjs';
|
|
8
|
+
|
|
9
|
+
const pluginId = 'phyzess-kitto-scopes';
|
|
10
|
+
const defaultRuntime = fileURLToPath(new URL('../', import.meta.url));
|
|
11
|
+
|
|
12
|
+
async function dshExecutable() {
|
|
13
|
+
for (const dir of (process.env.PATH ?? '').split(delimiter)) {
|
|
14
|
+
const candidate = resolve(dir, 'dsh');
|
|
15
|
+
try {
|
|
16
|
+
await access(candidate, constants.X_OK);
|
|
17
|
+
if ((await lstat(candidate)).isDirectory()) continue;
|
|
18
|
+
const entry = await realpath(candidate);
|
|
19
|
+
if (entry.endsWith('/mise') || dir.endsWith('/shims')) {
|
|
20
|
+
const result = spawnSync(entry.endsWith('/mise') ? entry : 'mise', ['which', 'dsh'], { encoding: 'utf8', timeout: 8000 });
|
|
21
|
+
if (result.status === 0 && result.stdout.trim()) return result.stdout.trim();
|
|
22
|
+
}
|
|
23
|
+
return candidate;
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (!['ENOENT', 'EACCES', 'ENOTDIR'].includes(error.code)) throw error;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
throw new Error('DSH must be installed and available on PATH to configure its profile.');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function readPatch(path) {
|
|
32
|
+
try {
|
|
33
|
+
const info = await lstat(path);
|
|
34
|
+
if (!info.isFile()) throw new Error(`DSH profile patch is not a regular file: ${path}`);
|
|
35
|
+
return { content: await readFile(path, 'utf8'), mode: info.mode & 0o777 };
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (error.code !== 'ENOENT') throw error;
|
|
38
|
+
return { content: null, mode: 0o600 };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function installDshScope({ dryRun, home, runtime = defaultRuntime, dshProfile = 'web' }) {
|
|
43
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(dshProfile) || dshProfile === 'desktop') {
|
|
44
|
+
throw new Error('Invalid DSH CLI profile name.');
|
|
45
|
+
}
|
|
46
|
+
const configuredHome = process.env.DSH_HOME?.trim() || join(home, '.dsh');
|
|
47
|
+
const dshHome = resolve(configuredHome === '~' ? home
|
|
48
|
+
: configuredHome.startsWith('~/') ? join(home, configuredHome.slice(2)) : configuredHome);
|
|
49
|
+
const path = join(dshHome, 'profiles', dshProfile, 'cordis.patch.yml');
|
|
50
|
+
const plugin = join(runtime, 'integration', 'scoped-dsh', 'index.mjs');
|
|
51
|
+
const executable = await dshExecutable();
|
|
52
|
+
const [{ isSeq, parseDocument }, { PROFILE_TEMPLATES }] = await Promise.all([
|
|
53
|
+
importFromDsh(executable, 'yaml'),
|
|
54
|
+
importFromDsh(executable, '@deepseek-ai/dsh-official-bundles'),
|
|
55
|
+
]);
|
|
56
|
+
if (!Object.hasOwn(PROFILE_TEMPLATES, dshProfile) && (await readPatch(join(dirname(path), 'package.json'))).content === null) {
|
|
57
|
+
throw new Error(`Initialize the native DSH profile ${dshProfile} before setup.`);
|
|
58
|
+
}
|
|
59
|
+
const before = await readPatch(path);
|
|
60
|
+
const document = parseDocument(before.content ?? '[]\n', {
|
|
61
|
+
customTags: [{ tag: 'tag:yaml.org,2002:js', resolve: value => value }],
|
|
62
|
+
});
|
|
63
|
+
if (document.errors.length) throw document.errors[0];
|
|
64
|
+
if (!isSeq(document.contents)) throw new Error(`DSH profile patch must be a YAML sequence: ${path}`);
|
|
65
|
+
|
|
66
|
+
const rows = document.toJS().flatMap(item => item?.insert ?? []).filter(row => row?.id === pluginId);
|
|
67
|
+
if (rows.length) {
|
|
68
|
+
if (rows.length === 1 && rows[0].name === plugin) {
|
|
69
|
+
if (dryRun) console.log(`DSH scoped configuration already registered: ${path}`);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
throw new Error(`DSH profile already contains a different ${pluginId} entry: ${path}`);
|
|
73
|
+
}
|
|
74
|
+
if (dryRun) {
|
|
75
|
+
console.log(`DSH scoped configuration: ${path}`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
document.add({ insert: [{ id: pluginId, name: plugin }] });
|
|
79
|
+
document.contents.flow = false;
|
|
80
|
+
await mkdir(dirname(path), { recursive: true });
|
|
81
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
82
|
+
try {
|
|
83
|
+
await writeFile(temporary, document.toString(), { flag: 'wx', mode: before.mode });
|
|
84
|
+
if ((await readPatch(path)).content !== before.content) {
|
|
85
|
+
throw new Error(`DSH profile patch changed during setup: ${path}`);
|
|
86
|
+
}
|
|
87
|
+
await rename(temporary, path);
|
|
88
|
+
} finally {
|
|
89
|
+
await rm(temporary, { force: true });
|
|
90
|
+
}
|
|
91
|
+
console.log(`DSH scoped configuration registered for the ${dshProfile} profile. Restart running DSH servers for this profile.`);
|
|
92
|
+
}
|
package/lib/scope-pi.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { lstat, mkdir, readlink, symlink } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const packageDir = fileURLToPath(new URL('../', import.meta.url));
|
|
7
|
+
|
|
8
|
+
function piAgentDir(home) {
|
|
9
|
+
const configured = process.env.PI_CODING_AGENT_DIR;
|
|
10
|
+
if (!configured) return join(home, '.pi/agent');
|
|
11
|
+
if (configured === '~') return home;
|
|
12
|
+
if (configured.startsWith('~/')) return join(home, configured.slice(2));
|
|
13
|
+
if (configured.startsWith('file://')) return fileURLToPath(configured);
|
|
14
|
+
return resolve(configured);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function installPiScope({ dryRun = false, home = homedir(), runtime = packageDir } = {}) {
|
|
18
|
+
const adapter = resolve(runtime, 'integration/scoped-pi/index.mjs');
|
|
19
|
+
const path = join(piAgentDir(home), 'extensions', 'kitto-scopes.js');
|
|
20
|
+
|
|
21
|
+
async function existingAdapter() {
|
|
22
|
+
const info = await lstat(path).catch(error => {
|
|
23
|
+
if (error.code !== 'ENOENT') throw error;
|
|
24
|
+
});
|
|
25
|
+
if (!info) return false;
|
|
26
|
+
if (info.isSymbolicLink() && resolve(dirname(path), await readlink(path)) === adapter) return true;
|
|
27
|
+
throw new Error(`Pi scope extension path is already occupied: ${path}`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (await existingAdapter()) return { path, changed: false };
|
|
31
|
+
if (!dryRun) {
|
|
32
|
+
await mkdir(dirname(path), { recursive: true });
|
|
33
|
+
try {
|
|
34
|
+
await symlink(adapter, path, 'file');
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (error.code !== 'EEXIST' || !await existingAdapter()) throw error;
|
|
37
|
+
return { path, changed: false };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { path, changed: true };
|
|
41
|
+
}
|