@kriya-ai/harness 2.0.0 → 2.1.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.
@@ -0,0 +1,176 @@
1
+ import { createHash } from "node:crypto"
2
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
3
+ import { dirname, join } from "node:path"
4
+
5
+ import { kriyaHome } from "./paths.js"
6
+
7
+ // Own models (Kriya-Tavi docs/kriya-harness/OWN_MODELS.md): the person's own
8
+ // API keys for OpenAI-compatible providers, and their own orchestration (head
9
+ // and worker from Kriya's tiers, their own models and the S-1 local model).
10
+ // Keys live only in ~/.kriya/own-models.json (mode 600) and in the launcher's
11
+ // memory for the relay. They never go to Kriya, a log, the Web UI (last four
12
+ // characters only), DSH's process (hashes only, for redaction) or a model.
13
+
14
+ export class OwnModelsError extends Error {}
15
+
16
+ export const PROVIDERS = [
17
+ { id: "openrouter", name: "OpenRouter", url: "https://openrouter.ai/api/v1", keys: "https://openrouter.ai/settings/keys" },
18
+ { id: "openai", name: "OpenAI", url: "https://api.openai.com/v1", keys: "https://platform.openai.com/api-keys" },
19
+ { id: "deepseek", name: "DeepSeek", url: "https://api.deepseek.com/v1", keys: "https://platform.deepseek.com/api_keys" },
20
+ { id: "groq", name: "Groq", url: "https://api.groq.com/openai/v1", keys: "https://console.groq.com/keys" },
21
+ { id: "together", name: "Together AI", url: "https://api.together.xyz/v1", keys: "https://api.together.xyz/settings/api-keys" },
22
+ { id: "mistral", name: "Mistral", url: "https://api.mistral.ai/v1", keys: "https://console.mistral.ai/api-keys" },
23
+ { id: "custom", name: "Custom (OpenAI-compatible)", url: null, keys: null },
24
+ ]
25
+
26
+ export const KEY = /^[\x21-\x7e]{8,400}$/
27
+ export const MODEL = /^[\w.:\/@+-]{1,120}$/
28
+ export const MAX_MODELS = 12
29
+ const TIERS = ["balanced", "budget", "escalation"]
30
+ export const DEFAULT_CONTEXT = 131_072
31
+ const clampContext = (n) => Math.min(2_000_000, Math.max(16_384, Number.isSafeInteger(n) ? n : DEFAULT_CONTEXT))
32
+
33
+ export const ownFile = (home = kriyaHome()) => join(home, "own-models.json")
34
+
35
+ const empty = () => ({ version: 1, keys: {}, models: [], orchestra: null })
36
+
37
+ /** The stored setup; an empty one when the file is missing or broken */
38
+ export function readOwn(file = ownFile()) {
39
+ try {
40
+ const v = JSON.parse(readFileSync(file, "utf8"))
41
+ return {
42
+ version: 1,
43
+ keys: v.keys && typeof v.keys === "object" ? Object.fromEntries(Object.entries(v.keys).filter(([p, k]) => PROVIDERS.some((x) => x.id === p) && typeof k?.key === "string" && KEY.test(k.key))) : {},
44
+ models: Array.isArray(v.models) ? v.models.filter((m) => typeof m?.id === "string" && MODEL.test(m.model ?? "") && v.keys?.[m.provider]).slice(0, MAX_MODELS) : [],
45
+ orchestra: v.orchestra && typeof v.orchestra.head === "string" && typeof v.orchestra.worker === "string" ? { head: v.orchestra.head, worker: v.orchestra.worker } : null,
46
+ }
47
+ } catch {
48
+ return empty()
49
+ }
50
+ }
51
+
52
+ function write(state, file) {
53
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
54
+ const tmp = `${file}.${process.pid}.tmp`
55
+ writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
56
+ chmodSync(tmp, 0o600)
57
+ renameSync(tmp, file)
58
+ return state
59
+ }
60
+
61
+ /** A custom endpoint: https only, no credentials in the address */
62
+ export function customUrl(value) {
63
+ let url
64
+ try {
65
+ url = new URL(String(value ?? "").trim())
66
+ } catch {
67
+ throw new OwnModelsError("That isn't an address. A custom provider is an https URL ending at its API, e.g. https://api.example.com/v1.")
68
+ }
69
+ if (url.protocol !== "https:") throw new OwnModelsError("A custom provider must use https. For a model on this computer, use --local-model.")
70
+ if (url.username || url.password || url.search || url.hash) throw new OwnModelsError("Put the key in the key field, not in the address.")
71
+ return url.href.replace(/\/+$/, "")
72
+ }
73
+
74
+ export const providerUrl = (provider, stored) => PROVIDERS.find((p) => p.id === provider)?.url ?? stored?.url ?? null
75
+
76
+ export function saveKey(provider, key, url, file = ownFile()) {
77
+ if (!PROVIDERS.some((p) => p.id === provider)) throw new OwnModelsError("Kriya doesn't know that provider.")
78
+ const k = String(key ?? "").trim()
79
+ if (!KEY.test(k)) throw new OwnModelsError("That doesn't look like an API key (8 to 400 characters, no spaces).")
80
+ const state = readOwn(file)
81
+ state.keys[provider] = { key: k, ...(provider === "custom" && { url: customUrl(url) }) }
82
+ return write(state, file)
83
+ }
84
+
85
+ /** Removes a provider's key, its models, and an orchestration that used them */
86
+ export function removeKey(provider, file = ownFile()) {
87
+ const state = readOwn(file)
88
+ delete state.keys[provider]
89
+ const gone = new Set(state.models.filter((m) => m.provider === provider).map((m) => m.id))
90
+ state.models = state.models.filter((m) => !gone.has(m.id))
91
+ if (state.orchestra && (gone.has(state.orchestra.head) || gone.has(state.orchestra.worker))) state.orchestra = null
92
+ return write(state, file)
93
+ }
94
+
95
+ export function addModel(provider, model, contextWindow, file = ownFile()) {
96
+ const state = readOwn(file)
97
+ if (!state.keys[provider]) throw new OwnModelsError("Add that provider's key first.")
98
+ if (!MODEL.test(String(model ?? ""))) throw new OwnModelsError("That isn't a model id.")
99
+ if (state.models.some((m) => m.provider === provider && m.model === model)) return state
100
+ if (state.models.length >= MAX_MODELS) throw new OwnModelsError(`At most ${MAX_MODELS} of your own models; remove one first.`)
101
+ const n = Math.max(0, ...state.models.map((m) => Number(/-(\d+)$/.exec(m.id)?.[1] ?? 0))) + 1
102
+ state.models.push({ id: `own-${n}`, provider, model, contextWindow: clampContext(contextWindow) })
103
+ return write(state, file)
104
+ }
105
+
106
+ export function removeModel(id, file = ownFile()) {
107
+ const state = readOwn(file)
108
+ state.models = state.models.filter((m) => m.id !== id)
109
+ if (state.orchestra && (state.orchestra.head === id || state.orchestra.worker === id)) state.orchestra = null
110
+ return write(state, file)
111
+ }
112
+
113
+ /** The person's orchestration: head and worker, each a Kriya tier, one of their models, or "local"; null clears it */
114
+ export function setOrchestra(choice, file = ownFile()) {
115
+ const state = readOwn(file)
116
+ if (choice === null) return write({ ...state, orchestra: null }, file)
117
+ const ok = (id) => TIERS.includes(id) || id === "local" || state.models.some((m) => m.id === id)
118
+ if (!ok(choice?.head) || !ok(choice?.worker)) throw new OwnModelsError("Choose the head and the worker from the lists.")
119
+ if (choice.head === choice.worker) throw new OwnModelsError("The head and the worker must be different models.")
120
+ if (choice.head === "local") throw new OwnModelsError("The local model builds; the head plans, so choose a stronger model for it.")
121
+ return write({ ...state, orchestra: { head: choice.head, worker: choice.worker } }, file)
122
+ }
123
+
124
+ // Short in the model picker: "Custom", not "Custom (OpenAI-compatible)"
125
+ const label = (m) => `${m.provider === "custom" ? "Custom" : (PROVIDERS.find((p) => p.id === m.provider)?.name ?? m.provider)} · ${m.model}`.slice(0, 80)
126
+
127
+ /** What the Web UI may see: no key, only its last four characters */
128
+ export function publicView(file = ownFile()) {
129
+ const s = readOwn(file)
130
+ return {
131
+ providers: PROVIDERS.map((p) => ({ id: p.id, name: p.name, keysUrl: p.keys, saved: Boolean(s.keys[p.id]), ...(s.keys[p.id] && { last4: s.keys[p.id].key.slice(-4) }), ...(p.id === "custom" && s.keys.custom?.url && { url: s.keys.custom.url }) })),
132
+ models: s.models.map((m) => ({ id: m.id, provider: m.provider, model: m.model, name: label(m), contextWindow: m.contextWindow })),
133
+ orchestra: s.orchestra,
134
+ }
135
+ }
136
+
137
+ /** The provider's models (GET <url>/models with the person's key), with context windows where the provider says */
138
+ export async function listProviderModels(provider, file = ownFile(), fetchImpl = fetch) {
139
+ const s = readOwn(file)
140
+ const stored = s.keys[provider]
141
+ if (!stored) throw new OwnModelsError("Add that provider's key first.")
142
+ const url = providerUrl(provider, stored)
143
+ let answer
144
+ try {
145
+ answer = await fetchImpl(`${url}/models`, { headers: { authorization: `Bearer ${stored.key}`, accept: "application/json" }, signal: AbortSignal.timeout(15_000), redirect: "error" })
146
+ } catch {
147
+ throw new OwnModelsError(`Couldn't reach ${new URL(url).host}.`)
148
+ }
149
+ if (answer.status === 401 || answer.status === 403) throw new OwnModelsError("The provider refused that key. Check it and save it again.")
150
+ if (!answer.ok) throw new OwnModelsError(`The provider answered ${answer.status}.`)
151
+ const body = await answer.json().catch(() => ({}))
152
+ const list = Array.isArray(body?.data) ? body.data : []
153
+ return list
154
+ .filter((m) => typeof m?.id === "string" && MODEL.test(m.id))
155
+ .map((m) => ({ id: m.id, ...(Number.isSafeInteger(m.context_length) && { contextWindow: m.context_length }) }))
156
+ .sort((a, b) => a.id.localeCompare(b.id))
157
+ .slice(0, 2000)
158
+ }
159
+
160
+ /** sha256 of each saved key: DSH's redactor gets these, never a key */
161
+ export const keyHashes = (file = ownFile()) => Object.values(readOwn(file).keys).map((k) => createHash("sha256").update(k.key).digest("hex"))
162
+
163
+ /**
164
+ * What a launch uses, only with the owner's harness.ownModels: the models the
165
+ * picker lists (no key, no address), the relay's routes (with keys, launcher
166
+ * memory only) and the person's orchestration when every part of it is usable.
167
+ * @param {{ allowed: string[], local?: boolean }} opts
168
+ */
169
+ export function launchOwn(file = ownFile(), { allowed = TIERS, local = false } = {}) {
170
+ const s = readOwn(file)
171
+ const models = s.models.map((m) => ({ id: m.id, name: label(m), contextWindow: clampContext(m.contextWindow) }))
172
+ const routes = Object.fromEntries(s.models.map((m) => [m.id, { url: providerUrl(m.provider, s.keys[m.provider]), model: m.model, key: s.keys[m.provider].key, provider: m.provider }]))
173
+ const usable = (id) => allowed.includes(id) || Boolean(routes[id]) || (id === "local" && local)
174
+ const orchestra = s.orchestra && usable(s.orchestra.head) && usable(s.orchestra.worker) ? s.orchestra : undefined
175
+ return { models, routes, ...(orchestra && { orchestra }), hashes: keyHashes(file) }
176
+ }
@@ -0,0 +1,63 @@
1
+ import { call, KriyaError } from "./api.js"
2
+
3
+ // Own models (Kriya-Tavi docs/kriya-harness/OWN_MODELS.md): the counts of
4
+ // calls through the person's own keys (and S-1's local model), sent to Kriya
5
+ // in batches: provider, model, requests, tokens and the provider's reported
6
+ // cost. Never a prompt, an answer or a key. Kriya answering 404 means the
7
+ // owner's harness.ownModels is off: reporting stops for this run.
8
+
9
+ export const FLUSH_MS = 30_000
10
+ const MAX_BATCH = 50
11
+ const MAX_KEYS = 500
12
+
13
+ /**
14
+ * @param {{ device: { url: string, token: string }, post?: (body: any) => Promise<any>, every?: number, log?: (text: string) => void }} options
15
+ */
16
+ export function usageReporter({ device, post = (body) => call(device.url, "POST", "/own-usage", { token: device.token, body }), every = FLUSH_MS, log = () => {} }) {
17
+ const pending = new Map()
18
+ let stopped = false
19
+ let flushing = null
20
+ const add = (e) => {
21
+ if (stopped || !e?.provider || !e?.model) return
22
+ const key = `${e.provider}\0${e.model}`
23
+ const now = pending.get(key) ?? { provider: e.provider, model: String(e.model).slice(0, 120), requests: 0, inputTokens: 0, outputTokens: 0 }
24
+ now.requests += e.requests ?? 1
25
+ now.inputTokens += e.inputTokens ?? 0
26
+ now.outputTokens += e.outputTokens ?? 0
27
+ // A cost only while every call so far reported one: a partial sum would understate
28
+ if (e.reportedCostMicroUsd !== undefined && (now.requests === (e.requests ?? 1) || now.reportedCostMicroUsd !== undefined)) now.reportedCostMicroUsd = (now.reportedCostMicroUsd ?? 0) + e.reportedCostMicroUsd
29
+ else delete now.reportedCostMicroUsd
30
+ if (pending.size < MAX_KEYS || pending.has(key)) pending.set(key, now)
31
+ }
32
+ const flush = () =>
33
+ (flushing ??= (async () => {
34
+ while (!stopped && pending.size) {
35
+ const batch = [...pending.values()].slice(0, MAX_BATCH)
36
+ for (const e of batch) pending.delete(`${e.provider}\0${e.model}`)
37
+ try {
38
+ await post({ entries: batch.map((e) => ({ ...e, requests: Math.min(e.requests, 10_000) })) })
39
+ } catch (error) {
40
+ if (error instanceof KriyaError && error.status === 404) {
41
+ stopped = true
42
+ pending.clear()
43
+ return
44
+ }
45
+ // Kept for the next try, bounded
46
+ for (const e of batch) if (pending.size < MAX_KEYS) pending.set(`${e.provider}\0${e.model}`, e)
47
+ log(`own-model usage not sent yet (${error?.code ?? error?.message ?? "error"}); will retry`)
48
+ return
49
+ }
50
+ }
51
+ })().finally(() => (flushing = null)))
52
+ const timer = setInterval(flush, every)
53
+ timer.unref?.()
54
+ return {
55
+ add,
56
+ flush,
57
+ pending: () => [...pending.values()],
58
+ close: () => {
59
+ clearInterval(timer)
60
+ return flush()
61
+ },
62
+ }
63
+ }
package/src/profiles.js CHANGED
@@ -51,6 +51,10 @@ export const LINKED = {
51
51
  "@kriya-ai/harness-router": join(PACKAGE_ROOT, "plugins", "router"),
52
52
  "@kriya-ai/harness-projects": join(PACKAGE_ROOT, "plugins", "projects"),
53
53
  "@kriya-ai/harness-fs-freshness": join(PACKAGE_ROOT, "plugins", "fs-freshness"),
54
+ "@kriya-ai/harness-directory-picker": join(PACKAGE_ROOT, "plugins", "directory-picker"),
55
+ "@kriya-ai/harness-cockpit": join(PACKAGE_ROOT, "plugins", "cockpit"),
56
+ "@kriya-ai/harness-providers": join(PACKAGE_ROOT, "plugins", "providers"),
57
+ "@kriya-ai/harness-keyguard": join(PACKAGE_ROOT, "plugins", "keyguard"),
54
58
  "@kriya-ai/harness-loop": join(PACKAGE_ROOT, "plugins", "loop"),
55
59
  "@kriya-ai/harness-budget": join(PACKAGE_ROOT, "plugins", "budget"),
56
60
  "@kriya-ai/harness-grounding": join(PACKAGE_ROOT, "plugins", "grounding"),
package/src/proof.js ADDED
@@ -0,0 +1,78 @@
1
+ // S-3 (Kriya-Tavi docs/kriya-harness/TASK_PROOF.md; owner decisions 2026-11-24):
2
+ // what a task started from Kriya reports back, computed by code on this
3
+ // computer. The verdict, each step's attempts, who built each attempt and the
4
+ // gates come from the loop's own ledger (verify.js verdict), never from model
5
+ // text. Changes are file names with line counts: no code leaves the computer.
6
+
7
+ import { snapshot, trackedRoot, treeChanges } from "./checkpoints.js"
8
+ import { stepLabel, verdict } from "./verify.js"
9
+
10
+ const GATE = /^G-[A-Z0-9-]{2,20}$/
11
+ export const MAX_FILES = 200
12
+
13
+ const modelNames = (env) => {
14
+ try {
15
+ return JSON.parse(env.KRIYA_MODEL_NAMES || "{}")
16
+ } catch {
17
+ return {}
18
+ }
19
+ }
20
+
21
+ /** The steps' proof from a progress ledger, or undefined without a plan */
22
+ export function stepsProof(progress, env = process.env) {
23
+ const plan = progress?.plan
24
+ if (!plan?.steps?.length) return undefined
25
+ const ledger = { ...progress, runs: progress.runs ?? [] }
26
+ const v = verdict(ledger)
27
+ const named = modelNames(env)
28
+ const head = env.KRIYA_ORCHESTRA_HEAD
29
+ const who = (tier) => ({
30
+ level: head && env.KRIYA_ORCHESTRA === "on" ? (tier === head ? "head" : "worker") : "single",
31
+ name: String(named[tier] ?? `Kriya ${tier}`).slice(0, 80),
32
+ ...(tier === "local" && { local: true }),
33
+ })
34
+ const steps = plan.steps.map((step, i) => {
35
+ const label = stepLabel(plan, i + 1)
36
+ const found = v.steps.find((s) => s.step === label)
37
+ const last = ledger.runs.findLast((r) => r.step === label)
38
+ return {
39
+ n: i + 1,
40
+ title: String(step.title ?? "").slice(0, 120),
41
+ verdict: found?.status ?? "not run",
42
+ attempts: found?.attempts ?? 0,
43
+ builtBy: (progress.builders ?? []).filter((b) => b.step === label && !b.polish && typeof b.tier === "string" && b.tier).slice(0, 8).map((b) => who(b.tier)),
44
+ gates: (last?.gates ?? []).filter((g) => GATE.test(g?.id ?? "")).slice(0, 20).map((g) => ({ id: g.id, status: String(g.status).slice(0, 20) })),
45
+ }
46
+ })
47
+ return { verdict: v.status, steps: steps.slice(0, 12), ...(v.touched?.length && { touchedChecks: v.touched.slice(0, 20).map((p) => String(p).slice(0, 300)) }) }
48
+ }
49
+
50
+ /** The folder's working tree before a task, or null where it can't be read */
51
+ export async function baseline(folder) {
52
+ try {
53
+ const tracked = await trackedRoot(folder)
54
+ return tracked ? { root: tracked.root, tree: await snapshot(tracked.root) } : null
55
+ } catch {
56
+ return null
57
+ }
58
+ }
59
+
60
+ /** Files changed since `base`: names, status and line counts only */
61
+ export async function changesSince(base) {
62
+ if (!base) return null
63
+ try {
64
+ const files = await treeChanges(base.root, base.tree, await snapshot(base.root))
65
+ const total = files.reduce((t, f) => ({ added: t.added + (f.added ?? 0), deleted: t.deleted + (f.deleted ?? 0) }), { added: 0, deleted: 0 })
66
+ return {
67
+ files: files.slice(0, MAX_FILES).map((f) => ({
68
+ path: String(f.path).slice(0, 300),
69
+ status: f.status,
70
+ ...(f.binary ? { binary: true } : { added: f.added ?? 0, deleted: f.deleted ?? 0 }),
71
+ })),
72
+ count: files.length,
73
+ ...total,
74
+ }
75
+ } catch {
76
+ return null
77
+ }
78
+ }