@christang/keel 5.88.0 → 5.89.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/README.md +10 -4
- package/README.zh-CN.md +5 -1
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +237 -38
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/plugins/keel/.claude-plugin/plugin.json +1 -1
- package/plugins/keel/.codex-plugin/plugin.json +1 -1
- package/plugins/keel/scripts/forward.js +126 -0
- package/plugins/keel/scripts/mail-hook.js +12 -0
- package/plugins/keel/scripts/pretooluse-guard.js +24 -2
- package/plugins/keel/scripts/session-start.js +84 -1
- package/scripts/validate_codex_receiving.py +155 -1
- package/scripts/validate_plugin.py +649 -2
|
@@ -5,7 +5,10 @@
|
|
|
5
5
|
// file edits while an explicit keel/guard.json manifest is active. Absence of
|
|
6
6
|
// the manifest allows everything silently; a present-but-untrusted manifest
|
|
7
7
|
// fails closed. The hook never writes state, never spawns the keel CLI, and
|
|
8
|
-
// always exits 0 — denial is expressed only through hook output.
|
|
8
|
+
// always exits 0 — denial is expressed only through hook output. While no
|
|
9
|
+
// manifest is active it may instead run the newer installed copy of itself
|
|
10
|
+
// (forward.js, #204); while one is, the loaded guard keeps deciding, so a task
|
|
11
|
+
// finishes under the guard it started with. The
|
|
9
12
|
// repository is the guard's scope: a path resolving outside it is not a product
|
|
10
13
|
// write and passes through, decided before the manifest is read so that no
|
|
11
14
|
// manifest state can reach it.
|
|
@@ -14,6 +17,16 @@ const crypto = require("crypto");
|
|
|
14
17
|
const fs = require("fs");
|
|
15
18
|
const path = require("path");
|
|
16
19
|
|
|
20
|
+
// A newer installed copy of this script runs in its place when the host has
|
|
21
|
+
// installed one (forward.js, #204). A copy of this script without forward.js
|
|
22
|
+
// beside it simply runs its own logic.
|
|
23
|
+
let handOff = () => null;
|
|
24
|
+
try {
|
|
25
|
+
({ handOff } = require("./forward"));
|
|
26
|
+
} catch {
|
|
27
|
+
// Copied on its own: no hand-off.
|
|
28
|
+
}
|
|
29
|
+
|
|
17
30
|
const MANIFEST_SCHEMA = "keel-write-guard/v1";
|
|
18
31
|
const FILE_EDIT_TOOLS = new Map([
|
|
19
32
|
["Edit", "file_path"],
|
|
@@ -145,15 +158,24 @@ function repoRelative(repo, target) {
|
|
|
145
158
|
}
|
|
146
159
|
|
|
147
160
|
function main() {
|
|
161
|
+
const input = readStdin();
|
|
148
162
|
let event = {};
|
|
149
163
|
try {
|
|
150
|
-
event = JSON.parse(
|
|
164
|
+
event = JSON.parse(input || "{}");
|
|
151
165
|
} catch {
|
|
152
166
|
event = {};
|
|
153
167
|
}
|
|
154
168
|
const repo =
|
|
155
169
|
typeof event.cwd === "string" && event.cwd ? event.cwd : process.cwd();
|
|
156
170
|
|
|
171
|
+
// An active task keeps the guard it started under: hand off only while no
|
|
172
|
+
// manifest exists. A copy that fails to run returns null, and this guard's
|
|
173
|
+
// own decision follows.
|
|
174
|
+
if (!fs.existsSync(path.join(repo, "keel", "guard.json"))) {
|
|
175
|
+
const handed = handOff(__filename, input, 8000);
|
|
176
|
+
if (handed !== null) return handed;
|
|
177
|
+
}
|
|
178
|
+
|
|
157
179
|
const pathField = FILE_EDIT_TOOLS.get(event.tool_name);
|
|
158
180
|
if (!pathField) return 0;
|
|
159
181
|
|
|
@@ -15,6 +15,16 @@ const fs = require("fs");
|
|
|
15
15
|
const path = require("path");
|
|
16
16
|
const { spawnSync } = require("child_process");
|
|
17
17
|
|
|
18
|
+
// A newer installed copy of this script runs in its place when the host has
|
|
19
|
+
// installed one (forward.js, #204). A copy of this script without forward.js
|
|
20
|
+
// beside it simply runs its own logic.
|
|
21
|
+
let handOff = () => null;
|
|
22
|
+
try {
|
|
23
|
+
({ handOff } = require("./forward"));
|
|
24
|
+
} catch {
|
|
25
|
+
// Copied on its own: no hand-off.
|
|
26
|
+
}
|
|
27
|
+
|
|
18
28
|
// This text is injected into the agent; the human reads the `systemMessage`
|
|
19
29
|
// line instead. Both channels ship on every branch, degraded ones included,
|
|
20
30
|
// and neither makes the other redundant: the host's line says what the state
|
|
@@ -252,6 +262,71 @@ function versionReport(cwd, cli, pathCli = null) {
|
|
|
252
262
|
+ `\`/reload-plugins\` or at the next session start. ${remedy}${shadow}`;
|
|
253
263
|
}
|
|
254
264
|
|
|
265
|
+
// A handed-off run (forward.js, #204) executes the installed version, so its
|
|
266
|
+
// hooks, CLI, and version report are already the new ones. What it cannot
|
|
267
|
+
// bring forward is what the host loaded when the session started: skills,
|
|
268
|
+
// agents, and the declared hooks. They are compared between the loaded tree —
|
|
269
|
+
// the cache keeps each version under its own name beside this one — and this
|
|
270
|
+
// tree, and only a difference earns a line, naming the reload and nothing
|
|
271
|
+
// else. A loaded tree that cannot be found is reported as possibly different,
|
|
272
|
+
// because silence would claim a comparison that never happened.
|
|
273
|
+
function treeDigest(dir) {
|
|
274
|
+
const hash = require("crypto").createHash("sha256");
|
|
275
|
+
const walk = (current, prefix) => {
|
|
276
|
+
let entries;
|
|
277
|
+
try {
|
|
278
|
+
entries = fs.readdirSync(current, { withFileTypes: true });
|
|
279
|
+
} catch {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
283
|
+
const full = path.join(current, entry.name);
|
|
284
|
+
const name = `${prefix}${entry.name}`;
|
|
285
|
+
if (entry.isDirectory()) {
|
|
286
|
+
walk(full, `${name}/`);
|
|
287
|
+
} else if (entry.isFile()) {
|
|
288
|
+
hash.update(`${name}\0`);
|
|
289
|
+
hash.update(fs.readFileSync(full));
|
|
290
|
+
hash.update("\0");
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
walk(dir, "");
|
|
295
|
+
return hash.digest("hex");
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function declaredHooks(root) {
|
|
299
|
+
try {
|
|
300
|
+
const manifest = path.join(root, ".claude-plugin", "plugin.json");
|
|
301
|
+
return JSON.stringify(JSON.parse(fs.readFileSync(manifest, "utf8")).hooks || null);
|
|
302
|
+
} catch {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function adoptionReport() {
|
|
308
|
+
const loadedVersion = (process.env.KEEL_HOOK_FORWARDED || "").trim();
|
|
309
|
+
if (!loadedVersion) return null;
|
|
310
|
+
const running = pluginManifest().version;
|
|
311
|
+
const root = path.resolve(__dirname, "..", "..", "..");
|
|
312
|
+
const loaded = path.join(path.dirname(root), loadedVersion);
|
|
313
|
+
let differs;
|
|
314
|
+
if (!fs.existsSync(path.join(loaded, ".claude-plugin", "plugin.json"))) {
|
|
315
|
+
differs = "skills, agents, or hooks may differ";
|
|
316
|
+
} else {
|
|
317
|
+
const changed = [];
|
|
318
|
+
for (const [name, rel] of [["skills", "plugins/keel/skills"], ["agents", "plugins/keel/agents"]]) {
|
|
319
|
+
if (treeDigest(path.join(loaded, rel)) !== treeDigest(path.join(root, rel))) changed.push(name);
|
|
320
|
+
}
|
|
321
|
+
if (declaredHooks(loaded) !== declaredHooks(root)) changed.push("declared hooks");
|
|
322
|
+
if (changed.length === 0) return null;
|
|
323
|
+
differs = `${changed.join(" and ")} changed`;
|
|
324
|
+
}
|
|
325
|
+
return `hooks now run the installed plugin ${running} in place of the loaded `
|
|
326
|
+
+ `${loadedVersion}; its ${differs}, and \`/reload-plugins\` loads them — the `
|
|
327
|
+
+ "only step left.";
|
|
328
|
+
}
|
|
329
|
+
|
|
255
330
|
// The `keel` a bare command resolves, asked only when this hook ran its own
|
|
256
331
|
// CLI; with no such command there is nothing to compare.
|
|
257
332
|
function pathCliVersion(cwd) {
|
|
@@ -371,9 +446,12 @@ function fallback(reason) {
|
|
|
371
446
|
}
|
|
372
447
|
|
|
373
448
|
function main() {
|
|
449
|
+
const input = readStdin();
|
|
450
|
+
const handed = handOff(__filename, input, 12000);
|
|
451
|
+
if (handed !== null) return handed;
|
|
374
452
|
let event = {};
|
|
375
453
|
try {
|
|
376
|
-
event = JSON.parse(
|
|
454
|
+
event = JSON.parse(input || "{}");
|
|
377
455
|
} catch {
|
|
378
456
|
event = {};
|
|
379
457
|
}
|
|
@@ -482,6 +560,11 @@ function main() {
|
|
|
482
560
|
versionMatch[0],
|
|
483
561
|
cli.packaged ? pathCliVersion(cwd) : null
|
|
484
562
|
);
|
|
563
|
+
const adoption = adoptionReport();
|
|
564
|
+
if (adoption) {
|
|
565
|
+
lines.push(`- ${adoption}`);
|
|
566
|
+
human.splice(human.length - 1, 0, adoption[0].toUpperCase() + adoption.slice(1));
|
|
567
|
+
}
|
|
485
568
|
if (drift) {
|
|
486
569
|
lines.push(`- ${drift}`);
|
|
487
570
|
human.splice(human.length - 1, 0, drift[0].toUpperCase() + drift.slice(1));
|
|
@@ -283,12 +283,166 @@ The executable SHALL print exactly `hello keel`.
|
|
|
283
283
|
print("consumer: clean Codex init/doctor, proposal, recorded task-start, public red/green behavior, Review, task-complete and change-close passed; guard enforcement remained manual")
|
|
284
284
|
|
|
285
285
|
|
|
286
|
+
UPGRADE_HOOK = r"""const fs = require("fs");
|
|
287
|
+
try { fs.readFileSync(0, "utf8"); } catch {}
|
|
288
|
+
const v = JSON.parse(fs.readFileSync(__dirname + "/../.codex-plugin/plugin.json", "utf8")).version;
|
|
289
|
+
const name = process.argv[2] === "ss" ? "SessionStart" : "UserPromptSubmit";
|
|
290
|
+
process.stdout.write(JSON.stringify({hookSpecificOutput: {hookEventName: name,
|
|
291
|
+
additionalContext: `UPGRADE-PROBE version=${v} dir=${__dirname}`}}));
|
|
292
|
+
"""
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def write_upgrade_plugin(repo, version):
|
|
296
|
+
plugin = repo / "plugins/probe"
|
|
297
|
+
if plugin.exists():
|
|
298
|
+
shutil.rmtree(plugin)
|
|
299
|
+
(plugin / ".codex-plugin").mkdir(parents=True)
|
|
300
|
+
(plugin / "scripts").mkdir()
|
|
301
|
+
(plugin / "hooks").mkdir()
|
|
302
|
+
(plugin / ".codex-plugin/plugin.json").write_text(json.dumps(
|
|
303
|
+
{"name": "probe", "version": version, "hooks": "./hooks/codex.json"}))
|
|
304
|
+
(plugin / "scripts/hook.js").write_text(UPGRADE_HOOK)
|
|
305
|
+
(plugin / "hooks/codex.json").write_text(json.dumps({"hooks": {
|
|
306
|
+
"SessionStart": [{"hooks": [{"type": "command", "timeout": 10,
|
|
307
|
+
"command": 'node "${PLUGIN_ROOT}/scripts/hook.js" ss'}]}],
|
|
308
|
+
"UserPromptSubmit": [{"hooks": [{"type": "command", "timeout": 10,
|
|
309
|
+
"command": 'node "${PLUGIN_ROOT}/scripts/hook.js" ups'}]}]}}))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class AppServer:
|
|
313
|
+
"""A long-lived `codex app-server`, the shape a running Codex session has."""
|
|
314
|
+
def __init__(self, repo, env):
|
|
315
|
+
self.process = subprocess.Popen(["codex", "app-server"], cwd=repo, env=env, stdin=subprocess.PIPE,
|
|
316
|
+
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, bufsize=1)
|
|
317
|
+
self.selector = selectors.DefaultSelector()
|
|
318
|
+
self.selector.register(self.process.stdout, selectors.EVENT_READ)
|
|
319
|
+
self.number = 0
|
|
320
|
+
self.rpc("initialize", {"clientInfo": {"name": "keel-upgrade-probe", "version": "1"},
|
|
321
|
+
"capabilities": {"experimentalApi": True}})
|
|
322
|
+
self.process.stdin.write('{"method":"initialized"}\n'); self.process.stdin.flush()
|
|
323
|
+
|
|
324
|
+
def pump(self, seconds):
|
|
325
|
+
deadline = time.monotonic() + seconds
|
|
326
|
+
while time.monotonic() < deadline:
|
|
327
|
+
if self.selector.select(0.5):
|
|
328
|
+
if not self.process.stdout.readline():
|
|
329
|
+
raise AssertionError("Codex app-server exited")
|
|
330
|
+
|
|
331
|
+
def rpc(self, method, params):
|
|
332
|
+
self.number += 1
|
|
333
|
+
number = self.number
|
|
334
|
+
self.process.stdin.write(json.dumps({"id": number, "method": method, "params": params}) + "\n")
|
|
335
|
+
self.process.stdin.flush()
|
|
336
|
+
deadline = time.monotonic() + 30
|
|
337
|
+
while time.monotonic() < deadline:
|
|
338
|
+
if self.selector.select(1):
|
|
339
|
+
line = self.process.stdout.readline()
|
|
340
|
+
if not line:
|
|
341
|
+
raise AssertionError(f"Codex app-server exited during {method}")
|
|
342
|
+
value = json.loads(line)
|
|
343
|
+
if value.get("id") == number:
|
|
344
|
+
assert "error" not in value, value
|
|
345
|
+
return value["result"]
|
|
346
|
+
raise AssertionError(f"Codex app-server timed out: {method}")
|
|
347
|
+
|
|
348
|
+
def close(self):
|
|
349
|
+
self.selector.close()
|
|
350
|
+
self.process.terminate(); self.process.wait(timeout=5)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def native_upgrade():
|
|
354
|
+
"""#204: a running Codex session's next hook runs the upgraded plugin.
|
|
355
|
+
|
|
356
|
+
Isolated CODEX_HOME, a request-capture endpoint so no model runs, and a
|
|
357
|
+
throwaway plugin whose hooks report their own version and directory. The
|
|
358
|
+
hooks are trusted in the isolated config only, by the hashes app-server
|
|
359
|
+
reports, never in the personal one."""
|
|
360
|
+
assert shutil.which("codex"), "native upgrade probe requires the Codex CLI"
|
|
361
|
+
requests = []
|
|
362
|
+
class Capture(BaseHTTPRequestHandler):
|
|
363
|
+
def do_POST(self):
|
|
364
|
+
requests.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))
|
|
365
|
+
body = b'{"error":{"message":"Keel probe captured the request; no model executes","type":"invalid_request_error"}}'
|
|
366
|
+
self.send_response(400); self.send_header("Content-Type", "application/json")
|
|
367
|
+
self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
|
|
368
|
+
def log_message(self, *args):
|
|
369
|
+
pass
|
|
370
|
+
import re
|
|
371
|
+
with tempfile.TemporaryDirectory(prefix="keel-native-upgrade-") as raw:
|
|
372
|
+
base = Path(raw); repo = base / "repo"; home = base / "codex-home"
|
|
373
|
+
repo.mkdir(); home.mkdir(); run(["git", "init", "-q", str(repo)])
|
|
374
|
+
market = repo / ".agents/plugins/marketplace.json"
|
|
375
|
+
market.parent.mkdir(parents=True)
|
|
376
|
+
market.write_text(json.dumps({"name": "probe-market", "plugins": [
|
|
377
|
+
{"name": "probe", "source": {"source": "local", "path": "./plugins/probe"},
|
|
378
|
+
"policy": {"installation": "AVAILABLE"}}]}))
|
|
379
|
+
write_upgrade_plugin(repo, "1.0.0")
|
|
380
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), Capture)
|
|
381
|
+
worker = threading.Thread(target=server.serve_forever, daemon=True); worker.start()
|
|
382
|
+
app = None
|
|
383
|
+
try:
|
|
384
|
+
(home / "config.toml").write_text(f"""model = "keel-probe"
|
|
385
|
+
model_provider = "keel_probe"
|
|
386
|
+
[model_providers.keel_probe]
|
|
387
|
+
name = "Keel local request capture"
|
|
388
|
+
base_url = "http://127.0.0.1:{server.server_port}/v1"
|
|
389
|
+
wire_api = "responses"
|
|
390
|
+
requires_openai_auth = false
|
|
391
|
+
request_max_retries = 0
|
|
392
|
+
stream_max_retries = 0
|
|
393
|
+
[projects.{json.dumps(str(repo))}]
|
|
394
|
+
trust_level = "trusted"
|
|
395
|
+
""")
|
|
396
|
+
env = dict(os.environ, CODEX_HOME=str(home)); env.pop("OPENAI_API_KEY", None)
|
|
397
|
+
run(["codex", "plugin", "marketplace", "add", str(repo)], cwd=repo, env=env)
|
|
398
|
+
run(["codex", "plugin", "add", "probe@probe-market"], cwd=repo, env=env)
|
|
399
|
+
app = AppServer(repo, env)
|
|
400
|
+
hooks = app.rpc("hooks/list", {"cwds": [str(repo)]})["data"][0]["hooks"]
|
|
401
|
+
app.close(); app = None
|
|
402
|
+
with open(home / "config.toml", "a") as config:
|
|
403
|
+
for hook in hooks:
|
|
404
|
+
config.write(f'\n[hooks.state.{json.dumps(hook["key"])}]\n'
|
|
405
|
+
f'trusted_hash = {json.dumps(hook["currentHash"])}\n')
|
|
406
|
+
|
|
407
|
+
def turn(thread, text):
|
|
408
|
+
before = len(requests)
|
|
409
|
+
app.rpc("turn/start", {"threadId": thread, "input": [{"type": "text", "text": text}]})
|
|
410
|
+
deadline = time.monotonic() + 30
|
|
411
|
+
while len(requests) == before and time.monotonic() < deadline:
|
|
412
|
+
app.pump(1)
|
|
413
|
+
assert len(requests) > before, f"no model request for {text!r}"
|
|
414
|
+
return set(re.findall(r"UPGRADE-PROBE version=(\S+) dir=([^\s\"\\]+)", json.dumps(requests[-1])))
|
|
415
|
+
|
|
416
|
+
app = AppServer(repo, env)
|
|
417
|
+
cache = home / "plugins/cache/probe-market/probe"
|
|
418
|
+
thread = app.rpc("thread/start", {"cwd": str(repo)})["thread"]["id"]
|
|
419
|
+
first = turn(thread, "upgrade probe one")
|
|
420
|
+
assert {v for v, _ in first} == {"1.0.0"}, first
|
|
421
|
+
write_upgrade_plugin(repo, "2.0.0")
|
|
422
|
+
run(["codex", "plugin", "add", "probe@probe-market"], cwd=repo, env=env)
|
|
423
|
+
assert sorted(p.name for p in cache.iterdir()) == ["2.0.0"], sorted(p.name for p in cache.iterdir())
|
|
424
|
+
trust = [h["trustStatus"] for h in app.rpc("hooks/list", {"cwds": [str(repo)]})["data"][0]["hooks"]]
|
|
425
|
+
assert trust == ["trusted", "trusted"], trust
|
|
426
|
+
second = turn(thread, "upgrade probe two")
|
|
427
|
+
fresh = {(v, d) for v, d in second if v == "2.0.0"}
|
|
428
|
+
assert fresh and all(d.startswith(os.path.realpath(cache / "2.0.0")) for _, d in fresh), second
|
|
429
|
+
print(run(["codex", "--version"], cwd=repo, env=env).stdout.strip())
|
|
430
|
+
print("native-upgrade: after codex plugin add of 2.0.0 under a running app-server, the same thread's next hook ran 2.0.0 from its new directory; 1.0.0's directory was deleted and both hooks stayed trusted; no model executed and no personal trust was written")
|
|
431
|
+
finally:
|
|
432
|
+
if app is not None:
|
|
433
|
+
app.close()
|
|
434
|
+
server.shutdown(); server.server_close(); worker.join(timeout=5)
|
|
435
|
+
|
|
436
|
+
|
|
286
437
|
if __name__ == "__main__":
|
|
287
438
|
parser = argparse.ArgumentParser()
|
|
288
439
|
parser.add_argument("--native", action="store_true")
|
|
289
440
|
parser.add_argument("--consumer", action="store_true")
|
|
441
|
+
parser.add_argument("--native-upgrade", action="store_true")
|
|
290
442
|
args = parser.parse_args()
|
|
291
|
-
if args.
|
|
443
|
+
if args.native_upgrade:
|
|
444
|
+
native_upgrade()
|
|
445
|
+
elif args.native:
|
|
292
446
|
native()
|
|
293
447
|
elif args.consumer:
|
|
294
448
|
consumer()
|