ceulen 0.11.0 → 0.13.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 +100 -1
- package/extensions/index.ts +5 -1
- package/extensions/lib/env.test.ts +147 -0
- package/extensions/lib/env.ts +180 -0
- package/extensions/lib/order.test.ts +74 -0
- package/extensions/lib/registry.test.ts +8 -5
- package/extensions/lib/registry.ts +23 -4
- package/extensions/modules/a2a/configPanel.ts +42 -1
- package/extensions/modules/a2a/lib/config.ts +8 -3
- package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
- package/extensions/modules/advisor/index.ts +6 -3
- package/extensions/modules/advisor/test/module.test.ts +31 -0
- package/extensions/modules/classifier/index.ts +55 -1
- package/extensions/modules/classifier/test/classifier.test.ts +62 -0
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/jfind/index.ts +115 -0
- package/extensions/modules/jfind/lib/cascade.ts +377 -0
- package/extensions/modules/jfind/lib/format.ts +12 -0
- package/extensions/modules/jfind/lib/judge.ts +74 -0
- package/extensions/modules/jfind/lib/lexical.ts +232 -0
- package/extensions/modules/jfind/lib/questions.ts +178 -0
- package/extensions/modules/jfind/lib/tree.ts +374 -0
- package/extensions/modules/jfind/test/cascade.test.ts +305 -0
- package/extensions/modules/notify/index.ts +33 -0
- package/extensions/modules/notify/lib/notify.ts +99 -0
- package/extensions/modules/notify/test/notify.test.ts +95 -0
- package/extensions/modules/plan/lib/plan-tools.ts +13 -0
- package/extensions/modules/repair/configPanel.ts +7 -1
- package/extensions/modules/repair/index.ts +158 -3
- package/extensions/modules/repair/lib/auto-generated.ts +89 -0
- package/extensions/modules/repair/lib/read-archive.ts +101 -0
- package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
- package/extensions/modules/repair/lib/settings.ts +4 -1
- package/extensions/modules/repair/test/freshness.test.ts +41 -1
- package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
- package/extensions/modules/repair/test/readers.test.ts +291 -0
- package/extensions/modules/repair/test/settings.test.ts +2 -1
- package/extensions/modules/router/configPanel.ts +4 -4
- package/extensions/modules/router/index.ts +1 -1
- package/extensions/modules/router/lib/config.ts +9 -4
- package/extensions/modules/router/lib/systemone.ts +17 -4
- package/extensions/modules/router/test/unit.test.ts +46 -1
- package/extensions/modules/rules/index.ts +13 -3
- package/extensions/modules/rules/lib/rules.ts +24 -12
- package/extensions/modules/rules/test/lib.test.ts +20 -0
- package/extensions/modules/rules/test/module.test.ts +21 -0
- package/extensions/modules/sg/index.ts +129 -0
- package/extensions/modules/sg/lib/ops.ts +144 -0
- package/extensions/modules/sg/lib/sg-cli.ts +104 -0
- package/extensions/modules/sg/test/sg.test.ts +128 -0
- package/extensions/modules/shells/index.ts +210 -0
- package/extensions/modules/shells/lib/sessions.ts +344 -0
- package/extensions/modules/shells/test/sessions.test.ts +275 -0
- package/extensions/modules/subagent/index.ts +11 -5
- package/extensions/modules/subagent/lib/herdr.ts +5 -0
- package/extensions/modules/subagent/lib/routing.ts +31 -8
- package/extensions/modules/subagent/lib/runner.ts +8 -2
- package/extensions/modules/subagent/test/routing.test.ts +45 -0
- package/extensions/modules/web/configPanel.ts +67 -8
- package/extensions/modules/web/index.ts +34 -0
- package/extensions/modules/web/lib/pdf.ts +181 -0
- package/extensions/modules/web/test/configPanel.test.ts +7 -3
- package/extensions/modules/web/test/extension.test.ts +2 -1
- package/extensions/modules/web/test/settings.test.ts +6 -0
- package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
- package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
- package/package.json +3 -3
|
@@ -29,6 +29,13 @@ import {
|
|
|
29
29
|
type Peer,
|
|
30
30
|
} from "./lib/config.js";
|
|
31
31
|
import { a2aServerRunning as a2aServerRunningIndex, restartA2AServer as restartA2AServerIndex } from "./index.js";
|
|
32
|
+
import { writeSecretEnvs } from "../../lib/env.js";
|
|
33
|
+
|
|
34
|
+
/** Env var name for one gateway secret (per-key diversion). */
|
|
35
|
+
function gatewayTokenEnv(key: string, field: "token" | "upstreamToken"): string {
|
|
36
|
+
const keyEnv = key.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
|
|
37
|
+
return field === "token" ? `A2A_GATEWAY_${keyEnv}_TOKEN` : `A2A_GATEWAY_${keyEnv}_UPSTREAM_TOKEN`;
|
|
38
|
+
}
|
|
32
39
|
|
|
33
40
|
/** Restart bridge — defaults to the index.ts exports; tests inject via
|
|
34
41
|
* __setRestartBridgeForTests (the panel must not spin real servers). */
|
|
@@ -380,10 +387,43 @@ export function a2aConfig(pi: ExtensionAPI): ModuleConfig {
|
|
|
380
387
|
gatewayChanged,
|
|
381
388
|
editedGatewayKeys,
|
|
382
389
|
});
|
|
390
|
+
// SECRETS DIVERSION: gateway tokens never persist in settings.json.
|
|
391
|
+
// Tokens the user actually edited → .env.local (0600, ingested at
|
|
392
|
+
// startup, env wins at read time); the loader's per-key env fallback
|
|
393
|
+
// (config.ts) resolves them at read time. The settings patch keeps
|
|
394
|
+
// every non-secret field (URL, name, heartbeat, enabled).
|
|
395
|
+
const secretEnvs: Record<string, string> = {};
|
|
396
|
+
const diverted = (patch: (a2a: any) => any): (a2a: any) => any => (a2a: any) => {
|
|
397
|
+
const out = patch(a2a);
|
|
398
|
+
if (out?.discovery && typeof out.discovery === "object") {
|
|
399
|
+
const scrub = (entry: Record<string, any>, key: string | null, editedToken: boolean, editedUpstream: boolean) => {
|
|
400
|
+
if (editedToken && entry.token) {
|
|
401
|
+
secretEnvs[key ? gatewayTokenEnv(key, "token") : "A2A_GATEWAY_TOKEN"] = String(entry.token);
|
|
402
|
+
entry.token = "";
|
|
403
|
+
}
|
|
404
|
+
if (editedUpstream && entry.upstreamToken) {
|
|
405
|
+
secretEnvs[key ? gatewayTokenEnv(key, "upstreamToken") : "A2A_GATEWAY_UPSTREAM_TOKEN"] = String(entry.upstreamToken);
|
|
406
|
+
entry.upstreamToken = undefined;
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
if (out.discovery.gateway && typeof out.discovery.gateway === "object") {
|
|
410
|
+
scrub(out.discovery.gateway, null, editedGatewayKeys.has("gateway.token"), editedGatewayKeys.has("gateway.upstreamToken"));
|
|
411
|
+
}
|
|
412
|
+
if (out.discovery.gateways && typeof out.discovery.gateways === "object") {
|
|
413
|
+
for (const [k, entry] of Object.entries(out.discovery.gateways as Record<string, any>)) {
|
|
414
|
+
if (entry && typeof entry === "object") {
|
|
415
|
+
scrub(entry, k, editedGatewayKeys.has(`gw.${k}.token`), editedGatewayKeys.has(`gw.${k}.upstreamToken`));
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return out;
|
|
421
|
+
};
|
|
383
422
|
const written = writeSettingsA2A({
|
|
384
423
|
cwd: ctx.cwd,
|
|
385
|
-
patch: builtPatch,
|
|
424
|
+
patch: diverted(builtPatch),
|
|
386
425
|
});
|
|
426
|
+
const savedSecrets = Object.keys(secretEnvs).length > 0 ? writeSecretEnvs(secretEnvs) : [];
|
|
387
427
|
|
|
388
428
|
// Live apply — config is read per call; no /reload needed.
|
|
389
429
|
setConfigOverrides({
|
|
@@ -395,6 +435,7 @@ export function a2aConfig(pi: ExtensionAPI): ModuleConfig {
|
|
|
395
435
|
});
|
|
396
436
|
|
|
397
437
|
const notes = [`A2A config saved to ${written} — applied live.`];
|
|
438
|
+
if (savedSecrets.length) notes.push(`Gateway token(s) saved to .env.local (${savedSecrets.length}) — never settings.json.`);
|
|
398
439
|
// Env overrides still shadowing edited fields.
|
|
399
440
|
const envOverrides = [...edited]
|
|
400
441
|
.map((k) => (k.startsWith("a2a.") ? ENV_SHADOW[k.slice("a2a.".length)] : undefined))
|
|
@@ -503,7 +503,9 @@ export function loadConfig(opts: {
|
|
|
503
503
|
url: gwUrl,
|
|
504
504
|
token: gwToken,
|
|
505
505
|
name: dg.name ? String(dg.name) : undefined,
|
|
506
|
-
|
|
506
|
+
// Secrets live in .env.local (panel diversion) — env fallback keeps
|
|
507
|
+
// settings.json free of tokens while the value still resolves.
|
|
508
|
+
upstreamToken: dg.upstreamToken != null ? String(dg.upstreamToken) : (env.A2A_GATEWAY_UPSTREAM_TOKEN || undefined),
|
|
507
509
|
heartbeatSec: num(dg.heartbeatSec, 60),
|
|
508
510
|
channel: dg.channel === undefined ? undefined : bool(dg.channel, true),
|
|
509
511
|
};
|
|
@@ -518,15 +520,18 @@ export function loadConfig(opts: {
|
|
|
518
520
|
if (!GATEWAY_KEY_RE.test(key)) continue;
|
|
519
521
|
if (!raw || typeof raw !== "object") continue;
|
|
520
522
|
const g = raw as Record<string, any>;
|
|
523
|
+
// Per-gateway secret env names (panel diversion — tokens never persist
|
|
524
|
+
// in settings.json): A2A_GATEWAY_<KEY>_TOKEN / _UPSTREAM_TOKEN.
|
|
525
|
+
const keyEnv = key.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
|
|
521
526
|
const u = String(g.url ?? "");
|
|
522
|
-
const t = String(g.token ?? "");
|
|
527
|
+
const t = String(g.token ?? env[`A2A_GATEWAY_${keyEnv}_TOKEN`] ?? "");
|
|
523
528
|
const enabled = g.enabled !== undefined ? bool(g.enabled, true) : Boolean(u && t);
|
|
524
529
|
gateways[key] = {
|
|
525
530
|
enabled,
|
|
526
531
|
url: u,
|
|
527
532
|
token: t,
|
|
528
533
|
name: g.name ? String(g.name) : undefined,
|
|
529
|
-
upstreamToken: g.upstreamToken ? String(g.upstreamToken) : undefined,
|
|
534
|
+
upstreamToken: g.upstreamToken != null ? String(g.upstreamToken) : (env[`A2A_GATEWAY_${keyEnv}_UPSTREAM_TOKEN`] || undefined),
|
|
530
535
|
heartbeatSec: num(g.heartbeatSec, 60),
|
|
531
536
|
channel: g.channel === undefined ? undefined : bool(g.channel, true),
|
|
532
537
|
};
|
|
@@ -277,7 +277,7 @@ describe("configPanel contribution", () => {
|
|
|
277
277
|
);
|
|
278
278
|
});
|
|
279
279
|
|
|
280
|
-
it("gateway token: an EDITED token
|
|
280
|
+
it("gateway token: an EDITED token diverts to .env.local — never settings.json; unrelated edits touch nothing", async () => {
|
|
281
281
|
await withoutA2AEnv(() =>
|
|
282
282
|
withIsolatedPiDir(async (dir) => {
|
|
283
283
|
// Operator has a gateway configured in the GLOBAL file (env-sourced token case:
|
|
@@ -302,16 +302,19 @@ describe("configPanel contribution", () => {
|
|
|
302
302
|
hb.set(90);
|
|
303
303
|
await (cfg.save as SaveFn)(new Set(["a2a.gw.work.heartbeatSec"]), ctx);
|
|
304
304
|
let written = JSON.parse(fs.readFileSync(globalSettings, "utf-8"));
|
|
305
|
-
assert.equal(written.a2a.discovery.gateways.work.token, "file-token", "unedited token survives an unrelated edit");
|
|
305
|
+
assert.equal(written.a2a.discovery.gateways.work.token, "file-token", "unedited token survives an unrelated edit (legacy value untouched)");
|
|
306
306
|
|
|
307
|
-
// Now edit the token itself →
|
|
307
|
+
// Now edit the token itself → diverts to .env.local, scrubbed from settings.json.
|
|
308
308
|
const cfg2 = a2aConfig({} as never);
|
|
309
309
|
cfg2.groups();
|
|
310
310
|
const tok = rowsOf(cfg2.groups()).find((r) => r.key === "a2a.gw.work.token")!;
|
|
311
311
|
tok.set("rotated-token");
|
|
312
312
|
await (cfg2.save as SaveFn)(new Set(["a2a.gw.work.token"]), ctx);
|
|
313
313
|
written = JSON.parse(fs.readFileSync(globalSettings, "utf-8"));
|
|
314
|
-
assert.
|
|
314
|
+
assert.ok(!written.a2a.discovery.gateways.work.token, "edited token must NOT persist in settings.json");
|
|
315
|
+
const envLocal = fs.readFileSync(path.join(process.env.PI_CODING_AGENT_DIR!, ".env.local"), "utf-8");
|
|
316
|
+
assert.match(envLocal, /A2A_GATEWAY_WORK_TOKEN=rotated-token/, "edited token diverted to .env.local");
|
|
317
|
+
assert.equal(process.env.A2A_GATEWAY_WORK_TOKEN, "rotated-token", "live session resolves the diverted token immediately");
|
|
315
318
|
}),
|
|
316
319
|
);
|
|
317
320
|
});
|
|
@@ -89,7 +89,6 @@ export default function advisorModule(pi: ExtensionAPI): void {
|
|
|
89
89
|
// watchEnabled is only updated at the end of this function.
|
|
90
90
|
const willWatch = masterChanged ? next.enabled : watchEnabled;
|
|
91
91
|
const rt = runtime;
|
|
92
|
-
const wasEmpty = !rt || rt.models.length === 0;
|
|
93
92
|
if (rt) {
|
|
94
93
|
rt.config = next;
|
|
95
94
|
rt.models = next.models;
|
|
@@ -98,8 +97,12 @@ export default function advisorModule(pi: ExtensionAPI): void {
|
|
|
98
97
|
rt.stats.paused = false;
|
|
99
98
|
rt.failures = 0;
|
|
100
99
|
}
|
|
101
|
-
// Enabling mid-session must not replay history
|
|
102
|
-
|
|
100
|
+
// Enabling mid-session must not replay history: reseed on FIRST
|
|
101
|
+
// activation (cursor still undefined), which covers BOTH the 0→N chain
|
|
102
|
+
// transition and the enable-only save on a session that started with
|
|
103
|
+
// enabled:false + a configured chain (a no-chain or disabled session
|
|
104
|
+
// never seeds the cursor, so `undefined` is exactly "not yet active").
|
|
105
|
+
if (willWatch && rt.models.length > 0 && rt.cursor === undefined) reseedCursor(rt, ctx);
|
|
103
106
|
}
|
|
104
107
|
// An explicit master change re-arms/disarms the session; otherwise a
|
|
105
108
|
// /advisor watch-off override stays in place.
|
|
@@ -261,6 +261,37 @@ describe("advisor module wiring", () => {
|
|
|
261
261
|
await fire(pi, state, "agent_settled", step(available(fakeCtx(entries)), "tui"));
|
|
262
262
|
assert.equal(calls, 0, "nothing new since the reseed → no review of the pre-existing turn");
|
|
263
263
|
});
|
|
264
|
+
|
|
265
|
+
it("session_start(review off, chain configured) + enable-only save reseeds the cursor (no history replay)", async () => {
|
|
266
|
+
// Live-found defect (reviewer 2026-10-06): the reseed keyed on the 0→N
|
|
267
|
+
// chain transition, so enabling `Review settled turns` on a session that
|
|
268
|
+
// STARTED with enabled:false + a configured chain left cursor undefined —
|
|
269
|
+
// the first settled turn counted the ENTIRE session's tool calls and
|
|
270
|
+
// reviewed the whole transcript. The reseed must key on first activation.
|
|
271
|
+
const { pi, state } = createFakePi();
|
|
272
|
+
advisorModule(pi);
|
|
273
|
+
writeSettings({ advisor: { enabled: false, models: [MODEL] } });
|
|
274
|
+
let ctx = available(fakeCtx(toolCalls(4)));
|
|
275
|
+
await fire(pi, state, "session_start", ctx);
|
|
276
|
+
const rt = __getRuntimeForTest();
|
|
277
|
+
assert.ok(rt, "runtime created");
|
|
278
|
+
assert.equal(rt!.models.length, 1, "chain was configured all along");
|
|
279
|
+
assert.equal(rt!.cursor, undefined, "review off at start → cursor never seeded");
|
|
280
|
+
|
|
281
|
+
// Enable ONLY the review — the chain is untouched.
|
|
282
|
+
const entries = toolCalls(4);
|
|
283
|
+
ctx = available(fakeCtx(entries));
|
|
284
|
+
const m = advisorConfig();
|
|
285
|
+
m.groups()[0]!.rows[0]!.set(true);
|
|
286
|
+
await m.save(new Set(["advisor.enabled"]), ctx);
|
|
287
|
+
|
|
288
|
+
assert.equal(rt!.cursor, entries.at(-1).id, "enable-only save reseeds to the tail — history is not replayed");
|
|
289
|
+
|
|
290
|
+
let calls = 0;
|
|
291
|
+
__setIsolatedForTest(async (_c, models) => { calls++; return { text: "", model: models[0], usage: NO_USAGE }; });
|
|
292
|
+
await fire(pi, state, "agent_settled", step(available(fakeCtx(entries)), "tui"));
|
|
293
|
+
assert.equal(calls, 0, "no new work since enable → no review");
|
|
294
|
+
});
|
|
264
295
|
});
|
|
265
296
|
|
|
266
297
|
describe("advisor review flow", () => {
|
|
@@ -228,6 +228,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
228
228
|
|
|
229
229
|
const cache = createVerdictCache();
|
|
230
230
|
|
|
231
|
+
// Failure circuit-breaker (advisor's MAX_CONSECUTIVE_FAILURES precedent):
|
|
232
|
+
// the bash hot path must never pay the classify deadline per command. With
|
|
233
|
+
// the transport's 30s deadline, a cataloged-but-dead endpoint would stall
|
|
234
|
+
// every unique non-risky command ~30s — repeatedly, buying nothing (the
|
|
235
|
+
// verdict never gates execution). After 3 consecutive failures the hook
|
|
236
|
+
// fails open instantly for CLASSIFIER_PAUSE_COOLDOWN_MS; a successful
|
|
237
|
+
// verdict or a settings change re-arms immediately.
|
|
238
|
+
let consecutiveFailures = 0;
|
|
239
|
+
let pausedUntil = 0;
|
|
240
|
+
let pausedSettingsRef = "";
|
|
241
|
+
const CLASSIFIER_PAUSE_AFTER = 3;
|
|
242
|
+
const CLASSIFIER_PAUSE_COOLDOWN_MS = 5 * 60_000;
|
|
243
|
+
// The bash hot path's OWN wait budget. The verdict is annotation-only in
|
|
244
|
+
// pi 1.0.0 (no approval prompt to skip), so nothing justifies parking a
|
|
245
|
+
// tool call on a slow Jev: a verdict that misses this budget reads as
|
|
246
|
+
// "no verdict" (fail open to the normal prompt, audited). The 30s
|
|
247
|
+
// transport deadline stays as the hard backstop; the circuit breaker
|
|
248
|
+
// above then stops repeated retries.
|
|
249
|
+
const CLASSIFIER_HOOK_BUDGET_MS = 2_500;
|
|
250
|
+
|
|
231
251
|
pi.on("tool_call", async (event, ctx) => {
|
|
232
252
|
if (event.toolName !== "bash") return undefined;
|
|
233
253
|
const command = String(event.input?.command || "");
|
|
@@ -236,6 +256,24 @@ export default function (pi: ExtensionAPI) {
|
|
|
236
256
|
const s = getClassifierSettings();
|
|
237
257
|
if (!s.permission.enabled) return undefined;
|
|
238
258
|
|
|
259
|
+
// Circuit open → instant fail-open (no network attempt). A changed
|
|
260
|
+
// settings object re-arms at once: the operator switching the classifier
|
|
261
|
+
// model mid-pause should not wait out the cooldown.
|
|
262
|
+
const settingsRef = JSON.stringify([s.model, s.permission.enabled, s.permission.mode, s.permission.threshold]);
|
|
263
|
+
if (settingsRef !== pausedSettingsRef) {
|
|
264
|
+
pausedSettingsRef = settingsRef;
|
|
265
|
+
if (consecutiveFailures >= CLASSIFIER_PAUSE_AFTER) consecutiveFailures = 0; // manual remediation
|
|
266
|
+
}
|
|
267
|
+
// Circuit open? Instant fail-open. Else, if the pause window has ELAPSED
|
|
268
|
+
// (pausedUntil > 0 — 0 means "never paused", which must not reset the
|
|
269
|
+
// counter), close the circuit and retry.
|
|
270
|
+
const paused = consecutiveFailures >= CLASSIFIER_PAUSE_AFTER;
|
|
271
|
+
if (paused && Date.now() < pausedUntil) return undefined;
|
|
272
|
+
if (paused && pausedUntil > 0 && Date.now() >= pausedUntil) {
|
|
273
|
+
consecutiveFailures = 0; // cooldown elapsed → retry
|
|
274
|
+
pausedUntil = 0;
|
|
275
|
+
}
|
|
276
|
+
|
|
239
277
|
// static list first — credential-touching / irreversible commands never
|
|
240
278
|
// reach Jev and never leave the normal prompt
|
|
241
279
|
if (segments(command).some(isRisky)) return undefined;
|
|
@@ -265,6 +303,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
265
303
|
const started = Date.now();
|
|
266
304
|
try {
|
|
267
305
|
const answers = await askJev(ctx, state, questions);
|
|
306
|
+
consecutiveFailures = 0;
|
|
268
307
|
const rev = noul(answers, "reversible");
|
|
269
308
|
const serves = state.task ? noul(answers, "serves_task") : rev; // no task → reversibility only
|
|
270
309
|
const ok = rev >= s.permission.threshold && serves >= s.permission.threshold;
|
|
@@ -273,12 +312,27 @@ export default function (pi: ExtensionAPI) {
|
|
|
273
312
|
await audit({ command, ...decision, ms: Date.now() - started, model: s.model || "(auto)" });
|
|
274
313
|
return decision;
|
|
275
314
|
} catch (e) {
|
|
315
|
+
consecutiveFailures++;
|
|
316
|
+
if (consecutiveFailures >= CLASSIFIER_PAUSE_AFTER) {
|
|
317
|
+
pausedUntil = Date.now() + CLASSIFIER_PAUSE_COOLDOWN_MS;
|
|
318
|
+
await audit({ command, pause: true, failures: consecutiveFailures, cooldown_ms: CLASSIFIER_PAUSE_COOLDOWN_MS });
|
|
319
|
+
}
|
|
276
320
|
await audit({ command, error: String(e instanceof Error ? e.message : e), ms: Date.now() - started, model: s.model || "(auto)" });
|
|
277
321
|
return null; // fail-safe: fall back to the normal prompt
|
|
278
322
|
}
|
|
279
323
|
};
|
|
280
324
|
|
|
281
|
-
|
|
325
|
+
// Race the verdict against the hook budget — pi awaits this handler
|
|
326
|
+
// before executing bash, so the budget (not the transport deadline) is
|
|
327
|
+
// what the user feels. A late verdict is discarded (no cache poison).
|
|
328
|
+
let decision: { approve: boolean; reversible: number; serves_task: number } | null | undefined = cached;
|
|
329
|
+
if (decision === undefined) {
|
|
330
|
+
const budget = AbortSignal.timeout(CLASSIFIER_HOOK_BUDGET_MS);
|
|
331
|
+
decision = await Promise.race([
|
|
332
|
+
decide(),
|
|
333
|
+
new Promise<null>((resolve) => budget.addEventListener("abort", () => resolve(null), { once: true })),
|
|
334
|
+
]);
|
|
335
|
+
}
|
|
282
336
|
|
|
283
337
|
// Both modes only annotate; neither changes execution (pi 1.0.0 has no
|
|
284
338
|
// approval prompt for tool_call to skip — see module docstring). Enforce
|
|
@@ -374,6 +374,68 @@ describe("permission hook", () => {
|
|
|
374
374
|
} finally { fx2.cleanup(); }
|
|
375
375
|
});
|
|
376
376
|
|
|
377
|
+
it("circuit breaker: 3 consecutive classify failures pause the hook (instant fail-open, no network attempt)", async () => {
|
|
378
|
+
// With the transport's 30s deadline, a dead endpoint would stall every
|
|
379
|
+
// unique non-risky command ~30s — repeatedly. After 3 consecutive
|
|
380
|
+
// failures the hook must fail open instantly until the cooldown.
|
|
381
|
+
let classifyCalls = 0;
|
|
382
|
+
let fail = true;
|
|
383
|
+
const registry = stubRegistry({
|
|
384
|
+
classify: async () => {
|
|
385
|
+
classifyCalls++;
|
|
386
|
+
if (fail) throw new Error("endpoint dead");
|
|
387
|
+
return { stopReason: "stop", answers: { reversible: { type: "bool", probability: 0.99 } } };
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
const fx = await hookFixture(registry);
|
|
391
|
+
try {
|
|
392
|
+
fx.messageEnd("do some work");
|
|
393
|
+
// Three DISTINCT commands (fresh cache keys) each pay one failed call.
|
|
394
|
+
assert.equal(await fx.call("ls -la"), undefined);
|
|
395
|
+
assert.equal(await fx.call("git status"), undefined);
|
|
396
|
+
assert.equal(await fx.call("pwd"), undefined);
|
|
397
|
+
assert.equal(classifyCalls, 3);
|
|
398
|
+
assert.ok(readFileSync(fx.logPath, "utf8").includes('"pause":true'), "pause transition audited");
|
|
399
|
+
|
|
400
|
+
// Circuit open: further commands fail open with NO network attempt.
|
|
401
|
+
assert.equal(await fx.call("cat file.txt"), undefined);
|
|
402
|
+
assert.equal(await fx.call("echo hi"), undefined);
|
|
403
|
+
assert.equal(classifyCalls, 3, "no classify attempts while paused");
|
|
404
|
+
} finally { fx.cleanup(); }
|
|
405
|
+
|
|
406
|
+
// Fresh module state = fresh breaker; a healthy verdict serves normally.
|
|
407
|
+
const fx2 = await hookFixture(registry);
|
|
408
|
+
try {
|
|
409
|
+
fail = false;
|
|
410
|
+
fx2.messageEnd("more work");
|
|
411
|
+
assert.equal(await fx2.call("ls"), undefined);
|
|
412
|
+
assert.equal(classifyCalls, 4, "healthy verdict went through");
|
|
413
|
+
} finally { fx2.cleanup(); }
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
it("hook budget: a slow classify loses the race — bash proceeds without waiting for the verdict", async () => {
|
|
417
|
+
// pi awaits the tool_call handler before executing bash; the verdict is
|
|
418
|
+
// annotation-only, so a slow Jev must not sit on the hot path. A verdict
|
|
419
|
+
// slower than the budget is discarded (no cache poison).
|
|
420
|
+
let classifyCalls = 0;
|
|
421
|
+
const registry = stubRegistry({
|
|
422
|
+
classify: async () => {
|
|
423
|
+
classifyCalls++;
|
|
424
|
+
await new Promise((r) => setTimeout(r, 60_000)); // way over budget
|
|
425
|
+
return { stopReason: "stop", answers: { reversible: { type: "bool", probability: 0.99 } } };
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
const fx = await hookFixture(registry);
|
|
429
|
+
try {
|
|
430
|
+
fx.messageEnd("slow endpoint");
|
|
431
|
+
const t0 = Date.now();
|
|
432
|
+
assert.equal(await fx.call("ls -la"), undefined);
|
|
433
|
+
const elapsed = Date.now() - t0;
|
|
434
|
+
assert.ok(elapsed < 5_000, `hook returned in ${elapsed}ms — budget raced, not the 30s transport deadline`);
|
|
435
|
+
assert.equal(classifyCalls, 1, "one attempt was made (then raced away)");
|
|
436
|
+
} finally { fx.cleanup(); }
|
|
437
|
+
});
|
|
438
|
+
|
|
377
439
|
it("classify error / no-model → fail-safe to prompt", async () => {
|
|
378
440
|
for (const registry of [
|
|
379
441
|
stubRegistry({ classify: async () => ({ stopReason: "error", errorMessage: "boom", answers: {} }) }),
|
|
@@ -306,8 +306,8 @@ describe("core module contract", () => {
|
|
|
306
306
|
it("nextDisabled excludes core modules; withEnableRow adds no row for them", async () => {
|
|
307
307
|
const { nextDisabled, withEnableRow } = await import("../../config/index.js");
|
|
308
308
|
// working = enabled set; nextDisabled lists the NOT-enabled non-core modules.
|
|
309
|
-
assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "rules", "attachments", "gh", "
|
|
310
|
-
assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "gh", "rules", "steering", "zai", "rtk", "config", "attachments", "permission"])), [], "all-on → nothing disabled");
|
|
309
|
+
assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "jfind", "web", "rules", "attachments", "gh", "sg", "notify", "rtk", "steering", "permission", "shells"]);
|
|
310
|
+
assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "jfind", "web", "gh", "sg", "notify", "rules", "steering", "zai", "rtk", "config", "attachments", "permission", "shells"])), [], "all-on → nothing disabled");
|
|
311
311
|
for (const core of ["composer", "advisor", "router", "classifier", "usage", "ux", "config"]) {
|
|
312
312
|
assert.ok(!nextDisabled(new Set()).includes(core), `core (${core}) is never disableable`);
|
|
313
313
|
}
|
|
@@ -34,7 +34,7 @@ function toolGroups(): PanelGroup[] {
|
|
|
34
34
|
describe("render smoke — ported modules' /config sections", () => {
|
|
35
35
|
it("renders Enable + per-tool rows inside the boxed frame with zero overflow", () => {
|
|
36
36
|
const groups = toolGroups();
|
|
37
|
-
assert.equal(groups.length,
|
|
37
|
+
assert.equal(groups.length, 20, "serena + fff + jfind + ux + munin + classifier + advisor + subagent + repair + plan + todo + web + rules + a2a + gh + sg + notify + cron + shells + steering·think (rtk has no tools)");
|
|
38
38
|
const m = new ConfigPanelModel(groups, theme, "Settings");
|
|
39
39
|
m.getHeight = () => 40;
|
|
40
40
|
for (const w of [110, 100, 80, 60]) {
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// jfind — semantic code find: describe what code does, get files + line
|
|
2
|
+
// ranges. Ported from OMP's jfind cascade; the judge routes through pi's
|
|
3
|
+
// modelRegistry.classify (System One via the router provider).
|
|
4
|
+
|
|
5
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { existsSync, statSync } from "node:fs";
|
|
7
|
+
import { resolve as resolvePath } from "node:path";
|
|
8
|
+
import { Type } from "typebox";
|
|
9
|
+
import { readDisabledTools } from "../../lib/tools.js";
|
|
10
|
+
import { formatBytes } from "./lib/format.js";
|
|
11
|
+
import { runCascade, FIND_TIMEOUT_MS, type CascadeResult } from "./lib/cascade.js";
|
|
12
|
+
import { createJudge } from "./lib/judge.js";
|
|
13
|
+
import { rankedHeat } from "./lib/tree.js";
|
|
14
|
+
|
|
15
|
+
/** Line ranges shown per hit in the model-facing text, strongest first. */
|
|
16
|
+
const RANGES_SHOWN = 3;
|
|
17
|
+
|
|
18
|
+
function formatBytesCeulen(bytes: number): string {
|
|
19
|
+
return formatBytes(bytes);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export default function jfindModule(pi: ExtensionAPI): void {
|
|
23
|
+
const disabled = readDisabledTools();
|
|
24
|
+
pi.registerTool({
|
|
25
|
+
name: "jfind",
|
|
26
|
+
label: "Semantic Find",
|
|
27
|
+
defaultActive: !disabled.has("jfind"),
|
|
28
|
+
description:
|
|
29
|
+
"Semantic code find: describe a BEHAVIOR (\"where do we parse CLI flags\", \"retry with backoff around provider calls\") and get the files and line ranges that implement it, strongest first. " +
|
|
30
|
+
"A lexical keyword scan ranks candidates, then a System One judge (the router's classifier models) ranks filenames, passage sketches, and full passages in three waves. " +
|
|
31
|
+
"Use when grep/ffgrep can't phrase the search as a literal pattern; needs a classifier model to be configured (router catalog). Slower than grep (a few seconds of judging).",
|
|
32
|
+
promptSnippet: "Semantic find: locate code by describing what it does",
|
|
33
|
+
promptGuidelines: [
|
|
34
|
+
"Describe the behavior, not the keywords: jfind judges passages semantically.",
|
|
35
|
+
'Put must-have identifiers in quotes ("spawn", "writeStdin") — quoted phrases become hard lexical keywords.',
|
|
36
|
+
"No hits doesn't mean the code doesn't exist — fall back to ffgrep/fffind for literal patterns.",
|
|
37
|
+
],
|
|
38
|
+
parameters: Type.Object({
|
|
39
|
+
query: Type.String({ description: 'What the code does, e.g. "parse cron expressions into next-fire times".' }),
|
|
40
|
+
keywords: Type.Optional(Type.Array(Type.String(), { description: "Extra literal keywords folded into the lexical prior." })),
|
|
41
|
+
path: Type.Optional(Type.String({ description: "Search scope: a directory (default the session cwd) or a single file." })),
|
|
42
|
+
}),
|
|
43
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
44
|
+
const query = (params.query as string).trim();
|
|
45
|
+
if (query.length === 0) throw new Error("`query` must be a non-empty description");
|
|
46
|
+
const cwd = ctx?.cwd || process.cwd();
|
|
47
|
+
const scopeInput = typeof params.path === "string" ? params.path.trim() : "";
|
|
48
|
+
let root = resolvePath(cwd);
|
|
49
|
+
if (scopeInput.length > 0) {
|
|
50
|
+
root = resolvePath(cwd, scopeInput);
|
|
51
|
+
if (!existsSync(root)) throw new Error(`Path not found: ${scopeInput}`);
|
|
52
|
+
if (!statSync(root).isFile() && !statSync(root).isDirectory()) {
|
|
53
|
+
throw new Error(`Path is neither a file nor a directory: ${scopeInput}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
let judge;
|
|
57
|
+
try {
|
|
58
|
+
judge = createJudge(ctx);
|
|
59
|
+
} catch (err) {
|
|
60
|
+
return {
|
|
61
|
+
content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
|
|
62
|
+
isError: true as const,
|
|
63
|
+
details: { query },
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const timeout = AbortSignal.timeout(FIND_TIMEOUT_MS);
|
|
67
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
68
|
+
let result: CascadeResult;
|
|
69
|
+
try {
|
|
70
|
+
result = await runCascade({
|
|
71
|
+
root,
|
|
72
|
+
query,
|
|
73
|
+
extraKeywords: (params.keywords as string[] | undefined) ?? [],
|
|
74
|
+
judge,
|
|
75
|
+
signal: combined,
|
|
76
|
+
onProgress: (message) => onUpdate?.({ content: [{ type: "text", text: message }], details: undefined }),
|
|
77
|
+
});
|
|
78
|
+
} catch (err) {
|
|
79
|
+
if (timeout.aborted && !signal?.aborted) {
|
|
80
|
+
throw new Error(`jfind timed out after ${Math.round(FIND_TIMEOUT_MS / 1000)}s — narrow the query or scope (path param)`);
|
|
81
|
+
}
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
const { stats, threshold, keywords } = result;
|
|
85
|
+
const scope = scopeInput.length > 0 ? ` in ${scopeInput}` : "";
|
|
86
|
+
const out: string[] = [];
|
|
87
|
+
if (result.hits.length === 0) {
|
|
88
|
+
out.push(`no hits for "${query}"${scope} (τ ${threshold.toFixed(2)})`);
|
|
89
|
+
} else {
|
|
90
|
+
out.push(`${result.hits.length} hit(s) for "${query}"${scope} (τ ${threshold.toFixed(2)}), strongest first`, "");
|
|
91
|
+
for (const hit of result.hits) {
|
|
92
|
+
const coverage = hit.truncated ? `${hit.linesSeen} lines judged, partial` : `${hit.linesSeen} lines judged`;
|
|
93
|
+
out.push(`${hit.rel} ${hit.contentScore.toFixed(2)} ${coverage}`);
|
|
94
|
+
for (const range of rankedHeat(hit.ranges, RANGES_SHOWN)) {
|
|
95
|
+
const span = range.start === range.end ? String(range.start) : `${range.start}-${range.end}`;
|
|
96
|
+
out.push(` ${hit.rel}:${span} ${range.p.toFixed(2)} ${range.snippet}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
out.push(
|
|
101
|
+
"",
|
|
102
|
+
`listed ${stats.listed} · judged ${stats.judged} · read ${stats.filesRead} files (${formatBytesCeulen(stats.fileBytes)}) · ${stats.requests} requests · ${stats.inputTokens + stats.outputTokens} tokens · keywords: ${keywords.join(", ")}`,
|
|
103
|
+
);
|
|
104
|
+
if (stats.failures.length > 0) {
|
|
105
|
+
out.push(`${stats.errors} of ${stats.requests} requests failed:`, ...stats.failures.map((f) => ` ${f}`));
|
|
106
|
+
}
|
|
107
|
+
const allFailed = stats.requests > 0 && stats.errors === stats.requests;
|
|
108
|
+
return {
|
|
109
|
+
content: [{ type: "text", text: out.join("\n") }],
|
|
110
|
+
isError: allFailed,
|
|
111
|
+
details: { query, keywords, threshold, hits: result.hits.length, stats },
|
|
112
|
+
};
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
}
|