@eloxiv/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/AgentSkills.d.ts +51 -0
  4. package/dist/AgentSkills.d.ts.map +1 -0
  5. package/dist/AgentSkills.js +264 -0
  6. package/dist/AgentSkills.js.map +1 -0
  7. package/dist/AgentWeb.d.ts +83 -0
  8. package/dist/AgentWeb.d.ts.map +1 -0
  9. package/dist/AgentWeb.js +436 -0
  10. package/dist/AgentWeb.js.map +1 -0
  11. package/dist/App.d.ts +213 -0
  12. package/dist/App.d.ts.map +1 -0
  13. package/dist/App.js +357 -0
  14. package/dist/App.js.map +1 -0
  15. package/dist/Blueprint.d.ts +47 -0
  16. package/dist/Blueprint.d.ts.map +1 -0
  17. package/dist/Blueprint.js +241 -0
  18. package/dist/Blueprint.js.map +1 -0
  19. package/dist/Brand.d.ts +42 -0
  20. package/dist/Brand.d.ts.map +1 -0
  21. package/dist/Brand.js +370 -0
  22. package/dist/Brand.js.map +1 -0
  23. package/dist/Changelog.d.ts +22 -0
  24. package/dist/Changelog.d.ts.map +1 -0
  25. package/dist/Changelog.js +117 -0
  26. package/dist/Changelog.js.map +1 -0
  27. package/dist/Cli.d.ts +17 -0
  28. package/dist/Cli.d.ts.map +1 -0
  29. package/dist/Cli.js +810 -0
  30. package/dist/Cli.js.map +1 -0
  31. package/dist/DbAdmin.d.ts +18 -0
  32. package/dist/DbAdmin.d.ts.map +1 -0
  33. package/dist/DbAdmin.js +91 -0
  34. package/dist/DbAdmin.js.map +1 -0
  35. package/dist/Dependencies.d.ts +53 -0
  36. package/dist/Dependencies.d.ts.map +1 -0
  37. package/dist/Dependencies.js +132 -0
  38. package/dist/Dependencies.js.map +1 -0
  39. package/dist/Deploy.d.ts +39 -0
  40. package/dist/Deploy.d.ts.map +1 -0
  41. package/dist/Deploy.js +458 -0
  42. package/dist/Deploy.js.map +1 -0
  43. package/dist/Docs.d.ts +71 -0
  44. package/dist/Docs.d.ts.map +1 -0
  45. package/dist/Docs.js +240 -0
  46. package/dist/Docs.js.map +1 -0
  47. package/dist/Doctor.d.ts +56 -0
  48. package/dist/Doctor.d.ts.map +1 -0
  49. package/dist/Doctor.js +368 -0
  50. package/dist/Doctor.js.map +1 -0
  51. package/dist/Dossier.d.ts +23 -0
  52. package/dist/Dossier.d.ts.map +1 -0
  53. package/dist/Dossier.js +92 -0
  54. package/dist/Dossier.js.map +1 -0
  55. package/dist/Emit.d.ts +26 -0
  56. package/dist/Emit.d.ts.map +1 -0
  57. package/dist/Emit.js +51 -0
  58. package/dist/Emit.js.map +1 -0
  59. package/dist/Errors.d.ts +26 -0
  60. package/dist/Errors.d.ts.map +1 -0
  61. package/dist/Errors.js +17 -0
  62. package/dist/Errors.js.map +1 -0
  63. package/dist/Evals.d.ts +52 -0
  64. package/dist/Evals.d.ts.map +1 -0
  65. package/dist/Evals.js +126 -0
  66. package/dist/Evals.js.map +1 -0
  67. package/dist/Files.d.ts +47 -0
  68. package/dist/Files.d.ts.map +1 -0
  69. package/dist/Files.js +145 -0
  70. package/dist/Files.js.map +1 -0
  71. package/dist/Generate.d.ts +80 -0
  72. package/dist/Generate.d.ts.map +1 -0
  73. package/dist/Generate.js +310 -0
  74. package/dist/Generate.js.map +1 -0
  75. package/dist/Guards.d.ts +45 -0
  76. package/dist/Guards.d.ts.map +1 -0
  77. package/dist/Guards.js +530 -0
  78. package/dist/Guards.js.map +1 -0
  79. package/dist/Inspect.d.ts +125 -0
  80. package/dist/Inspect.d.ts.map +1 -0
  81. package/dist/Inspect.js +270 -0
  82. package/dist/Inspect.js.map +1 -0
  83. package/dist/Keychain.d.ts +57 -0
  84. package/dist/Keychain.d.ts.map +1 -0
  85. package/dist/Keychain.js +73 -0
  86. package/dist/Keychain.js.map +1 -0
  87. package/dist/Lock.d.ts +13 -0
  88. package/dist/Lock.d.ts.map +1 -0
  89. package/dist/Lock.js +145 -0
  90. package/dist/Lock.js.map +1 -0
  91. package/dist/Mcp.d.ts +91 -0
  92. package/dist/Mcp.d.ts.map +1 -0
  93. package/dist/Mcp.js +128 -0
  94. package/dist/Mcp.js.map +1 -0
  95. package/dist/Merge.d.ts +18 -0
  96. package/dist/Merge.d.ts.map +1 -0
  97. package/dist/Merge.js +43 -0
  98. package/dist/Merge.js.map +1 -0
  99. package/dist/Migrate.d.ts +78 -0
  100. package/dist/Migrate.d.ts.map +1 -0
  101. package/dist/Migrate.js +288 -0
  102. package/dist/Migrate.js.map +1 -0
  103. package/dist/Plugins.d.ts +36 -0
  104. package/dist/Plugins.d.ts.map +1 -0
  105. package/dist/Plugins.js +304 -0
  106. package/dist/Plugins.js.map +1 -0
  107. package/dist/Postgres.d.ts +73 -0
  108. package/dist/Postgres.d.ts.map +1 -0
  109. package/dist/Postgres.js +294 -0
  110. package/dist/Postgres.js.map +1 -0
  111. package/dist/Publish.d.ts +23 -0
  112. package/dist/Publish.d.ts.map +1 -0
  113. package/dist/Publish.js +59 -0
  114. package/dist/Publish.js.map +1 -0
  115. package/dist/Registry.d.ts +539 -0
  116. package/dist/Registry.d.ts.map +1 -0
  117. package/dist/Registry.js +340 -0
  118. package/dist/Registry.js.map +1 -0
  119. package/dist/Remote.d.ts +90 -0
  120. package/dist/Remote.d.ts.map +1 -0
  121. package/dist/Remote.js +1006 -0
  122. package/dist/Remote.js.map +1 -0
  123. package/dist/Run.d.ts +120 -0
  124. package/dist/Run.d.ts.map +1 -0
  125. package/dist/Run.js +477 -0
  126. package/dist/Run.js.map +1 -0
  127. package/dist/SyncGen.d.ts +118 -0
  128. package/dist/SyncGen.d.ts.map +1 -0
  129. package/dist/SyncGen.js +392 -0
  130. package/dist/SyncGen.js.map +1 -0
  131. package/dist/Update.d.ts +301 -0
  132. package/dist/Update.d.ts.map +1 -0
  133. package/dist/Update.js +627 -0
  134. package/dist/Update.js.map +1 -0
  135. package/dist/bin.d.ts +3 -0
  136. package/dist/bin.d.ts.map +1 -0
  137. package/dist/bin.js +42 -0
  138. package/dist/bin.js.map +1 -0
  139. package/dist/docs/backlog.md +56 -0
  140. package/dist/docs/ci.md +277 -0
  141. package/dist/docs/cli.md +696 -0
  142. package/dist/docs/connectors/google.md +115 -0
  143. package/dist/docs/connectors/http-openapi.md +7 -0
  144. package/dist/docs/connectors/mcp.md +8 -0
  145. package/dist/docs/connectors/microsoft-graph.md +75 -0
  146. package/dist/docs/connectors/openai.md +25 -0
  147. package/dist/docs/connectors/slack.md +162 -0
  148. package/dist/docs/connectors/workos.md +39 -0
  149. package/dist/docs/contracts/README.md +173 -0
  150. package/dist/docs/contracts/action-consent.md +92 -0
  151. package/dist/docs/contracts/action-registry.md +85 -0
  152. package/dist/docs/contracts/actor.md +100 -0
  153. package/dist/docs/contracts/agent-resources.md +90 -0
  154. package/dist/docs/contracts/agent-runtime.md +257 -0
  155. package/dist/docs/contracts/approvals.md +126 -0
  156. package/dist/docs/contracts/audit.md +75 -0
  157. package/dist/docs/contracts/auth-provider.md +74 -0
  158. package/dist/docs/contracts/calendar-provider.md +46 -0
  159. package/dist/docs/contracts/client-sdk.md +245 -0
  160. package/dist/docs/contracts/collab-document.md +151 -0
  161. package/dist/docs/contracts/command.md +44 -0
  162. package/dist/docs/contracts/connections.md +235 -0
  163. package/dist/docs/contracts/context-accounting.md +50 -0
  164. package/dist/docs/contracts/daemon.md +243 -0
  165. package/dist/docs/contracts/db-tx.md +53 -0
  166. package/dist/docs/contracts/delegation.md +68 -0
  167. package/dist/docs/contracts/device-control.md +103 -0
  168. package/dist/docs/contracts/directory-provider.md +36 -0
  169. package/dist/docs/contracts/directory.md +161 -0
  170. package/dist/docs/contracts/document-source.md +33 -0
  171. package/dist/docs/contracts/files.md +115 -0
  172. package/dist/docs/contracts/flags.md +83 -0
  173. package/dist/docs/contracts/host.md +68 -0
  174. package/dist/docs/contracts/http-api.md +43 -0
  175. package/dist/docs/contracts/ingestion.md +130 -0
  176. package/dist/docs/contracts/ingress.md +141 -0
  177. package/dist/docs/contracts/invocation.md +260 -0
  178. package/dist/docs/contracts/local-client.md +108 -0
  179. package/dist/docs/contracts/locale.md +56 -0
  180. package/dist/docs/contracts/machine-identity.md +117 -0
  181. package/dist/docs/contracts/mail-provider.md +49 -0
  182. package/dist/docs/contracts/memory.md +53 -0
  183. package/dist/docs/contracts/messaging.md +40 -0
  184. package/dist/docs/contracts/metering.md +139 -0
  185. package/dist/docs/contracts/model-provider.md +84 -0
  186. package/dist/docs/contracts/module-manifest.md +213 -0
  187. package/dist/docs/contracts/notification-channel.md +90 -0
  188. package/dist/docs/contracts/notifications.md +123 -0
  189. package/dist/docs/contracts/outbox.md +80 -0
  190. package/dist/docs/contracts/privacy.md +110 -0
  191. package/dist/docs/contracts/progress.md +52 -0
  192. package/dist/docs/contracts/query-surface.md +108 -0
  193. package/dist/docs/contracts/readiness.md +63 -0
  194. package/dist/docs/contracts/release.md +142 -0
  195. package/dist/docs/contracts/result-rendering.md +61 -0
  196. package/dist/docs/contracts/sandbox.md +186 -0
  197. package/dist/docs/contracts/scheduler.md +148 -0
  198. package/dist/docs/contracts/screen-context.md +81 -0
  199. package/dist/docs/contracts/search.md +120 -0
  200. package/dist/docs/contracts/secrets.md +74 -0
  201. package/dist/docs/contracts/settings.md +109 -0
  202. package/dist/docs/contracts/sharing.md +77 -0
  203. package/dist/docs/contracts/slot.md +48 -0
  204. package/dist/docs/contracts/space.md +67 -0
  205. package/dist/docs/contracts/storage-adapter.md +45 -0
  206. package/dist/docs/contracts/storage-backend.md +56 -0
  207. package/dist/docs/contracts/sync.md +213 -0
  208. package/dist/docs/contracts/telemetry.md +80 -0
  209. package/dist/docs/contracts/theme-tokens.md +50 -0
  210. package/dist/docs/contracts/tool-source.md +58 -0
  211. package/dist/docs/contracts/versioning.md +99 -0
  212. package/dist/docs/contracts/view.md +65 -0
  213. package/dist/docs/contracts/work-items.md +99 -0
  214. package/dist/docs/contracts/workflow.md +82 -0
  215. package/dist/docs/decisions.md +163 -0
  216. package/dist/docs/example-app.md +192 -0
  217. package/dist/docs/getting-started.md +927 -0
  218. package/dist/docs/goal.md +54 -0
  219. package/dist/docs/parity.md +29 -0
  220. package/dist/docs/performance.md +129 -0
  221. package/dist/docs/registry/README.md +74 -0
  222. package/dist/docs/registry/app.md +38 -0
  223. package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
  224. package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
  225. package/dist/docs/registry/calendar.md +35 -0
  226. package/dist/docs/registry/chat-ui-foldkit.md +30 -0
  227. package/dist/docs/registry/desktop-rune.md +49 -0
  228. package/dist/docs/registry/desktop.md +32 -0
  229. package/dist/docs/registry/eloxiv-action.md +25 -0
  230. package/dist/docs/registry/eloxiv-connector.md +25 -0
  231. package/dist/docs/registry/eloxiv-module.md +25 -0
  232. package/dist/docs/registry/eloxiv-policy.md +25 -0
  233. package/dist/docs/registry/eloxiv-view.md +25 -0
  234. package/dist/docs/registry/hello-ui-foldkit.md +29 -0
  235. package/dist/docs/registry/hello.md +39 -0
  236. package/dist/docs/registry/home-ui-foldkit.md +27 -0
  237. package/dist/docs/registry/home.md +29 -0
  238. package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
  239. package/dist/docs/registry/mail-ui-foldkit.md +27 -0
  240. package/dist/docs/registry/mail.md +34 -0
  241. package/dist/docs/registry/meeting-prep.md +26 -0
  242. package/dist/docs/registry/members-ui-foldkit.md +28 -0
  243. package/dist/docs/registry/mobile.md +37 -0
  244. package/dist/docs/registry/notes-ui-foldkit.md +27 -0
  245. package/dist/docs/registry/notes.md +26 -0
  246. package/dist/docs/registry/people-ui-foldkit.md +28 -0
  247. package/dist/docs/registry/people.md +38 -0
  248. package/dist/docs/registry/shell-foldkit.md +34 -0
  249. package/dist/docs/registry/theme.md +25 -0
  250. package/dist/docs/registry/ui-conformance.md +30 -0
  251. package/dist/docs/release.md +100 -0
  252. package/dist/docs/scaffold.md +826 -0
  253. package/dist/docs/security/threat-model.md +299 -0
  254. package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
  255. package/dist/index.d.ts +8 -0
  256. package/dist/index.d.ts.map +1 -0
  257. package/dist/index.js +8 -0
  258. package/dist/index.js.map +1 -0
  259. package/package.json +48 -3
  260. package/src/AgentSkills.ts +329 -0
  261. package/src/AgentWeb.ts +507 -0
  262. package/src/App.ts +435 -0
  263. package/src/Blueprint.ts +276 -0
  264. package/src/Brand.ts +415 -0
  265. package/src/Changelog.ts +136 -0
  266. package/src/Cli.ts +1458 -0
  267. package/src/DbAdmin.ts +115 -0
  268. package/src/Dependencies.ts +170 -0
  269. package/src/Deploy.ts +563 -0
  270. package/src/Docs.ts +309 -0
  271. package/src/Doctor.ts +424 -0
  272. package/src/Dossier.ts +148 -0
  273. package/src/Emit.ts +68 -0
  274. package/src/Errors.ts +18 -0
  275. package/src/Evals.ts +153 -0
  276. package/src/Files.ts +152 -0
  277. package/src/Generate.ts +402 -0
  278. package/src/Guards.ts +541 -0
  279. package/src/Inspect.ts +358 -0
  280. package/src/Keychain.ts +107 -0
  281. package/src/Lock.ts +174 -0
  282. package/src/Mcp.ts +159 -0
  283. package/src/Merge.ts +70 -0
  284. package/src/Migrate.ts +331 -0
  285. package/src/Plugins.ts +347 -0
  286. package/src/Postgres.ts +353 -0
  287. package/src/Publish.ts +64 -0
  288. package/src/Registry.ts +405 -0
  289. package/src/Remote.ts +1158 -0
  290. package/src/Run.ts +541 -0
  291. package/src/SyncGen.ts +570 -0
  292. package/src/Update.ts +873 -0
  293. package/src/bin.ts +46 -0
  294. package/src/index.ts +7 -0
package/src/Evals.ts ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Agent evals from the CLI (docs/cli.md, "eval"):
3
+ *
4
+ * eloxiv eval [--module <m>]... [--model <spec>] the app's module skills' eval cases through the real agent
5
+ * runtime on a fresh database (`@eloxiv/testing`'s runner)
6
+ * eloxiv eval promote <run> ... a finished run of the app's agent turned into an eval case,
7
+ * only with a reviewed prompt and explicit allowlists
8
+ *
9
+ * Promotion takes production behaviour into a test without taking production data with it. What a case keeps is what
10
+ * the reviewer names: the prompt is the one they write (bounded; the person's own words are never copied), the run
11
+ * may have called only the tools they allow (and read only the query views they allow), a call's input keeps only
12
+ * the fields they name, and the answer is checked only for the words they give. Anything else in the trace makes the
13
+ * promotion refuse, saying what. Writing the case into a skill's eval file needs `--reviewed`.
14
+ */
15
+ import { EvalCase, SkillEvals } from "@eloxiv/contracts"
16
+ import { Schema } from "effect"
17
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs"
18
+ import { dirname, join } from "node:path"
19
+ import { CliError } from "./Errors.ts"
20
+
21
+ /** The longest prompt a promoted case may carry. */
22
+ export const MAX_PROMPT_CHARS = 2000
23
+
24
+ /**
25
+ * `@eloxiv/testing`'s eval runner as the app (or a directory above it) installed it: its build, for an installed
26
+ * package (Node strips no types under `node_modules`), its source for Eloxiv's own workspace package.
27
+ */
28
+ export const evalEntry = (dir: string): string => {
29
+ for (let current = dir; ; current = dirname(current)) {
30
+ const pkg = join(current, "node_modules", "@eloxiv", "testing")
31
+ if (existsSync(pkg)) {
32
+ const real = realpathSync(pkg)
33
+ const installed = real.split(/[\\/]/).includes("node_modules")
34
+ for (const file of installed ? ["dist/EvalMain.js", "src/EvalMain.ts"] : ["src/EvalMain.ts", "dist/EvalMain.js"])
35
+ if (existsSync(join(real, file))) return join(real, file)
36
+ }
37
+ if (dirname(current) === current) break
38
+ }
39
+ throw new CliError({
40
+ message: `${dir} has no @eloxiv/testing (the eval runner): add it to the app's devDependencies and run pnpm install`,
41
+ })
42
+ }
43
+
44
+ export interface PromotionReview {
45
+ /** The case's name. */
46
+ readonly name: string
47
+ /** The prompt the case sends: written (or reviewed) by a person, at most MAX_PROMPT_CHARS. */
48
+ readonly prompt: string
49
+ /** The tools the run may have called (the agent's tool names, e.g. `notes_write`). */
50
+ readonly allowTools: ReadonlyArray<string>
51
+ /** The query views the run may have read through the `query` tool. */
52
+ readonly allowViews: ReadonlyArray<string>
53
+ /** Per tool, the input fields a case keeps (everything else in a call's input is dropped). */
54
+ readonly keepInput: Readonly<Record<string, ReadonlyArray<string>>>
55
+ readonly answerIncludes: ReadonlyArray<string>
56
+ readonly forbiddenTools: ReadonlyArray<string>
57
+ }
58
+
59
+ interface ToolCall {
60
+ readonly toolName: string
61
+ readonly input: unknown
62
+ }
63
+
64
+ export interface Promotion {
65
+ readonly case: EvalCase
66
+ /** What was left out of each call, for the reviewer: `<tool>.<field>`. */
67
+ readonly dropped: ReadonlyArray<string>
68
+ }
69
+
70
+ /**
71
+ * Turn a finished run's events into an eval case under `review`. Refuses (CliError, every reason at once) a run that
72
+ * did not succeed, an empty or overlong prompt, a call to a tool not allowed, and a read of a view not allowed.
73
+ */
74
+ export const promoteTrace = (
75
+ events: ReadonlyArray<{ readonly type: string; readonly data: Record<string, unknown> }>,
76
+ review: PromotionReview,
77
+ ): Promotion => {
78
+ const problems: Array<string> = []
79
+ const finished = events.find((e) => e.type === "run-finished")
80
+ if (finished === undefined) problems.push("the run has not finished")
81
+ else if (finished.data["status"] !== "succeeded")
82
+ problems.push(`the run ended ${String(finished.data["status"])}: only a run that succeeded is promoted`)
83
+ const prompt = review.prompt.trim()
84
+ if (prompt === "")
85
+ problems.push(
86
+ "--prompt is required: the case's prompt, written or reviewed by you (the person's own words are not copied)",
87
+ )
88
+ if (prompt.length > MAX_PROMPT_CHARS)
89
+ problems.push(`the prompt is ${prompt.length} characters; at most ${MAX_PROMPT_CHARS}`)
90
+ if (review.allowTools.length === 0) problems.push("--allow-tool is required: the tools the run may have called")
91
+ const steps = events
92
+ .filter((e) => e.type === "model-step")
93
+ .map((e) => (Array.isArray(e.data["toolCalls"]) ? (e.data["toolCalls"] as ReadonlyArray<ToolCall>) : []))
94
+ .filter((calls) => calls.length > 0)
95
+ for (const call of steps.flat()) {
96
+ if (!review.allowTools.includes(call.toolName))
97
+ problems.push(`the run called ${call.toolName}, which --allow-tool does not allow`)
98
+ if (call.toolName === "query") {
99
+ const view = (call.input as { view?: unknown } | undefined)?.view
100
+ if (typeof view !== "string" || !review.allowViews.includes(view)) {
101
+ problems.push(`the run read the view ${String(view)}, which --allow-view does not allow`)
102
+ }
103
+ }
104
+ }
105
+ // Tool calls a device served (a turn handed to one of the person's devices) are events of their own: held to the
106
+ // same allowlist, though a case cannot replay them.
107
+ for (const event of events.filter((e) => e.type === "tool-call")) {
108
+ const tool = event.data["toolName"]
109
+ if (typeof tool === "string" && !review.allowTools.includes(tool))
110
+ problems.push(`the run called ${tool}, which --allow-tool does not allow`)
111
+ }
112
+ if (problems.length > 0) throw new CliError({ message: `Not promoted: ${[...new Set(problems)].join("; ")}` })
113
+ const dropped: Array<string> = []
114
+ const kept = (call: ToolCall) => {
115
+ const keep = review.keepInput[call.toolName] ?? (call.toolName === "query" ? ["view"] : [])
116
+ const input = (call.input ?? {}) as Record<string, unknown>
117
+ for (const field of Object.keys(input)) if (!keep.includes(field)) dropped.push(`${call.toolName}.${field}`)
118
+ return Object.fromEntries(Object.entries(input).filter(([field]) => keep.includes(field)))
119
+ }
120
+ const candidate = {
121
+ name: review.name,
122
+ prompt,
123
+ expect: {
124
+ toolCalls: steps.flat().map((call) => {
125
+ const input = kept(call)
126
+ return Object.keys(input).length === 0 ? { tool: call.toolName } : { tool: call.toolName, input }
127
+ }),
128
+ ...(review.forbiddenTools.length === 0 ? {} : { forbiddenTools: review.forbiddenTools }),
129
+ ...(review.answerIncludes.length === 0 ? {} : { answerIncludes: review.answerIncludes }),
130
+ },
131
+ // The scripted provider's turns (CI): the same calls with the kept inputs, then an answer holding the words the
132
+ // case checks. Review the inputs: a field the case dropped may be one the action needs.
133
+ script: [
134
+ ...steps.map((calls) => ({ toolCalls: calls.map((call) => ({ tool: call.toolName, input: kept(call) })) })),
135
+ { text: review.answerIncludes.length === 0 ? "Done." : review.answerIncludes.join(", ") },
136
+ ],
137
+ }
138
+ const decoded = Schema.decodeUnknownSync(EvalCase)(candidate)
139
+ return { case: decoded, dropped: [...new Set(dropped)] }
140
+ }
141
+
142
+ /** Add `promoted` to a skill's eval file (refusing a case name it already has). */
143
+ export const addCase = (file: string, promoted: EvalCase) => {
144
+ if (!existsSync(file))
145
+ throw new CliError({
146
+ message: `${file} does not exist: name a skill's eval file (skills.<id>.evals in its module's contract)`,
147
+ })
148
+ const evals = Schema.decodeUnknownSync(SkillEvals)(JSON.parse(readFileSync(file, "utf8")))
149
+ if (evals.cases.some((c) => c.name === promoted.name))
150
+ throw new CliError({ message: `${file} already has a case named ${promoted.name}` })
151
+ writeFileSync(file, `${JSON.stringify({ ...evals, cases: [...evals.cases, promoted] }, null, 2)}\n`)
152
+ return evals.cases.length + 1
153
+ }
package/src/Files.ts ADDED
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The app's files as the CLI touches them: target paths normalised and kept inside the app, writes and
3
+ * deletes refused through symbolic links, and contents read as bytes (text only when they are valid UTF-8).
4
+ */
5
+ import { Effect, FileSystem, Option, Path } from "effect"
6
+ import { CliError } from "./Errors.ts"
7
+
8
+ /**
9
+ * Normalise a target path relative to the app (`./src/a`, `src//a` and `src\a` are `src/a`), or `undefined`
10
+ * if it is absolute, empty or leaves the app (`..`).
11
+ */
12
+ export const normaliseTarget = (target: string): string | undefined => {
13
+ if (target.startsWith("/") || target.startsWith("\\") || /^[a-zA-Z]:/.test(target)) return undefined
14
+ const segments = target.split(/[\\/]/).filter((segment) => segment !== "" && segment !== ".")
15
+ if (segments.length === 0 || segments.includes("..")) return undefined
16
+ return segments.join("/")
17
+ }
18
+
19
+ const checked = (relative: string) =>
20
+ Effect.gen(function* () {
21
+ const normal = normaliseTarget(relative)
22
+ if (normal === undefined) return yield* new CliError({ message: `${relative} is outside the app` })
23
+ return normal
24
+ })
25
+
26
+ /** The absolute path of a file of the app, for reading: the path must stay inside the app. */
27
+ export const appPath = (dir: string, relative: string) =>
28
+ Effect.gen(function* () {
29
+ const path = yield* Path.Path
30
+ return path.join(dir, yield* checked(relative))
31
+ })
32
+
33
+ /**
34
+ * The one rule for every path the CLI writes or deletes (add, update, eject, restore, clean, generate, mcp): the
35
+ * absolute path of `relative` inside the app, after checking, before anything is touched, that
36
+ *
37
+ * - every ancestor below the app directory that exists is a real directory, not a symbolic link (even a dangling
38
+ * one) nor a file, so nothing is written or deleted through a link;
39
+ * - the path itself is not a symbolic link (`"write"`), or, when it is to be deleted (`"remove"`), may be one: the
40
+ * link is deleted, never what it points at;
41
+ * - resolved (`realpath` of its deepest existing ancestor, with the rest appended), it lies inside the resolved app
42
+ * directory.
43
+ *
44
+ * The returned path is under the resolved app directory.
45
+ */
46
+ export const safeAppPath = (dir: string, relative: string, mode: "write" | "remove") =>
47
+ Effect.gen(function* () {
48
+ const fs = yield* FileSystem.FileSystem
49
+ const path = yield* Path.Path
50
+ const normal = yield* checked(relative)
51
+ const verb = mode === "write" ? "write" : "delete"
52
+ const root = yield* fs
53
+ .realPath(dir)
54
+ .pipe(Effect.mapError(() => new CliError({ message: `Cannot resolve the app directory ${dir}` })))
55
+ const segments = normal.split("/")
56
+ let current = root
57
+ let walked = ""
58
+ let deepestExisting = root
59
+ for (const [index, segment] of segments.entries()) {
60
+ current = path.join(current, segment)
61
+ walked = walked === "" ? segment : `${walked}/${segment}`
62
+ const info = yield* fs.lstat(current).pipe(Effect.option)
63
+ if (Option.isNone(info)) break
64
+ const last = index === segments.length - 1
65
+ if (info.value.type === "SymbolicLink" && !(last && mode === "remove")) {
66
+ return yield* new CliError({
67
+ message: `Refusing to ${verb} ${normal}: ${walked} is a symbolic link, and going through it could leave the app`,
68
+ })
69
+ }
70
+ if (!last && info.value.type !== "Directory") {
71
+ return yield* new CliError({ message: `Refusing to ${verb} ${normal}: ${walked} is not a directory` })
72
+ }
73
+ if (!last || info.value.type !== "SymbolicLink") deepestExisting = current
74
+ }
75
+ // Resolved, the path must still be inside the resolved app directory.
76
+ const resolvedBase = yield* fs
77
+ .realPath(deepestExisting)
78
+ .pipe(Effect.mapError(() => new CliError({ message: `Cannot resolve ${normal} in the app` })))
79
+ const rest = path.relative(deepestExisting, path.join(root, normal))
80
+ const resolved = rest === "" ? resolvedBase : path.join(resolvedBase, rest)
81
+ const inside = path.relative(root, resolved)
82
+ if (inside === "" || inside.startsWith("..") || path.isAbsolute(inside)) {
83
+ return yield* new CliError({ message: `Refusing to ${verb} ${normal}: it resolves outside the app` })
84
+ }
85
+ return path.join(root, normal)
86
+ })
87
+
88
+ /** The absolute path of a file of the app, for writing or deleting a file (`safeAppPath`'s `"write"` rule). */
89
+ export const writablePath = (dir: string, relative: string) => safeAppPath(dir, relative, "write")
90
+
91
+ /** Read a file of the app as bytes, or `undefined` if it does not exist. */
92
+ export const readAppBytes = (dir: string, relative: string) =>
93
+ Effect.gen(function* () {
94
+ const fs = yield* FileSystem.FileSystem
95
+ const file = yield* appPath(dir, relative)
96
+ if (!(yield* fs.exists(file))) return undefined
97
+ return yield* fs.readFile(file)
98
+ })
99
+
100
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true })
101
+ const encoder = new TextEncoder()
102
+
103
+ /** Whether `text` can be line-merged: no NUL. */
104
+ export const isMergeableText = (text: string) => !text.includes("\u0000")
105
+
106
+ /**
107
+ * The bytes as text when they are valid UTF-8 that round-trips exactly and hold no NUL; otherwise
108
+ * `undefined` (binary: compared byte for byte, never line-merged).
109
+ */
110
+ export const asText = (bytes: Uint8Array): string | undefined => {
111
+ let text: string
112
+ try {
113
+ text = decoder.decode(bytes)
114
+ } catch {
115
+ return undefined
116
+ }
117
+ if (!isMergeableText(text) || !sameBytes(encoder.encode(text), bytes)) return undefined
118
+ return text
119
+ }
120
+
121
+ export const sameBytes = (a: Uint8Array, b: Uint8Array) => {
122
+ if (a.length !== b.length) return false
123
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
124
+ return true
125
+ }
126
+
127
+ /** Whether the app's bytes are exactly `text` encoded as UTF-8. */
128
+ export const bytesEqualText = (bytes: Uint8Array, text: string) => sameBytes(bytes, encoder.encode(text))
129
+
130
+ export const sha256Bytes = (bytes: Uint8Array) =>
131
+ Effect.promise(async () => {
132
+ const digest = await crypto.subtle.digest("SHA-256", bytes)
133
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("")
134
+ })
135
+
136
+ /** Write `content` to a file of the app (creating its directory), refusing symbolic links on the way. */
137
+ export const writeAppFile = (dir: string, relative: string, content: string | Uint8Array) =>
138
+ Effect.gen(function* () {
139
+ const fs = yield* FileSystem.FileSystem
140
+ const path = yield* Path.Path
141
+ const destination = yield* writablePath(dir, relative)
142
+ yield* fs.makeDirectory(path.dirname(destination), { recursive: true })
143
+ if (typeof content === "string") yield* fs.writeFileString(destination, content)
144
+ else yield* fs.writeFile(destination, content)
145
+ })
146
+
147
+ /** Delete a file of the app, refusing symbolic links on the way. */
148
+ export const removeAppFile = (dir: string, relative: string) =>
149
+ Effect.gen(function* () {
150
+ const fs = yield* FileSystem.FileSystem
151
+ yield* fs.remove(yield* writablePath(dir, relative))
152
+ })