@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,23 @@
1
+ {
2
+ "name": "@kriya-ai/harness-skills",
3
+ "description": "The Skills page of the Kriya Harness Web UI: see, add, copy and edit the agent's SKILL.md skills",
4
+ "version": "0.1.0",
5
+ "private": true,
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./client": "./client.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "dsh": {
14
+ "client": {
15
+ "inject": [
16
+ "@deepseek-ai/dsh-client-ui-layout",
17
+ "@deepseek-ai/dsh-client-ui-sidebar"
18
+ ],
19
+ "platform": "web"
20
+ }
21
+ },
22
+ "license": "UNLICENSED"
23
+ }
package/src/api.js ADDED
@@ -0,0 +1,97 @@
1
+ import { CLIENT_VERSION } from "./paths.js"
2
+
3
+ // The Kriya Harness API client (docs/kriya-harness/API_AND_CONTRACTS.md in
4
+ // the Kriya repository; the same contract as contract/contract.json). Every
5
+ // request carries X-Kriya-Harness; authenticated ones the device token.
6
+ // Errors come back as { error, message } and are thrown as KriyaError.
7
+
8
+ export const BASE_PATH = "/api/harness/v1"
9
+
10
+ export class KriyaError extends Error {
11
+ /**
12
+ * @param {number} status
13
+ * @param {string} code
14
+ * @param {string} message
15
+ * @param {Record<string, unknown>} [extra]
16
+ */
17
+ constructor(status, code, message, extra = {}) {
18
+ super(message)
19
+ this.status = status
20
+ this.code = code
21
+ this.extra = extra
22
+ }
23
+ }
24
+
25
+ /**
26
+ * @param {string} url Kriya origin
27
+ * @param {string} method
28
+ * @param {string} path below BASE_PATH
29
+ * @param {{ token?: string, body?: unknown, signal?: AbortSignal, headers?: Record<string, string>, raw?: boolean }} [options]
30
+ * `raw`: the Response itself for 2xx and 304 (a skill body, an ETag check, a checkpoint)
31
+ * A FormData body goes as multipart (fetch sets the boundary); anything else as JSON
32
+ */
33
+ export async function call(url, method, path, { token, body, bodyText, signal, headers: extra = {}, raw = false } = {}) {
34
+ const headers = { "X-Kriya-Harness": CLIENT_VERSION, Accept: "application/json", ...extra }
35
+ if (token) headers.Authorization = `Bearer ${token}`
36
+ const form = body instanceof FormData
37
+ if (body !== undefined && !form && bodyText === undefined) headers["Content-Type"] = "application/json"
38
+ let response
39
+ try {
40
+ response = await fetch(`${url}${BASE_PATH}${path}`, {
41
+ method,
42
+ headers,
43
+ // bodyText: sent as given, with the caller's own Content-Type (e.g. an encoded body)
44
+ body: bodyText !== undefined ? bodyText : body === undefined || form ? body : JSON.stringify(body),
45
+ signal: signal ?? AbortSignal.timeout(30_000),
46
+ })
47
+ } catch (error) {
48
+ throw new KriyaError(0, "network", `Couldn't reach ${url} (${error?.cause?.code ?? error?.name ?? "network error"}).`)
49
+ }
50
+ if (raw && (response.ok || response.status === 304)) return response
51
+ if (response.status === 204) return null
52
+ const text = await response.text()
53
+ let data = null
54
+ try {
55
+ data = text ? JSON.parse(text) : null
56
+ } catch {
57
+ // Not JSON: a proxy page or an outage; reported below without its body
58
+ }
59
+ if (!response.ok) {
60
+ const { error, message, ...extra } = data && typeof data === "object" ? data : {}
61
+ throw new KriyaError(
62
+ response.status,
63
+ typeof error === "string" ? error : "http_error",
64
+ typeof message === "string" ? message : `Kriya answered ${response.status}.`,
65
+ extra
66
+ )
67
+ }
68
+ return data
69
+ }
70
+
71
+ /**
72
+ * Inside DSH: the signed-in device, from the variables the launcher sets
73
+ * (src/launch.js), for the Kriya plugins. Null when signed out.
74
+ */
75
+ export function deviceFromEnv(env = process.env) {
76
+ const token = env.KRIYA_DEVICE_TOKEN
77
+ const gateway = env.KRIYA_GATEWAY_URL
78
+ if (!token || !gateway?.endsWith(BASE_PATH)) return null
79
+ return { token, url: gateway.slice(0, -BASE_PATH.length) }
80
+ }
81
+
82
+ /** @param {string} url @param {{ deviceName: string, platform: string }} device */
83
+ export const deviceCode = (url, device) =>
84
+ call(url, "POST", "/device/code", { body: { ...device, clientVersion: CLIENT_VERSION } })
85
+
86
+ /** @param {string} url @param {string} code */
87
+ export const deviceToken = (url, code) =>
88
+ call(url, "POST", "/device/token", { body: { deviceCode: code } })
89
+
90
+ /** @param {string} url @param {string} token */
91
+ export const me = (url, token) => call(url, "GET", "/me", { token })
92
+
93
+ /** @param {string} url @param {string} token */
94
+ export const models = (url, token) => call(url, "GET", "/models", { token })
95
+
96
+ /** @param {string} url @param {string} token */
97
+ export const revokeDevice = (url, token) => call(url, "DELETE", "/device", { token })
package/src/browser.js ADDED
@@ -0,0 +1,286 @@
1
+ import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs"
2
+ import { tmpdir } from "node:os"
3
+ import { join } from "node:path"
4
+
5
+ import { kriyaHome } from "./paths.js"
6
+
7
+ // The agent's localhost browser (browser stage 2; WORKSPACE_PANEL_SKILLS_PLUGINS.md
8
+ // §3b in the Kriya repository): the Chrome already on this computer, driven
9
+ // through playwright-core, headless, with its own profile in
10
+ // ~/.kriya/browser/. It opens only apps on this computer: every navigation
11
+ // request (any frame) must be a loopback http(s) address that isn't Kriya
12
+ // Harness's own port, or it is aborted before it is sent. A page's other
13
+ // requests (fonts, its own API calls) are allowed. One browser and one page
14
+ // per harness process, shared by the agent's tools and the person's view.
15
+
16
+ export class BrowserError extends Error {}
17
+
18
+ // Where Google Chrome lives on macOS, Linux and Windows (playwright's "chrome" channel uses the same)
19
+ export const CHROME_PATHS = [
20
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
21
+ "/usr/bin/google-chrome",
22
+ "/usr/bin/google-chrome-stable",
23
+ "/opt/google/chrome/chrome",
24
+ ...(process.env.LOCALAPPDATA ? [join(process.env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe")] : []),
25
+ ...(process.env.PROGRAMFILES ? [join(process.env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe")] : []),
26
+ ...(process.env["PROGRAMFILES(X86)"] ? [join(process.env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe")] : []),
27
+ ]
28
+
29
+ // Other Chromium browsers, used when Google Chrome isn't there
30
+ export const CHROMIUM_PATHS = [
31
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
32
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
33
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
34
+ "/usr/bin/microsoft-edge",
35
+ "/usr/bin/brave-browser",
36
+ "/usr/bin/chromium",
37
+ "/usr/bin/chromium-browser",
38
+ "/snap/bin/chromium",
39
+ ...(process.env["PROGRAMFILES(X86)"] ? [join(process.env["PROGRAMFILES(X86)"], "Microsoft", "Edge", "Application", "msedge.exe")] : []),
40
+ ]
41
+
42
+ /** What the agent's browser launches with: Google Chrome's channel, else another Chromium browser, else null */
43
+ export function browserTarget(exists = existsSync, chrome = CHROME_PATHS, others = CHROMIUM_PATHS) {
44
+ if (chrome.some((p) => exists(p))) return { channel: "chrome" }
45
+ const executablePath = others.find((p) => exists(p))
46
+ return executablePath ? { executablePath } : null
47
+ }
48
+
49
+ /** Whether a browser the agent can use is installed */
50
+ export const chromeInstalled = (exists = existsSync, paths = CHROME_PATHS, others = CHROMIUM_PATHS) => browserTarget(exists, paths, others) !== null
51
+
52
+ // Chrome allows one process per profile; `kriya` and a task from Kriya can run at once
53
+ const PROFILE_BUSY = /ProcessSingleton|SingletonLock|profile.*(in use|already)|user data directory is already/i
54
+
55
+ const RING = 200
56
+ const TEXT_LIMIT = 8000
57
+ const ELEMENTS = 150
58
+ export const VIEWPORT = { width: 1280, height: 800 }
59
+
60
+ /**
61
+ * A loopback http(s) address to open, normalised, or { error }. The same
62
+ * rule as the Preview tab (plugins/preview/client.js previewUrl).
63
+ * @param {unknown} input
64
+ * @param {{ selfPort?: string }} [self] the Web UI's own port, refused
65
+ */
66
+ export function localUrl(input, { selfPort } = {}) {
67
+ let text = typeof input === "string" ? input.trim() : ""
68
+ if (!text) return { error: "Give a local address, e.g. localhost:3000." }
69
+ if (/^\d{2,5}(\/|$)/.test(text)) text = `localhost:${text}`
70
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) text = `http://${text}`
71
+ let url
72
+ try {
73
+ url = new URL(text)
74
+ } catch {
75
+ return { error: "That isn't an address." }
76
+ }
77
+ if (url.protocol !== "http:" && url.protocol !== "https:") return { error: "Only http and https addresses." }
78
+ if (url.username || url.password) return { error: "Addresses with a user name or password aren't opened." }
79
+ const host = url.hostname.replace(/^\[|\]$/g, "")
80
+ const loopback = host === "localhost" || host.endsWith(".localhost") || host === "::1" || /^127(\.\d{1,3}){3}$/.test(host)
81
+ if (!loopback) return { error: "This browser opens apps on this computer only (localhost)." }
82
+ const port = url.port || (url.protocol === "https:" ? "443" : "80")
83
+ if (selfPort && port === String(selfPort)) return { error: "That's Kriya Harness itself; open your app's port instead." }
84
+ return { url: url.href }
85
+ }
86
+
87
+ const push = (ring, item) => {
88
+ ring.push(item)
89
+ if (ring.length > RING) ring.shift()
90
+ }
91
+
92
+ // Elements a person or test would act on, in page order
93
+ const INTERACTIVE = "a[href], button, input:not([type=hidden]), select, textarea, summary, [role=button], [role=link], [role=checkbox], [role=tab], [role=menuitem], [contenteditable=true], [onclick]"
94
+
95
+ export class LocalBrowser {
96
+ /**
97
+ * @param {{ selfPort?: string | (() => string | number | undefined), profileDir?: string, launch?: (dir: string, options: object) => Promise<any> }} [options]
98
+ * selfPort: the Web UI's own port (or a getter, read when a page is opened), refused
99
+ * launch: playwright's chromium.launchPersistentContext (injected for tests)
100
+ */
101
+ constructor({ selfPort, profileDir = join(kriyaHome(), "browser", "profile"), launch } = {}) {
102
+ this.port = typeof selfPort === "function" ? selfPort : () => selfPort
103
+ this.profileDir = profileDir
104
+ this.launch = launch
105
+ this.console = []
106
+ this.network = []
107
+ this.refs = []
108
+ this.blocked = []
109
+ this.starting = undefined
110
+ }
111
+
112
+ /** The page, starting Chrome on first use */
113
+ async page() {
114
+ if (this.current && !this.current.isClosed()) return this.current
115
+ this.starting ??= this.start().finally(() => (this.starting = undefined))
116
+ return this.starting
117
+ }
118
+
119
+ async start() {
120
+ let launch = this.launch
121
+ if (!launch) {
122
+ const { chromium } = await import("playwright-core")
123
+ launch = (dir, options) => chromium.launchPersistentContext(dir, options)
124
+ }
125
+ mkdirSync(this.profileDir, { recursive: true, mode: 0o700 })
126
+ const options = {
127
+ ...(browserTarget() ?? { channel: "chrome" }),
128
+ headless: true,
129
+ viewport: VIEWPORT,
130
+ acceptDownloads: false,
131
+ // Nothing of the person's: no extensions, no sync, no first-run calls home
132
+ args: ["--no-first-run", "--disable-sync", "--disable-extensions", "--disable-background-networking", "--disable-component-update"],
133
+ }
134
+ try {
135
+ try {
136
+ this.context = await launch(this.profileDir, options)
137
+ } catch (error) {
138
+ if (!PROFILE_BUSY.test(String(error?.message))) throw error
139
+ // Another kriya has the profile open: this process gets its own for this run
140
+ this.spareProfile = mkdtempSync(join(tmpdir(), "kriya-browser-"))
141
+ this.context = await launch(this.spareProfile, options)
142
+ }
143
+ } catch (error) {
144
+ throw new BrowserError(
145
+ /executable|channel|not found|ENOENT/i.test(String(error?.message)) ? "No Chrome, Edge, Brave or Chromium on this computer; the agent's browser needs one." : `Chrome didn't start: ${String(error?.message ?? error).split("\n")[0]}`
146
+ )
147
+ }
148
+ await this.context.route("**/*", (route) => {
149
+ const request = route.request()
150
+ if (request.isNavigationRequest() && localUrl(request.url(), { selfPort: this.port()?.toString() }).error) {
151
+ push(this.blocked, { at: Date.now(), url: request.url().slice(0, 300) })
152
+ return route.abort("blockedbyclient")
153
+ }
154
+ return route.continue()
155
+ })
156
+ const page = this.context.pages()[0] ?? (await this.context.newPage())
157
+ page.on("framenavigated", (frame) => {
158
+ if (frame === page.mainFrame() && !localUrl(frame.url(), { selfPort: this.port()?.toString() }).error) this.lastLocal = frame.url()
159
+ })
160
+ page.on("console", (m) => push(this.console, { at: Date.now(), type: m.type(), text: m.text().slice(0, 1000) }))
161
+ page.on("pageerror", (e) => push(this.console, { at: Date.now(), type: "error", text: String(e?.message ?? e).slice(0, 1000) }))
162
+ page.on("response", (r) => push(this.network, { at: Date.now(), method: r.request().method(), url: r.url().slice(0, 300), status: r.status() }))
163
+ page.on("requestfailed", (r) => push(this.network, { at: Date.now(), method: r.method(), url: r.url().slice(0, 300), status: null, failure: r.failure()?.errorText }))
164
+ this.current = page
165
+ return page
166
+ }
167
+
168
+ /** Opens a local address; anything else is refused before Chrome sees it */
169
+ async open(input) {
170
+ const { url, error } = localUrl(input, { selfPort: this.port()?.toString() })
171
+ if (error) throw new BrowserError(error)
172
+ const page = await this.page()
173
+ try {
174
+ const response = await page.goto(url, { waitUntil: "load", timeout: 30_000 })
175
+ return { url: page.url(), title: await page.title(), status: response?.status() ?? null }
176
+ } catch (error) {
177
+ throw new BrowserError(/ERR_CONNECTION_REFUSED/.test(String(error?.message)) ? `Nothing is listening at ${url}: is the app running?` : `Couldn't open ${url}: ${String(error?.message ?? error).split("\n")[0]}`)
178
+ }
179
+ }
180
+
181
+ /**
182
+ * After an action: a navigation refused by the guard leaves Chrome on its
183
+ * error page, so go back to the last local page and say what was refused.
184
+ */
185
+ async settle(page, since) {
186
+ await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => {})
187
+ const refused = this.blocked.filter((b) => b.at >= since).map((b) => b.url)
188
+ if (page.url().startsWith("chrome-error://") && this.lastLocal) await page.goto(this.lastLocal, { waitUntil: "load", timeout: 30_000 }).catch(() => {})
189
+ return { url: page.url(), title: await page.title(), ...(refused.length && { refused }) }
190
+ }
191
+
192
+ async requireOpen() {
193
+ const page = await this.page()
194
+ if (page.url() === "about:blank") throw new BrowserError("No page is open: call browser_open with your app's local address first.")
195
+ return page
196
+ }
197
+
198
+ /** The page's text and the elements on it, each with a ref for click and type */
199
+ async read() {
200
+ const page = await this.requireOpen()
201
+ const handles = await page.$$(INTERACTIVE)
202
+ const elements = []
203
+ this.refs = []
204
+ for (const handle of handles) {
205
+ if (elements.length >= ELEMENTS) break
206
+ const info = await handle.evaluate((el) => {
207
+ const r = el.getBoundingClientRect()
208
+ const label = el.getAttribute("aria-label") || el.innerText || el.value || el.getAttribute("placeholder") || el.getAttribute("title") || el.getAttribute("name") || ""
209
+ return { visible: r.width > 0 && r.height > 0, role: el.getAttribute("role") || el.tagName.toLowerCase(), type: el.getAttribute("type") || undefined, name: String(label).replace(/\s+/g, " ").trim().slice(0, 80) }
210
+ })
211
+ if (!info.visible) continue
212
+ this.refs.push(handle)
213
+ elements.push({ ref: `e${this.refs.length}`, role: info.role, ...(info.type && { type: info.type }), name: info.name })
214
+ }
215
+ const text = (await page.evaluate(() => document.body?.innerText ?? "")).replace(/\n{3,}/g, "\n\n").trim()
216
+ return { url: page.url(), title: await page.title(), text: text.length > TEXT_LIMIT ? `${text.slice(0, TEXT_LIMIT)}\n… (cut)` : text, elements }
217
+ }
218
+
219
+ handle(ref) {
220
+ const n = /^e(\d+)$/.exec(String(ref ?? ""))?.[1]
221
+ const handle = n && this.refs[Number(n) - 1]
222
+ if (!handle) throw new BrowserError("Unknown element ref: call browser_read first and use one of its refs.")
223
+ return handle
224
+ }
225
+
226
+ async click(ref) {
227
+ const page = await this.requireOpen()
228
+ const since = Date.now()
229
+ await this.handle(ref).click({ timeout: 10_000 })
230
+ return this.settle(page, since)
231
+ }
232
+
233
+ async type(ref, text) {
234
+ await this.requireOpen()
235
+ if (typeof text !== "string" || text.length > 2000) throw new BrowserError("Text to type is a string of at most 2000 characters.")
236
+ await this.handle(ref).fill(text, { timeout: 10_000 })
237
+ return { typed: text.length }
238
+ }
239
+
240
+ async press(key) {
241
+ const page = await this.requireOpen()
242
+ if (typeof key !== "string" || !/^[A-Za-z0-9+]{1,30}$/.test(key)) throw new BrowserError("A key is a name like Enter, Tab, Escape or ArrowDown.")
243
+ const since = Date.now()
244
+ await page.keyboard.press(key)
245
+ return { pressed: key, ...(await this.settle(page, since)) }
246
+ }
247
+
248
+ /** A JPEG of the visible page, base64 */
249
+ async screenshot() {
250
+ const page = await this.requireOpen()
251
+ return { url: page.url(), mimeType: "image/jpeg", data: (await page.screenshot({ type: "jpeg", quality: 70 })).toString("base64") }
252
+ }
253
+
254
+ /** The person's view: a JPEG of whatever is open (blank before anything is), and where */
255
+ async frame() {
256
+ if (!this.current || this.current.isClosed()) return undefined
257
+ const page = this.current
258
+ return { url: page.url(), data: await page.screenshot({ type: "jpeg", quality: 60 }) }
259
+ }
260
+
261
+ /** The person clicks or scrolls the view at x, y in page pixels */
262
+ async pointer({ x, y, kind = "click", deltaY = 0 }) {
263
+ const page = await this.requireOpen()
264
+ if (![x, y].every((v) => Number.isFinite(v) && v >= 0 && v <= 10_000)) throw new BrowserError("A point is two numbers in the page.")
265
+ const since = Date.now()
266
+ if (kind === "wheel") await page.mouse.wheel(0, Math.max(-5000, Math.min(5000, Number(deltaY) || 0)))
267
+ else await page.mouse.click(x, y)
268
+ return this.settle(page, since)
269
+ }
270
+
271
+ logs({ since = 0 } = {}) {
272
+ return { console: this.console.filter((m) => m.at > since), blocked: this.blocked.filter((b) => b.at > since) }
273
+ }
274
+
275
+ requests({ since = 0 } = {}) {
276
+ return this.network.filter((r) => r.at > since)
277
+ }
278
+
279
+ async close() {
280
+ const context = this.context
281
+ this.context = this.current = undefined
282
+ await context?.close().catch(() => {})
283
+ if (this.spareProfile) rmSync(this.spareProfile, { recursive: true, force: true })
284
+ this.spareProfile = undefined
285
+ }
286
+ }
package/src/changes.js ADDED
@@ -0,0 +1,191 @@
1
+ import { execFile } from "node:child_process"
2
+ import { lstatSync, openSync, readSync, closeSync } from "node:fs"
3
+ import { join } from "node:path"
4
+ import { promisify } from "node:util"
5
+
6
+ import { sessionBase, snapshot, trackedRoot, treeChanges, treeFileDiff } from "./checkpoints.js"
7
+
8
+ // The Changes tab (plugins/changes): what the agent (or you) changed in a
9
+ // session's folder, as git sees it against HEAD — staged, unstaged and
10
+ // untracked together, like a review. Read-only: git is run with an argument
11
+ // array (never a shell), without optional locks, and a file's diff is only
12
+ // ever produced for a path git itself listed as changed.
13
+
14
+ const run = promisify(execFile)
15
+ // git's own tree for "nothing": the base of a repository with no commit yet
16
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
17
+ const MAX_FILES = 500
18
+ const MAX_DIFF_BYTES = 512 * 1024
19
+ // Untracked files are counted by reading them; bigger ones show no line count
20
+ const MAX_COUNT_BYTES = 1024 * 1024
21
+
22
+ export class ChangesError extends Error {}
23
+
24
+ async function git(root, args, { okCodes = [0], maxBuffer = 8 * 1024 * 1024 } = {}) {
25
+ try {
26
+ const { stdout } = await run("git", ["-C", root, ...args], {
27
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C" },
28
+ maxBuffer,
29
+ timeout: 15_000,
30
+ })
31
+ return stdout
32
+ } catch (error) {
33
+ // `git diff --no-index` exits 1 when the files differ
34
+ if (okCodes.includes(error.code) && typeof error.stdout === "string") return error.stdout
35
+ throw error
36
+ }
37
+ }
38
+
39
+ /** The repository holding `cwd`, or null when it isn't in one (or git is missing). */
40
+ export async function repoRoot(cwd) {
41
+ try {
42
+ return (await git(cwd, ["rev-parse", "--show-toplevel"])).trim() || null
43
+ } catch {
44
+ return null
45
+ }
46
+ }
47
+
48
+ async function base(root) {
49
+ try {
50
+ await git(root, ["rev-parse", "--verify", "--quiet", "HEAD"])
51
+ return "HEAD"
52
+ } catch {
53
+ return EMPTY_TREE
54
+ }
55
+ }
56
+
57
+ // `git status --porcelain=v1 -z`: "XY path\0", renames add "orig\0"
58
+ function parseStatus(text) {
59
+ const out = []
60
+ const parts = text.split("\0")
61
+ for (let i = 0; i < parts.length; i++) {
62
+ const entry = parts[i]
63
+ if (entry.length < 4) continue
64
+ const x = entry[0]
65
+ const y = entry[1]
66
+ const path = entry.slice(3)
67
+ const renamed = x === "R" || x === "C"
68
+ const from = renamed ? parts[++i] : undefined
69
+ const status =
70
+ x === "?" ? "added" : x === "D" || y === "D" ? "deleted" : renamed ? "renamed" : x === "A" ? "added" : x === "U" || y === "U" ? "conflict" : "modified"
71
+ out.push({ path, status, untracked: x === "?", ...(from && { from }) })
72
+ }
73
+ return out
74
+ }
75
+
76
+ // `git diff --numstat -z`: "added\tdeleted\tpath\0" or, for a rename,
77
+ // "added\tdeleted\t\0from\0to\0"; binary files show "-\t-"
78
+ function parseNumstat(text) {
79
+ const counts = new Map()
80
+ const parts = text.split("\0")
81
+ for (let i = 0; i < parts.length; i++) {
82
+ const match = /^(-|\d+)\t(-|\d+)\t(.*)$/s.exec(parts[i])
83
+ if (!match) continue
84
+ let path = match[3]
85
+ if (path === "") {
86
+ i++
87
+ path = parts[++i]
88
+ }
89
+ counts.set(path, match[1] === "-" ? { binary: true } : { added: Number(match[1]), deleted: Number(match[2]) })
90
+ }
91
+ return counts
92
+ }
93
+
94
+ function countLines(file) {
95
+ try {
96
+ const stat = lstatSync(file)
97
+ if (!stat.isFile()) return { binary: true }
98
+ if (stat.size > MAX_COUNT_BYTES) return {}
99
+ const buffer = Buffer.alloc(stat.size)
100
+ const fd = openSync(file, "r")
101
+ try {
102
+ readSync(fd, buffer, 0, stat.size, 0)
103
+ } finally {
104
+ closeSync(fd)
105
+ }
106
+ if (buffer.includes(0)) return { binary: true }
107
+ const text = buffer.toString("utf8")
108
+ const lines = text.length === 0 ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0)
109
+ return { added: lines, deleted: 0 }
110
+ } catch {
111
+ return {}
112
+ }
113
+ }
114
+
115
+ /**
116
+ * A folder in no repository (2026-11-04): what changed in this session,
117
+ * from the session's first checkpoint (the files before the agent's first
118
+ * change) to the files now, through Kriya's private store. No session or no
119
+ * checkpoint yet: nothing has changed.
120
+ */
121
+ async function sessionChanges(cwd, sessionId, since) {
122
+ const tracked = await trackedRoot(cwd)
123
+ if (!tracked?.shadow) return { git: false }
124
+ const shape = { git: true, shadow: true, root: tracked.root, branch: null, truncated: false, added: 0, deleted: 0 }
125
+ const base = sessionId ? await sessionBase(tracked.root, sessionId, since) : undefined
126
+ if (!base) return { ...shape, files: [], since: null }
127
+ const now = await snapshot(tracked.root)
128
+ const all = await treeChanges(tracked.root, base, now)
129
+ const files = all.slice(0, MAX_FILES)
130
+ const sum = (key) => files.reduce((n, f) => n + (f[key] ?? 0), 0)
131
+ return { ...shape, files, truncated: all.length > MAX_FILES, added: sum("added"), deleted: sum("deleted"), since: "session", base, now }
132
+ }
133
+
134
+ /**
135
+ * Every changed file under `cwd`'s repository against HEAD, with line counts;
136
+ * in a folder with no repository, what changed in the session.
137
+ * @param {string} cwd
138
+ * @param {string} [sessionId]
139
+ * @param {number} [since] when the session began (ms), so its builders' changes count
140
+ */
141
+ export async function listChanges(cwd, sessionId, since) {
142
+ const root = await repoRoot(cwd)
143
+ if (!root) return sessionChanges(cwd, sessionId, since)
144
+ const [statusText, branchText, from] = await Promise.all([
145
+ git(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]),
146
+ git(root, ["rev-parse", "--abbrev-ref", "HEAD"]).catch(() => ""),
147
+ base(root),
148
+ ])
149
+ const counts = parseNumstat(await git(root, ["diff", "--numstat", "-z", "-M", from, "--"]))
150
+ const all = parseStatus(statusText)
151
+ const files = all.slice(0, MAX_FILES).map((file) => ({
152
+ ...file,
153
+ ...(file.untracked ? countLines(join(root, file.path)) : (counts.get(file.path) ?? {})),
154
+ }))
155
+ const sum = (key) => files.reduce((n, f) => n + (f[key] ?? 0), 0)
156
+ return {
157
+ git: true,
158
+ root,
159
+ branch: branchText.trim() === "HEAD" ? null : branchText.trim() || null,
160
+ files,
161
+ truncated: all.length > MAX_FILES,
162
+ added: sum("added"),
163
+ deleted: sum("deleted"),
164
+ }
165
+ }
166
+
167
+ /**
168
+ * One changed file's unified diff against HEAD. `path` must be one that
169
+ * listChanges reported, so the browser can't name any other file.
170
+ * @param {string} cwd
171
+ * @param {unknown} path
172
+ */
173
+ export async function fileDiff(cwd, path, sessionId, since) {
174
+ if (typeof path !== "string" || path === "" || path.includes("\0")) throw new ChangesError("Which file?")
175
+ const changes = await listChanges(cwd, sessionId, since)
176
+ if (!changes.git) throw new ChangesError("Kriya doesn't track this folder (your home folder or a drive root).")
177
+ const file = changes.files.find((f) => f.path === path)
178
+ if (!file) throw new ChangesError("That file has no changes.")
179
+ if (file.binary) return { path, binary: true, diff: "", truncated: false }
180
+ if (changes.shadow) {
181
+ const text = await treeFileDiff(changes.root, changes.base, changes.now, path, file.from)
182
+ const truncated = Buffer.byteLength(text) > MAX_DIFF_BYTES
183
+ return { path, binary: false, diff: truncated ? Buffer.from(text).subarray(0, MAX_DIFF_BYTES).toString("utf8") : text, truncated }
184
+ }
185
+ const args = file.untracked
186
+ ? ["diff", "--no-color", "--no-index", "--", "/dev/null", path]
187
+ : ["diff", "--no-color", "-M", await base(changes.root), "--", ...(file.from ? [file.from] : []), path]
188
+ const text = await git(changes.root, args, { okCodes: [0, 1], maxBuffer: 32 * 1024 * 1024 })
189
+ const truncated = Buffer.byteLength(text) > MAX_DIFF_BYTES
190
+ return { path, binary: false, diff: truncated ? Buffer.from(text).subarray(0, MAX_DIFF_BYTES).toString("utf8") : text, truncated }
191
+ }