@blackbelt-technology/pi-system-one 0.8.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 +48 -0
- package/package.json +31 -0
- package/src/backends/attempt.ts +44 -0
- package/src/backends/http.ts +45 -0
- package/src/backends/llm.ts +30 -0
- package/src/capabilities.ts +51 -0
- package/src/catalog.ts +81 -0
- package/src/config.ts +269 -0
- package/src/decision-log.ts +70 -0
- package/src/egress.ts +46 -0
- package/src/fs-util.ts +20 -0
- package/src/index.ts +16 -0
- package/src/keys.ts +57 -0
- package/src/paths.ts +14 -0
- package/src/predict.ts +128 -0
- package/src/registry.ts +43 -0
- package/src/safe-json.ts +32 -0
- package/src/types.ts +171 -0
- package/src/validate.ts +66 -0
- package/src/warn.ts +16 -0
package/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# @blackbelt-technology/pi-system-one
|
|
2
|
+
|
|
3
|
+
Typed System-1 decisions (`choice` / `score` / `noul`) for pi extensions and the
|
|
4
|
+
pi-dashboard server, through one user-controlled registry of backends:
|
|
5
|
+
|
|
6
|
+
- hosted TypeSafe Jev and any `/v1/systemone` endpoint (`http`),
|
|
7
|
+
- dashboard-managed local Von / Laya servers (`managed`, loopback only),
|
|
8
|
+
- a pi chat-model role such as `@fast` as a slow fallback (`llm`).
|
|
9
|
+
|
|
10
|
+
Node built-ins only. No runtime dependencies.
|
|
11
|
+
|
|
12
|
+
## Use
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { predict } from "@blackbelt-technology/pi-system-one";
|
|
16
|
+
|
|
17
|
+
const r = await predict({
|
|
18
|
+
consumer: { id: "my-ext:is_destructive", failurePolicy: "fail-open" },
|
|
19
|
+
state: JSON.stringify({ command: "rm -rf build/" }),
|
|
20
|
+
questions: { destructive: { type: "noul", instructions: "Does this command delete user data?" } },
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
if (!r.ok) {
|
|
24
|
+
// r.reason: no-backend | capability | off-machine | timeout | error
|
|
25
|
+
// apply your declared policy (r.policy)
|
|
26
|
+
} else if (r.mode === "enforce" && (r.answers.destructive as { noul: number }).noul >= (r.thresholds.destructive ?? 1)) {
|
|
27
|
+
// act only on calibrated, enforced answers
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The adapter never allows or blocks anything itself: it reports `mode`,
|
|
32
|
+
`thresholds` and `policy`, and the consumer decides. Answers are advisory
|
|
33
|
+
(`shadow`) until the user measures a backend for your consumer with the
|
|
34
|
+
dashboard's Test and saves it as `enforce`.
|
|
35
|
+
|
|
36
|
+
## Configuration
|
|
37
|
+
|
|
38
|
+
`~/.pi/agent/system-one.json`, edited from the dashboard settings section
|
|
39
|
+
"Decision models (System 1)". Nothing leaves the machine unless
|
|
40
|
+
`allowOffMachine` is `true`. Keys come from an env var (e.g.
|
|
41
|
+
`TYPESAFE_API_KEY`) or `~/.pi/agent/system-one/auth.json` (0600), never from the
|
|
42
|
+
config file.
|
|
43
|
+
|
|
44
|
+
Full reference: [`docs/system-one.md`](https://github.com/BlackBeltTechnology/pi-agent-dashboard/blob/develop/docs/system-one.md).
|
|
45
|
+
|
|
46
|
+
## License
|
|
47
|
+
|
|
48
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@blackbelt-technology/pi-system-one",
|
|
3
|
+
"version": "0.8.0",
|
|
4
|
+
"description": "System-1 decision adapter: predict() over choice/score/noul via a user-controlled registry of typed decision backends (hosted, managed-local, chat-role fallback). Node built-ins only; usable from pi extensions and the dashboard server.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
|
|
13
|
+
"directory": "packages/system-one"
|
|
14
|
+
},
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./src/index.ts",
|
|
17
|
+
"./capabilities": "./src/capabilities.ts"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"src/",
|
|
21
|
+
"!src/__tests__",
|
|
22
|
+
"!**/AGENTS.md",
|
|
23
|
+
"!**/*.AGENTS.md"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "vitest run"
|
|
27
|
+
},
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=22.19"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared attempt plumbing: a per-attempt AbortController fired by the
|
|
3
|
+
* adapter's own timer or by the caller's signal, and an outcome union.
|
|
4
|
+
* See change: add-system-one-registry.
|
|
5
|
+
*/
|
|
6
|
+
import type { FailReason } from "../types.js";
|
|
7
|
+
|
|
8
|
+
export type RawOutcome = { ok: true; raw: unknown; model: string } | { ok: false; outcome: Exclude<FailReason, "no-backend"> };
|
|
9
|
+
|
|
10
|
+
export interface AttemptScope {
|
|
11
|
+
signal: AbortSignal;
|
|
12
|
+
/** Resolves to "timeout" when the adapter timer or caller abort fires. */
|
|
13
|
+
aborted: Promise<"timeout">;
|
|
14
|
+
timedOut(): boolean;
|
|
15
|
+
dispose(): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function attemptScope(timeoutMs: number, caller?: AbortSignal): AttemptScope {
|
|
19
|
+
const ac = new AbortController();
|
|
20
|
+
let fired = false;
|
|
21
|
+
let resolveAbort!: (v: "timeout") => void;
|
|
22
|
+
const aborted = new Promise<"timeout">((r) => {
|
|
23
|
+
resolveAbort = r;
|
|
24
|
+
});
|
|
25
|
+
const fire = () => {
|
|
26
|
+
if (fired) return;
|
|
27
|
+
fired = true;
|
|
28
|
+
ac.abort();
|
|
29
|
+
resolveAbort("timeout");
|
|
30
|
+
};
|
|
31
|
+
const timer = setTimeout(fire, timeoutMs);
|
|
32
|
+
const onCaller = () => fire();
|
|
33
|
+
if (caller?.aborted) fire();
|
|
34
|
+
else caller?.addEventListener("abort", onCaller, { once: true });
|
|
35
|
+
return {
|
|
36
|
+
signal: ac.signal,
|
|
37
|
+
aborted,
|
|
38
|
+
timedOut: () => fired,
|
|
39
|
+
dispose() {
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
caller?.removeEventListener("abort", onCaller);
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `http` backend: `POST <url>` with the TypeSafe `/v1/systemone` body
|
|
3
|
+
* (`model`, `state`, `questions`). Redirects are errors (`redirect: "error"`),
|
|
4
|
+
* so a loopback server cannot bounce state to a remote host (design D6).
|
|
5
|
+
* Only http:/https: URLs are accepted. See change: add-system-one-registry.
|
|
6
|
+
*/
|
|
7
|
+
import { parseBackendUrl } from "../egress.js";
|
|
8
|
+
import type { Questions } from "../types.js";
|
|
9
|
+
import { attemptScope, type RawOutcome } from "./attempt.js";
|
|
10
|
+
|
|
11
|
+
export interface HttpCall {
|
|
12
|
+
url: string;
|
|
13
|
+
model: string;
|
|
14
|
+
key?: string;
|
|
15
|
+
timeoutMs: number;
|
|
16
|
+
state: string;
|
|
17
|
+
questions: Questions;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function callHttp(c: HttpCall): Promise<RawOutcome> {
|
|
22
|
+
if (!parseBackendUrl(c.url)) return { ok: false, outcome: "error" };
|
|
23
|
+
const scope = attemptScope(c.timeoutMs, c.signal);
|
|
24
|
+
try {
|
|
25
|
+
const headers: Record<string, string> = { "content-type": "application/json" };
|
|
26
|
+
if (c.key) headers.authorization = `Bearer ${c.key}`;
|
|
27
|
+
const work = (async (): Promise<RawOutcome> => {
|
|
28
|
+
const res = await fetch(c.url, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers,
|
|
31
|
+
body: JSON.stringify({ model: c.model, state: c.state, questions: c.questions }),
|
|
32
|
+
redirect: "error",
|
|
33
|
+
signal: scope.signal,
|
|
34
|
+
});
|
|
35
|
+
if (!res.ok) return { ok: false, outcome: "error" };
|
|
36
|
+
const body = (await res.json()) as { model?: unknown; answers?: unknown } | null;
|
|
37
|
+
const model = typeof body?.model === "string" && body.model ? body.model : c.model;
|
|
38
|
+
return { ok: true, raw: body?.answers, model };
|
|
39
|
+
})().catch((): RawOutcome => ({ ok: false, outcome: scope.timedOut() ? "timeout" : "error" }));
|
|
40
|
+
const r = await Promise.race([work, scope.aborted]);
|
|
41
|
+
return r === "timeout" ? { ok: false, outcome: "timeout" } : r;
|
|
42
|
+
} finally {
|
|
43
|
+
scope.dispose();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `llm` backend: delegates to an injected `LlmCaller` (design D3). The adapter
|
|
3
|
+
* enforces the timeout with its own timer and signal whether or not the caller
|
|
4
|
+
* honours the signal. See change: add-system-one-registry.
|
|
5
|
+
*/
|
|
6
|
+
import type { LlmCaller, Questions } from "../types.js";
|
|
7
|
+
import { attemptScope, type RawOutcome } from "./attempt.js";
|
|
8
|
+
|
|
9
|
+
export async function callLlm(
|
|
10
|
+
caller: LlmCaller,
|
|
11
|
+
role: string,
|
|
12
|
+
state: string,
|
|
13
|
+
questions: Questions,
|
|
14
|
+
timeoutMs: number,
|
|
15
|
+
signal?: AbortSignal,
|
|
16
|
+
): Promise<RawOutcome> {
|
|
17
|
+
const scope = attemptScope(timeoutMs, signal);
|
|
18
|
+
try {
|
|
19
|
+
const work = Promise.resolve()
|
|
20
|
+
.then(() => caller.call({ role, state, questions, signal: scope.signal }))
|
|
21
|
+
.then(
|
|
22
|
+
(r): RawOutcome => ({ ok: true, raw: r?.answers, model: typeof r?.model === "string" && r.model ? r.model : role }),
|
|
23
|
+
(): RawOutcome => ({ ok: false, outcome: scope.timedOut() ? "timeout" : "error" }),
|
|
24
|
+
);
|
|
25
|
+
const r = await Promise.race([work, scope.aborted]);
|
|
26
|
+
return r === "timeout" ? { ok: false, outcome: "timeout" } : r;
|
|
27
|
+
} finally {
|
|
28
|
+
scope.dispose();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Capability checks. Per request (spec: system-one-adapter, "Capability check
|
|
3
|
+
* per request"): estimated tokens = (state chars + longest question chars) ÷ 4
|
|
4
|
+
* — under-counts CJK, accepted. Per consumer (settings-UI filter):
|
|
5
|
+
* `incompatReasons`. A capability of `null` (unknown) never excludes.
|
|
6
|
+
* See change: add-system-one-registry.
|
|
7
|
+
*/
|
|
8
|
+
import type { Capabilities, ConsumerRequires, Question, Questions } from "./types.js";
|
|
9
|
+
|
|
10
|
+
function questionChars(q: Question): number {
|
|
11
|
+
let n = q.instructions.length;
|
|
12
|
+
if (q.type === "choice") for (const [k, v] of Object.entries(q.criteria)) n += k.length + v.length;
|
|
13
|
+
else if (q.type === "score") for (const v of q.criteria) n += v.length;
|
|
14
|
+
else if (q.criteria) n += q.criteria.true.length + q.criteria.false.length;
|
|
15
|
+
return n;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function estimateTokens(state: string, questions: Questions): number {
|
|
19
|
+
let longest = 0;
|
|
20
|
+
for (const q of Object.values(questions)) longest = Math.max(longest, questionChars(q));
|
|
21
|
+
return (state.length + longest) / 4;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `true` when the request fits the backend's known capabilities. */
|
|
25
|
+
export function fitsCapabilities(caps: Required<Capabilities>, state: string, questions: Questions): boolean {
|
|
26
|
+
if (caps.maxContextTokens != null && estimateTokens(state, questions) > caps.maxContextTokens) return false;
|
|
27
|
+
for (const q of Object.values(questions)) {
|
|
28
|
+
if (caps.primitives != null && !caps.primitives.includes(q.type)) return false;
|
|
29
|
+
if (q.type === "choice" && caps.maxOptions != null && Object.keys(q.criteria).length > caps.maxOptions) return false;
|
|
30
|
+
}
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Why a backend cannot meet a consumer's declared `requires` ([] = compatible). */
|
|
35
|
+
export function incompatReasons(caps: Required<Capabilities>, req: ConsumerRequires | undefined): string[] {
|
|
36
|
+
if (!req) return [];
|
|
37
|
+
const out: string[] = [];
|
|
38
|
+
if (req.minContextTokens != null && caps.maxContextTokens != null && caps.maxContextTokens < req.minContextTokens)
|
|
39
|
+
out.push(`context ${caps.maxContextTokens} < ${req.minContextTokens}`);
|
|
40
|
+
if (req.maxOptions != null && caps.maxOptions != null && caps.maxOptions < req.maxOptions)
|
|
41
|
+
out.push(`options ${caps.maxOptions} < ${req.maxOptions}`);
|
|
42
|
+
if (req.languages?.length && caps.languages != null && !caps.languages.includes("multi")) {
|
|
43
|
+
const missing = req.languages.filter((l) => !caps.languages?.includes(l));
|
|
44
|
+
if (missing.length) out.push(`language ${missing.join(",")}`);
|
|
45
|
+
}
|
|
46
|
+
if (req.primitives?.length && caps.primitives != null) {
|
|
47
|
+
const missing = req.primitives.filter((p) => !caps.primitives?.includes(p));
|
|
48
|
+
if (missing.length) out.push(`primitive ${missing.join(",")}`);
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
package/src/catalog.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Built-in catalog of known System-1 models (spec: system-one-settings-ui,
|
|
3
|
+
* "Backend catalog with capability metadata"). A backend whose `model` (http)
|
|
4
|
+
* or `engine` + `checkpoint` (managed) matches an entry inherits its
|
|
5
|
+
* capabilities, `keyRef` and price, unless overridden in config.
|
|
6
|
+
* `languages`: `multi` = any language. See change: add-system-one-registry.
|
|
7
|
+
*/
|
|
8
|
+
import type { Backend, Capabilities, Primitive } from "./types.js";
|
|
9
|
+
|
|
10
|
+
const ALL: Primitive[] = ["choice", "score", "noul"];
|
|
11
|
+
|
|
12
|
+
export interface CatalogEntry {
|
|
13
|
+
model: string;
|
|
14
|
+
capabilities: Required<Capabilities>;
|
|
15
|
+
/** Display label for the language column. */
|
|
16
|
+
languageLabel: string;
|
|
17
|
+
hosted: boolean;
|
|
18
|
+
keyRef?: string;
|
|
19
|
+
priceUsdPerMTok?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const CATALOG: readonly CatalogEntry[] = [
|
|
23
|
+
{
|
|
24
|
+
model: "jev-1.13.0",
|
|
25
|
+
capabilities: { maxContextTokens: 32_000, maxOptions: 255, languages: ["en", "multi"], primitives: ALL },
|
|
26
|
+
languageLabel: "en-first",
|
|
27
|
+
hosted: true,
|
|
28
|
+
keyRef: "TYPESAFE_API_KEY",
|
|
29
|
+
priceUsdPerMTok: 0.042,
|
|
30
|
+
},
|
|
31
|
+
{ model: "von-1.2", capabilities: { maxContextTokens: 8_192, maxOptions: null, languages: ["en"], primitives: ALL }, languageLabel: "en", hosted: false },
|
|
32
|
+
{ model: "laya", capabilities: { maxContextTokens: 512, maxOptions: null, languages: ["en"], primitives: ALL }, languageLabel: "en", hosted: false },
|
|
33
|
+
{
|
|
34
|
+
model: "laya-multilingual",
|
|
35
|
+
capabilities: { maxContextTokens: 1_024, maxOptions: null, languages: ["multi"], primitives: ALL },
|
|
36
|
+
languageLabel: "multi",
|
|
37
|
+
hosted: false,
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
model: "laya-typed-decisions",
|
|
41
|
+
capabilities: { maxContextTokens: 1_024, maxOptions: null, languages: ["en"], primitives: ALL },
|
|
42
|
+
languageLabel: "en",
|
|
43
|
+
hosted: false,
|
|
44
|
+
},
|
|
45
|
+
{ model: "kev", capabilities: { maxContextTokens: null, maxOptions: null, languages: ["en"], primitives: ALL }, languageLabel: "en", hosted: false },
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
/** Default checkpoint per managed engine. */
|
|
49
|
+
export const DEFAULT_CHECKPOINT = { von: "von-1.2", laya: "laya" } as const;
|
|
50
|
+
|
|
51
|
+
/** The model id a backend is expected to serve (null for `llm`). */
|
|
52
|
+
export function backendModel(b: Backend): string | null {
|
|
53
|
+
if (b.kind === "http") return b.model;
|
|
54
|
+
if (b.kind === "managed") return b.checkpoint ?? DEFAULT_CHECKPOINT[b.engine];
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function catalogEntry(b: Backend): CatalogEntry | undefined {
|
|
59
|
+
const m = backendModel(b);
|
|
60
|
+
return m === null ? undefined : CATALOG.find((e) => e.model === m);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const UNKNOWN: Required<Capabilities> = { maxContextTokens: null, maxOptions: null, languages: null, primitives: null };
|
|
64
|
+
|
|
65
|
+
/** Catalog capabilities overlaid by config (an explicit `null` means unknown). */
|
|
66
|
+
export function effectiveCapabilities(b: Backend): Required<Capabilities> {
|
|
67
|
+
const base = catalogEntry(b)?.capabilities ?? UNKNOWN;
|
|
68
|
+
const o = b.capabilities ?? {};
|
|
69
|
+
const pick = <K extends keyof Capabilities>(k: K) => (Object.hasOwn(o, k) ? (o[k] ?? null) : base[k]) as Required<Capabilities>[K];
|
|
70
|
+
return {
|
|
71
|
+
maxContextTokens: pick("maxContextTokens"),
|
|
72
|
+
maxOptions: pick("maxOptions"),
|
|
73
|
+
languages: pick("languages"),
|
|
74
|
+
primitives: pick("primitives"),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function effectiveKeyRef(b: Backend): string | undefined {
|
|
79
|
+
if (b.kind !== "http") return undefined;
|
|
80
|
+
return b.keyRef ?? catalogEntry(b)?.keyRef;
|
|
81
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config load (spec: system-one-config). User file `~/.pi/agent/system-one.json`
|
|
3
|
+
* plus an optional project override `<cwd>/.pi/system-one.json`, read only for
|
|
4
|
+
* `project.trusted === true`. Every layer parses into null-prototype objects
|
|
5
|
+
* with `__proto__`/`constructor`/`prototype` dropped (design D12). The project
|
|
6
|
+
* layer may only set `presets.<activePreset>.consumers.<id>.chain`, restricted
|
|
7
|
+
* to user-defined on-machine backends. Files are re-read only when their mtime
|
|
8
|
+
* (or size) changes. See change: add-system-one-registry.
|
|
9
|
+
*/
|
|
10
|
+
import { readFileSync, statSync } from "node:fs";
|
|
11
|
+
import { isOffMachine, parseBackendUrl } from "./egress.js";
|
|
12
|
+
import { projectConfigPath, userConfigPath } from "./paths.js";
|
|
13
|
+
import { isObj, own, type Plain, safeParse } from "./safe-json.js";
|
|
14
|
+
import type { Backend, CalibrationRecord, Capabilities, Preset, Primitive, ProjectRef, SystemOneConfig } from "./types.js";
|
|
15
|
+
import { _resetWarnings, warnOnce } from "./warn.js";
|
|
16
|
+
|
|
17
|
+
export { userConfigPath } from "./paths.js";
|
|
18
|
+
|
|
19
|
+
// ---------- reset hooks (tests) ----------
|
|
20
|
+
const resetHooks: Array<() => void> = [];
|
|
21
|
+
export function onReset(fn: () => void): void {
|
|
22
|
+
resetHooks.push(fn);
|
|
23
|
+
}
|
|
24
|
+
/** Clear caches, per-process warning and registration memory. Tests only. */
|
|
25
|
+
export function _resetForTests(): void {
|
|
26
|
+
cache.clear();
|
|
27
|
+
_resetWarnings();
|
|
28
|
+
for (const fn of resetHooks) fn();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// ---------- raw file cache ----------
|
|
32
|
+
interface CacheEntry {
|
|
33
|
+
mtimeMs: number;
|
|
34
|
+
size: number;
|
|
35
|
+
value: Plain | null;
|
|
36
|
+
}
|
|
37
|
+
const cache = new Map<string, CacheEntry>();
|
|
38
|
+
|
|
39
|
+
/** Parsed file (null-prototype) or `null` when absent/invalid. mtime-cached. */
|
|
40
|
+
function readLayer(path: string): Plain | null {
|
|
41
|
+
let st: { mtimeMs: number; size: number };
|
|
42
|
+
try {
|
|
43
|
+
st = statSync(path);
|
|
44
|
+
} catch {
|
|
45
|
+
cache.delete(path);
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
const hit = cache.get(path);
|
|
49
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.value;
|
|
50
|
+
let value: Plain | null = null;
|
|
51
|
+
try {
|
|
52
|
+
const parsed = safeParse(readFileSync(path, "utf8"), (p) => warnOnce(`${path}: dropped forbidden key "${p}"`));
|
|
53
|
+
if (!isObj(parsed)) warnOnce(`${path}: not a JSON object; ignoring file`);
|
|
54
|
+
else if (own(parsed, "version") !== 1) warnOnce(`${path}: unsupported version ${JSON.stringify(own(parsed, "version"))}; ignoring file`);
|
|
55
|
+
else value = parsed;
|
|
56
|
+
} catch {
|
|
57
|
+
warnOnce(`${path}: invalid JSON; ignoring file`);
|
|
58
|
+
}
|
|
59
|
+
cache.set(path, { mtimeMs: st.mtimeMs, size: st.size, value });
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------- normalization ----------
|
|
64
|
+
const BACKEND_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
65
|
+
const KEY_LIKE = ["apiKey", "key", "token"];
|
|
66
|
+
const PRIMITIVES = new Set<Primitive>(["choice", "score", "noul"]);
|
|
67
|
+
|
|
68
|
+
const map = <T>(): Record<string, T> => Object.create(null);
|
|
69
|
+
const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
|
|
70
|
+
const posNum = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined);
|
|
71
|
+
const strArr = (v: unknown): string[] | undefined => (Array.isArray(v) && v.every((x) => typeof x === "string") ? [...v] : undefined);
|
|
72
|
+
|
|
73
|
+
function normCapabilities(v: unknown): Capabilities | undefined {
|
|
74
|
+
if (!isObj(v)) return undefined;
|
|
75
|
+
const out: Capabilities = {};
|
|
76
|
+
for (const k of ["maxContextTokens", "maxOptions"] as const) {
|
|
77
|
+
if (!Object.hasOwn(v, k)) continue;
|
|
78
|
+
const n = own(v, k);
|
|
79
|
+
out[k] = n === null ? null : (posNum(n) ?? null);
|
|
80
|
+
}
|
|
81
|
+
if (Object.hasOwn(v, "languages")) out.languages = own(v, "languages") === null ? null : (strArr(own(v, "languages")) ?? null);
|
|
82
|
+
if (Object.hasOwn(v, "primitives")) {
|
|
83
|
+
const p = strArr(own(v, "primitives"));
|
|
84
|
+
out.primitives = p ? (p.filter((x) => PRIMITIVES.has(x as Primitive)) as Primitive[]) : null;
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
type Common = Pick<Backend, "timeoutMs" | "capabilities">;
|
|
90
|
+
|
|
91
|
+
function normHttp(id: string, v: Plain, file: string, common: Common): Backend | null {
|
|
92
|
+
const url = str(own(v, "url"));
|
|
93
|
+
if (!url || !parseBackendUrl(url)) {
|
|
94
|
+
warnOnce(`${file}: backend "${id}" needs an http: or https: url; ignoring it`);
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
const keyRef = str(own(v, "keyRef"));
|
|
98
|
+
return { kind: "http", url, model: str(own(v, "model")) ?? "", ...(keyRef ? { keyRef } : {}), ...common };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const validPort = (p: unknown): p is number => Number.isInteger(p) && (p as number) > 0 && (p as number) < 65536;
|
|
102
|
+
|
|
103
|
+
function normManaged(id: string, v: Plain, file: string, common: Common): Backend | null {
|
|
104
|
+
const engine = own(v, "engine");
|
|
105
|
+
if (engine !== "von" && engine !== "laya") {
|
|
106
|
+
warnOnce(`${file}: managed backend "${id}" needs engine "von" or "laya"; ignoring it`);
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
const port = own(v, "port");
|
|
110
|
+
const checkpoint = str(own(v, "checkpoint"));
|
|
111
|
+
return {
|
|
112
|
+
kind: "managed",
|
|
113
|
+
engine,
|
|
114
|
+
...(checkpoint ? { checkpoint } : {}),
|
|
115
|
+
...(validPort(port) ? { port } : {}),
|
|
116
|
+
...(own(v, "autostart") === true ? { autostart: true } : {}),
|
|
117
|
+
...common,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function normLlm(id: string, v: Plain, file: string, common: Common): Backend | null {
|
|
122
|
+
const role = str(own(v, "role"));
|
|
123
|
+
if (!role) {
|
|
124
|
+
warnOnce(`${file}: llm backend "${id}" needs a role; ignoring it`);
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
return { kind: "llm", role, ...common };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const KIND_NORMALIZERS: Record<string, (id: string, v: Plain, file: string, common: Common) => Backend | null> = {
|
|
131
|
+
http: normHttp,
|
|
132
|
+
managed: normManaged,
|
|
133
|
+
llm: normLlm,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
export function normBackend(id: string, v: unknown, file: string): Backend | null {
|
|
137
|
+
if (!BACKEND_ID.test(id)) {
|
|
138
|
+
warnOnce(`${file}: backend id "${id}" is invalid; ignoring it`);
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
if (!isObj(v)) return null;
|
|
142
|
+
for (const k of KEY_LIKE.filter((k) => Object.hasOwn(v, k)))
|
|
143
|
+
warnOnce(`${file}: backend "${id}" has key-like field "${k}"; ignored (keys never live in the config)`);
|
|
144
|
+
const kind = own(v, "kind");
|
|
145
|
+
const norm = typeof kind === "string" && Object.hasOwn(KIND_NORMALIZERS, kind) ? KIND_NORMALIZERS[kind] : undefined;
|
|
146
|
+
if (!norm) {
|
|
147
|
+
warnOnce(`${file}: backend "${id}" has unknown kind ${JSON.stringify(kind)}; ignoring it`);
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
const timeoutMs = posNum(own(v, "timeoutMs"));
|
|
151
|
+
const capabilities = normCapabilities(own(v, "capabilities"));
|
|
152
|
+
return norm(id, v, file, { ...(timeoutMs ? { timeoutMs } : {}), ...(capabilities ? { capabilities } : {}) });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function normChain(v: unknown): string[] {
|
|
156
|
+
return strArr(v) ?? [];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function normPreset(v: unknown): Preset | null {
|
|
160
|
+
if (!isObj(v)) return null;
|
|
161
|
+
const preset: Preset = { chain: normChain(own(v, "chain")) };
|
|
162
|
+
const consumers = own(v, "consumers");
|
|
163
|
+
if (isObj(consumers)) {
|
|
164
|
+
preset.consumers = map();
|
|
165
|
+
for (const cid of Object.keys(consumers)) {
|
|
166
|
+
const c = own(consumers, cid);
|
|
167
|
+
if (isObj(c)) preset.consumers[cid] = { chain: normChain(own(c, "chain")) };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return preset;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function normCalibration(v: unknown): CalibrationRecord | null {
|
|
174
|
+
if (!isObj(v)) return null;
|
|
175
|
+
const mode = own(v, "mode");
|
|
176
|
+
const model = str(own(v, "model"));
|
|
177
|
+
if ((mode !== "shadow" && mode !== "enforce") || !model) return null;
|
|
178
|
+
const thresholds: Record<string, number> = map();
|
|
179
|
+
const t = own(v, "thresholds");
|
|
180
|
+
if (isObj(t)) for (const k of Object.keys(t)) if (typeof t[k] === "number") thresholds[k] = t[k] as number;
|
|
181
|
+
return { mode, thresholds, model, measuredAt: str(own(v, "measuredAt")) ?? "" };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Normalize every own entry of an object-valued key into a null-prototype map. */
|
|
185
|
+
function mapOwn<T>(raw: Plain, key: string, norm: (k: string, v: unknown) => T | null): Record<string, T> {
|
|
186
|
+
const out = map<T>();
|
|
187
|
+
const src = own(raw, key);
|
|
188
|
+
if (!isObj(src)) return out;
|
|
189
|
+
for (const k of Object.keys(src)) {
|
|
190
|
+
const v = norm(k, own(src, k));
|
|
191
|
+
if (v) out[k] = v;
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Normalize a parsed user layer into a full config. Exported for the plugin server. */
|
|
197
|
+
export function normalizeUser(raw: Plain | null, file: string): SystemOneConfig {
|
|
198
|
+
if (!raw) return { version: 1, allowOffMachine: false, backends: map(), presets: map(), activePreset: "", calibration: map() };
|
|
199
|
+
return {
|
|
200
|
+
version: 1,
|
|
201
|
+
allowOffMachine: own(raw, "allowOffMachine") === true,
|
|
202
|
+
backends: mapOwn(raw, "backends", (id, v) => normBackend(id, v, file)),
|
|
203
|
+
presets: mapOwn(raw, "presets", (_n, v) => normPreset(v)),
|
|
204
|
+
activePreset: str(own(raw, "activePreset")) ?? "",
|
|
205
|
+
calibration: mapOwn(raw, "calibration", (_k, v) => normCalibration(v)),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const PROJECT_RULE = "project files may only set presets.<activePreset>.consumers.<id>.chain";
|
|
210
|
+
|
|
211
|
+
/** Warn once for every key of `obj` outside `allowed`, prefixed by `path`. */
|
|
212
|
+
function warnIgnored(file: string, obj: Plain, allowed: string[], path: string): void {
|
|
213
|
+
for (const k of Object.keys(obj)) if (!allowed.includes(k)) warnOnce(`${file}: ignoring "${path}${k}" (${PROJECT_RULE})`);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Project chain entries kept only when user-defined AND on-machine (no LlmCaller here → llm is off-machine). */
|
|
217
|
+
function projectChain(cfg: SystemOneConfig, cid: string, raw: unknown, file: string): string[] {
|
|
218
|
+
return normChain(raw).filter((id) => {
|
|
219
|
+
const b = Object.hasOwn(cfg.backends, id) ? cfg.backends[id] : undefined;
|
|
220
|
+
const why = !b ? "not a backend in the user config" : isOffMachine(b) ? "a project cannot select an off-machine backend" : null;
|
|
221
|
+
if (why) warnOnce(`${file}: dropping "${id}" from consumer "${cid}": ${why}`);
|
|
222
|
+
return why === null;
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function applyProjectConsumers(cfg: SystemOneConfig, name: string, consumers: Plain, file: string): void {
|
|
227
|
+
for (const cid of Object.keys(consumers)) {
|
|
228
|
+
const c = own(consumers, cid);
|
|
229
|
+
if (!isObj(c)) continue;
|
|
230
|
+
warnIgnored(file, c, ["chain"], `presets.${name}.consumers.${cid}.`);
|
|
231
|
+
const raw = own(c, "chain");
|
|
232
|
+
const chain = projectChain(cfg, cid, raw, file);
|
|
233
|
+
// Every requested id dropped → no override: the user's chain stays in force.
|
|
234
|
+
if (chain.length === 0 && normChain(raw).length > 0) continue;
|
|
235
|
+
if (!Object.hasOwn(cfg.presets, name)) cfg.presets[name] = { chain: [] };
|
|
236
|
+
const target = cfg.presets[name];
|
|
237
|
+
target.consumers ??= map();
|
|
238
|
+
target.consumers[cid] = { chain };
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Merge the permitted project keys onto `cfg` (mutates). */
|
|
243
|
+
function applyProject(cfg: SystemOneConfig, raw: Plain, file: string): void {
|
|
244
|
+
warnIgnored(file, raw, ["version", "presets"], "");
|
|
245
|
+
const presets = own(raw, "presets");
|
|
246
|
+
if (!isObj(presets)) return;
|
|
247
|
+
warnIgnored(file, presets, [cfg.activePreset], "presets.");
|
|
248
|
+
const p = Object.hasOwn(presets, cfg.activePreset) ? own(presets, cfg.activePreset) : undefined;
|
|
249
|
+
if (!isObj(p)) return;
|
|
250
|
+
warnIgnored(file, p, ["consumers"], `presets.${cfg.activePreset}.`);
|
|
251
|
+
const consumers = own(p, "consumers");
|
|
252
|
+
if (isObj(consumers)) applyProjectConsumers(cfg, cfg.activePreset, consumers, file);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export interface LoadOptions {
|
|
256
|
+
project?: ProjectRef;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The effective config for one call. Cheap on repeat (mtime cache). */
|
|
260
|
+
export function loadConfig(opts: LoadOptions = {}): SystemOneConfig {
|
|
261
|
+
const file = userConfigPath();
|
|
262
|
+
const cfg = normalizeUser(readLayer(file), file);
|
|
263
|
+
if (opts.project?.trusted === true) {
|
|
264
|
+
const pfile = projectConfigPath(opts.project.cwd);
|
|
265
|
+
const raw = readLayer(pfile);
|
|
266
|
+
if (raw) applyProject(cfg, raw, pfile);
|
|
267
|
+
}
|
|
268
|
+
return cfg;
|
|
269
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decision log (spec: system-one-adapter, "Decision log without state text";
|
|
3
|
+
* design D9). One JSONL file per process per UTC day:
|
|
4
|
+
* `~/.pi/agent/system-one/decisions/<YYYY-MM-DD>.<pid>.jsonl` (0600). Lines
|
|
5
|
+
* carry distributions, attempts, model, mode and a SHA-256 of the state —
|
|
6
|
+
* never state, instructions or keys. Failures are swallowed. Files older than
|
|
7
|
+
* 30 days are removed on library load. See change: add-system-one-registry.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { appendFileSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { decisionsDir } from "./paths.js";
|
|
13
|
+
import type { Answers, Attempt, Mode } from "./types.js";
|
|
14
|
+
|
|
15
|
+
const DAY_MS = 86_400_000;
|
|
16
|
+
const RETENTION_DAYS = 30;
|
|
17
|
+
const NAME_DAY = /^(\d{4}-\d{2}-\d{2})\./;
|
|
18
|
+
|
|
19
|
+
export interface DecisionLine {
|
|
20
|
+
consumerId: string;
|
|
21
|
+
attempts: Attempt[];
|
|
22
|
+
model: string | null;
|
|
23
|
+
mode: Mode | null;
|
|
24
|
+
answers: Answers | null;
|
|
25
|
+
reason?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
let madeDir = "";
|
|
29
|
+
|
|
30
|
+
export function logDecision(line: DecisionLine, state: string): void {
|
|
31
|
+
try {
|
|
32
|
+
const dir = decisionsDir();
|
|
33
|
+
if (madeDir !== dir) {
|
|
34
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
35
|
+
madeDir = dir;
|
|
36
|
+
}
|
|
37
|
+
const day = new Date().toISOString().slice(0, 10);
|
|
38
|
+
const stateSha256 = createHash("sha256").update(state).digest("hex");
|
|
39
|
+
const record = { ts: new Date().toISOString(), ...line, stateSha256 };
|
|
40
|
+
appendFileSync(join(dir, `${day}.${process.pid}.jsonl`), `${JSON.stringify(record)}\n`, { mode: 0o600 });
|
|
41
|
+
} catch {
|
|
42
|
+
// never fail predict on a log write
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Whole UTC days between the file's day (from its name, else its mtime) and `now`. */
|
|
47
|
+
function ageDays(name: string, path: string, now: number): number {
|
|
48
|
+
const m = NAME_DAY.exec(name);
|
|
49
|
+
const fileDay = m ? Date.parse(`${m[1]}T00:00:00Z`) : Math.floor(statSync(path).mtimeMs / DAY_MS) * DAY_MS;
|
|
50
|
+
return Math.floor((Math.floor(now / DAY_MS) * DAY_MS - fileDay) / DAY_MS);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function pruneDecisionLogs(now = Date.now()): void {
|
|
54
|
+
try {
|
|
55
|
+
const dir = decisionsDir();
|
|
56
|
+
for (const name of readdirSync(dir)) {
|
|
57
|
+
if (!name.endsWith(".jsonl")) continue;
|
|
58
|
+
const p = join(dir, name);
|
|
59
|
+
try {
|
|
60
|
+
if (ageDays(name, p, now) > RETENTION_DAYS) rmSync(p, { force: true });
|
|
61
|
+
} catch {
|
|
62
|
+
// raced with another process
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
} catch {
|
|
66
|
+
// no dir yet
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
pruneDecisionLogs();
|
package/src/egress.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Egress classification by destination (design D6). An `http` backend is
|
|
3
|
+
* on-machine only when its URL host is loopback: `localhost`, `127.0.0.0/8`,
|
|
4
|
+
* or `[::1]`. Anything else — including `localhost.` and IPv4-mapped IPv6 —
|
|
5
|
+
* is off-machine. `managed` resolves to loopback. `llm` asks the caller.
|
|
6
|
+
* See change: add-system-one-registry.
|
|
7
|
+
*/
|
|
8
|
+
import type { Backend, LlmCaller } from "./types.js";
|
|
9
|
+
|
|
10
|
+
const V4_LOOPBACK = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
|
11
|
+
|
|
12
|
+
export function isLoopbackHost(hostname: string): boolean {
|
|
13
|
+
const h = hostname.toLowerCase();
|
|
14
|
+
if (h === "localhost" || h === "[::1]") return true;
|
|
15
|
+
const m = V4_LOOPBACK.exec(h);
|
|
16
|
+
return !!m && m.slice(1).every((o) => Number(o) <= 255);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Parse an http backend URL; `null` for an unparseable or non-http(s) URL. */
|
|
20
|
+
export function parseBackendUrl(url: string): URL | null {
|
|
21
|
+
try {
|
|
22
|
+
const u = new URL(url);
|
|
23
|
+
return u.protocol === "http:" || u.protocol === "https:" ? u : null;
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* `true` when calling this backend may send data off this machine. An `llm`
|
|
31
|
+
* backend is on-machine only when `isLocal(role)` returns exactly `true`; a
|
|
32
|
+
* throwing or missing caller counts as off-machine.
|
|
33
|
+
*/
|
|
34
|
+
export function isOffMachine(b: Backend, llm?: LlmCaller): boolean {
|
|
35
|
+
if (b.kind === "managed") return false;
|
|
36
|
+
if (b.kind === "http") {
|
|
37
|
+
const u = parseBackendUrl(b.url);
|
|
38
|
+
return !u || !isLoopbackHost(u.hostname);
|
|
39
|
+
}
|
|
40
|
+
if (!llm) return true;
|
|
41
|
+
try {
|
|
42
|
+
return llm.isLocal(b.role) !== true;
|
|
43
|
+
} catch {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/fs-util.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Owner-only atomic write: temp file (0600) + rename. On any failure the temp
|
|
3
|
+
* file is removed and the target is left untouched.
|
|
4
|
+
* See change: add-system-one-registry.
|
|
5
|
+
*/
|
|
6
|
+
import { chmodSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { dirname } from "node:path";
|
|
8
|
+
|
|
9
|
+
export function atomicWrite0600(path: string, text: string): void {
|
|
10
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
11
|
+
const tmp = `${path}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
12
|
+
try {
|
|
13
|
+
writeFileSync(tmp, text, { mode: 0o600 });
|
|
14
|
+
chmodSync(tmp, 0o600);
|
|
15
|
+
renameSync(tmp, path);
|
|
16
|
+
} catch (err) {
|
|
17
|
+
rmSync(tmp, { force: true });
|
|
18
|
+
throw err;
|
|
19
|
+
}
|
|
20
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @blackbelt-technology/pi-system-one — public surface.
|
|
3
|
+
* See change: add-system-one-registry.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export { estimateTokens, fitsCapabilities, incompatReasons } from "./capabilities.js";
|
|
7
|
+
export { backendModel, CATALOG, type CatalogEntry, catalogEntry, DEFAULT_CHECKPOINT, effectiveCapabilities, effectiveKeyRef } from "./catalog.js";
|
|
8
|
+
export { loadConfig, normalizeUser, normBackend, userConfigPath } from "./config.js";
|
|
9
|
+
export { isLoopbackHost, isOffMachine, parseBackendUrl } from "./egress.js";
|
|
10
|
+
export { atomicWrite0600 } from "./fs-util.js";
|
|
11
|
+
export { authPath, isValidKeyRef, type KeyStatus, keyStatus, writeKey } from "./keys.js";
|
|
12
|
+
export { agentDir, consumersDir, decisionsDir, projectConfigPath, stateDir } from "./paths.js";
|
|
13
|
+
export { predict, resolveChain } from "./predict.js";
|
|
14
|
+
export { CONSUMER_ID, consumerFile } from "./registry.js";
|
|
15
|
+
export { isObj, safeParse } from "./safe-json.js";
|
|
16
|
+
export * from "./types.js";
|
package/src/keys.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API key sources (spec: system-one-config, "API key sources"; design D7).
|
|
3
|
+
* First match wins: env var named by `keyRef`, then
|
|
4
|
+
* `~/.pi/agent/system-one/auth.json` (0600, keyed by `keyRef`). Writes are
|
|
5
|
+
* atomic (temp file + rename). Nothing here ever returns a key to a caller
|
|
6
|
+
* other than the HTTP backend. See change: add-system-one-registry.
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { atomicWrite0600 } from "./fs-util.js";
|
|
10
|
+
import { authPath } from "./paths.js";
|
|
11
|
+
import { isObj, own, safeParse } from "./safe-json.js";
|
|
12
|
+
|
|
13
|
+
export { authPath } from "./paths.js";
|
|
14
|
+
|
|
15
|
+
const KEY_REF = /^[A-Z_][A-Z0-9_]{0,127}$/;
|
|
16
|
+
export const isValidKeyRef = (ref: string): boolean => KEY_REF.test(ref);
|
|
17
|
+
|
|
18
|
+
function readFileKeys(): Record<string, string> {
|
|
19
|
+
const out: Record<string, string> = Object.create(null);
|
|
20
|
+
try {
|
|
21
|
+
const v = safeParse(readFileSync(authPath(), "utf8"), () => {});
|
|
22
|
+
if (isObj(v)) for (const k of Object.keys(v)) if (typeof own(v, k) === "string") out[k] = own(v, k) as string;
|
|
23
|
+
} catch {
|
|
24
|
+
// absent or unreadable → no file keys
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The key for `keyRef`, or undefined. Only the http backend calls this. */
|
|
30
|
+
export function resolveKey(keyRef: string): string | undefined {
|
|
31
|
+
if (!isValidKeyRef(keyRef)) return undefined;
|
|
32
|
+
const env = process.env[keyRef];
|
|
33
|
+
if (env) return env;
|
|
34
|
+
const k = readFileKeys()[keyRef];
|
|
35
|
+
return k || undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface KeyStatus {
|
|
39
|
+
set: boolean;
|
|
40
|
+
source: "env" | "file" | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function keyStatus(keyRef: string): KeyStatus {
|
|
44
|
+
if (!isValidKeyRef(keyRef)) return { set: false, source: null };
|
|
45
|
+
if (process.env[keyRef]) return { set: true, source: "env" };
|
|
46
|
+
if (readFileKeys()[keyRef]) return { set: true, source: "file" };
|
|
47
|
+
return { set: false, source: null };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Store (or, with an empty value, remove) a key. Atomic; mode 0600. */
|
|
51
|
+
export function writeKey(keyRef: string, value: string): void {
|
|
52
|
+
if (!isValidKeyRef(keyRef)) throw new Error(`invalid keyRef "${keyRef}"`);
|
|
53
|
+
const keys = readFileKeys();
|
|
54
|
+
if (value) keys[keyRef] = value;
|
|
55
|
+
else delete keys[keyRef];
|
|
56
|
+
atomicWrite0600(authPath(), `${JSON.stringify(keys, null, 2)}\n`);
|
|
57
|
+
}
|
package/src/paths.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Filesystem locations. Resolved per call from `os.homedir()` so tests that
|
|
3
|
+
* swap HOME per file see their own tree. See change: add-system-one-registry.
|
|
4
|
+
*/
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
|
|
8
|
+
export const agentDir = (): string => join(homedir(), ".pi", "agent");
|
|
9
|
+
export const userConfigPath = (): string => join(agentDir(), "system-one.json");
|
|
10
|
+
export const projectConfigPath = (cwd: string): string => join(cwd, ".pi", "system-one.json");
|
|
11
|
+
export const stateDir = (): string => join(agentDir(), "system-one");
|
|
12
|
+
export const consumersDir = (): string => join(stateDir(), "consumers");
|
|
13
|
+
export const decisionsDir = (): string => join(stateDir(), "decisions");
|
|
14
|
+
export const authPath = (): string => join(stateDir(), "auth.json");
|
package/src/predict.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `predict` — the single System-1 entry point (spec: system-one-adapter).
|
|
3
|
+
* Resolves the chain (consumer override > preset chain > empty), then for each
|
|
4
|
+
* entry: egress gate → capability gate → call → validate. First success wins;
|
|
5
|
+
* no backend is retried; a caller abort stops the chain. The adapter reports
|
|
6
|
+
* `mode`/`thresholds`/`policy` and never allows or blocks anything itself
|
|
7
|
+
* (design D4). See change: add-system-one-registry.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { RawOutcome } from "./backends/attempt.js";
|
|
11
|
+
import { callHttp } from "./backends/http.js";
|
|
12
|
+
import { callLlm } from "./backends/llm.js";
|
|
13
|
+
import { fitsCapabilities } from "./capabilities.js";
|
|
14
|
+
import { backendModel, effectiveCapabilities, effectiveKeyRef } from "./catalog.js";
|
|
15
|
+
import { loadConfig } from "./config.js";
|
|
16
|
+
import { logDecision } from "./decision-log.js";
|
|
17
|
+
import { isOffMachine } from "./egress.js";
|
|
18
|
+
import { resolveKey } from "./keys.js";
|
|
19
|
+
import { CONSUMER_ID, registerConsumer } from "./registry.js";
|
|
20
|
+
import type { Answers, Attempt, Backend, FailReason, LlmCaller, Mode, PredictRequest, PredictResult, SystemOneConfig } from "./types.js";
|
|
21
|
+
import { normalizeAnswers } from "./validate.js";
|
|
22
|
+
import { warnOnce } from "./warn.js";
|
|
23
|
+
|
|
24
|
+
const HTTP_TIMEOUT_MS = 2_000;
|
|
25
|
+
const LLM_TIMEOUT_MS = 15_000;
|
|
26
|
+
|
|
27
|
+
/** The chain `predict` would try for `consumerId`, undefined ids dropped. */
|
|
28
|
+
export function resolveChain(cfg: SystemOneConfig, consumerId: string): string[] {
|
|
29
|
+
const preset = Object.hasOwn(cfg.presets, cfg.activePreset) ? cfg.presets[cfg.activePreset] : undefined;
|
|
30
|
+
const override = preset?.consumers && Object.hasOwn(preset.consumers, consumerId) ? preset.consumers[consumerId] : undefined;
|
|
31
|
+
const chain = override?.chain ?? preset?.chain ?? [];
|
|
32
|
+
return chain.filter((id) => {
|
|
33
|
+
if (Object.hasOwn(cfg.backends, id)) return true;
|
|
34
|
+
warnOnce(`chain entry "${id}" names an undefined backend; ignoring it`);
|
|
35
|
+
return false;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Why `b` must be skipped before any request, or null to call it. */
|
|
40
|
+
function gate(b: Backend, cfg: SystemOneConfig, req: PredictRequest): FailReason | null {
|
|
41
|
+
if (b.kind === "llm" && !req.llmCaller) return "no-backend";
|
|
42
|
+
if (!cfg.allowOffMachine && isOffMachine(b, req.llmCaller)) return "off-machine";
|
|
43
|
+
if (!fitsCapabilities(effectiveCapabilities(b), req.state, req.questions)) return "capability";
|
|
44
|
+
if (b.kind === "managed" && !b.port) return "no-backend";
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** One network attempt against an already-gated backend. */
|
|
49
|
+
function call(b: Backend, req: PredictRequest): Promise<RawOutcome> {
|
|
50
|
+
const { state, questions, signal } = req;
|
|
51
|
+
if (b.kind === "llm") return callLlm(req.llmCaller as LlmCaller, b.role, state, questions, b.timeoutMs ?? LLM_TIMEOUT_MS, signal);
|
|
52
|
+
const url = b.kind === "managed" ? `http://127.0.0.1:${b.port}/v1/systemone` : b.url;
|
|
53
|
+
const keyRef = effectiveKeyRef(b);
|
|
54
|
+
return callHttp({
|
|
55
|
+
url,
|
|
56
|
+
model: backendModel(b) ?? "",
|
|
57
|
+
key: keyRef ? resolveKey(keyRef) : undefined,
|
|
58
|
+
timeoutMs: b.timeoutMs ?? HTTP_TIMEOUT_MS,
|
|
59
|
+
state,
|
|
60
|
+
questions,
|
|
61
|
+
signal,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** `mode` + `thresholds` from the exact `<backend>::<consumer>` record whose model matches. */
|
|
66
|
+
function calibrationFor(cfg: SystemOneConfig, backendId: string, consumerId: string, model: string): { mode: Mode; thresholds: Record<string, number> } {
|
|
67
|
+
const key = `${backendId}::${consumerId}`;
|
|
68
|
+
const rec = Object.hasOwn(cfg.calibration, key) ? cfg.calibration[key] : undefined;
|
|
69
|
+
if (!rec || rec.model !== model) return { mode: "shadow", thresholds: {} };
|
|
70
|
+
return { mode: rec.mode === "enforce" ? "enforce" : "shadow", thresholds: { ...rec.thresholds } };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type AttemptResult =
|
|
74
|
+
| { ok: true; answers: Answers; model: string; latencyMs: number }
|
|
75
|
+
| { ok: false; outcome: Exclude<FailReason, "no-backend">; latencyMs: number };
|
|
76
|
+
|
|
77
|
+
/** Call + validate one gated backend; a malformed answer is an `error` attempt. */
|
|
78
|
+
async function attempt(b: Backend, req: PredictRequest): Promise<AttemptResult> {
|
|
79
|
+
const a0 = performance.now();
|
|
80
|
+
const out = await call(b, req);
|
|
81
|
+
const latencyMs = performance.now() - a0;
|
|
82
|
+
if (!out.ok) return { ok: false, outcome: out.outcome, latencyMs };
|
|
83
|
+
const answers = normalizeAnswers(req.questions, out.raw);
|
|
84
|
+
return answers ? { ok: true, answers, model: out.model, latencyMs } : { ok: false, outcome: "error", latencyMs };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function chainFor(cfg: SystemOneConfig, req: PredictRequest): string[] {
|
|
88
|
+
if (req.onlyBackend === undefined) return resolveChain(cfg, req.consumer.id);
|
|
89
|
+
return Object.hasOwn(cfg.backends, req.onlyBackend) ? [req.onlyBackend] : [];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function predict(req: PredictRequest): Promise<PredictResult> {
|
|
93
|
+
const t0 = performance.now();
|
|
94
|
+
const { consumer, state, signal } = req;
|
|
95
|
+
const policy = consumer.failurePolicy;
|
|
96
|
+
const attempts: Attempt[] = [];
|
|
97
|
+
const fail = (reason: FailReason): PredictResult => {
|
|
98
|
+
logDecision({ consumerId: consumer.id, attempts, model: null, mode: null, answers: null, reason }, state);
|
|
99
|
+
return { ok: false, reason, policy, attempts };
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
if (typeof consumer.id !== "string" || !CONSUMER_ID.test(consumer.id)) return { ok: false, reason: "error", policy, attempts };
|
|
103
|
+
registerConsumer(consumer);
|
|
104
|
+
const cfg = loadConfig({ project: req.project });
|
|
105
|
+
|
|
106
|
+
let last: FailReason = "no-backend";
|
|
107
|
+
for (const backendId of chainFor(cfg, req)) {
|
|
108
|
+
if (signal?.aborted) return fail("timeout");
|
|
109
|
+
const b = cfg.backends[backendId];
|
|
110
|
+
const skip = gate(b, cfg, req);
|
|
111
|
+
if (skip) {
|
|
112
|
+
attempts.push({ backendId, outcome: skip, latencyMs: 0 });
|
|
113
|
+
last = skip;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const a = await attempt(b, req);
|
|
117
|
+
attempts.push({ backendId, outcome: a.ok ? "ok" : a.outcome, latencyMs: a.latencyMs });
|
|
118
|
+
if (!a.ok) {
|
|
119
|
+
last = a.outcome;
|
|
120
|
+
if (signal?.aborted) return fail("timeout");
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const { mode, thresholds } = calibrationFor(cfg, backendId, consumer.id, a.model);
|
|
124
|
+
logDecision({ consumerId: consumer.id, attempts, model: a.model, mode, answers: a.answers }, state);
|
|
125
|
+
return { ok: true, answers: a.answers, backendId, model: a.model, mode, thresholds, latencyMs: performance.now() - t0, attempts };
|
|
126
|
+
}
|
|
127
|
+
return fail(last);
|
|
128
|
+
}
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Consumer self-registration (design D8). One file per consumer:
|
|
3
|
+
* `~/.pi/agent/system-one/consumers/<sha256(id)>.json` (0600, atomic). Written
|
|
4
|
+
* at most once per id per process for an unchanged declaration; a changed
|
|
5
|
+
* declaration rewrites it. Write failures never fail `predict`.
|
|
6
|
+
* See change: add-system-one-registry.
|
|
7
|
+
*/
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { onReset } from "./config.js";
|
|
11
|
+
import { atomicWrite0600 } from "./fs-util.js";
|
|
12
|
+
import { consumersDir } from "./paths.js";
|
|
13
|
+
import type { ConsumerDeclaration } from "./types.js";
|
|
14
|
+
|
|
15
|
+
export const CONSUMER_ID = /^[a-z0-9][a-z0-9:._-]{0,127}$/;
|
|
16
|
+
|
|
17
|
+
const written = new Map<string, string>();
|
|
18
|
+
onReset(() => written.clear());
|
|
19
|
+
|
|
20
|
+
export const consumerFile = (id: string): string =>
|
|
21
|
+
join(consumersDir(), `${createHash("sha256").update(id).digest("hex")}.json`);
|
|
22
|
+
|
|
23
|
+
function canonical(d: ConsumerDeclaration): string {
|
|
24
|
+
return JSON.stringify({
|
|
25
|
+
id: d.id,
|
|
26
|
+
label: d.label ?? null,
|
|
27
|
+
failurePolicy: d.failurePolicy,
|
|
28
|
+
requires: d.requires ?? null,
|
|
29
|
+
fixtures: d.fixtures ?? null,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function registerConsumer(d: ConsumerDeclaration): void {
|
|
34
|
+
const key = canonical(d);
|
|
35
|
+
if (written.get(d.id) === key) return;
|
|
36
|
+
written.set(d.id, key);
|
|
37
|
+
try {
|
|
38
|
+
const record = { ...JSON.parse(key), lastSeen: new Date().toISOString() };
|
|
39
|
+
atomicWrite0600(consumerFile(d.id), `${JSON.stringify(record, null, 2)}\n`);
|
|
40
|
+
} catch {
|
|
41
|
+
// best effort; the next process retries
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/safe-json.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prototype-safe JSON parse: every object becomes a null-prototype object and
|
|
3
|
+
* keys named `__proto__`, `constructor` or `prototype` are dropped at any
|
|
4
|
+
* depth, each reported by path. `JSON.parse` defines `__proto__` as an own
|
|
5
|
+
* property (it never invokes the setter), so the walk sees it and drops it.
|
|
6
|
+
* See change: add-system-one-registry (design D12).
|
|
7
|
+
*/
|
|
8
|
+
const FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);
|
|
9
|
+
|
|
10
|
+
export type Plain = { [k: string]: unknown };
|
|
11
|
+
|
|
12
|
+
export function safeParse(text: string, onDropped: (path: string) => void): unknown {
|
|
13
|
+
return clean(JSON.parse(text), "", onDropped);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function clean(v: unknown, path: string, onDropped: (path: string) => void): unknown {
|
|
17
|
+
if (Array.isArray(v)) return v.map((x, i) => clean(x, `${path}[${i}]`, onDropped));
|
|
18
|
+
if (v === null || typeof v !== "object") return v;
|
|
19
|
+
const out: Plain = Object.create(null);
|
|
20
|
+
for (const k of Object.keys(v)) {
|
|
21
|
+
const p = path ? `${path}.${k}` : k;
|
|
22
|
+
if (FORBIDDEN.has(k)) {
|
|
23
|
+
onDropped(p);
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
out[k] = clean((v as Plain)[k], p, onDropped);
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const isObj = (v: unknown): v is Plain => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
32
|
+
export const own = (o: Plain, k: string): unknown => (Object.hasOwn(o, k) ? o[k] : undefined);
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public contract of the System-1 adapter. Mirrors specs `system-one-adapter`
|
|
3
|
+
* and `system-one-config`. See change: add-system-one-registry.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export type Primitive = "choice" | "score" | "noul";
|
|
7
|
+
|
|
8
|
+
export interface ChoiceQuestion {
|
|
9
|
+
type: "choice";
|
|
10
|
+
instructions: string;
|
|
11
|
+
criteria: Record<string, string>;
|
|
12
|
+
}
|
|
13
|
+
export interface ScoreQuestion {
|
|
14
|
+
type: "score";
|
|
15
|
+
instructions: string;
|
|
16
|
+
/** Ordered levels; the answer is an index in `[0, levels-1]`. */
|
|
17
|
+
criteria: string[];
|
|
18
|
+
}
|
|
19
|
+
export interface NoulQuestion {
|
|
20
|
+
type: "noul";
|
|
21
|
+
instructions: string;
|
|
22
|
+
criteria?: { true: string; false: string };
|
|
23
|
+
}
|
|
24
|
+
export type Question = ChoiceQuestion | ScoreQuestion | NoulQuestion;
|
|
25
|
+
export type Questions = Record<string, Question>;
|
|
26
|
+
|
|
27
|
+
export interface ChoiceAnswer {
|
|
28
|
+
choice: string;
|
|
29
|
+
probabilities: Record<string, number>;
|
|
30
|
+
confidence: number;
|
|
31
|
+
}
|
|
32
|
+
export interface ScoreAnswer {
|
|
33
|
+
score: number;
|
|
34
|
+
probabilities: number[];
|
|
35
|
+
confidence: number;
|
|
36
|
+
}
|
|
37
|
+
export interface NoulAnswer {
|
|
38
|
+
noul: number;
|
|
39
|
+
}
|
|
40
|
+
export type Answer = ChoiceAnswer | ScoreAnswer | NoulAnswer;
|
|
41
|
+
export type Answers = Record<string, Answer>;
|
|
42
|
+
|
|
43
|
+
export type FailurePolicy = "fail-open" | "fail-closed" | "deterministic";
|
|
44
|
+
export type FailReason = "no-backend" | "capability" | "off-machine" | "timeout" | "error";
|
|
45
|
+
export type Mode = "shadow" | "enforce";
|
|
46
|
+
|
|
47
|
+
export interface ConsumerRequires {
|
|
48
|
+
minContextTokens?: number;
|
|
49
|
+
maxOptions?: number;
|
|
50
|
+
languages?: string[];
|
|
51
|
+
primitives?: Primitive[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ConsumerDeclaration {
|
|
55
|
+
id: string;
|
|
56
|
+
label?: string;
|
|
57
|
+
failurePolicy: FailurePolicy;
|
|
58
|
+
requires?: ConsumerRequires;
|
|
59
|
+
/** Absolute path to a JSON array of `{ state, questions, expected }`. */
|
|
60
|
+
fixtures?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface ProjectRef {
|
|
64
|
+
cwd: string;
|
|
65
|
+
/** pi's project-trust decision for `cwd`. Never hard-code `true`. */
|
|
66
|
+
trusted: boolean;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface PredictRequest {
|
|
70
|
+
consumer: ConsumerDeclaration;
|
|
71
|
+
state: string;
|
|
72
|
+
questions: Questions;
|
|
73
|
+
signal?: AbortSignal;
|
|
74
|
+
project?: ProjectRef;
|
|
75
|
+
/** Required for `llm` chain entries; absent → such entries skip `no-backend`. */
|
|
76
|
+
llmCaller?: LlmCaller;
|
|
77
|
+
/**
|
|
78
|
+
* Bypass the chain and try only this backend (the eval runner). Egress and
|
|
79
|
+
* capability checks still apply.
|
|
80
|
+
*/
|
|
81
|
+
onlyBackend?: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface Attempt {
|
|
85
|
+
backendId: string;
|
|
86
|
+
outcome: "ok" | FailReason;
|
|
87
|
+
latencyMs: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export type PredictResult =
|
|
91
|
+
| {
|
|
92
|
+
ok: true;
|
|
93
|
+
answers: Answers;
|
|
94
|
+
backendId: string;
|
|
95
|
+
model: string;
|
|
96
|
+
mode: Mode;
|
|
97
|
+
thresholds: Record<string, number>;
|
|
98
|
+
latencyMs: number;
|
|
99
|
+
attempts: Attempt[];
|
|
100
|
+
}
|
|
101
|
+
| { ok: false; reason: FailReason; policy: FailurePolicy; attempts: Attempt[] };
|
|
102
|
+
|
|
103
|
+
// ---------- LLM seam ----------
|
|
104
|
+
|
|
105
|
+
export interface LlmCallArgs {
|
|
106
|
+
role: string;
|
|
107
|
+
state: string;
|
|
108
|
+
questions: Questions;
|
|
109
|
+
signal: AbortSignal;
|
|
110
|
+
}
|
|
111
|
+
export interface LlmCaller {
|
|
112
|
+
call(args: LlmCallArgs): Promise<{ answers: unknown; model: string }>;
|
|
113
|
+
/** `true` only when the resolved provider runs inference on this machine. */
|
|
114
|
+
isLocal(role: string): boolean;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ---------- config ----------
|
|
118
|
+
|
|
119
|
+
/** A capability value of `null` (JSON) / `undefined` means unknown. */
|
|
120
|
+
export interface Capabilities {
|
|
121
|
+
maxContextTokens?: number | null;
|
|
122
|
+
maxOptions?: number | null;
|
|
123
|
+
languages?: string[] | null;
|
|
124
|
+
primitives?: Primitive[] | null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface HttpBackend {
|
|
128
|
+
kind: "http";
|
|
129
|
+
url: string;
|
|
130
|
+
model: string;
|
|
131
|
+
keyRef?: string;
|
|
132
|
+
timeoutMs?: number;
|
|
133
|
+
capabilities?: Capabilities;
|
|
134
|
+
}
|
|
135
|
+
export interface ManagedBackend {
|
|
136
|
+
kind: "managed";
|
|
137
|
+
engine: "von" | "laya";
|
|
138
|
+
checkpoint?: string;
|
|
139
|
+
port?: number;
|
|
140
|
+
autostart?: boolean;
|
|
141
|
+
timeoutMs?: number;
|
|
142
|
+
capabilities?: Capabilities;
|
|
143
|
+
}
|
|
144
|
+
export interface LlmBackend {
|
|
145
|
+
kind: "llm";
|
|
146
|
+
role: string;
|
|
147
|
+
timeoutMs?: number;
|
|
148
|
+
capabilities?: Capabilities;
|
|
149
|
+
}
|
|
150
|
+
export type Backend = HttpBackend | ManagedBackend | LlmBackend;
|
|
151
|
+
|
|
152
|
+
export interface Preset {
|
|
153
|
+
chain: string[];
|
|
154
|
+
consumers?: Record<string, { chain: string[] }>;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export interface CalibrationRecord {
|
|
158
|
+
mode: Mode;
|
|
159
|
+
thresholds: Record<string, number>;
|
|
160
|
+
model: string;
|
|
161
|
+
measuredAt: string;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface SystemOneConfig {
|
|
165
|
+
version: 1;
|
|
166
|
+
allowOffMachine: boolean;
|
|
167
|
+
backends: Record<string, Backend>;
|
|
168
|
+
presets: Record<string, Preset>;
|
|
169
|
+
activePreset: string;
|
|
170
|
+
calibration: Record<string, CalibrationRecord>;
|
|
171
|
+
}
|
package/src/validate.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response validation + normalization. Every requested question must have an
|
|
3
|
+
* answer constrained to its options; anything else makes the whole response
|
|
4
|
+
* invalid (`null`), which the adapter records as `error` for that backend.
|
|
5
|
+
* Missing `probabilities` → the picked option gets 1.0; missing `confidence`
|
|
6
|
+
* → the picked option's probability. See change: add-system-one-registry.
|
|
7
|
+
*/
|
|
8
|
+
import type { Answer, Answers, ChoiceQuestion, Question, Questions, ScoreQuestion } from "./types.js";
|
|
9
|
+
|
|
10
|
+
type Rec = Record<string, unknown>;
|
|
11
|
+
const isRec = (v: unknown): v is Rec => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
12
|
+
const prob = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
|
|
13
|
+
|
|
14
|
+
/** Probabilities over exactly the declared keys (absent keys → 0), or null. */
|
|
15
|
+
function choiceProbs(keys: string[], picked: string, raw: unknown): Record<string, number> | null {
|
|
16
|
+
if (raw === undefined) return Object.fromEntries(keys.map((k) => [k, k === picked ? 1 : 0]));
|
|
17
|
+
if (!isRec(raw) || Object.keys(raw).some((k) => !keys.includes(k))) return null;
|
|
18
|
+
const out: Record<string, number> = {};
|
|
19
|
+
for (const k of keys) {
|
|
20
|
+
const p = Object.hasOwn(raw, k) ? raw[k] : 0;
|
|
21
|
+
if (!prob(p)) return null;
|
|
22
|
+
out[k] = p;
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function normChoice(q: ChoiceQuestion, a: Rec): Answer | null {
|
|
28
|
+
const keys = Object.keys(q.criteria);
|
|
29
|
+
if (typeof a.choice !== "string" || !keys.includes(a.choice)) return null;
|
|
30
|
+
const probabilities = choiceProbs(keys, a.choice, a.probabilities);
|
|
31
|
+
if (!probabilities) return null;
|
|
32
|
+
const confidence = a.confidence === undefined ? probabilities[a.choice] : a.confidence;
|
|
33
|
+
return prob(confidence) ? { choice: a.choice, probabilities, confidence } : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function scoreProbs(levels: number, picked: number, raw: unknown): number[] | null {
|
|
37
|
+
if (raw === undefined) return Array.from({ length: levels }, (_, i) => (i === picked ? 1 : 0));
|
|
38
|
+
return Array.isArray(raw) && raw.length === levels && raw.every(prob) ? [...raw] : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function normScore(q: ScoreQuestion, a: Rec): Answer | null {
|
|
42
|
+
const s = a.score;
|
|
43
|
+
if (typeof s !== "number" || !Number.isFinite(s) || s < 0 || s > q.criteria.length - 1) return null;
|
|
44
|
+
const probabilities = scoreProbs(q.criteria.length, Math.round(s), a.probabilities);
|
|
45
|
+
if (!probabilities) return null;
|
|
46
|
+
const confidence = a.confidence === undefined ? probabilities[Math.round(s)] : a.confidence;
|
|
47
|
+
return prob(confidence) ? { score: s, probabilities, confidence } : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function normOne(q: Question, a: Rec): Answer | null {
|
|
51
|
+
if (q.type === "choice") return normChoice(q, a);
|
|
52
|
+
if (q.type === "score") return normScore(q, a);
|
|
53
|
+
return prob(a.noul) ? { noul: a.noul } : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function normalizeAnswers(questions: Questions, raw: unknown): Answers | null {
|
|
57
|
+
if (!isRec(raw)) return null;
|
|
58
|
+
const out: Answers = {};
|
|
59
|
+
for (const [id, q] of Object.entries(questions)) {
|
|
60
|
+
const a = Object.hasOwn(raw, id) ? raw[id] : undefined;
|
|
61
|
+
const ans = isRec(a) ? normOne(q, a) : null;
|
|
62
|
+
if (!ans) return null;
|
|
63
|
+
out[id] = ans;
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
package/src/warn.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `[system-one]` warnings, deduplicated per process by message.
|
|
3
|
+
* See change: add-system-one-registry.
|
|
4
|
+
*/
|
|
5
|
+
const seen = new Set<string>();
|
|
6
|
+
|
|
7
|
+
export function warnOnce(message: string): void {
|
|
8
|
+
const line = `[system-one] ${message}`;
|
|
9
|
+
if (seen.has(line)) return;
|
|
10
|
+
seen.add(line);
|
|
11
|
+
console.warn(line);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function _resetWarnings(): void {
|
|
15
|
+
seen.clear();
|
|
16
|
+
}
|