@kriya-ai/harness 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +379 -2
- package/SAFETY.md +162 -0
- package/THIRD_PARTY_NOTICES.md +7911 -0
- package/bin/kriya.js +577 -0
- package/bundle/cordis.patch.yml +397 -0
- package/contract/SOURCE.md +15 -0
- package/contract/contract.json +1355 -0
- package/package.json +57 -4
- package/plugins/anchor/index.js +56 -0
- package/plugins/anchor/package.json +13 -0
- package/plugins/approvals/index.js +183 -0
- package/plugins/approvals/package.json +13 -0
- package/plugins/brand/DESIGN.md +112 -0
- package/plugins/brand/client.js +826 -0
- package/plugins/brand/index.js +15 -0
- package/plugins/brand/package.json +25 -0
- package/plugins/brand/src/client.js +823 -0
- package/plugins/browser/index.js +218 -0
- package/plugins/browser/package.json +13 -0
- package/plugins/budget/index.js +108 -0
- package/plugins/budget/package.json +13 -0
- package/plugins/changes/client.js +245 -0
- package/plugins/changes/index.js +75 -0
- package/plugins/changes/package.json +22 -0
- package/plugins/edit/client.js +113 -0
- package/plugins/edit/index.js +58 -0
- package/plugins/edit/package.json +23 -0
- package/plugins/fs-freshness/index.js +28 -0
- package/plugins/fs-freshness/package.json +13 -0
- package/plugins/graph/client.js +178 -0
- package/plugins/graph/index.js +4 -0
- package/plugins/graph/package.json +22 -0
- package/plugins/kriya-handoff/index.js +194 -0
- package/plugins/kriya-handoff/package.json +13 -0
- package/plugins/kriya-tools/index.js +189 -0
- package/plugins/kriya-tools/package.json +13 -0
- package/plugins/loop/index.js +743 -0
- package/plugins/loop/package.json +13 -0
- package/plugins/mirror/index.js +235 -0
- package/plugins/mirror/package.json +13 -0
- package/plugins/overview/client.js +276 -0
- package/plugins/overview/index.js +95 -0
- package/plugins/overview/package.json +22 -0
- package/plugins/preview/client.js +337 -0
- package/plugins/preview/index.js +4 -0
- package/plugins/preview/package.json +22 -0
- package/plugins/progress/client.js +290 -0
- package/plugins/progress/index.js +100 -0
- package/plugins/progress/package.json +22 -0
- package/plugins/projects/client.js +249 -0
- package/plugins/projects/index.js +30 -0
- package/plugins/projects/package.json +24 -0
- package/plugins/rea/index.js +256 -0
- package/plugins/rea/package.json +10 -0
- package/plugins/rea/skill/LICENSE +21 -0
- package/plugins/rea/skill/SKILL.md +360 -0
- package/plugins/rea/skill/references/android-applications.md +36 -0
- package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
- package/plugins/rea/skill/references/evidence-workflows.md +71 -0
- package/plugins/rea/skill/references/javascript-applications.md +218 -0
- package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
- package/plugins/rea/skill/references/runtime-observation.md +78 -0
- package/plugins/remote/index.js +297 -0
- package/plugins/remote/package.json +10 -0
- package/plugins/router/index.js +84 -0
- package/plugins/router/package.json +13 -0
- package/plugins/sessions/client.js +68 -0
- package/plugins/sessions/index.js +79 -0
- package/plugins/sessions/package.json +20 -0
- package/plugins/skills/client.js +504 -0
- package/plugins/skills/index.js +166 -0
- package/plugins/skills/package.json +23 -0
- package/src/api.js +97 -0
- package/src/browser.js +286 -0
- package/src/changes.js +191 -0
- package/src/checkpoints.js +313 -0
- package/src/daemon.js +503 -0
- package/src/doctor.js +137 -0
- package/src/edit/core/anchors.js +102 -0
- package/src/edit/core/audio.js +158 -0
- package/src/edit/core/faces.js +99 -0
- package/src/edit/core/ffmpeg.js +258 -0
- package/src/edit/core/handoff.js +220 -0
- package/src/edit/core/history.js +90 -0
- package/src/edit/core/layout.js +92 -0
- package/src/edit/core/mix.js +115 -0
- package/src/edit/core/ops.js +602 -0
- package/src/edit/core/plan.js +266 -0
- package/src/edit/core/project.d.ts +134 -0
- package/src/edit/core/project.js +307 -0
- package/src/edit/core/reframe.js +125 -0
- package/src/edit/core/solver.js +416 -0
- package/src/edit/core/time.js +110 -0
- package/src/edit/core/tonemap.js +57 -0
- package/src/edit/director/ask.js +120 -0
- package/src/edit/director/gateway.js +16 -0
- package/src/edit/director/revise.js +186 -0
- package/src/edit/engine/capabilities.js +33 -0
- package/src/edit/engine/captions.js +154 -0
- package/src/edit/engine/color.js +269 -0
- package/src/edit/engine/confine.js +67 -0
- package/src/edit/engine/dna.js +148 -0
- package/src/edit/engine/index.js +473 -0
- package/src/edit/engine/loudness.js +43 -0
- package/src/edit/engine/media.js +57 -0
- package/src/edit/engine/motion.js +281 -0
- package/src/edit/engine/packs.js +87 -0
- package/src/edit/engine/probe.js +101 -0
- package/src/edit/engine/receipt.js +123 -0
- package/src/edit/engine/tool.js +101 -0
- package/src/edit/gates/copy.js +113 -0
- package/src/edit/gates/index.js +430 -0
- package/src/edit/gates/picture.js +130 -0
- package/src/edit/gates/sound.js +58 -0
- package/src/edit/gates/speech.js +127 -0
- package/src/edit/gates/text.js +196 -0
- package/src/edit/gates/text.swift +22 -0
- package/src/edit/graph/index.js +139 -0
- package/src/edit/graph/journal.js +69 -0
- package/src/edit/graph/scheduler.js +79 -0
- package/src/edit/host/client.js +58 -0
- package/src/edit/host/deliver.js +119 -0
- package/src/edit/host/jobs.js +84 -0
- package/src/edit/host/main.js +135 -0
- package/src/edit/host/paths.js +11 -0
- package/src/edit/host/projects.js +415 -0
- package/src/edit/host/server.js +391 -0
- package/src/edit/host/taste.js +135 -0
- package/src/edit/host/tavi.js +417 -0
- package/src/edit/host/watch.js +141 -0
- package/src/edit/index/db.js +109 -0
- package/src/edit/index/index.js +236 -0
- package/src/edit/index/layers/faces.js +78 -0
- package/src/edit/index/layers/faces.swift +18 -0
- package/src/edit/index/layers/meta.js +35 -0
- package/src/edit/index/layers/music.js +146 -0
- package/src/edit/index/layers/quality.js +120 -0
- package/src/edit/index/layers/retakes.js +132 -0
- package/src/edit/index/layers/screen.js +99 -0
- package/src/edit/index/layers/shots.js +29 -0
- package/src/edit/index/layers/sound.js +42 -0
- package/src/edit/index/layers/words.js +64 -0
- package/src/edit/index/story.js +248 -0
- package/src/edit/index/views.js +71 -0
- package/src/edit/loop/governor.js +112 -0
- package/src/edit/loop/loop.js +69 -0
- package/src/edit/loop/make.js +115 -0
- package/src/edit/loop/repair.js +97 -0
- package/src/edit/loop/replay.js +32 -0
- package/src/edit/recipes/multicam.js +461 -0
- package/src/edit/recipes/reel.js +202 -0
- package/src/edit/recipes/short-from-long.js +237 -0
- package/src/edit/recipes/tutorial.js +137 -0
- package/src/edit/recipes/youtube.js +155 -0
- package/src/edit/runtime/cli.js +126 -0
- package/src/edit/runtime/doctor.js +122 -0
- package/src/edit/runtime/fetch.js +15 -0
- package/src/edit/runtime/licences.js +88 -0
- package/src/edit/runtime/manifest.js +73 -0
- package/src/edit/runtime/setup.js +252 -0
- package/src/failure.js +69 -0
- package/src/gateway-proxy.js +213 -0
- package/src/intent.js +130 -0
- package/src/launch.js +315 -0
- package/src/live.js +81 -0
- package/src/local-skills.js +284 -0
- package/src/login.js +82 -0
- package/src/loop.js +428 -0
- package/src/modes.js +128 -0
- package/src/overview.js +71 -0
- package/src/paths.js +30 -0
- package/src/profiles.js +92 -0
- package/src/projects.js +104 -0
- package/src/recon.js +244 -0
- package/src/rules.js +139 -0
- package/src/runner.bundle.js +21172 -0
- package/src/sentinel.js +248 -0
- package/src/skill-switches.js +130 -0
- package/src/store.js +58 -0
- package/src/strict.js +124 -0
- package/src/verify.js +659 -0
- package/src/world.js +268 -0
- package/studio/dist/index.html +14 -0
- package/studio/dist/studio.css +163 -0
- package/studio/dist/studio.js +1 -0
|
@@ -0,0 +1,743 @@
|
|
|
1
|
+
import { createUserMessage } from "@deepseek-ai/dsh-llm"
|
|
2
|
+
import { defineTool } from "@deepseek-ai/dsh-tools"
|
|
3
|
+
|
|
4
|
+
import { execFile } from "node:child_process"
|
|
5
|
+
import { existsSync } from "node:fs"
|
|
6
|
+
import { extname, join, resolve } from "node:path"
|
|
7
|
+
|
|
8
|
+
import { checkpoint, restoreTree } from "../../src/checkpoints.js"
|
|
9
|
+
import { rankSkills } from "../../src/intent.js"
|
|
10
|
+
import { builderLimits, loopStateText, MAX_STEPS, nextStep, planStatus, readPlan, runStep, savePlan, seededPlan, writeSnapshot } from "../../src/loop.js"
|
|
11
|
+
import { blastRadius, importers, importGraph, insideFolder, MAX_READ_LINES, outline, ReconError, readPage } from "../../src/recon.js"
|
|
12
|
+
import { confirmedRules } from "../../src/rules.js"
|
|
13
|
+
import { projectRoot } from "../../src/skill-switches.js"
|
|
14
|
+
import { TASK_KINDS } from "../../src/strict.js"
|
|
15
|
+
import { confirmedCheck, currentVerdict, VerifyError, verifyStep } from "../../src/verify.js"
|
|
16
|
+
|
|
17
|
+
// The Kriya loop, node half (H14a; KRIYA_LOOP.md in the Kriya repository):
|
|
18
|
+
// `kriya_verify` runs the project's confirmed check and reports pass, fail
|
|
19
|
+
// or blocked from its exit code. It takes no command: the person confirmed
|
|
20
|
+
// the check with `kriya verify use`, so the model can neither change what
|
|
21
|
+
// "passing" means nor run anything it couldn't run with bash. The command
|
|
22
|
+
// runs the way DSH's own bash tool runs one: in the session's folder,
|
|
23
|
+
// under the session's standing sandbox policy, through ctx.shell.
|
|
24
|
+
// Before every tool call that can change files, the working tree is saved
|
|
25
|
+
// as a checkpoint on Kriya's own git ref (src/checkpoints.js, H14b), so
|
|
26
|
+
// `kriya undo` goes back one step; not in Read only, where nothing changes.
|
|
27
|
+
// Off unless kriya was started with --loop (the bundle row's switch).
|
|
28
|
+
// Loop v2 (KRIYA_LOOP_V2=on, `--loop-v2`; KRIYA_LOOP_V2.md): plan steps
|
|
29
|
+
// name the steps they need, failures carry a class, a pass that changed
|
|
30
|
+
// tests must hold on the originals, a worse attempt is set aside, and the
|
|
31
|
+
// person's confirmed rules reach the builders. Off, everything is as v1.
|
|
32
|
+
// The loop guard (KRIYA_LOOP_GUARD=on, `--loop-guard`): an agent stopping with
|
|
33
|
+
// plan steps still to do is sent back; a step stops spending builders when
|
|
34
|
+
// more can't help; a builder that died on an error isn't an attempt; and a
|
|
35
|
+
// resumed step keeps its last failure. Off, none of it happens.
|
|
36
|
+
// The strict loop (`--strict-loop`, includes the guard): the task contract,
|
|
37
|
+
// the fast rungs before the person's check, weakened tests and silenced
|
|
38
|
+
// compilers refused, bug fixes proved red then green, a step as one
|
|
39
|
+
// transaction. Recon (`--recon`): code_outline, code_impact and bounded
|
|
40
|
+
// reads. JIT tools (`--jit-tools`): a builder gets browser and reverse-
|
|
41
|
+
// engineering tools only when its step needs them, and a hint of the skills
|
|
42
|
+
// that fit. All off by default.
|
|
43
|
+
|
|
44
|
+
export const name = "kriya-loop"
|
|
45
|
+
export const inject = ["tools", "shell", "workingDirectory", "shellEnv", "systemPrompt"]
|
|
46
|
+
|
|
47
|
+
// Long enough for a real test suite; DSH's executor kills it after this
|
|
48
|
+
const TIMEOUT_MS = 10 * 60_000
|
|
49
|
+
|
|
50
|
+
// DSH's tools that can change files: fs write and edit, the shells, and
|
|
51
|
+
// code runs (PTC, workflows)
|
|
52
|
+
export const FILE_TOOLS = new Set(["write", "edit", "bash", "pwsh", "run_code", "workflow"])
|
|
53
|
+
|
|
54
|
+
/** What a checkpoint is called: the tool and what it was about to do */
|
|
55
|
+
export function checkpointLabel(exec) {
|
|
56
|
+
const args = exec.arguments && typeof exec.arguments === "object" ? exec.arguments : {}
|
|
57
|
+
const about = [args.description, args.path, args.file_path, args.command].find((v) => typeof v === "string" && v.trim())
|
|
58
|
+
return `before ${exec.name}${about ? `: ${about}` : ""}`
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The pre-execute hook: a checkpoint before a file-changing call, one at a
|
|
63
|
+
* time per folder (they share Kriya's index), then the call. A checkpoint
|
|
64
|
+
* that fails is logged and the call goes ahead: it's a safety net, not a gate.
|
|
65
|
+
* @param {{ cwd: (exec: any) => Promise<string>, readOnly: (exec: any) => boolean, save?: typeof checkpoint, warn: (text: string) => void }} host
|
|
66
|
+
*/
|
|
67
|
+
export function checkpointHook(host) {
|
|
68
|
+
const save = host.save ?? checkpoint
|
|
69
|
+
const queues = new Map()
|
|
70
|
+
return async (exec, next) => {
|
|
71
|
+
if (FILE_TOOLS.has(exec.name) && exec.agent && !host.readOnly(exec)) {
|
|
72
|
+
try {
|
|
73
|
+
const cwd = await host.cwd(exec)
|
|
74
|
+
const previous = queues.get(cwd) ?? Promise.resolve()
|
|
75
|
+
const mine = previous.then(() => save(cwd, String(exec.agent.id), checkpointLabel(exec)))
|
|
76
|
+
queues.set(cwd, mine.catch(() => {}))
|
|
77
|
+
await mine
|
|
78
|
+
} catch (error) {
|
|
79
|
+
host.warn(`no checkpoint before ${exec.name}: ${error?.message ?? error}`)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return next()
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const GUIDANCE =
|
|
87
|
+
"This project has a verify step. After you change files for a step of the task, call kriya_verify " +
|
|
88
|
+
"with a short step label. Only its result says whether the work passes: never say tests pass, " +
|
|
89
|
+
"or that the task is done, without a passing kriya_verify. On a failure, fix the cause using the " +
|
|
90
|
+
"output and call it again; after the last attempt the step is blocked: stop, and tell the person " +
|
|
91
|
+
"what failed and why.\n\n" +
|
|
92
|
+
`For a task with several parts, plan first: call kriya_plan with the goal and at most ${MAX_STEPS} ordered steps ` +
|
|
93
|
+
"(each a title, done_when and the files it touches), then call kriya_step for step 1, 2, … in order. " +
|
|
94
|
+
"kriya_step has a fresh agent build the step and the harness check it, retrying with the error; " +
|
|
95
|
+
"don't redo a step's work yourself. If a step is blocked, stop and report it. End with each step's result."
|
|
96
|
+
|
|
97
|
+
export const GUIDANCE_V2 =
|
|
98
|
+
" Give each step `after`: the numbers of the earlier steps it needs (none for a step that needs nothing); " +
|
|
99
|
+
"a step whose needed step is blocked is skipped, so the others still run."
|
|
100
|
+
|
|
101
|
+
function present(value) {
|
|
102
|
+
switch (value.status) {
|
|
103
|
+
case "not configured":
|
|
104
|
+
return [
|
|
105
|
+
"No check is confirmed for this project, so nothing was run and the work is not checked.",
|
|
106
|
+
value.suggestions.length
|
|
107
|
+
? `The person can confirm one with \`kriya verify use <number>\`:\n${value.suggestions.map((s, i) => `${i + 1}. ${s.command} (${s.source})`).join("\n")}`
|
|
108
|
+
: "The project defines no check the harness recognises; the person can set one with `kriya verify use \"<command>\"`.",
|
|
109
|
+
"Tell the person this; don't claim the work passes.",
|
|
110
|
+
].join("\n")
|
|
111
|
+
case "blocked":
|
|
112
|
+
return `Step "${value.step}" is blocked: \`${value.command}\` failed ${value.attempts === undefined ? "" : `on all ${value.attempts} runs `}and isn't run again. Stop and tell the person what failed.${value.output ? `\n\n${value.output}` : ""}`
|
|
113
|
+
case "pass":
|
|
114
|
+
return `Step "${value.step}" passes: \`${value.command}\` exited 0. Session verdict: ${value.verdict}.${
|
|
115
|
+
value.touched?.length
|
|
116
|
+
? ` This work changes test or check files (${value.touched.join(", ")}): tell the person, since a changed test can pass for the wrong reason.`
|
|
117
|
+
: ""
|
|
118
|
+
}`
|
|
119
|
+
default:
|
|
120
|
+
return [
|
|
121
|
+
`Step "${value.step}" fails: \`${value.command}\` ${value.timedOut ? "timed out" : `exited ${value.exitCode ?? "without a code"}`}. ${value.attemptsLeft} attempt${value.attemptsLeft === 1 ? "" : "s"} left.`,
|
|
122
|
+
value.failure === "tests changed"
|
|
123
|
+
? `It passed only with changed tests or check files (${value.weakened.join(", ")}); with the originals it fails, as below. Fix the code, not the tests.`
|
|
124
|
+
: value.failure && `Failure class: ${value.failure}.`,
|
|
125
|
+
value.output,
|
|
126
|
+
value.rules?.length && `Rules for this project, confirmed by the person:\n${value.rules.join("\n")}`,
|
|
127
|
+
]
|
|
128
|
+
.filter(Boolean)
|
|
129
|
+
.join("\n\n")
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* @param {{ cwd: (exec: any) => Promise<string>, run: (command: string, exec: any) => Promise<{ exitCode: number | null, timedOut: boolean, aborted?: boolean, output: string }> }} host
|
|
135
|
+
*/
|
|
136
|
+
export function verifyTool(host) {
|
|
137
|
+
return defineTool({
|
|
138
|
+
name: "kriya_verify",
|
|
139
|
+
description:
|
|
140
|
+
"Run this project's confirmed check (its tests, lint or build, as the person chose) for one step of the task, and get pass, fail or blocked from its exit code. Takes no command. Call it after changing files; a step is blocked after 4 failed runs.",
|
|
141
|
+
parameters: {
|
|
142
|
+
step: { type: "string", description: "A short label for the step being checked, e.g. \"2 parser handles empty input\" (default: all)." },
|
|
143
|
+
},
|
|
144
|
+
output: {
|
|
145
|
+
schema: {
|
|
146
|
+
type: "object",
|
|
147
|
+
// The fields after status and step depend on it (pass, fail, blocked, not configured)
|
|
148
|
+
additionalProperties: true,
|
|
149
|
+
properties: {
|
|
150
|
+
status: { type: "string", required: true },
|
|
151
|
+
step: { type: "string", required: true },
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
render: (_args, value) => [{ type: "text", text: present(value) }],
|
|
155
|
+
},
|
|
156
|
+
async execute(args, exec) {
|
|
157
|
+
if (!exec.agent) throw new VerifyError("kriya_verify needs a session.")
|
|
158
|
+
const cwd = await host.cwd(exec)
|
|
159
|
+
const result = await verifyStep({ cwd, sessionId: String(exec.agent.id), step: args.step, run: (command) => host.run(command, exec, cwd), ...(host.v2 && { v2: host.v2(exec) }), ...(host.guard && { guard: true }), ...(host.strict && { strict: host.strict(exec) }) })
|
|
160
|
+
const rules = host.v2 && result.status === "fail" ? confirmedRules(cwd) : []
|
|
161
|
+
return rules.length ? { ...result, rules } : result
|
|
162
|
+
},
|
|
163
|
+
presentCall: (args) => ({ card: "generic", title: "Verify", kind: "execute", rawInput: typeof args.step === "string" ? args.step : "all" }),
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const PLAN_STEP = {
|
|
168
|
+
type: "object",
|
|
169
|
+
additionalProperties: false,
|
|
170
|
+
properties: {
|
|
171
|
+
title: { type: "string", required: true, description: "What the step does, in a few words." },
|
|
172
|
+
done_when: { type: "string", required: true, description: "What is true when the step is finished, checkable by the project's check." },
|
|
173
|
+
files: { type: "array", items: { type: "string" }, description: "Files the step expects to touch." },
|
|
174
|
+
},
|
|
175
|
+
}
|
|
176
|
+
const PLAN_STEP_V2 = {
|
|
177
|
+
...PLAN_STEP,
|
|
178
|
+
properties: {
|
|
179
|
+
...PLAN_STEP.properties,
|
|
180
|
+
after: { type: "array", items: { type: "number" }, description: "Numbers of the earlier steps this one needs; [] for none. Default: the step before it." },
|
|
181
|
+
},
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// The task contract: what kriya_plan adds under the strict loop. It can only add to what must hold
|
|
185
|
+
const CONTRACT = {
|
|
186
|
+
kind: { type: "string", enum: TASK_KINDS, description: "What sort of task this is; it bounds the plan (a surgical_bugfix has at most 2 steps, and its fix must be proved red then green)." },
|
|
187
|
+
invariants: { type: "array", items: { type: "string" }, description: "Paths that must not change, e.g. db/schema.ts or migrations/*." },
|
|
188
|
+
acceptance: { type: "array", items: { type: "string" }, description: "Up to 3 commands that must also exit 0, beyond the project's check." },
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// The pre-mortem: what kriya_plan adds under the defensive engine
|
|
192
|
+
const PREMORTEM = {
|
|
193
|
+
premortem: {
|
|
194
|
+
type: "object",
|
|
195
|
+
additionalProperties: false,
|
|
196
|
+
description: "Needed for a plan of 2 or more steps: think through how this breaks before building it.",
|
|
197
|
+
properties: {
|
|
198
|
+
failures: { type: "array", items: { type: "object", additionalProperties: false, properties: { what: { type: "string", description: "One way this could crash or misbehave at run time." }, covered_by: { type: "string", description: "The test file, existing or to be written, that proves it can't happen." } } }, description: "At least 2." },
|
|
199
|
+
blast_radius: { type: "array", items: { type: "string" }, description: "Other features, tables or routes that share this surface." },
|
|
200
|
+
negatives: { type: "array", items: { type: "string" }, description: "Bad inputs to handle: nulls, empty states, boundaries, timeouts." },
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** What the harness itself traced from the plan's files, so the agent can compare it with what it declared */
|
|
206
|
+
function traced(cwd, plan) {
|
|
207
|
+
const root = projectRoot(cwd)
|
|
208
|
+
const files = [...new Set(plan.steps.flatMap((s) => s.files))].filter((f) => existsSync(join(root, f)))
|
|
209
|
+
if (!files.length) return undefined
|
|
210
|
+
const graph = importGraph(root)
|
|
211
|
+
const r = blastRadius(graph, files.map((rel) => ({ rel, before: graph.text(rel), after: graph.text(rel) })))
|
|
212
|
+
const near = [...r.direct, ...r.transitive]
|
|
213
|
+
if (!near.length && !r.tests.length) return undefined
|
|
214
|
+
return `Traced from the plan's files: ${near.length} file${near.length === 1 ? "" : "s"} can be reached (${near.slice(0, 8).join(", ")}${near.length > 8 ? ", …" : ""}); ${r.tests.length} test file${r.tests.length === 1 ? "" : "s"} will run before any pass. If your blast_radius misses these, plan for them now.`
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export const NO_CHECK_PLAN =
|
|
218
|
+
"No check is confirmed for this project yet. When a step leaves a build or test script, Kriya asks the person to pick it, so have the first step add one. " +
|
|
219
|
+
"Until then steps are built but not checked; the person can also confirm one with `kriya verify use \"<command>\"`."
|
|
220
|
+
|
|
221
|
+
// Long enough to answer, short enough that a person who walked away doesn't stall a long task
|
|
222
|
+
export const CHECK_QUESTION_MS = 120_000
|
|
223
|
+
const NOT_NOW = "Not now"
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* The harness itself asks the person which found check to use: the question goes straight to their UI,
|
|
227
|
+
* so the model can't answer it. Only an offered command they selected counts; a typed one stays
|
|
228
|
+
* `kriya verify use`. Undefined with no UI (`kriya run`), on no answer, and when the turn stops.
|
|
229
|
+
* @returns {Promise<string | undefined>}
|
|
230
|
+
*/
|
|
231
|
+
export async function askCheck(questions, exec, found) {
|
|
232
|
+
const offered = found.slice(0, 3)
|
|
233
|
+
const answer = await questions
|
|
234
|
+
?.ask({
|
|
235
|
+
agent: exec.agent,
|
|
236
|
+
signal: AbortSignal.any([exec.signal, AbortSignal.timeout(CHECK_QUESTION_MS)]),
|
|
237
|
+
questions: [
|
|
238
|
+
{
|
|
239
|
+
id: "kriya-check",
|
|
240
|
+
header: "Check",
|
|
241
|
+
question: "Which command should decide whether each step works?",
|
|
242
|
+
detail: "Kriya runs it after every step and sends failures back to be fixed. These came from the project's files, which the agent may have written, so pick one only if it really tests the work. For any other command, run kriya verify use in a terminal: a typed answer here isn't used.",
|
|
243
|
+
options: [...offered.map((c) => ({ label: c.command, description: `From ${c.source}` })), { label: NOT_NOW, description: "Steps stay not checked. You can pick one later in the Progress tab." }],
|
|
244
|
+
},
|
|
245
|
+
],
|
|
246
|
+
})
|
|
247
|
+
.catch(() => undefined)
|
|
248
|
+
const picked = answer?.answers?.find((a) => a.id === "kriya-check")?.selected?.[0]
|
|
249
|
+
return offered.find((c) => c.command === picked)?.command
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// DSH refuses a tool's output holding an undefined value, after the tool already ran:
|
|
253
|
+
// a recorded plan came back as an error and spent a plan slot. An absent field is simply left out
|
|
254
|
+
const plain = (value) => JSON.parse(JSON.stringify(value))
|
|
255
|
+
|
|
256
|
+
const renderStatus = (rows) =>
|
|
257
|
+
rows.map((r) => `${r.n}. ${r.title}${r.after?.length ? ` (after ${r.after.join(", ")})` : ""}: ${r.status}${r.attempts ? ` (${r.attempts} run${r.attempts === 1 ? "" : "s"})` : ""}`).join("\n")
|
|
258
|
+
|
|
259
|
+
/** @param {{ isBuilder: (exec: any) => boolean, cwd: (exec: any) => Promise<string>, v2?: unknown }} host */
|
|
260
|
+
export function planTool(host) {
|
|
261
|
+
return defineTool({
|
|
262
|
+
name: "kriya_plan",
|
|
263
|
+
description: `Record the plan for a task with several parts: a goal and 1 to ${MAX_STEPS} ordered steps. Then run each with kriya_step, in order.`,
|
|
264
|
+
parameters: {
|
|
265
|
+
goal: { type: "string", required: true, description: "What the task is for, in one sentence." },
|
|
266
|
+
steps: { type: "array", required: true, items: host.v2 ? PLAN_STEP_V2 : PLAN_STEP, description: `1 to ${MAX_STEPS} ordered steps.` },
|
|
267
|
+
...(host.strict && CONTRACT),
|
|
268
|
+
...(host.defensive && PREMORTEM),
|
|
269
|
+
},
|
|
270
|
+
output: {
|
|
271
|
+
schema: { type: "object", additionalProperties: true, properties: { steps: { type: "array", required: true, items: { type: "object", additionalProperties: true, properties: {} } } } },
|
|
272
|
+
render: (_args, value) => [
|
|
273
|
+
{
|
|
274
|
+
type: "text",
|
|
275
|
+
text: `Plan recorded (${value.steps.length} step${value.steps.length === 1 ? "" : "s"}):\n${renderStatus(value.steps)}\nRun step 1 with kriya_step.${
|
|
276
|
+
value.unchecked ? `\n${NO_CHECK_PLAN}` : ""
|
|
277
|
+
}${value.radius ? `\n${value.radius}` : ""}`,
|
|
278
|
+
},
|
|
279
|
+
],
|
|
280
|
+
},
|
|
281
|
+
async execute(args, exec) {
|
|
282
|
+
if (!exec.agent) throw new VerifyError("kriya_plan needs a session.")
|
|
283
|
+
if (host.isBuilder(exec)) throw new VerifyError("A step's builder doesn't plan; build your step and stop.")
|
|
284
|
+
const cwd = await host.cwd(exec)
|
|
285
|
+
const id = String(exec.agent.id)
|
|
286
|
+
const seed = seededPlan()
|
|
287
|
+
// The person drew this plan in Kriya Flows: it isn't the model's to change
|
|
288
|
+
if (seed && readPlan(cwd, id)) throw new VerifyError("The person set this plan in Kriya. Run its steps with kriya_step; it can't be replanned here.")
|
|
289
|
+
savePlan(cwd, id, seed ?? args, undefined, { v2: Boolean(host.v2), strict: Boolean(host.strict), defensive: Boolean(host.defensive) })
|
|
290
|
+
writeSnapshot(cwd, id)
|
|
291
|
+
return plain({ steps: planStatus(cwd, id), ...(!(host.checked ?? confirmedCheck)(cwd) && { unchecked: true }), ...(host.defensive && { radius: traced(cwd, readPlan(cwd, id)) }) })
|
|
292
|
+
},
|
|
293
|
+
presentCall: (args) => ({ card: "generic", title: "Plan", kind: "think", rawInput: typeof args.goal === "string" ? args.goal : "" }),
|
|
294
|
+
})
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function presentStep(value) {
|
|
298
|
+
const head = `Step ${value.step} (${value.title}): ${value.status}${value.attempts ? ` after ${value.attempts} run${value.attempts === 1 ? "" : "s"}` : ""}.`
|
|
299
|
+
const lines = [head]
|
|
300
|
+
if (value.status === "not checked")
|
|
301
|
+
lines.push("No check is confirmed for this project, so the step was built but not checked. Tell the person; they can confirm one with `kriya verify use <number>`.")
|
|
302
|
+
if (value.status === "blocked") lines.push(`\`${value.command}\` ${value.stalled ? `was stopped early: ${value.stalled}, so more builders wouldn't help` : "kept failing"}. Stop and tell the person what failed:`, value.output)
|
|
303
|
+
if (value.status === "interrupted") lines.push("Call kriya_step for this step again; if it comes back interrupted again, stop and tell the person.")
|
|
304
|
+
if (value.status === "pass" && value.verdict) lines.push(`Session verdict so far: ${value.verdict}.`)
|
|
305
|
+
for (const [i, b] of (value.builders ?? []).entries())
|
|
306
|
+
if (b.limit) lines.push(`Builder ${i + 1} was stopped at its limit (${b.limit}); the check ran on the files it left.`)
|
|
307
|
+
const aside = value.builders?.filter((b) => b.setAside).length
|
|
308
|
+
if (aside) lines.push(`${aside} attempt${aside === 1 ? " was" : "s were"} set aside for failing further from passing than an earlier one (kept in kriya undo --list).`)
|
|
309
|
+
if (value.note) lines.push(value.note)
|
|
310
|
+
if (value.rolledBack) lines.push("The step's files went back to how they were before it; the attempts are kept in kriya undo --list.")
|
|
311
|
+
const rolled = value.builders?.filter((b) => b.rolledBack).length
|
|
312
|
+
if (rolled) lines.push("Attempts that broke the build were undone along the way.")
|
|
313
|
+
const last = value.builders?.at(-1)?.summary
|
|
314
|
+
if (last) lines.push(`The builder's own summary (not evidence): ${last}`)
|
|
315
|
+
return lines.filter(Boolean).join("\n")
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* @param {{ isBuilder: (exec: any) => boolean, cwd: (exec: any) => Promise<string>, spawn: (exec: any, prompt: string, label: string) => Promise<any>, verify: (exec: any, cwd: string, label: string) => Promise<any>, steps?: (exec: any, cwd: string) => object }} host
|
|
320
|
+
* steps: loop v2's snapshot, restore and rules for runStep
|
|
321
|
+
*/
|
|
322
|
+
export function stepTool(host) {
|
|
323
|
+
return defineTool({
|
|
324
|
+
name: "kriya_step",
|
|
325
|
+
description:
|
|
326
|
+
"Run one step of the recorded plan: a fresh agent builds it, the harness runs the project's confirmed check, and a failure goes back to a new builder with its output, up to 4 runs; then the step is blocked. Steps run in order.",
|
|
327
|
+
parameters: {
|
|
328
|
+
step: { type: "number", required: true, description: "The step's number in the plan, from 1." },
|
|
329
|
+
},
|
|
330
|
+
output: {
|
|
331
|
+
schema: { type: "object", additionalProperties: true, properties: { status: { type: "string", required: true } } },
|
|
332
|
+
render: (_args, value) => [{ type: "text", text: presentStep(value) }],
|
|
333
|
+
},
|
|
334
|
+
async execute(args, exec) {
|
|
335
|
+
if (!exec.agent) throw new VerifyError("kriya_step needs a session.")
|
|
336
|
+
if (host.isBuilder(exec)) throw new VerifyError("A step's builder doesn't run steps; build your step and stop.")
|
|
337
|
+
const cwd = await host.cwd(exec)
|
|
338
|
+
const id = String(exec.agent.id)
|
|
339
|
+
const n = Math.trunc(Number(args.step))
|
|
340
|
+
writeSnapshot(cwd, id, { current: n })
|
|
341
|
+
const result = await runStep({
|
|
342
|
+
cwd,
|
|
343
|
+
sessionId: id,
|
|
344
|
+
n,
|
|
345
|
+
hasCheck: Boolean((host.checked ?? confirmedCheck)(cwd)),
|
|
346
|
+
...(host.limits && { limits: host.limits }),
|
|
347
|
+
spawn: (prompt, label, live) => host.spawn(exec, prompt, label, live),
|
|
348
|
+
verify: (label) => host.verify(exec, cwd, label),
|
|
349
|
+
...(host.steps && { v2: host.steps(exec, cwd) }),
|
|
350
|
+
...(host.guardSteps && { guard: host.guardSteps(exec, cwd) }),
|
|
351
|
+
...(host.questions && { pickCheck: (found) => askCheck(host.questions(), exec, found) }),
|
|
352
|
+
}).catch((error) => {
|
|
353
|
+
// An abort rejects with DSH's plain reason ({ kind: "user" }), which reads as "[object Object]"
|
|
354
|
+
throw error instanceof Error ? error : new VerifyError("The step was stopped before it finished.")
|
|
355
|
+
})
|
|
356
|
+
writeSnapshot(cwd, id)
|
|
357
|
+
return plain(result)
|
|
358
|
+
},
|
|
359
|
+
presentCall: (args) => ({ card: "generic", title: "Build and check a step", kind: "execute", rawInput: `step ${args.step}` }),
|
|
360
|
+
})
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// The steps left when a builder is told to wrap up
|
|
364
|
+
export const BUILDER_WARN_STEPS = 8
|
|
365
|
+
|
|
366
|
+
export const builderWarning = (left) =>
|
|
367
|
+
`Kriya: about ${left} step${left === 1 ? "" : "s"} or a few minutes left for this step's builder. Finish the core change now, ` +
|
|
368
|
+
"stop anything you started in the background, and end with what you changed. You are stopped at the limit and the check runs on what you left."
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Bounds each step's builder by code (src/loop.js builderLimits): counts its
|
|
372
|
+
* steps and time, warns once near the limit, refuses its next step at the
|
|
373
|
+
* limit, and keeps its live record (steps, last tool) for the Progress tab.
|
|
374
|
+
* Only agents registered with `start` are bounded; the parent and every
|
|
375
|
+
* other agent pass through. Free of DSH so it can be tested alone.
|
|
376
|
+
* @param {{ maxSteps: number, maxMinutes: number }} limits
|
|
377
|
+
* @param {{ now?: () => number, message?: (text: string) => any }} [host]
|
|
378
|
+
*/
|
|
379
|
+
export function builderGuard(limits, host = {}) {
|
|
380
|
+
const now = host.now ?? Date.now
|
|
381
|
+
const message =
|
|
382
|
+
host.message ??
|
|
383
|
+
((text) => createUserMessage({ content: [{ type: "text", text }], source: { kind: "kriya-loop", form: "notice", summary: "step builder limit" } }))
|
|
384
|
+
/** @type {Map<string, { live: any, started: number, steps: number, warned: boolean }>} */
|
|
385
|
+
const bounded = new Map()
|
|
386
|
+
return {
|
|
387
|
+
start: (id, live) => bounded.set(String(id), { live, started: now(), steps: 0, warned: false }),
|
|
388
|
+
end: (id) => bounded.delete(String(id)),
|
|
389
|
+
/** agent/pre-step (waterfall) */
|
|
390
|
+
async preStep({ agent }, next) {
|
|
391
|
+
const s = bounded.get(String(agent?.id))
|
|
392
|
+
if (!s) return next()
|
|
393
|
+
s.steps += 1
|
|
394
|
+
s.live.steps = s.steps
|
|
395
|
+
const tokens = host.tokens?.(agent)
|
|
396
|
+
if (tokens > (s.live.tokens ?? 0)) s.live.tokens = tokens
|
|
397
|
+
const elapsed = now() - s.started
|
|
398
|
+
const reason = s.steps > limits.maxSteps ? `${limits.maxSteps} steps` : elapsed > limits.maxMinutes * 60_000 ? `${limits.maxMinutes} minutes` : null
|
|
399
|
+
if (reason) {
|
|
400
|
+
s.live.stopped ??= reason
|
|
401
|
+
return { kind: "reject" }
|
|
402
|
+
}
|
|
403
|
+
const decision = await next()
|
|
404
|
+
const left = limits.maxSteps - s.steps + 1
|
|
405
|
+
const late = left <= BUILDER_WARN_STEPS || elapsed > limits.maxMinutes * 48_000
|
|
406
|
+
if (s.warned || !late || decision.kind !== "enter") return decision
|
|
407
|
+
s.warned = true
|
|
408
|
+
return { ...decision, messages: [...decision.messages, message(builderWarning(Math.max(1, left)))] }
|
|
409
|
+
},
|
|
410
|
+
/** tools/pre-execute (waterfall): the builder's latest tool, for the Progress tab */
|
|
411
|
+
async preExecute(exec, next) {
|
|
412
|
+
const s = exec.agent && bounded.get(String(exec.agent.id))
|
|
413
|
+
if (s) s.live.last = exec.name
|
|
414
|
+
return next()
|
|
415
|
+
},
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// U8: said once in a turn when the files changed after the last passing check
|
|
420
|
+
export const RECHECK =
|
|
421
|
+
"Files changed after the last passing kriya_verify, so that pass no longer covers the work. " +
|
|
422
|
+
"Call kriya_verify again before you finish; don't say the work passes until it does."
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* The agent/turn-stopping hook (U8): a "verified" session whose files changed
|
|
426
|
+
* since is stale; the agent is asked once per turn to check again. Data
|
|
427
|
+
* decides (the files' fingerprint), never what the model says.
|
|
428
|
+
* @param {{ cwd: (exec: any) => Promise<string>, verdict?: typeof currentVerdict, message?: (text: string) => any }} host
|
|
429
|
+
*/
|
|
430
|
+
export function recheckHook(host) {
|
|
431
|
+
const verdictOf = host.verdict ?? currentVerdict
|
|
432
|
+
const message = host.message ?? ((text) => createUserMessage({ content: [{ type: "text", text }], source: { kind: "kriya-loop", form: "notice", summary: "check again" } }))
|
|
433
|
+
const asked = new WeakMap()
|
|
434
|
+
return async ({ agent, turn, signal }) => {
|
|
435
|
+
if (asked.get(agent) === turn) return
|
|
436
|
+
const cwd = await host.cwd({ agent, signal })
|
|
437
|
+
const now = await verdictOf(cwd, String(agent.id))
|
|
438
|
+
if (!now.stale) return
|
|
439
|
+
asked.set(agent, turn)
|
|
440
|
+
agent.steer(message(RECHECK))
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// The loop guard: said when an agent stops with plan steps it could still run
|
|
445
|
+
export const finishNotice = (step) =>
|
|
446
|
+
`The plan isn't finished: step ${step.n} (${step.title}) is ${step.status === "fail" ? "failing" : "not started"}. ` +
|
|
447
|
+
`Run it with kriya_step. If it can't go on, say exactly why; don't report the task as done.`
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* The agent/turn-stopping hook (loop guard): the records decide, never what
|
|
451
|
+
* the model says. Once per turn and step reached, so an agent that keeps
|
|
452
|
+
* stopping is asked again only after a step has moved, at most once per step.
|
|
453
|
+
* @param {{ cwd: (exec: any) => Promise<string>, readOnly?: (exec: any) => boolean, rows?: typeof planStatus, message?: (text: string) => any }} host
|
|
454
|
+
*/
|
|
455
|
+
export function finishHook(host) {
|
|
456
|
+
const rowsOf = host.rows ?? planStatus
|
|
457
|
+
const message = host.message ?? ((text) => createUserMessage({ content: [{ type: "text", text }], source: { kind: "kriya-loop", form: "notice", summary: "finish the plan" } }))
|
|
458
|
+
const asked = new WeakMap()
|
|
459
|
+
return async ({ agent, turn, signal }) => {
|
|
460
|
+
if (host.readOnly?.({ agent })) return
|
|
461
|
+
const cwd = await host.cwd({ agent, signal })
|
|
462
|
+
const rows = rowsOf(cwd, String(agent.id))
|
|
463
|
+
const next = nextStep(rows)
|
|
464
|
+
if (!next) return
|
|
465
|
+
const mark = `${turn}:${next.n}`
|
|
466
|
+
if (asked.get(agent) === mark) return
|
|
467
|
+
asked.set(agent, mark)
|
|
468
|
+
agent.steer(message(finishNotice(next)))
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
export const GUIDANCE_STRICT =
|
|
473
|
+
" Give kriya_plan the task contract: kind, invariants (paths that must not change) and acceptance (commands that must also exit 0). " +
|
|
474
|
+
"Each check runs cheapest first, so a syntax or type error comes back before the tests run. Tests may be added, never weakened; " +
|
|
475
|
+
"don't add any, @ts-ignore or empty catches to get past a check. A bug fix must fail on the old code: add the failing test."
|
|
476
|
+
|
|
477
|
+
export const GUIDANCE_DEFENSIVE =
|
|
478
|
+
" Think before you build: ask what else this change could break and how it could fail at run time. A plan of 2 or more steps needs a premortem: " +
|
|
479
|
+
"failures (each with the test that proves it can't happen), blast_radius and negatives. Tests of neighbouring code run before any pass; the diff is " +
|
|
480
|
+
"checked for broken callers and missing awaits; anything new needs a test with a bad input."
|
|
481
|
+
|
|
482
|
+
export const GUIDANCE_RECON =
|
|
483
|
+
` Before reading a file, call code_outline for its symbols and read only the lines you need (at most ${MAX_READ_LINES} per read). Before changing something shared, call code_impact to see what imports it.`
|
|
484
|
+
|
|
485
|
+
function reconTools(host) {
|
|
486
|
+
const OBJECT = { schema: { type: "object", additionalProperties: true, properties: {} } }
|
|
487
|
+
const guarded = (work) => async (args, exec) => {
|
|
488
|
+
try {
|
|
489
|
+
return await work(await host.cwd(exec), args)
|
|
490
|
+
} catch (error) {
|
|
491
|
+
if (error instanceof ReconError) throw new VerifyError(error.message)
|
|
492
|
+
throw error
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return [
|
|
496
|
+
defineTool({
|
|
497
|
+
name: "code_outline",
|
|
498
|
+
description: "A source file's functions, classes, types and constants with their line numbers, and its length. Use it before reading a file, then read only the lines you need.",
|
|
499
|
+
parameters: { path: { type: "string", required: true, description: "The file, relative to the session's folder." } },
|
|
500
|
+
output: { ...OBJECT, render: (_a, v) => [{ type: "text", text: `${v.path} (${v.lines} lines)\n${v.symbols.map((s) => `${s.line}: ${s.kind} ${s.name}`).join("\n") || "No symbols recognised."}${v.cut ? `\n… ${v.cut} more` : ""}` }] },
|
|
501
|
+
execute: guarded((cwd, args) => outline(cwd, args.path)),
|
|
502
|
+
presentCall: (args) => ({ card: "generic", title: "Outline", kind: "read", rawInput: String(args.path ?? "") }),
|
|
503
|
+
}),
|
|
504
|
+
defineTool({
|
|
505
|
+
name: "code_impact",
|
|
506
|
+
description: "The project's files that import a file, so you know what a change can break before you make it.",
|
|
507
|
+
parameters: { path: { type: "string", required: true, description: "The file, relative to the session's folder." } },
|
|
508
|
+
output: { ...OBJECT, render: (_a, v) => [{ type: "text", text: v.importers.length ? `Imported by:\n${v.importers.join("\n")}` : "Nothing in this project imports it, as far as its import lines show." }] },
|
|
509
|
+
execute: guarded((cwd, args) => {
|
|
510
|
+
insideFolder(cwd, args.path)
|
|
511
|
+
return { importers: importers(cwd, args.path).slice(0, 100) }
|
|
512
|
+
}),
|
|
513
|
+
presentCall: (args) => ({ card: "generic", title: "Impact", kind: "read", rawInput: String(args.path ?? "") }),
|
|
514
|
+
}),
|
|
515
|
+
]
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** tools/post-execute (recon): a long read reaches the model as one page, never as a refusal */
|
|
519
|
+
export function readHook() {
|
|
520
|
+
return async (exec, result, next) => {
|
|
521
|
+
const decision = await next()
|
|
522
|
+
if (exec.name !== "read" || !exec.agent || decision.kind !== "accept" || result.isError || Object.hasOwn(decision, "content")) return decision
|
|
523
|
+
const text = readPage(result.value ?? {})
|
|
524
|
+
return text ? { ...decision, content: [{ type: "text", text }] } : decision
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const PARSERS = { ".js": ["node", ["--check"]], ".mjs": ["node", ["--check"]], ".cjs": ["node", ["--check"]], ".py": ["python3", ["-c", "import ast,sys; ast.parse(open(sys.argv[1]).read(), sys.argv[1])"]] }
|
|
529
|
+
|
|
530
|
+
/** The parse error of one file, or undefined: reads it, never runs it */
|
|
531
|
+
export function parseError(file) {
|
|
532
|
+
const parser = PARSERS[extname(file)]
|
|
533
|
+
if (!parser) return Promise.resolve(undefined)
|
|
534
|
+
return new Promise((done) => execFile(parser[0], [...parser[1], file], { timeout: 10_000 }, (error, _out, stderr) => done(error && !error.killed && error.code !== "ENOENT" ? String(stderr).trim().slice(0, 1200) : undefined)))
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** tools/post-execute (strict): level 1 of the ladder, on the edit itself, so a broken file costs no check run */
|
|
538
|
+
export function syntaxHook(host) {
|
|
539
|
+
const check = host.parse ?? parseError
|
|
540
|
+
return async (exec, result, next) => {
|
|
541
|
+
const decision = await next()
|
|
542
|
+
const path = exec.arguments?.file_path
|
|
543
|
+
if (decision.kind !== "accept" || result.isError || !["write", "edit"].includes(exec.name) || typeof path !== "string" || !exec.agent || Object.hasOwn(decision, "content") || Object.hasOwn(decision, "value")) return decision
|
|
544
|
+
const error = await check(resolve(await host.cwd(exec), path))
|
|
545
|
+
if (!error) return decision
|
|
546
|
+
return { ...decision, content: [...(result.content ?? []), { type: "text", text: `This file no longer parses; fix it before going on:\n${error}` }] }
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// Heavy tools by name, and the words in a step that need them
|
|
551
|
+
const HEAVY = [
|
|
552
|
+
[/^browser_/, /\b(browser|page|ui|css|layout|frontend|screen|visual|html|render\w*|click|form|button)\b/i],
|
|
553
|
+
[/^rea_/, /\b(reverse|binary|decompil\w*|disassembl\w*|apk|firmware)\b/i],
|
|
554
|
+
]
|
|
555
|
+
|
|
556
|
+
/** The tools a builder doesn't need for this step */
|
|
557
|
+
export function toolsToHide(names, step) {
|
|
558
|
+
const text = `${step.title} ${step.doneWhen} ${step.files.join(" ")}`
|
|
559
|
+
return names.filter((name) => HEAVY.some(([tool, words]) => tool.test(name) && !words.test(text)))
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export function apply(ctx) {
|
|
563
|
+
const sandboxPolicy = ctx.shell.sandboxMode === undefined ? undefined : ctx.get("sandboxPolicy")
|
|
564
|
+
const readOnly = (exec) => sandboxPolicy?.resolve({ session: exec.agent.session })?.mode === "read-only"
|
|
565
|
+
const v2 = process.env.KRIYA_LOOP_V2 === "on" ? (exec) => ({ readOnly: readOnly(exec) }) : undefined
|
|
566
|
+
const defensiveOn = process.env.KRIYA_DEFENSIVE === "on"
|
|
567
|
+
// The defensive engine's checks are rungs of the strict loop, so it brings it
|
|
568
|
+
const strictOn = defensiveOn || process.env.KRIYA_STRICT_LOOP === "on"
|
|
569
|
+
const reconOn = process.env.KRIYA_RECON === "on"
|
|
570
|
+
const jitOn = process.env.KRIYA_JIT_TOOLS === "on"
|
|
571
|
+
// The strict loop stands on the guard: it needs signatures and snapshots
|
|
572
|
+
const guarded = strictOn || process.env.KRIYA_LOOP_GUARD === "on"
|
|
573
|
+
const strict = strictOn ? (exec) => ({ readOnly: readOnly(exec), defensive: defensiveOn }) : undefined
|
|
574
|
+
// Each agent's folder, as its loop tools last resolved it (loop v2's state section)
|
|
575
|
+
const folders = new WeakMap()
|
|
576
|
+
const host = {
|
|
577
|
+
v2,
|
|
578
|
+
guard: guarded,
|
|
579
|
+
strict,
|
|
580
|
+
async cwd(exec) {
|
|
581
|
+
const cwd = await ctx.workingDirectory.ensure(exec.agent, exec.signal)
|
|
582
|
+
if (exec.agent) folders.set(exec.agent, cwd)
|
|
583
|
+
return cwd
|
|
584
|
+
},
|
|
585
|
+
async run(command, exec, workdir) {
|
|
586
|
+
const policy = sandboxPolicy?.resolve({ session: exec.agent.session })
|
|
587
|
+
const spec = ctx.shell.resolve({
|
|
588
|
+
command,
|
|
589
|
+
workdir,
|
|
590
|
+
timeoutMs: TIMEOUT_MS,
|
|
591
|
+
dshEnv: ctx.shellEnv.collect(exec),
|
|
592
|
+
...(policy !== undefined && { sandboxPolicy: policy }),
|
|
593
|
+
signal: exec.signal,
|
|
594
|
+
})
|
|
595
|
+
const result = await (await ctx.shell.execute(spec)).result()
|
|
596
|
+
return {
|
|
597
|
+
exitCode: result.exitCode,
|
|
598
|
+
timedOut: result.timedOut,
|
|
599
|
+
aborted: result.aborted,
|
|
600
|
+
output: [result.stdout.text, result.stderr.text].filter(Boolean).join("\n"),
|
|
601
|
+
}
|
|
602
|
+
},
|
|
603
|
+
}
|
|
604
|
+
ctx.tools.register(verifyTool(host))
|
|
605
|
+
|
|
606
|
+
// Fresh builders: DSH's in-process spawn provider, awaited by the caller
|
|
607
|
+
// (no parent notice), one level deep only. Their ids are remembered so a
|
|
608
|
+
// builder can't plan or run steps itself
|
|
609
|
+
const builders = new Set()
|
|
610
|
+
const limits = builderLimits()
|
|
611
|
+
const guard = builderGuard(limits, { tokens: (agent) => { try { return ctx.get("tokenMeter")?.measure(agent.session).totalTokens } catch { return undefined } } })
|
|
612
|
+
// A builder's mask, waiting for that builder (agent/created runs before its first step)
|
|
613
|
+
const masks = new Map()
|
|
614
|
+
const loopHost = {
|
|
615
|
+
questions: () => ctx.get("userQuestions"),
|
|
616
|
+
v2,
|
|
617
|
+
strict,
|
|
618
|
+
defensive: defensiveOn,
|
|
619
|
+
limits,
|
|
620
|
+
cwd: host.cwd,
|
|
621
|
+
isBuilder: (exec) => builders.has(String(exec.agent?.id)),
|
|
622
|
+
async spawn(exec, prompt, label, live) {
|
|
623
|
+
const subagents = ctx.get("subagents")
|
|
624
|
+
if (!subagents) throw new VerifyError("kriya_step needs DSH's subagents, which this profile doesn't load.")
|
|
625
|
+
if (jitOn && live) {
|
|
626
|
+
const step = readPlan(await host.cwd(exec), String(exec.agent.id))?.steps[live.n - 1]
|
|
627
|
+
const deny = step ? toolsToHide(ctx.tools.schemas(exec.agent).map((s) => s.name), step) : []
|
|
628
|
+
if (deny.length) masks.set(exec.agent, deny)
|
|
629
|
+
}
|
|
630
|
+
const activation = await subagents.startActivation({
|
|
631
|
+
provider: "spawn",
|
|
632
|
+
label,
|
|
633
|
+
request: { prompt: [{ type: "text", text: prompt }], parent: exec.agent, signal: exec.signal, maxDepth: 1 },
|
|
634
|
+
signal: exec.signal,
|
|
635
|
+
delivery: "caller",
|
|
636
|
+
})
|
|
637
|
+
const id = String(activation.childId)
|
|
638
|
+
builders.add(id)
|
|
639
|
+
if (live) guard.start(id, live)
|
|
640
|
+
masks.delete(exec.agent)
|
|
641
|
+
const stop = () => activation.dispose().catch(() => {})
|
|
642
|
+
exec.signal.addEventListener("abort", stop, { once: true })
|
|
643
|
+
// The step limit is checked between steps; a tool call that never
|
|
644
|
+
// returns is cut off a minute after the time limit
|
|
645
|
+
const hard = setTimeout(() => {
|
|
646
|
+
if (live) live.stopped ??= `${limits.maxMinutes} minutes`
|
|
647
|
+
stop()
|
|
648
|
+
}, (limits.maxMinutes + 1) * 60_000)
|
|
649
|
+
hard.unref?.()
|
|
650
|
+
try {
|
|
651
|
+
return await activation.result
|
|
652
|
+
} catch (error) {
|
|
653
|
+
// Disposed by the hard limit (not by the person): still checked
|
|
654
|
+
if (live?.stopped && !exec.signal.aborted) return { output: [], stopReason: "limit" }
|
|
655
|
+
throw error
|
|
656
|
+
} finally {
|
|
657
|
+
clearTimeout(hard)
|
|
658
|
+
guard.end(id)
|
|
659
|
+
exec.signal.removeEventListener("abort", stop)
|
|
660
|
+
}
|
|
661
|
+
},
|
|
662
|
+
verify: (exec, cwd, label) => verifyStep({ cwd, sessionId: String(exec.agent.id), step: label, run: (command) => host.run(command, exec, cwd), ...(v2 && { v2: v2(exec) }), ...(guarded && { guard: true }), ...(strict && { strict: strict(exec) }) }),
|
|
663
|
+
// Loop guard: what a builder left, to tell an attempt that changed nothing; never in Read only
|
|
664
|
+
...((guarded || reconOn || jitOn) && {
|
|
665
|
+
guardSteps: (exec, cwd) => ({
|
|
666
|
+
...(guarded && !readOnly(exec) && { snapshot: (label) => checkpoint(cwd, String(exec.agent.id), label).then((c) => c?.tree, () => undefined) }),
|
|
667
|
+
...(strictOn && !readOnly(exec) && { restore: (tree, label) => restoreTree(cwd, tree, label) }),
|
|
668
|
+
briefing: async (step) => {
|
|
669
|
+
const lines = []
|
|
670
|
+
if (reconOn) {
|
|
671
|
+
const using = [...new Set(step.files.flatMap((file) => { try { return importers(cwd, file) } catch { return [] } }))].slice(0, 20)
|
|
672
|
+
if (using.length) lines.push(`Files that import what this step touches, which a change can break: ${using.join(", ")}`)
|
|
673
|
+
}
|
|
674
|
+
if (jitOn) {
|
|
675
|
+
const skills = await ctx.get("skills")?.list({ cwd, scope: exec.agent }).catch(() => [])
|
|
676
|
+
const names = rankSkills(`${step.title} ${step.doneWhen}`, (skills ?? []).filter((s) => s.invocation?.modelInvocable !== false)).slice(0, 2).map((r) => r.name)
|
|
677
|
+
if (names.length) lines.push(`Skills likely to help this step: ${names.join(", ")}. Load the ones that fit with the skill tool.`)
|
|
678
|
+
}
|
|
679
|
+
return lines
|
|
680
|
+
},
|
|
681
|
+
}),
|
|
682
|
+
}),
|
|
683
|
+
// Loop v2: each attempt's files saved on the session's checkpoint ref, and restored from it; never in Read only
|
|
684
|
+
...(v2 && {
|
|
685
|
+
steps: (exec, cwd) =>
|
|
686
|
+
readOnly(exec)
|
|
687
|
+
? { rules: confirmedRules(cwd) }
|
|
688
|
+
: {
|
|
689
|
+
rules: confirmedRules(cwd),
|
|
690
|
+
snapshot: async (label) => (await checkpoint(cwd, String(exec.agent.id), label))?.tree,
|
|
691
|
+
restore: (tree, label) => restoreTree(cwd, tree, label),
|
|
692
|
+
},
|
|
693
|
+
}),
|
|
694
|
+
}
|
|
695
|
+
if (reconOn) {
|
|
696
|
+
for (const tool of reconTools(host)) ctx.tools.register(tool)
|
|
697
|
+
ctx.on("tools/post-execute", readHook())
|
|
698
|
+
}
|
|
699
|
+
if (strictOn) ctx.on("tools/post-execute", syntaxHook({ cwd: host.cwd }))
|
|
700
|
+
if (jitOn)
|
|
701
|
+
ctx.on("agent/created", ({ agent }) => {
|
|
702
|
+
for (const [parent, deny] of masks) if (ctx.get("agents")?.isOwnedBy(agent.id, parent)) agent.ctx.tools.restrict({ deny })
|
|
703
|
+
})
|
|
704
|
+
ctx.tools.register(planTool(loopHost))
|
|
705
|
+
ctx.tools.register(stepTool(loopHost))
|
|
706
|
+
ctx.on(
|
|
707
|
+
"tools/pre-execute",
|
|
708
|
+
checkpointHook({
|
|
709
|
+
cwd: host.cwd,
|
|
710
|
+
readOnly,
|
|
711
|
+
warn: (text) => ctx.logger("kriya-loop").warn(text),
|
|
712
|
+
})
|
|
713
|
+
)
|
|
714
|
+
ctx.on("agent/pre-step", guard.preStep)
|
|
715
|
+
ctx.on("tools/pre-execute", guard.preExecute)
|
|
716
|
+
ctx.on("agent/turn-stopping", recheckHook({ cwd: host.cwd }))
|
|
717
|
+
if (guarded) ctx.on("agent/turn-stopping", finishHook({ cwd: host.cwd, readOnly }))
|
|
718
|
+
ctx.systemPrompt.section({ name: "tool:kriya_verify", order: ctx.systemPrompt.getSectionOrder("TOOL_BASH"), text: `${GUIDANCE}${v2 ? GUIDANCE_V2 : ""}${strictOn ? GUIDANCE_STRICT : ""}${defensiveOn ? GUIDANCE_DEFENSIVE : ""}${reconOn ? GUIDANCE_RECON : ""}` })
|
|
719
|
+
// Long tasks: the plan's state per agent, in a late section that
|
|
720
|
+
// compaction never condenses (after DSH's suffix, before the anchor's), so
|
|
721
|
+
// the cached prefix stays the same. The folder is the one the agent's last
|
|
722
|
+
// loop tool ran in; before a plan there is nothing to show, so a session
|
|
723
|
+
// without a plan gets the same prompt as before. Loop v2 only until
|
|
724
|
+
// 2026-11-04; on with the loop since (owner: a real run lost its plan after
|
|
725
|
+
// compaction and goal rounds, and the Progress tab never moved)
|
|
726
|
+
{
|
|
727
|
+
ctx.systemPrompt.section({
|
|
728
|
+
name: "kriya:loop-state",
|
|
729
|
+
order: 10250,
|
|
730
|
+
interpolate: false,
|
|
731
|
+
text: ({ scope }) => {
|
|
732
|
+
// The folder a loop tool last resolved, else the session's own (a resumed session before any loop tool)
|
|
733
|
+
const cwd = scope && (folders.get(scope) ?? scope.session?.header?.cwd)
|
|
734
|
+
if (!cwd) return ""
|
|
735
|
+
try {
|
|
736
|
+
return loopStateText(cwd, String(scope.id))
|
|
737
|
+
} catch {
|
|
738
|
+
return ""
|
|
739
|
+
}
|
|
740
|
+
},
|
|
741
|
+
})
|
|
742
|
+
}
|
|
743
|
+
}
|