@kriya-ai/harness 0.0.0-stage → 0.2.1

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.
Files changed (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,218 @@
1
+ import { defineTool } from "@deepseek-ai/dsh-tools"
2
+
3
+ import { BrowserError, LocalBrowser, chromeInstalled } from "../../src/browser.js"
4
+
5
+ // The agent's localhost browser (browser stage 2), node half: the tools an
6
+ // agent tests and reviews a local app with, and the routes the Preview
7
+ // tab's "Agent's browser" view reads and drives, all on one shared
8
+ // LocalBrowser (src/browser.js): the installed Chrome, headless, loopback
9
+ // pages only. Off unless kriya was started with --browser-tools (KRIYA_BROWSER=on,
10
+ // the bundle row's switch): off, no tool, route or Chrome exists.
11
+ //
12
+ // Reading tools change nothing. browser_click, browser_type and
13
+ // browser_press act on the person's own local app, like a shell command in
14
+ // the workspace; in Read only they are refused. They never reach another
15
+ // site, type a password or pay: the engine opens loopback addresses only.
16
+
17
+ export const name = "kriya-browser"
18
+ // connection is optional: headless runs (kriya run) have the tools, not the view
19
+ export const inject = ["tools", "systemPrompt"]
20
+
21
+ export const ROUTES = { state: "/api/kriya.browser.state", frame: "/api/kriya.browser.frame", input: "/api/kriya.browser.input" }
22
+
23
+ export const GUIDANCE =
24
+ "You have a browser for apps running on this computer (localhost only). To test or review a web app you are building: " +
25
+ "start its dev server (in the background), then browser_open its local address, browser_read for its text and elements, " +
26
+ "browser_screenshot to see it, browser_click / browser_type / browser_press with refs from browser_read, and " +
27
+ "browser_console / browser_network for errors and failed requests. Check the page after each change; report what you saw, " +
28
+ "not what you expect. Use these tools to look at and use the app, not a Playwright, Puppeteer or headless-Chrome script of " +
29
+ "your own: the person watches these live in the Preview tab, and a script's browser is invisible to them. Write automated " +
30
+ "browser tests only when the task asks for them, and run them with the project's own test command. " +
31
+ "Other sites can't be opened. Never enter passwords, codes or payment details."
32
+
33
+ const text = (value) => [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }]
34
+ const OBJECT = { schema: { type: "object", additionalProperties: true, properties: {} } }
35
+
36
+ /**
37
+ * The tools, on one browser. `readOnly(exec)` refuses acting tools in Read only;
38
+ * `image(exec, jpeg)` returns an image block when the model takes images.
39
+ * @param {{ browser: LocalBrowser, readOnly: (exec: any) => boolean, image: (exec: any, data: Buffer) => Promise<any | undefined> }} host
40
+ */
41
+ export function tools(host) {
42
+ const { browser } = host
43
+ const acting = (exec) => {
44
+ if (host.readOnly(exec)) throw new BrowserError("Read only: the browser can open and read pages, not click or type.")
45
+ }
46
+ return [
47
+ defineTool({
48
+ name: "browser_open",
49
+ description: "Open an app running on this computer in the agent's browser: a local address such as localhost:3000 or http://127.0.0.1:5173/path. Other sites can't be opened.",
50
+ parameters: { url: { type: "string", required: true, description: "The local address, e.g. localhost:3000." } },
51
+ output: { ...OBJECT, render: (_a, v) => text(`Opened ${v.url} (${v.status ?? "no status"}): ${v.title || "untitled"}`) },
52
+ execute: (args) => browser.open(args.url),
53
+ presentCall: (args) => ({ card: "generic", title: "Open in browser", kind: "read", rawInput: String(args.url ?? "") }),
54
+ }),
55
+ defineTool({
56
+ name: "browser_read",
57
+ description: "The open page's address, title, visible text and its interactive elements, each with a ref (e1, e2, …) for browser_click and browser_type.",
58
+ parameters: {},
59
+ output: {
60
+ ...OBJECT,
61
+ render: (_a, v) => text(`${v.title} — ${v.url}\n\nElements:\n${v.elements.map((e) => `${e.ref} ${e.role}${e.type ? `[${e.type}]` : ""} ${JSON.stringify(e.name)}`).join("\n") || "(none)"}\n\nText:\n${v.text}`),
62
+ },
63
+ execute: () => browser.read(),
64
+ presentCall: () => ({ card: "generic", title: "Read the page", kind: "read", rawInput: "" }),
65
+ }),
66
+ defineTool({
67
+ name: "browser_screenshot",
68
+ description: "A screenshot of the open page, to see layout and visual state.",
69
+ parameters: {},
70
+ output: {
71
+ ...OBJECT,
72
+ render: (_a, v) => (v.image ? [{ type: "text", text: `Screenshot of ${v.url} (1280×800)` }, { type: "image", attachment: v.image }] : text(v.note)),
73
+ },
74
+ async execute(_args, exec) {
75
+ const shot = await browser.screenshot()
76
+ const image = await host.image(exec, Buffer.from(shot.data, "base64"))
77
+ return image ? { url: shot.url, image } : { url: shot.url, note: "This model can't take images; use browser_read for the page's text and elements. The person sees the page in the Preview tab." }
78
+ },
79
+ presentCall: () => ({ card: "generic", title: "Screenshot", kind: "read", rawInput: "" }),
80
+ }),
81
+ defineTool({
82
+ name: "browser_click",
83
+ description: "Click an element of the open page by its ref from browser_read. A link out of localhost is refused and the page stays.",
84
+ parameters: { ref: { type: "string", required: true, description: "An element ref from browser_read, e.g. e3." } },
85
+ output: { ...OBJECT, render: (_a, v) => text(`Clicked. Now on ${v.url}: ${v.title || "untitled"}${v.refused ? `. Refused (not local): ${v.refused.join(", ")}` : ""}. Call browser_read to see the result.`) },
86
+ execute(args, exec) {
87
+ acting(exec)
88
+ return browser.click(args.ref)
89
+ },
90
+ presentCall: (args) => ({ card: "generic", title: "Click", kind: "execute", rawInput: String(args.ref ?? "") }),
91
+ }),
92
+ defineTool({
93
+ name: "browser_type",
94
+ description: "Replace the text in an input, textarea or editable element of the open page (ref from browser_read). Never passwords, codes or payment details.",
95
+ parameters: { ref: { type: "string", required: true, description: "An element ref from browser_read." }, text: { type: "string", required: true, description: "The text to put in it." } },
96
+ output: { ...OBJECT, render: (_a, v) => text(`Typed ${v.typed} characters.`) },
97
+ execute(args, exec) {
98
+ acting(exec)
99
+ return browser.type(args.ref, args.text)
100
+ },
101
+ presentCall: (args) => ({ card: "generic", title: "Type", kind: "execute", rawInput: String(args.ref ?? "") }),
102
+ }),
103
+ defineTool({
104
+ name: "browser_press",
105
+ description: "Press a key on the open page, e.g. Enter, Tab, Escape, ArrowDown.",
106
+ parameters: { key: { type: "string", required: true, description: "The key's name." } },
107
+ output: { ...OBJECT, render: (_a, v) => text(`Pressed ${v.pressed}. Now on ${v.url}${v.refused ? `. Refused (not local): ${v.refused.join(", ")}` : ""}.`) },
108
+ execute(args, exec) {
109
+ acting(exec)
110
+ return browser.press(args.key)
111
+ },
112
+ presentCall: (args) => ({ card: "generic", title: "Press a key", kind: "execute", rawInput: String(args.key ?? "") }),
113
+ }),
114
+ defineTool({
115
+ name: "browser_console",
116
+ description: "The open page's console messages and uncaught errors, and any navigations the browser refused, newest last.",
117
+ parameters: {},
118
+ output: { ...OBJECT, render: (_a, v) => text([...v.console.map((m) => `[${m.type}] ${m.text}`), ...v.blocked.map((b) => `[refused] ${b.url}`)].join("\n") || "No console messages.") },
119
+ execute: () => browser.logs(),
120
+ presentCall: () => ({ card: "generic", title: "Console", kind: "read", rawInput: "" }),
121
+ }),
122
+ defineTool({
123
+ name: "browser_network",
124
+ description: "The open page's requests: method, address, status (failed requests have none), newest last.",
125
+ parameters: {},
126
+ output: { schema: { type: "array", items: { type: "object", additionalProperties: true, properties: {} } }, render: (_a, v) => text(v.map((r) => `${r.method} ${r.status ?? `failed (${r.failure ?? "?"})`} ${r.url}`).join("\n") || "No requests.") },
127
+ execute: () => browser.requests(),
128
+ presentCall: () => ({ card: "generic", title: "Network", kind: "read", rawInput: "" }),
129
+ }),
130
+ ]
131
+ }
132
+
133
+ const json = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } })
134
+
135
+ /** The Preview tab's routes: where the browser is, its latest frame, and the person's input */
136
+ export function routes(browser) {
137
+ return {
138
+ [ROUTES.state]: async () => json({ enabled: true, url: browser.current && !browser.current.isClosed() ? browser.current.url() : null }),
139
+ [ROUTES.frame]: async () => {
140
+ const frame = await browser.frame()
141
+ if (!frame) return new Response(null, { status: 204, headers: { "cache-control": "no-store" } })
142
+ return new Response(frame.data, { headers: { "content-type": "image/jpeg", "cache-control": "no-store", "x-kriya-url": encodeURI(frame.url) } })
143
+ },
144
+ [ROUTES.input]: async (request) => {
145
+ let body
146
+ try {
147
+ body = JSON.parse(await request.text())
148
+ } catch {
149
+ return json({ error: "A JSON body is needed." }, 400)
150
+ }
151
+ try {
152
+ if (body?.kind === "open") return json(await browser.open(body.url))
153
+ if (body?.kind === "click" || body?.kind === "wheel") return json(await browser.pointer({ x: Number(body.x), y: Number(body.y), kind: body.kind, deltaY: body.deltaY }))
154
+ if (body?.kind === "key") return json(await browser.press(body.key))
155
+ if (body?.kind === "text") {
156
+ if (typeof body.text !== "string" || body.text.length > 500) return json({ error: "Text is at most 500 characters." }, 400)
157
+ const page = await browser.requireOpen()
158
+ await page.keyboard.type(body.text)
159
+ return json({ typed: body.text.length })
160
+ }
161
+ return json({ error: "Unknown input." }, 400)
162
+ } catch (error) {
163
+ if (error instanceof BrowserError) return json({ error: error.message }, 400)
164
+ throw error
165
+ }
166
+ },
167
+ }
168
+ }
169
+
170
+ export function apply(ctx) {
171
+ // No Chrome, no browser: neither tools nor guidance, so the agent isn't offered what can't start
172
+ if (!chromeInstalled()) {
173
+ ctx.logger("kriya-browser").info("No Chrome, Edge, Brave or Chromium here, so the agent's browser is off")
174
+ return
175
+ }
176
+ const sandboxPolicy = ctx.get("sandboxPolicy")
177
+ const browser = new LocalBrowser({ selfPort: () => ctx.get("webServer")?.port })
178
+ ctx.effect(() => () => browser.close())
179
+ const host = {
180
+ browser,
181
+ readOnly: (exec) => sandboxPolicy?.resolve({ session: exec.agent?.session })?.mode === "read-only",
182
+ // An image block only when the session's model takes images (as DSH's read_image)
183
+ async image(exec, data) {
184
+ const attachments = ctx.get("attachments")
185
+ const llm = ctx.get("llm")
186
+ const routed = exec.agent?.session.requestHeader()?.config
187
+ const provider = routed?.provider ?? exec.agent?.options.provider
188
+ const model = routed?.model ?? exec.agent?.options.model
189
+ if (!attachments || !llm || !provider || !model) return undefined
190
+ const info = await llm.resolveModelInfo(provider, model, exec.signal).catch(() => undefined)
191
+ if (!info?.inputModalities?.includes("image")) return undefined
192
+ const ref = await attachments.saveImage({ data, mediaType: "image/jpeg", name: "browser.jpg" })
193
+ return { attachmentId: ref.attachmentId, mediaType: ref.mediaType, bytes: ref.bytes, width: ref.width, height: ref.height }
194
+ },
195
+ }
196
+ for (const tool of tools(host)) ctx.tools.register(tool)
197
+ const log = (error) => ctx.logger("kriya-browser").warn(error)
198
+ // Only where the web server runs (not in headless kriya run): the view's routes
199
+ ctx.inject(["connection"], (web) => {
200
+ for (const [path, handler] of Object.entries(routes(browser)))
201
+ web.effect(() =>
202
+ web.connection.fetch.register({
203
+ path,
204
+ methods: path === ROUTES.input ? ["POST"] : ["GET"],
205
+ requestBody: "buffered",
206
+ fetch: async (request) => {
207
+ try {
208
+ return await handler(request)
209
+ } catch (error) {
210
+ log(error)
211
+ return json({ error: "The browser couldn't do that; see the terminal for details." }, 500)
212
+ }
213
+ },
214
+ })
215
+ )
216
+ })
217
+ ctx.systemPrompt.section({ name: "tool:kriya_browser", order: ctx.systemPrompt.getSectionOrder("TOOL_BASH"), text: GUIDANCE })
218
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@kriya-ai/harness-browser",
3
+ "description": "The agent's localhost browser for Kriya Harness: tools to test and review apps running on this computer, on the installed Chrome",
4
+ "version": "0.1.0",
5
+ "private": true,
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "license": "UNLICENSED"
13
+ }
@@ -0,0 +1,108 @@
1
+ import { createUserMessage } from "@deepseek-ai/dsh-llm"
2
+
3
+ // The turn budget (harness upgrade U2, KU-ADR-04 in the Kriya repository's
4
+ // docs/kriya-harness/harness_upgradation). DSH's loop has no turn budget of
5
+ // its own (dsh-agent-loop README, "No built-in turn budget"): a model that
6
+ // never stops calling tools runs until the plan's monthly cap. This bounds
7
+ // one turn by code, never by the model: at most `maxSteps` steps, at most
8
+ // `maxMinutes` of wall time, and at most `maxRepeats` identical tool calls
9
+ // in a row (same tool, same arguments; DSH's own reminder only nudges at
10
+ // 3, 5 and 8). Near the step or time limit the agent is told once to wrap
11
+ // up; at a limit the next step is refused, so the turn ends "blocked" and
12
+ // `kriya run` exits 1, never "completed". Per agent, so a step's builder
13
+ // (kriya_step) has its own budget. Off unless kriya was started with
14
+ // --budget (the bundle row's switch).
15
+
16
+ export const name = "kriya-budget"
17
+
18
+ const whole = (value, fallback) => {
19
+ const n = Number(value)
20
+ return Number.isSafeInteger(n) && n > 0 ? n : fallback
21
+ }
22
+
23
+ /** The limits, from the launch environment; defaults when unset or unusable. */
24
+ export function budgetLimits(env = process.env) {
25
+ return {
26
+ maxSteps: whole(env.KRIYA_MAX_STEPS, 150),
27
+ maxMinutes: whole(env.KRIYA_TURN_MINUTES, 60),
28
+ maxRepeats: whole(env.KRIYA_MAX_REPEATS, 10),
29
+ }
30
+ }
31
+
32
+ // The steps left when the agent is told to wrap up
33
+ export const WARN_STEPS = 5
34
+
35
+ // Same tool, same arguments, whatever the key order
36
+ function canonical(value) {
37
+ if (Array.isArray(value)) return value.map(canonical)
38
+ if (value && typeof value === "object")
39
+ return Object.fromEntries(Object.keys(value).sort().map((k) => [k, canonical(value[k])]))
40
+ return value
41
+ }
42
+
43
+ export const warning = (left) =>
44
+ `Kriya's turn budget: about ${left} step${left === 1 ? "" : "s"} left in this turn. Finish the current change, ` +
45
+ "run the check if there is one, and reply with what is done and what isn't. The turn is stopped at the limit."
46
+
47
+ /**
48
+ * The guard's two hooks, free of DSH so they can be tested alone.
49
+ * @param {{ maxSteps: number, maxMinutes: number, maxRepeats: number }} limits
50
+ * @param {{ now?: () => number, message?: (text: string) => any, stopped?: (reason: string) => void }} [host]
51
+ */
52
+ export function budgetGuard(limits, host = {}) {
53
+ const now = host.now ?? Date.now
54
+ const message =
55
+ host.message ??
56
+ ((text) => createUserMessage({ content: [{ type: "text", text }], source: { kind: "kriya-budget", form: "notice", summary: "turn budget" } }))
57
+ /** @type {WeakMap<object, { turn: number, started: number, steps: number, last: string | null, repeats: number, warned: boolean }>} */
58
+ const turns = new WeakMap()
59
+
60
+ return {
61
+ /** agent/pre-step (waterfall): counts steps, warns once, refuses at a limit */
62
+ async preStep({ agent, turn }, next) {
63
+ let s = turns.get(agent)
64
+ if (!s || s.turn !== turn) {
65
+ s = { turn, started: now(), steps: 0, last: null, repeats: 0, warned: false }
66
+ turns.set(agent, s)
67
+ }
68
+ s.steps += 1
69
+ const elapsed = now() - s.started
70
+ const reason =
71
+ s.steps > limits.maxSteps
72
+ ? `${limits.maxSteps} steps`
73
+ : elapsed > limits.maxMinutes * 60_000
74
+ ? `${limits.maxMinutes} minutes`
75
+ : s.repeats >= limits.maxRepeats
76
+ ? `${s.repeats} identical calls in a row`
77
+ : null
78
+ if (reason) {
79
+ host.stopped?.(reason)
80
+ return { kind: "reject" }
81
+ }
82
+ const decision = await next()
83
+ const left = limits.maxSteps - s.steps + 1
84
+ const late = left <= WARN_STEPS || elapsed > limits.maxMinutes * 54_000
85
+ if (s.warned || !late || decision.kind !== "enter") return decision
86
+ s.warned = true
87
+ return { ...decision, messages: [...decision.messages, message(warning(Math.max(1, left)))] }
88
+ },
89
+ /** tools/post-execute (waterfall): counts identical calls in a row */
90
+ async postExecute(exec, _result, next) {
91
+ const s = exec.agent && turns.get(exec.agent)
92
+ if (s) {
93
+ const key = JSON.stringify([exec.name, canonical(exec.arguments ?? null)])
94
+ s.repeats = key === s.last ? s.repeats + 1 : 1
95
+ s.last = key
96
+ }
97
+ return next()
98
+ },
99
+ }
100
+ }
101
+
102
+ export function apply(ctx) {
103
+ const limits = budgetLimits()
104
+ const log = ctx.logger("kriya-budget")
105
+ const guard = budgetGuard(limits, { stopped: (reason) => log.warn(`turn stopped by its budget: ${reason}`) })
106
+ ctx.on("agent/pre-step", guard.preStep)
107
+ ctx.on("tools/post-execute", guard.postExecute)
108
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@kriya-ai/harness-budget",
3
+ "description": "Turn budget for Kriya Harness: bounds the steps, time and identical repeated tool calls of one turn, then lets the agent report and stops it",
4
+ "version": "0.1.0",
5
+ "private": true,
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "license": "UNLICENSED"
13
+ }
@@ -0,0 +1,245 @@
1
+ // The Changes tab, browser half: a right-sidebar page (the seat DSH's own
2
+ // Files tab uses: ctx.sidebarRightTabs.register plus the keyed
3
+ // sidebar.right.pane.tab body) listing every file changed in the session's
4
+ // folder against HEAD, with lines added and removed, and each file's diff.
5
+ // It talks only to this plugin's routes (index.js) on the shared /api
6
+ // channel. Plain React and DSH's theme tokens; no DSH file is edited (HD-02).
7
+ window.__ModuleLoader__.load({
8
+ id: "@kriya-ai/harness-changes",
9
+ factory: (require) => {
10
+ const React = require("react")
11
+ const { useCallback, useEffect, useState } = React
12
+ const h = React.createElement
13
+
14
+ const PLUGIN = "@kriya-ai/harness-changes"
15
+ const KIND = "kriya-changes"
16
+ const API = { list: "api/kriya.changes", diff: "api/kriya.changes.diff" }
17
+ // While the tab is on screen; a hidden tab doesn't poll
18
+ const REFRESH_MS = 4000
19
+
20
+ async function call(url) {
21
+ const response = await fetch(url, { credentials: "same-origin" })
22
+ const data = await response.json().catch(() => ({}))
23
+ if (!response.ok) throw new Error(data.error || `Kriya answered ${response.status}.`)
24
+ return data
25
+ }
26
+
27
+ const CSS = `
28
+ .kh-ch { display: flex; flex-direction: column; height: 100%; min-height: 0; color: var(--dsw-alias-label-primary); font-size: 13px; }
29
+ .kh-ch-head { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--dsw-alias-border-l2); }
30
+ .kh-ch-sum { flex: 1; min-width: 0; color: var(--dsw-alias-label-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
31
+ .kh-ch-sum b { color: var(--dsw-alias-label-primary); font-weight: 600; }
32
+ .kh-ch-btn { min-width: 44px; min-height: 44px; border: 0; border-radius: 10px; background: transparent; color: inherit; font: inherit; cursor: pointer; display: grid; place-items: center; }
33
+ .kh-ch-btn:hover { background: var(--dsw-alias-interactive-bg-hover); }
34
+ .kh-ch-btn:focus-visible, .kh-ch-row:focus-visible { outline: 2px solid var(--dsw-alias-link); outline-offset: -2px; }
35
+ .kh-ch-list { overflow: auto; flex: 0 1 auto; max-height: 45%; border-bottom: 1px solid var(--dsw-alias-border-l2); }
36
+ .kh-ch-list.full { max-height: none; flex: 1; border-bottom: 0; }
37
+ .kh-ch-row { display: flex; align-items: center; gap: 8px; width: 100%; min-height: 36px; padding: 4px 12px; border: 0; background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; }
38
+ .kh-ch-row:hover { background: var(--dsw-alias-interactive-bg-hover); }
39
+ .kh-ch-row[aria-current="true"] { background: var(--dsw-specific-sidebar-nav-item-active, var(--dsw-alias-interactive-bg-active)); }
40
+ .kh-ch-st { flex: none; width: 18px; height: 18px; border-radius: 5px; display: grid; place-items: center; font-size: 11px; font-weight: 700; font-family: var(--dsw-font-code, ui-monospace, monospace); }
41
+ .kh-ch-st.added { color: var(--dsw-alias-state-success-primary); background: var(--dsw-alias-state-success-tertiary); }
42
+ .kh-ch-st.deleted, .kh-ch-st.conflict { color: var(--dsw-alias-state-error-primary); background: var(--dsw-alias-interactive-bg-hover-danger); }
43
+ .kh-ch-st.modified, .kh-ch-st.renamed { color: var(--dsw-alias-state-warn-label); background: var(--dsw-alias-state-warn-tertiary); }
44
+ .kh-ch-path { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; direction: rtl; text-align: left; font-family: var(--dsw-font-code, ui-monospace, monospace); font-size: 12px; }
45
+ .kh-ch-path span { direction: ltr; unicode-bidi: plaintext; }
46
+ .kh-ch-dir { color: var(--dsw-alias-label-tertiary); }
47
+ .kh-ch-n { flex: none; font-family: var(--dsw-font-code, ui-monospace, monospace); font-size: 11.5px; }
48
+ .kh-ch-plus { color: var(--dsw-alias-state-success-primary); }
49
+ .kh-ch-minus { color: var(--dsw-alias-state-error-primary); margin-left: 6px; }
50
+ .kh-ch-diff { flex: 1; min-height: 0; overflow: auto; margin: 0; padding: 8px 0; font-family: var(--dsw-font-code, ui-monospace, monospace); font-size: 12px; line-height: 1.55; }
51
+ .kh-ch-line { display: block; padding: 0 12px; white-space: pre; min-width: max-content; }
52
+ .kh-ch-line.add { background: var(--dsw-alias-state-success-tertiary); }
53
+ .kh-ch-line.del { background: var(--dsw-alias-interactive-bg-hover-danger); }
54
+ .kh-ch-line.hunk { color: var(--dsw-alias-label-tertiary); background: var(--dsw-alias-bg-layer-1); }
55
+ .kh-ch-line.meta { color: var(--dsw-alias-label-tertiary); }
56
+ .kh-ch-note { padding: 16px 12px; color: var(--dsw-alias-label-tertiary); line-height: 1.5; }
57
+ .kh-ch-error { padding: 12px; color: var(--dsw-alias-state-error-primary); }
58
+ `
59
+
60
+ function installStyles() {
61
+ const tag = document.createElement("style")
62
+ tag.dataset.plugin = PLUGIN
63
+ tag.textContent = CSS
64
+ document.head.appendChild(tag)
65
+ return () => tag.remove()
66
+ }
67
+
68
+ // Two pages with a plus and a minus: what changed
69
+ function ChangesIcon({ size = 20 }) {
70
+ return h(
71
+ "svg",
72
+ { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true },
73
+ h("path", { d: "M8 3h7l4 4v11a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z" }),
74
+ h("path", { d: "M10 9.5h5M12.5 7v5" }),
75
+ h("path", { d: "M10 15.5h5" })
76
+ )
77
+ }
78
+
79
+ function RefreshIcon() {
80
+ return h(
81
+ "svg",
82
+ { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true },
83
+ h("path", { d: "M20 11a8 8 0 1 0-2.3 5.7" }),
84
+ h("path", { d: "M20 4v7h-7" })
85
+ )
86
+ }
87
+
88
+ const LETTER = { added: "A", modified: "M", deleted: "D", renamed: "R", conflict: "U" }
89
+
90
+ function splitPath(path) {
91
+ const at = path.lastIndexOf("/")
92
+ return at < 0 ? ["", path] : [path.slice(0, at + 1), path.slice(at + 1)]
93
+ }
94
+
95
+ function lineClass(line) {
96
+ if (line.startsWith("@@")) return "kh-ch-line hunk"
97
+ if (/^(diff --git|index |--- |\+\+\+ |new file|deleted file|similarity|rename |old mode|new mode)/.test(line)) return "kh-ch-line meta"
98
+ if (line.startsWith("+")) return "kh-ch-line add"
99
+ if (line.startsWith("-")) return "kh-ch-line del"
100
+ return "kh-ch-line"
101
+ }
102
+
103
+ function ChangesBody({ useTabInfo, sessionId }) {
104
+ const { tab } = useTabInfo()
105
+ const visible = tab?.visible !== false
106
+ const [data, setData] = useState(null)
107
+ const [error, setError] = useState(null)
108
+ const [selected, setSelected] = useState(null)
109
+ const [diff, setDiff] = useState(null)
110
+ const [diffError, setDiffError] = useState(null)
111
+
112
+ const load = useCallback(async () => {
113
+ if (!sessionId) return
114
+ try {
115
+ setData(await call(`${API.list}?${new URLSearchParams({ session: sessionId })}`))
116
+ setError(null)
117
+ } catch (e) {
118
+ setError(e.message)
119
+ }
120
+ }, [sessionId])
121
+
122
+ useEffect(() => {
123
+ if (!visible) return
124
+ load()
125
+ const timer = setInterval(load, REFRESH_MS)
126
+ return () => clearInterval(timer)
127
+ }, [load, visible])
128
+
129
+ // The open file's diff follows the list: reloaded when its counts move
130
+ const current = data?.files?.find((f) => f.path === selected)
131
+ const stamp = current ? `${current.status}:${current.added}:${current.deleted}` : null
132
+ useEffect(() => {
133
+ if (!selected || !stamp) {
134
+ setDiff(null)
135
+ return
136
+ }
137
+ let gone = false
138
+ call(`${API.diff}?${new URLSearchParams({ session: sessionId, path: selected })}`).then(
139
+ (d) => !gone && (setDiff(d), setDiffError(null)),
140
+ (e) => !gone && setDiffError(e.message)
141
+ )
142
+ return () => {
143
+ gone = true
144
+ }
145
+ }, [selected, stamp, sessionId])
146
+
147
+ const head = h(
148
+ "div",
149
+ { className: "kh-ch-head" },
150
+ h(
151
+ "div",
152
+ { className: "kh-ch-sum", role: "status" },
153
+ data?.git
154
+ ? [
155
+ h("b", { key: "n" }, `${data.files.length}${data.truncated ? "+" : ""} file${data.files.length === 1 ? "" : "s"}`),
156
+ " changed ",
157
+ h("span", { key: "a", className: "kh-ch-plus" }, `+${data.added}`),
158
+ h("span", { key: "d", className: "kh-ch-minus" }, `−${data.deleted}`),
159
+ data.branch ? ` · ${data.branch}` : data.shadow ? " · this session" : "",
160
+ ]
161
+ : "Changes"
162
+ ),
163
+ h("button", { className: "kh-ch-btn", type: "button", onClick: load, "aria-label": "Refresh changes", title: "Refresh" }, h(RefreshIcon))
164
+ )
165
+
166
+ let body
167
+ if (error) body = h("div", { className: "kh-ch-error", role: "alert" }, error)
168
+ else if (!data) body = h("div", { className: "kh-ch-note" }, "Reading changes…")
169
+ else if (!data.git) body = h("div", { className: "kh-ch-note" }, "Kriya doesn't track changes in your home folder or a drive root. Open a project folder to see what the agent changes.")
170
+ else if (data.files.length === 0)
171
+ body = h(
172
+ "div",
173
+ { className: "kh-ch-note" },
174
+ data.shadow
175
+ ? "Nothing changed in this session yet. This folder isn't a git repository, so Kriya keeps its own record from the agent's first change; your folder gets no .git."
176
+ : "No changes against the last commit."
177
+ )
178
+ else
179
+ body = [
180
+ h(
181
+ "nav",
182
+ { key: "list", className: selected ? "kh-ch-list" : "kh-ch-list full", "aria-label": "Changed files" },
183
+ ...data.files.map((f) => {
184
+ const [dir, base] = splitPath(f.path)
185
+ return h(
186
+ "button",
187
+ {
188
+ key: f.path,
189
+ type: "button",
190
+ className: "kh-ch-row",
191
+ "aria-current": selected === f.path ? "true" : undefined,
192
+ "aria-label": `${f.path}, ${f.status}${f.binary ? ", binary" : f.added === undefined ? "" : `, ${f.added} added, ${f.deleted} removed`}`,
193
+ title: f.from ? `${f.from} → ${f.path}` : f.path,
194
+ onClick: () => setSelected(selected === f.path ? null : f.path),
195
+ },
196
+ h("span", { className: `kh-ch-st ${f.status}`, "aria-hidden": true }, LETTER[f.status] ?? "M"),
197
+ h("span", { className: "kh-ch-path" }, h("span", null, h("span", { className: "kh-ch-dir" }, dir), base)),
198
+ h(
199
+ "span",
200
+ { className: "kh-ch-n", "aria-hidden": true },
201
+ f.binary ? "binary" : f.added === undefined ? "" : [h("span", { key: "a", className: "kh-ch-plus" }, `+${f.added}`), h("span", { key: "d", className: "kh-ch-minus" }, `−${f.deleted}`)]
202
+ )
203
+ )
204
+ })
205
+ ),
206
+ selected &&
207
+ (diffError
208
+ ? h("div", { key: "e", className: "kh-ch-error", role: "alert" }, diffError)
209
+ : !diff
210
+ ? h("div", { key: "l", className: "kh-ch-note" }, "Loading the diff…")
211
+ : diff.binary
212
+ ? h("div", { key: "b", className: "kh-ch-note" }, "A binary file: no line diff.")
213
+ : h(
214
+ "pre",
215
+ { key: "d", className: "kh-ch-diff", tabIndex: 0, "aria-label": `Diff of ${selected}` },
216
+ ...diff.diff.split("\n").map((line, i) => h("span", { key: i, className: lineClass(line) }, line || " ")),
217
+ diff.truncated && h("span", { className: "kh-ch-line meta" }, "… the rest of this diff is too long to show here.")
218
+ )),
219
+ ]
220
+
221
+ return h("div", { className: "kh-ch" }, head, body)
222
+ }
223
+
224
+ const definition = {
225
+ id: PLUGIN,
226
+ kind: KIND,
227
+ priority: "extension",
228
+ title: () => "Changes",
229
+ guide: [{ id: "changes", order: 15, title: () => "Changes", description: () => "What changed in this folder, file by file", icon: ChangesIcon }],
230
+ }
231
+
232
+ const inject = ["slots", "sidebarRightTabs"]
233
+
234
+ function apply(ctx) {
235
+ if (typeof document !== "undefined") ctx.effect(installStyles, "kriya-changes: styles")
236
+ ctx.effect(() => ctx.sidebarRightTabs.register(definition), "kriya-changes: type")
237
+ ctx.effect(
238
+ () => ctx.slots.inject("sidebar.right.pane.tab", () => ctx.slots.register({ name: "sidebar.right.pane.tab", key: PLUGIN }, ChangesBody)),
239
+ "kriya-changes: body"
240
+ )
241
+ }
242
+
243
+ return { apply, inject, ChangesBody, definition, API, lineClass }
244
+ },
245
+ })