@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,284 @@
1
+ import {
2
+ cpSync,
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ realpathSync,
9
+ renameSync,
10
+ rmSync,
11
+ symlinkSync,
12
+ unlinkSync,
13
+ writeFileSync,
14
+ } from "node:fs"
15
+ import { createRequire } from "node:module"
16
+ import { dirname, join, relative, resolve } from "node:path"
17
+
18
+ import { PACKAGE_ROOT, kriyaHome } from "./paths.js"
19
+ import { offFor, projectRoot } from "./skill-switches.js"
20
+
21
+ // `kriya skills`: local SKILL.md skills (superpowers, ponytail, ECC, your
22
+ // own) for the agent on this machine. DSH reads them from the folder's
23
+ // .dsh/skills and .agents/skills, ~/.kriya/skills and ~/.agents/skills; Kriya
24
+ // account skills come on top through the kriya bundle (H7) and aren't listed.
25
+
26
+ const require = createRequire(join(PACKAGE_ROOT, "package.json"))
27
+
28
+ /** Where `kriya skills link` puts skills: DSH_HOME/skills for every Kriya profile. */
29
+ export const skillsDir = () => join(kriyaHome(), "skills")
30
+
31
+ // The catalog renders at most this much of each description (dsh-tool-skill's
32
+ // catalogDescriptionMaxLength default), plus the name
33
+ const CATALOG_DESCRIPTION = 500
34
+ /** DSH's root labels, as folders a person recognises. */
35
+ export const SKILL_ROOTS = {
36
+ "project-dsh": ".dsh/skills (this project)",
37
+ "project-agents": ".agents/skills (this project)",
38
+ custom: "custom folder",
39
+ "user-dsh": "~/.kriya/skills",
40
+ "user-agents": "~/.agents/skills",
41
+ }
42
+
43
+ /** Above this many catalog characters, `kriya skills` warns about the cost. */
44
+ export const HEAVY_CATALOG = 40_000
45
+
46
+ const isLink = (path) => {
47
+ try {
48
+ return lstatSync(path).isSymbolicLink()
49
+ } catch {
50
+ return false
51
+ }
52
+ }
53
+
54
+ /**
55
+ * The skills the agent's catalog gets in `cwd`, read by DSH's own provider so
56
+ * this never disagrees with it. A name in several roots: the lower rank wins.
57
+ * shortcut: a minimal stand-in for DSH's Context (logger, get, effect, on);
58
+ * the exact DSH pin and tests/local-skills.test.js catch a change on upgrade.
59
+ * @param {string} cwd
60
+ * @param {{ agentsHome?: string }} [roots]
61
+ */
62
+ export async function visibleSkills(cwd, roots = {}) {
63
+ const { FileSystemSkillProvider } = await import(require.resolve("@deepseek-ai/dsh-skill-filesystem"))
64
+ const warnings = []
65
+ const note = (...args) => warnings.push(args.map(String).join(" "))
66
+ // DSH calls both ctx.logger(name) and ctx.logger.warn(...)
67
+ const logger = Object.assign(() => logger, { warn: note, error: note, info() {}, debug() {} })
68
+ const ctx = { logger, get: () => undefined, effect() {}, on: () => () => {} }
69
+ const provider = new FileSystemSkillProvider(
70
+ ctx,
71
+ { invalidate() {}, signal: new AbortController().signal },
72
+ { dshHome: kriyaHome(), agentsHome: roots.agentsHome, watch: false }
73
+ )
74
+ const found = [...(await provider.list({ cwd }))].sort((a, b) => a.rank - b.rank)
75
+ const skills = []
76
+ const shadowed = []
77
+ for (const skill of found) (skills.some((s) => s.name === skill.name) ? shadowed : skills).push(skill)
78
+ // Turned off (src/skill-switches.js): listed, but out of the catalog
79
+ const off = offFor(cwd)
80
+ const chars = (s) => s.name.length + Math.min(s.description.replace(/\s+/g, " ").trim().length, CATALOG_DESCRIPTION)
81
+ const invocable = skills.filter((s) => s.invocation?.modelInvocable !== false)
82
+ const catalogChars = invocable.filter((s) => !off.has(s.name)).reduce((n, s) => n + chars(s), 0)
83
+ const offChars = invocable.filter((s) => off.has(s.name)).reduce((n, s) => n + chars(s), 0)
84
+ // Links in ~/.kriya/skills whose target is gone (a plugin updated or moved)
85
+ const dir = skillsDir()
86
+ const broken = existsSync(dir)
87
+ ? readdirSync(dir).filter((name) => isLink(join(dir, name)) && !existsSync(join(dir, name)))
88
+ : []
89
+ return { skills, shadowed, catalogChars, offChars, off, broken, warnings }
90
+ }
91
+
92
+ export class SkillsError extends Error {}
93
+
94
+ /**
95
+ * Links each `<name>/SKILL.md` bundle in `folder` into ~/.kriya/skills. A name
96
+ * already there is left alone (yours, or linked before). Links, not copies,
97
+ * so a `git pull` of the source reaches the agent.
98
+ * @param {string} folder
99
+ * @param {string[]} [only] names to link; all by default
100
+ */
101
+ export function linkSkills(folder, only) {
102
+ const from = resolve(folder)
103
+ if (!existsSync(from)) throw new SkillsError(`${folder}: no such folder`)
104
+ const bundles = readdirSync(from).filter((name) => existsSync(join(from, name, "SKILL.md")))
105
+ if (only) {
106
+ const unknown = only.filter((name) => !bundles.includes(name))
107
+ if (unknown.length) throw new SkillsError(`not a skill in ${folder}: ${unknown.join(", ")}`)
108
+ }
109
+ if (bundles.length === 0) throw new SkillsError(`${folder} has no <name>/SKILL.md skills`)
110
+ const target = skillsDir()
111
+ mkdirSync(target, { recursive: true })
112
+ const linked = []
113
+ const kept = []
114
+ for (const name of only ?? bundles) {
115
+ const at = join(target, name)
116
+ if (existsSync(at) || isLink(at)) {
117
+ kept.push(name)
118
+ continue
119
+ }
120
+ symlinkSync(join(from, name), at, "dir")
121
+ linked.push(name)
122
+ }
123
+ return { linked, kept }
124
+ }
125
+
126
+ /** Removes a linked skill; a real folder in ~/.kriya/skills is never deleted. */
127
+ export function unlinkSkill(name) {
128
+ // A skill name, never a path out of ~/.kriya/skills
129
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(name)) throw new SkillsError(`${name} isn't a skill name`)
130
+ const at = join(skillsDir(), name)
131
+ if (!isLink(at)) {
132
+ throw new SkillsError(
133
+ existsSync(at) ? `${name} is a folder, not a link; remove it yourself if you mean to` : `${name} isn't linked`
134
+ )
135
+ }
136
+ unlinkSync(at)
137
+ }
138
+
139
+ /* ─────────────────────── the Skills page (plugins/skills) ─────────────────────── */
140
+
141
+ /** A skill name as DSH accepts it: kebab-case. */
142
+ export const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
143
+ /** The largest SKILL.md the Skills page saves. */
144
+ export const MAX_SKILL_BYTES = 64 * 1024
145
+
146
+ const named = (name) => {
147
+ if (typeof name !== "string" || !SKILL_NAME.test(name)) throw new SkillsError("That isn't a skill name.")
148
+ return name
149
+ }
150
+
151
+ // linked: a link into ~/.kriya/skills or a project root (editing would change
152
+ // its source, a plugin or a repository); yours: a real folder you own
153
+ function describe(skill, off = new Map()) {
154
+ const folder = skill.locator?.directory ?? dirname(skill.locator?.path ?? "")
155
+ const linked = isLink(folder)
156
+ return {
157
+ name: skill.name,
158
+ description: skill.description.replace(/\s+/g, " ").trim(),
159
+ where: SKILL_ROOTS[skill.source] ?? skill.source,
160
+ source: skill.source,
161
+ path: skill.locator?.path ?? null,
162
+ linked,
163
+ linkTarget: linked ? safeRealpath(folder) : null,
164
+ // A link in ~/.kriya/skills can become your own copy; elsewhere it can't
165
+ canCopy: linked && skill.source === "user-dsh",
166
+ editable: !linked && Boolean(skill.locator?.path),
167
+ modelInvocable: skill.invocation?.modelInvocable !== false,
168
+ userInvocable: skill.invocation?.userInvocable !== false,
169
+ // "on", "off-here" (this project) or "off-everywhere"
170
+ state: off.has(skill.name) ? `off-${off.get(skill.name)}` : "on",
171
+ }
172
+ }
173
+
174
+ function safeRealpath(path) {
175
+ try {
176
+ return realpathSync(path)
177
+ } catch {
178
+ return null
179
+ }
180
+ }
181
+
182
+ /** Everything the Skills page shows for the folder the agent works in. */
183
+ export async function skillsPage(cwd, roots = {}) {
184
+ const seen = await visibleSkills(cwd, roots)
185
+ return {
186
+ skills: seen.skills.map((s) => describe(s, seen.off)),
187
+ shadowed: seen.shadowed.map((s) => describe(s, seen.off)),
188
+ broken: seen.broken,
189
+ warnings: seen.warnings,
190
+ catalogChars: seen.catalogChars,
191
+ catalogTokens: Math.round(seen.catalogChars / 4),
192
+ // What the skills turned off would cost on every request
193
+ offTokens: Math.round(seen.offChars / 4),
194
+ project: projectRoot(cwd),
195
+ heavy: seen.catalogChars > HEAVY_CATALOG,
196
+ skillsDir: skillsDir(),
197
+ }
198
+ }
199
+
200
+ async function find(cwd, name, roots) {
201
+ const { skills } = await visibleSkills(cwd, roots)
202
+ const skill = skills.find((s) => s.name === named(name))
203
+ if (!skill) throw new SkillsError(`No skill named ${name} here.`)
204
+ return skill
205
+ }
206
+
207
+ /** One skill's SKILL.md, found through the catalog (never a path from the caller). */
208
+ export async function readSkillFile(cwd, name, roots = {}) {
209
+ const skill = await find(cwd, name, roots)
210
+ return { ...describe(skill, offFor(cwd)), content: readFileSync(skill.locator.path, "utf8") }
211
+ }
212
+
213
+ const frontmatterName = (content) => /^---\r?\n[\s\S]*?^name:\s*["']?([^"'\r\n]+?)["']?\s*$/m.exec(content)?.[1]
214
+
215
+ /**
216
+ * Saves a skill you own. DSH's parser checks the result: if it would drop the
217
+ * skill (bad frontmatter), the old file goes back and its warning is returned.
218
+ */
219
+ export async function saveSkillFile(cwd, name, content, roots = {}) {
220
+ if (typeof content !== "string") throw new SkillsError("Nothing to save.")
221
+ if (Buffer.byteLength(content) > MAX_SKILL_BYTES) throw new SkillsError("A skill can be at most 64 KB.")
222
+ const skill = await find(cwd, name, roots)
223
+ const info = describe(skill)
224
+ if (!info.editable) {
225
+ throw new SkillsError(
226
+ info.canCopy
227
+ ? "This skill is linked from elsewhere. Make your own copy first, so the source stays as it is."
228
+ : "This skill is linked from elsewhere; edit it where it comes from."
229
+ )
230
+ }
231
+ if (frontmatterName(content) !== name) {
232
+ throw new SkillsError(`Keep "name: ${name}" in the frontmatter; to rename, create a new skill.`)
233
+ }
234
+ // The file must really live in the skill's own folder (no link out of it)
235
+ const file = skill.locator.path
236
+ const real = safeRealpath(file)
237
+ if (!real || relative(safeRealpath(dirname(file)), real).startsWith("..")) {
238
+ throw new SkillsError("This skill's file is a link; edit it where it comes from.")
239
+ }
240
+ const before = readFileSync(file, "utf8")
241
+ const temp = `${file}.kriya-saving`
242
+ writeFileSync(temp, content)
243
+ renameSync(temp, file)
244
+ const after = await visibleSkills(cwd, roots)
245
+ if (!after.skills.some((s) => s.name === name)) {
246
+ writeFileSync(temp, before)
247
+ renameSync(temp, file)
248
+ const why = after.warnings.find((w) => w.includes(file) || w.includes(name)) ?? after.warnings[0]
249
+ throw new SkillsError(`Not saved: the agent couldn't read it${why ? ` (${why})` : ""}. Your previous version is kept.`)
250
+ }
251
+ return readSkillFile(cwd, name, roots)
252
+ }
253
+
254
+ /** Turns a link in ~/.kriya/skills into your own folder, a copy of its source. */
255
+ export async function copySkill(cwd, name, roots = {}) {
256
+ const at = join(skillsDir(), named(name))
257
+ if (!isLink(at)) throw new SkillsError(`${name} isn't a linked skill in ${skillsDir()}.`)
258
+ const source = safeRealpath(at)
259
+ if (!source) throw new SkillsError(`${name}'s source folder is gone; unlink it.`)
260
+ const temp = join(skillsDir(), `.${name}.kriya-copy`)
261
+ rmSync(temp, { recursive: true, force: true })
262
+ cpSync(source, temp, { recursive: true, dereference: true })
263
+ unlinkSync(at)
264
+ renameSync(temp, at)
265
+ return readSkillFile(cwd, name, roots)
266
+ }
267
+
268
+ /** A new skill of yours in ~/.kriya/skills, with a starting outline. */
269
+ export async function createSkill(cwd, name, description, roots = {}) {
270
+ named(name)
271
+ const text = typeof description === "string" ? description.replace(/\s+/g, " ").trim() : ""
272
+ if (text.length < 10) throw new SkillsError("Say when the agent should use it (at least 10 characters).")
273
+ if (text.length > 1000) throw new SkillsError("Keep the description under 1,000 characters.")
274
+ const { skills } = await visibleSkills(cwd, roots)
275
+ if (skills.some((s) => s.name === name)) throw new SkillsError(`There's already a skill named ${name}.`)
276
+ const folder = join(skillsDir(), name)
277
+ if (existsSync(folder) || isLink(folder)) throw new SkillsError(`${folder} already exists.`)
278
+ mkdirSync(folder, { recursive: true })
279
+ writeFileSync(
280
+ join(folder, "SKILL.md"),
281
+ `---\nname: ${name}\ndescription: ${JSON.stringify(text)}\n---\n\n# ${name}\n\nWrite how to do this job well: the steps, what to check, and what to avoid.\n`
282
+ )
283
+ return readSkillFile(cwd, name, roots)
284
+ }
package/src/login.js ADDED
@@ -0,0 +1,82 @@
1
+ import { spawn } from "node:child_process"
2
+ import { hostname } from "node:os"
3
+
4
+ import { deviceCode, deviceToken, KriyaError, me } from "./api.js"
5
+ import { writeDevice } from "./store.js"
6
+
7
+ // `kriya login` (P-AUTH, HD-05): the device flow. Ask for a code, show it
8
+ // and open the connect page, poll until the person approves it in their
9
+ // signed-in browser, keep the token (shown once) on this machine, then say
10
+ // who we're signed in as. The device never approves itself.
11
+
12
+ /** A device name the server accepts: 1–60 printable characters. */
13
+ export function deviceName() {
14
+ const name = hostname().replace(/[^\x20-\x7e]/g, "").trim().slice(0, 60)
15
+ return name || "My computer"
16
+ }
17
+
18
+ /** The connect page, with the code filled in so the person only confirms it. */
19
+ export function connectUrl(verificationUrl, userCode) {
20
+ const url = new URL(verificationUrl)
21
+ url.searchParams.set("code", userCode)
22
+ return url.toString()
23
+ }
24
+
25
+ function openBrowser(url) {
26
+ const [command, args] =
27
+ process.platform === "darwin"
28
+ ? ["open", [url]]
29
+ : process.platform === "win32"
30
+ ? ["cmd", ["/c", "start", "", url]]
31
+ : ["xdg-open", [url]]
32
+ try {
33
+ spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => {}).unref()
34
+ } catch {
35
+ // No browser here (a server, SSH): the printed link is enough
36
+ }
37
+ }
38
+
39
+ /**
40
+ * @param {string} url Kriya origin
41
+ * @param {{ say?: (line: string) => void, sleep?: (ms: number) => Promise<void>, browser?: boolean, now?: () => number }} [io]
42
+ */
43
+ export async function login(url, io = {}) {
44
+ const say = io.say ?? ((line) => process.stdout.write(`${line}\n`))
45
+ const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)))
46
+ const now = io.now ?? Date.now
47
+ const platform = ["darwin", "linux", "win32"].includes(process.platform) ? process.platform : "linux"
48
+
49
+ const code = await deviceCode(url, { deviceName: deviceName(), platform })
50
+ const link = connectUrl(code.verificationUrl, code.userCode)
51
+ say(
52
+ `Open ${code.verificationUrl} and enter ${code.userCode} (expires in ${Math.round(code.expiresIn / 60)} minutes).`
53
+ )
54
+ if (io.browser !== false) openBrowser(link)
55
+
56
+ const deadline = now() + code.expiresIn * 1000
57
+ let interval = code.interval * 1000
58
+ for (;;) {
59
+ await sleep(interval)
60
+ if (now() > deadline) throw new KriyaError(410, "expired", "The code expired. Run kriya login again.")
61
+ try {
62
+ const { token, deviceId } = await deviceToken(url, code.deviceCode)
63
+ writeDevice({ url, token, deviceId })
64
+ const who = await me(url, token)
65
+ say(`Signed in as ${who.displayName ?? "you"} · working as ${who.agent?.name ?? "your agent"}.`)
66
+ return { token, deviceId, me: who }
67
+ } catch (error) {
68
+ if (!(error instanceof KriyaError)) throw error
69
+ if (error.code === "pending") continue
70
+ // Kriya restarting (a deploy) while the person approves: keep waiting
71
+ // until the code expires
72
+ if (error.code === "network" || error.status >= 500) continue
73
+ // Polled too fast: back off by the interval, as the device flow asks
74
+ if (error.code === "rate_limited") {
75
+ interval += code.interval * 1000
76
+ continue
77
+ }
78
+ if (error.code === "denied") throw new KriyaError(403, "denied", "Sign-in was denied in Kriya.")
79
+ throw error
80
+ }
81
+ }
82
+ }