@howone/agent-cli 0.0.0-stage → 0.5.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 (228) hide show
  1. package/README.md +49 -2
  2. package/bin/index.d.mts +1 -0
  3. package/bin/index.mjs +2397 -0
  4. package/package.json +55 -4
  5. package/skills/howone/01-apps.md +29 -0
  6. package/skills/howone/02-develop.md +107 -0
  7. package/skills/howone/03-workflows.md +71 -0
  8. package/skills/howone/04-functions-and-data.md +41 -0
  9. package/skills/howone/05-capabilities.md +46 -0
  10. package/skills/howone/SKILL.md +52 -0
  11. package/templates/vite/.howone/skills/hallmark/SKILL.md +557 -0
  12. package/templates/vite/.howone/skills/hallmark/references/anti-patterns.md +418 -0
  13. package/templates/vite/.howone/skills/hallmark/references/assets.md +406 -0
  14. package/templates/vite/.howone/skills/hallmark/references/color.md +95 -0
  15. package/templates/vite/.howone/skills/hallmark/references/component-cookbook.md +265 -0
  16. package/templates/vite/.howone/skills/hallmark/references/components/c1-outlined-chip.md +12 -0
  17. package/templates/vite/.howone/skills/hallmark/references/components/c2-inline-form-as-cta.md +16 -0
  18. package/templates/vite/.howone/skills/hallmark/references/components/c3-typographic-link.md +8 -0
  19. package/templates/vite/.howone/skills/hallmark/references/components/c4-sticky-bottom-bar.md +16 -0
  20. package/templates/vite/.howone/skills/hallmark/references/components/f1-bento-grid.md +20 -0
  21. package/templates/vite/.howone/skills/hallmark/references/components/f2-sticky-scroll-stack.md +20 -0
  22. package/templates/vite/.howone/skills/hallmark/references/components/f3-tabular-spec-sheet.md +11 -0
  23. package/templates/vite/.howone/skills/hallmark/references/components/f4-step-sequence.md +11 -0
  24. package/templates/vite/.howone/skills/hallmark/references/components/f5-annotated-screenshot.md +11 -0
  25. package/templates/vite/.howone/skills/hallmark/references/components/f6-product-card-grid.md +41 -0
  26. package/templates/vite/.howone/skills/hallmark/references/components/ft1-mast-headed.md +13 -0
  27. package/templates/vite/.howone/skills/hallmark/references/components/ft2-inline-rule-single-line.md +10 -0
  28. package/templates/vite/.howone/skills/hallmark/references/components/ft3-index-style-category-list.md +12 -0
  29. package/templates/vite/.howone/skills/hallmark/references/components/ft4-dense-typographic.md +10 -0
  30. package/templates/vite/.howone/skills/hallmark/references/components/ft5-statement.md +21 -0
  31. package/templates/vite/.howone/skills/hallmark/references/components/ft6-letter-close.md +19 -0
  32. package/templates/vite/.howone/skills/hallmark/references/components/ft7-newsletter-first.md +27 -0
  33. package/templates/vite/.howone/skills/hallmark/references/components/ft8-marquee-scroll.md +25 -0
  34. package/templates/vite/.howone/skills/hallmark/references/components/h1-marquee.md +15 -0
  35. package/templates/vite/.howone/skills/hallmark/references/components/h2-split-diptych.md +15 -0
  36. package/templates/vite/.howone/skills/hallmark/references/components/h3-quote-led.md +11 -0
  37. package/templates/vite/.howone/skills/hallmark/references/components/h4-stat-led.md +14 -0
  38. package/templates/vite/.howone/skills/hallmark/references/components/h5-letter-hero.md +11 -0
  39. package/templates/vite/.howone/skills/hallmark/references/components/h6-photographic-fold.md +16 -0
  40. package/templates/vite/.howone/skills/hallmark/references/components/h7-demo-video-clipped-by-viewport-edge.md +27 -0
  41. package/templates/vite/.howone/skills/hallmark/references/components/h8-mockup-split-browser-framed.md +23 -0
  42. package/templates/vite/.howone/skills/hallmark/references/components/h9-custom-illustration-centerpiece.md +27 -0
  43. package/templates/vite/.howone/skills/hallmark/references/components/n1-wordmark-2-links.md +12 -0
  44. package/templates/vite/.howone/skills/hallmark/references/components/n10-floating-on-scroll-morph.md +19 -0
  45. package/templates/vite/.howone/skills/hallmark/references/components/n11-mega-menu.md +40 -0
  46. package/templates/vite/.howone/skills/hallmark/references/components/n12-banner-retract.md +34 -0
  47. package/templates/vite/.howone/skills/hallmark/references/components/n13-inline-cmdk-pill.md +39 -0
  48. package/templates/vite/.howone/skills/hallmark/references/components/n1b-saas-three-section.md +35 -0
  49. package/templates/vite/.howone/skills/hallmark/references/components/n2-floating-chip.md +14 -0
  50. package/templates/vite/.howone/skills/hallmark/references/components/n3-side-rail.md +14 -0
  51. package/templates/vite/.howone/skills/hallmark/references/components/n4-hidden-behind-k.md +9 -0
  52. package/templates/vite/.howone/skills/hallmark/references/components/n5-floating-pill.md +28 -0
  53. package/templates/vite/.howone/skills/hallmark/references/components/n6-newspaper-masthead.md +24 -0
  54. package/templates/vite/.howone/skills/hallmark/references/components/n7-brutal-slab.md +22 -0
  55. package/templates/vite/.howone/skills/hallmark/references/components/n8-terminal-command.md +21 -0
  56. package/templates/vite/.howone/skills/hallmark/references/components/n9-edge-aligned-minimal.md +17 -0
  57. package/templates/vite/.howone/skills/hallmark/references/components/s1-left-margin-numbered.md +15 -0
  58. package/templates/vite/.howone/skills/hallmark/references/components/s2-hanging.md +13 -0
  59. package/templates/vite/.howone/skills/hallmark/references/components/s3-sticky-pinned.md +19 -0
  60. package/templates/vite/.howone/skills/hallmark/references/components/s4-inline-no-break.md +11 -0
  61. package/templates/vite/.howone/skills/hallmark/references/components/s5-bottom-anchored.md +13 -0
  62. package/templates/vite/.howone/skills/hallmark/references/components/t1-pull-quote-with-marginalia.md +12 -0
  63. package/templates/vite/.howone/skills/hallmark/references/components/t2-logo-wall-hairline.md +19 -0
  64. package/templates/vite/.howone/skills/hallmark/references/components/t3-single-huge-quote.md +11 -0
  65. package/templates/vite/.howone/skills/hallmark/references/components/t4-numbered-stat-strip.md +14 -0
  66. package/templates/vite/.howone/skills/hallmark/references/contract.md +24 -0
  67. package/templates/vite/.howone/skills/hallmark/references/copy.md +182 -0
  68. package/templates/vite/.howone/skills/hallmark/references/custom-craft.md +626 -0
  69. package/templates/vite/.howone/skills/hallmark/references/custom-theme.md +367 -0
  70. package/templates/vite/.howone/skills/hallmark/references/design-md.md +116 -0
  71. package/templates/vite/.howone/skills/hallmark/references/export-formats.md +328 -0
  72. package/templates/vite/.howone/skills/hallmark/references/floating-nav.md +89 -0
  73. package/templates/vite/.howone/skills/hallmark/references/genres/atmospheric.md +69 -0
  74. package/templates/vite/.howone/skills/hallmark/references/genres/editorial.md +72 -0
  75. package/templates/vite/.howone/skills/hallmark/references/genres/modern-minimal.md +71 -0
  76. package/templates/vite/.howone/skills/hallmark/references/genres/playful.md +70 -0
  77. package/templates/vite/.howone/skills/hallmark/references/hero-enrichment.md +475 -0
  78. package/templates/vite/.howone/skills/hallmark/references/imagery-kit.md +170 -0
  79. package/templates/vite/.howone/skills/hallmark/references/interaction-and-states.md +208 -0
  80. package/templates/vite/.howone/skills/hallmark/references/layout-and-space.md +112 -0
  81. package/templates/vite/.howone/skills/hallmark/references/macrostructures/01-bento-grid.md +35 -0
  82. package/templates/vite/.howone/skills/hallmark/references/macrostructures/02-long-document.md +34 -0
  83. package/templates/vite/.howone/skills/hallmark/references/macrostructures/03-marquee-hero.md +31 -0
  84. package/templates/vite/.howone/skills/hallmark/references/macrostructures/04-stat-led.md +34 -0
  85. package/templates/vite/.howone/skills/hallmark/references/macrostructures/05-workbench.md +32 -0
  86. package/templates/vite/.howone/skills/hallmark/references/macrostructures/06-conversational-faq.md +33 -0
  87. package/templates/vite/.howone/skills/hallmark/references/macrostructures/07-manifesto.md +32 -0
  88. package/templates/vite/.howone/skills/hallmark/references/macrostructures/08-photographic.md +34 -0
  89. package/templates/vite/.howone/skills/hallmark/references/macrostructures/09-quote-led.md +32 -0
  90. package/templates/vite/.howone/skills/hallmark/references/macrostructures/10-specimen.md +32 -0
  91. package/templates/vite/.howone/skills/hallmark/references/macrostructures/11-catalogue.md +23 -0
  92. package/templates/vite/.howone/skills/hallmark/references/macrostructures/12-letter.md +23 -0
  93. package/templates/vite/.howone/skills/hallmark/references/macrostructures/13-index-first.md +23 -0
  94. package/templates/vite/.howone/skills/hallmark/references/macrostructures/14-narrative-workflow.md +23 -0
  95. package/templates/vite/.howone/skills/hallmark/references/macrostructures/15-split-studio.md +23 -0
  96. package/templates/vite/.howone/skills/hallmark/references/macrostructures/16-feature-stack.md +23 -0
  97. package/templates/vite/.howone/skills/hallmark/references/macrostructures/17-type-specimen.md +23 -0
  98. package/templates/vite/.howone/skills/hallmark/references/macrostructures/18-portfolio-grid.md +23 -0
  99. package/templates/vite/.howone/skills/hallmark/references/macrostructures/19-map-diagram.md +23 -0
  100. package/templates/vite/.howone/skills/hallmark/references/macrostructures/20-ecosystem-index.md +23 -0
  101. package/templates/vite/.howone/skills/hallmark/references/macrostructures/21-component-playground.md +23 -0
  102. package/templates/vite/.howone/skills/hallmark/references/macrostructures.md +89 -0
  103. package/templates/vite/.howone/skills/hallmark/references/microinteractions.md +258 -0
  104. package/templates/vite/.howone/skills/hallmark/references/motion.md +109 -0
  105. package/templates/vite/.howone/skills/hallmark/references/preview-examples.md +49 -0
  106. package/templates/vite/.howone/skills/hallmark/references/responsive.md +138 -0
  107. package/templates/vite/.howone/skills/hallmark/references/slop-test.md +192 -0
  108. package/templates/vite/.howone/skills/hallmark/references/structure.md +160 -0
  109. package/templates/vite/.howone/skills/hallmark/references/study.md +509 -0
  110. package/templates/vite/.howone/skills/hallmark/references/themes/carnival.md +301 -0
  111. package/templates/vite/.howone/skills/hallmark/references/themes/cobalt.md +146 -0
  112. package/templates/vite/.howone/skills/hallmark/references/themes/hum.md +403 -0
  113. package/templates/vite/.howone/skills/hallmark/references/themes/lumen.md +478 -0
  114. package/templates/vite/.howone/skills/hallmark/references/typography.md +243 -0
  115. package/templates/vite/.howone/skills/hallmark/references/verbs/audit.md +25 -0
  116. package/templates/vite/.howone/skills/hallmark/references/verbs/redesign.md +269 -0
  117. package/templates/vite/.howone/skills/howone/01-architect/01-app-generation.md +209 -0
  118. package/templates/vite/.howone/skills/howone/01-architect/02-manifest-codegen.md +194 -0
  119. package/templates/vite/.howone/skills/howone/02-entity-schema/01-schema-design.md +523 -0
  120. package/templates/vite/.howone/skills/howone/02-entity-schema/02-schema-operations.md +329 -0
  121. package/templates/vite/.howone/skills/howone/02-entity-schema/03-access-models.md +151 -0
  122. package/templates/vite/.howone/skills/howone/02-entity-schema/04-query-contracts.md +123 -0
  123. package/templates/vite/.howone/skills/howone/02-entity-schema/05-ai-persistence-patterns.md +255 -0
  124. package/templates/vite/.howone/skills/howone/03-ai-capabilities/01-ai-capability-architecture.md +215 -0
  125. package/templates/vite/.howone/skills/howone/03-ai-capabilities/02-workflow-contract-rules.md +427 -0
  126. package/templates/vite/.howone/skills/howone/03-ai-capabilities/03-service-capability-catalog.md +304 -0
  127. package/templates/vite/.howone/skills/howone/03-ai-capabilities/04-workflow-operations.md +164 -0
  128. package/templates/vite/.howone/skills/howone/03-ai-capabilities/05-ai-feature-playbooks.md +275 -0
  129. package/templates/vite/.howone/skills/howone/04-app-sdk/01-client-setup.md +162 -0
  130. package/templates/vite/.howone/skills/howone/04-app-sdk/02-entity-operations.md +163 -0
  131. package/templates/vite/.howone/skills/howone/04-app-sdk/03-auth.md +418 -0
  132. package/templates/vite/.howone/skills/howone/04-app-sdk/04-react-integration.md +138 -0
  133. package/templates/vite/.howone/skills/howone/04-app-sdk/05-file-upload.md +112 -0
  134. package/templates/vite/.howone/skills/howone/04-app-sdk/06-raw-http.md +128 -0
  135. package/templates/vite/.howone/skills/howone/04-app-sdk/07-ai-action-calls.md +210 -0
  136. package/templates/vite/.howone/skills/howone/04-app-sdk/08-ai-manifest-handoff.md +90 -0
  137. package/templates/vite/.howone/skills/howone/04-app-sdk/09-extension-boundaries.md +226 -0
  138. package/templates/vite/.howone/skills/howone/04-app-sdk/10-workflow-execute-sse.md +138 -0
  139. package/templates/vite/.howone/skills/howone/04-app-sdk/11-entity-data-access-patterns.md +310 -0
  140. package/templates/vite/.howone/skills/howone/04-app-sdk/12-query-dsl-and-responses.md +237 -0
  141. package/templates/vite/.howone/skills/howone/04-app-sdk/13-credits.md +31 -0
  142. package/templates/vite/.howone/skills/howone/SKILL.md +256 -0
  143. package/templates/vite/.howone/skills/howone/agents/openai.yaml +4 -0
  144. package/templates/vite/.howone/skills/howone/references/audio-generation.md +30 -0
  145. package/templates/vite/.howone/skills/howone/references/audio-recognition.md +30 -0
  146. package/templates/vite/.howone/skills/howone/references/common-errors.md +27 -0
  147. package/templates/vite/.howone/skills/howone/references/finance.md +28 -0
  148. package/templates/vite/.howone/skills/howone/references/image-editing.md +30 -0
  149. package/templates/vite/.howone/skills/howone/references/image-generation.md +30 -0
  150. package/templates/vite/.howone/skills/howone/references/version-evidence.md +47 -0
  151. package/templates/vite/.howone/skills/howone/references/video-generation.md +35 -0
  152. package/templates/vite/.howone/skills/howone/scripts/verify-project.mjs +151 -0
  153. package/templates/vite/.prettierignore +7 -0
  154. package/templates/vite/.prettierrc +11 -0
  155. package/templates/vite/AGENTS.md +87 -0
  156. package/templates/vite/README.md +21 -0
  157. package/templates/vite/components.json +25 -0
  158. package/templates/vite/eslint.config.js +23 -0
  159. package/templates/vite/index.html +12 -0
  160. package/templates/vite/package.json +58 -0
  161. package/templates/vite/public/vite.svg +1 -0
  162. package/templates/vite/src/App.tsx +17 -0
  163. package/templates/vite/src/assets/react.svg +1 -0
  164. package/templates/vite/src/components/theme-provider.tsx +230 -0
  165. package/templates/vite/src/components/ui/accordion.tsx +79 -0
  166. package/templates/vite/src/components/ui/alert-dialog.tsx +197 -0
  167. package/templates/vite/src/components/ui/alert.tsx +76 -0
  168. package/templates/vite/src/components/ui/aspect-ratio.tsx +11 -0
  169. package/templates/vite/src/components/ui/avatar.tsx +110 -0
  170. package/templates/vite/src/components/ui/badge.tsx +49 -0
  171. package/templates/vite/src/components/ui/breadcrumb.tsx +122 -0
  172. package/templates/vite/src/components/ui/button-group.tsx +83 -0
  173. package/templates/vite/src/components/ui/button.tsx +67 -0
  174. package/templates/vite/src/components/ui/calendar.tsx +222 -0
  175. package/templates/vite/src/components/ui/card.tsx +103 -0
  176. package/templates/vite/src/components/ui/carousel.tsx +240 -0
  177. package/templates/vite/src/components/ui/chart.tsx +373 -0
  178. package/templates/vite/src/components/ui/checkbox.tsx +31 -0
  179. package/templates/vite/src/components/ui/collapsible.tsx +33 -0
  180. package/templates/vite/src/components/ui/combobox.tsx +299 -0
  181. package/templates/vite/src/components/ui/command.tsx +193 -0
  182. package/templates/vite/src/components/ui/context-menu.tsx +261 -0
  183. package/templates/vite/src/components/ui/dialog.tsx +168 -0
  184. package/templates/vite/src/components/ui/direction.tsx +22 -0
  185. package/templates/vite/src/components/ui/drawer.tsx +132 -0
  186. package/templates/vite/src/components/ui/dropdown-menu.tsx +269 -0
  187. package/templates/vite/src/components/ui/empty.tsx +104 -0
  188. package/templates/vite/src/components/ui/field.tsx +238 -0
  189. package/templates/vite/src/components/ui/hover-card.tsx +42 -0
  190. package/templates/vite/src/components/ui/input-group.tsx +154 -0
  191. package/templates/vite/src/components/ui/input-otp.tsx +87 -0
  192. package/templates/vite/src/components/ui/input.tsx +19 -0
  193. package/templates/vite/src/components/ui/item.tsx +196 -0
  194. package/templates/vite/src/components/ui/kbd.tsx +26 -0
  195. package/templates/vite/src/components/ui/label.tsx +22 -0
  196. package/templates/vite/src/components/ui/menubar.tsx +280 -0
  197. package/templates/vite/src/components/ui/native-select.tsx +61 -0
  198. package/templates/vite/src/components/ui/navigation-menu.tsx +164 -0
  199. package/templates/vite/src/components/ui/pagination.tsx +129 -0
  200. package/templates/vite/src/components/ui/popover.tsx +87 -0
  201. package/templates/vite/src/components/ui/progress.tsx +31 -0
  202. package/templates/vite/src/components/ui/radio-group.tsx +42 -0
  203. package/templates/vite/src/components/ui/resizable.tsx +50 -0
  204. package/templates/vite/src/components/ui/scroll-area.tsx +53 -0
  205. package/templates/vite/src/components/ui/select.tsx +192 -0
  206. package/templates/vite/src/components/ui/separator.tsx +26 -0
  207. package/templates/vite/src/components/ui/sheet.tsx +145 -0
  208. package/templates/vite/src/components/ui/sidebar.tsx +700 -0
  209. package/templates/vite/src/components/ui/skeleton.tsx +13 -0
  210. package/templates/vite/src/components/ui/slider.tsx +59 -0
  211. package/templates/vite/src/components/ui/sonner.tsx +47 -0
  212. package/templates/vite/src/components/ui/spinner.tsx +10 -0
  213. package/templates/vite/src/components/ui/switch.tsx +33 -0
  214. package/templates/vite/src/components/ui/table.tsx +114 -0
  215. package/templates/vite/src/components/ui/tabs.tsx +90 -0
  216. package/templates/vite/src/components/ui/textarea.tsx +18 -0
  217. package/templates/vite/src/components/ui/toggle-group.tsx +89 -0
  218. package/templates/vite/src/components/ui/toggle.tsx +45 -0
  219. package/templates/vite/src/components/ui/tooltip.tsx +57 -0
  220. package/templates/vite/src/hooks/use-mobile.ts +19 -0
  221. package/templates/vite/src/index.css +133 -0
  222. package/templates/vite/src/lib/sdk.ts +34 -0
  223. package/templates/vite/src/lib/utils.ts +6 -0
  224. package/templates/vite/src/main.tsx +14 -0
  225. package/templates/vite/tsconfig.app.json +32 -0
  226. package/templates/vite/tsconfig.json +13 -0
  227. package/templates/vite/tsconfig.node.json +26 -0
  228. package/templates/vite/vite.config.ts +14 -0
package/bin/index.mjs ADDED
@@ -0,0 +1,2397 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { execFile, spawn } from "node:child_process";
4
+ import { appendFile, chmod, cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { promisify } from "node:util";
8
+ import { say, spinner } from "@astrojs/cli-kit";
9
+ import { cancel, confirm, isCancel, select, text } from "@clack/prompts";
10
+ import { copy, emptyDir, ensureDir, pathExists } from "fs-extra/esm";
11
+ import pc from "picocolors";
12
+ import validatePackageName from "validate-npm-package-name";
13
+ import yargsParser from "yargs-parser";
14
+ import { existsSync, watch } from "node:fs";
15
+ import os from "node:os";
16
+ import { createHash, randomUUID } from "node:crypto";
17
+ //#region src/errors.ts
18
+ var CliError = class extends Error {
19
+ constructor(code, message, details) {
20
+ super(message);
21
+ this.code = code;
22
+ this.details = details;
23
+ this.name = "CliError";
24
+ }
25
+ };
26
+ function configDir() {
27
+ const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
28
+ return path.join(base, "howone");
29
+ }
30
+ function credentialsPath() {
31
+ return path.join(configDir(), "credentials.json");
32
+ }
33
+ async function readCredentials() {
34
+ try {
35
+ const parsed = JSON.parse(await readFile(credentialsPath(), "utf-8"));
36
+ return parsed?.token && parsed.apiUrl ? parsed : null;
37
+ } catch (error) {
38
+ if (error.code === "ENOENT") return null;
39
+ throw error;
40
+ }
41
+ }
42
+ async function writeCredentials(credentials) {
43
+ await mkdir(configDir(), {
44
+ recursive: true,
45
+ mode: 448
46
+ });
47
+ const file = credentialsPath();
48
+ await writeFile(file, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 384 });
49
+ await chmod(file, 384);
50
+ }
51
+ async function deleteCredentials() {
52
+ await rm(credentialsPath(), { force: true });
53
+ }
54
+ /** 令牌优先级:--token > HOWONE_API_TOKEN(CI 用) > howone login 存下的。 */
55
+ async function resolveConnection(options) {
56
+ const stored = await readCredentials();
57
+ const apiUrl = (options.apiUrl ?? process.env.HOWONE_API_URL ?? stored?.apiUrl ?? "https://howone.dev").replace(/\/+$/, "");
58
+ if (options.token) return {
59
+ apiUrl,
60
+ token: options.token,
61
+ source: "flag"
62
+ };
63
+ const envToken = process.env.HOWONE_API_TOKEN ?? process.env.HOWONE_AGENT_TOKEN;
64
+ if (envToken) return {
65
+ apiUrl,
66
+ token: envToken,
67
+ source: "env"
68
+ };
69
+ if (stored && stored.apiUrl.replace(/\/+$/, "") === apiUrl) return {
70
+ apiUrl,
71
+ token: stored.token,
72
+ source: "login"
73
+ };
74
+ return {
75
+ apiUrl,
76
+ token: void 0,
77
+ source: "none"
78
+ };
79
+ }
80
+ //#endregion
81
+ //#region src/work-with/api.ts
82
+ var HowoneApi = class HowoneApi {
83
+ constructor(apiUrl, token) {
84
+ this.apiUrl = apiUrl;
85
+ this.token = token;
86
+ }
87
+ static async connect(options, { requireAuth = true } = {}) {
88
+ const connection = await resolveConnection(options);
89
+ if (requireAuth && !connection.token) throw new CliError("E_AUTH_REQUIRED", "Not logged in. Run `howone login`, or set HOWONE_API_TOKEN.");
90
+ return new HowoneApi(connection.apiUrl, connection.token);
91
+ }
92
+ url(apiPath, query) {
93
+ const url = new URL(apiPath.startsWith("/") ? apiPath : `/${apiPath}`, `${this.apiUrl}/`);
94
+ for (const [key, value] of Object.entries(query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
95
+ return url.toString();
96
+ }
97
+ headers(options, accept = "application/json") {
98
+ const headers = new Headers({ Accept: accept });
99
+ if (options.body !== void 0) headers.set("Content-Type", "application/json");
100
+ if (this.token && !options.anonymous) headers.set("Authorization", `Bearer ${this.token}`);
101
+ return headers;
102
+ }
103
+ async request(method, apiPath, options = {}) {
104
+ const response = await this.fetch(method, apiPath, options);
105
+ const text = await response.text();
106
+ const body = text ? parseJson(text) : null;
107
+ if (!response.ok) throw toApiError(response.status, body);
108
+ return body;
109
+ }
110
+ /** 读 text/event-stream,每个事件回调一次;服务端发 `event: error` 时抛错。 */
111
+ async stream(method, apiPath, options, onEvent) {
112
+ const response = await this.fetch(method, apiPath, options, "text/event-stream");
113
+ if (!response.ok) {
114
+ const text = await response.text();
115
+ throw toApiError(response.status, text ? parseJson(text) : null);
116
+ }
117
+ if (!response.body) return;
118
+ const reader = response.body.getReader();
119
+ const decoder = new TextDecoder();
120
+ let buffer = "";
121
+ while (true) {
122
+ const { value, done } = await reader.read();
123
+ if (done) break;
124
+ buffer += decoder.decode(value, { stream: true });
125
+ let boundary = buffer.indexOf("\n\n");
126
+ while (boundary >= 0) {
127
+ const chunk = buffer.slice(0, boundary);
128
+ buffer = buffer.slice(boundary + 2);
129
+ const event = parseSseChunk(chunk);
130
+ if (event) await onEvent(event);
131
+ boundary = buffer.indexOf("\n\n");
132
+ }
133
+ }
134
+ const tail = parseSseChunk(buffer);
135
+ if (tail) await onEvent(tail);
136
+ }
137
+ async fetch(method, apiPath, options, accept) {
138
+ try {
139
+ return await fetch(this.url(apiPath, options.query), {
140
+ method,
141
+ headers: this.headers(options, accept),
142
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
143
+ signal: options.signal
144
+ });
145
+ } catch (error) {
146
+ throw new CliError("E_NETWORK", `Cannot reach ${this.apiUrl}: ${error instanceof Error ? error.message : String(error)}`);
147
+ }
148
+ }
149
+ };
150
+ function parseSseChunk(chunk) {
151
+ let event = "message";
152
+ const data = [];
153
+ for (const line of chunk.split("\n")) if (line.startsWith("event:")) event = line.slice(6).trim();
154
+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
155
+ if (!data.length) return null;
156
+ return {
157
+ event,
158
+ data: parseJson(data.join("\n"))
159
+ };
160
+ }
161
+ function parseJson(text) {
162
+ try {
163
+ return JSON.parse(text);
164
+ } catch {
165
+ return text;
166
+ }
167
+ }
168
+ function toApiError(status, body) {
169
+ const error = body && typeof body === "object" ? body.error : void 0;
170
+ const record = error && typeof error === "object" ? error : {};
171
+ return new CliError(typeof record.code === "string" ? record.code : status === 401 ? "E_AUTH_REQUIRED" : status === 403 ? "E_FORBIDDEN" : status === 404 ? "E_NOT_FOUND" : "E_API_REQUEST_FAILED", typeof record.message === "string" ? record.message : typeof error === "string" ? error : `HowOne API request failed: HTTP ${status}`, {
172
+ status,
173
+ body
174
+ });
175
+ }
176
+ //#endregion
177
+ //#region src/work-with/files.ts
178
+ const execFileAsync$1 = promisify(execFile);
179
+ /** 单文件上限。平台归档拒收大文件(曾有 core dump 进版本),这里先拦。 */
180
+ const MAX_FILE_BYTES = 5 * 1024 * 1024;
181
+ /** 本地绑定信息,只在本机,不同步到沙箱。 */
182
+ const LOCAL_STATE_FILE = ".howone/cli.json";
183
+ const EXCLUDED_DIRS = new Set([
184
+ "node_modules",
185
+ ".git",
186
+ "dist",
187
+ "build",
188
+ "coverage",
189
+ ".turbo",
190
+ ".vite",
191
+ ".next",
192
+ ".cache"
193
+ ]);
194
+ function isExcludedPath(relativePath) {
195
+ const parts = relativePath.split("/");
196
+ if (parts.some((part) => EXCLUDED_DIRS.has(part))) return true;
197
+ const base = parts[parts.length - 1] ?? "";
198
+ if (base === ".env" || base.startsWith(".env.")) return true;
199
+ if (base === ".DS_Store" || base.endsWith(".log")) return true;
200
+ return relativePath === LOCAL_STATE_FILE;
201
+ }
202
+ /**
203
+ * 列出要同步的文件。在 git 仓库里用 `git ls-files` 尊重 .gitignore,
204
+ * 否则自己遍历;两种情况都再套一层硬排除(node_modules、.env 等)。
205
+ */
206
+ async function buildLocalManifest(root) {
207
+ const candidates = await listGitFiles(root) ?? await walk(root, "");
208
+ const files = [];
209
+ const rejected = [];
210
+ for (const relativePath of [...new Set(candidates)].sort()) {
211
+ if (isExcludedPath(relativePath)) continue;
212
+ const absolute = path.join(root, relativePath);
213
+ let info;
214
+ try {
215
+ info = await lstat(absolute);
216
+ } catch (error) {
217
+ if (error.code === "ENOENT") continue;
218
+ throw error;
219
+ }
220
+ if (info.isSymbolicLink()) {
221
+ rejected.push({
222
+ path: relativePath,
223
+ reason: "symlink"
224
+ });
225
+ continue;
226
+ }
227
+ if (!info.isFile()) continue;
228
+ if (info.size > 5242880) {
229
+ rejected.push({
230
+ path: relativePath,
231
+ reason: "too_large"
232
+ });
233
+ continue;
234
+ }
235
+ const content = await readFile(absolute);
236
+ files.push({
237
+ path: relativePath,
238
+ size: info.size,
239
+ sha256: sha256(content)
240
+ });
241
+ }
242
+ return {
243
+ files,
244
+ rejected
245
+ };
246
+ }
247
+ function sha256(content) {
248
+ return createHash("sha256").update(content).digest("hex");
249
+ }
250
+ function assertNoRejected(manifest) {
251
+ if (!manifest.rejected.length) return;
252
+ throw new CliError("E_FILES_REJECTED", `Refusing to sync: ${manifest.rejected.map((item) => `${item.path} (${item.reason})`).join(", ")}. Symlinks and files over ${MAX_FILE_BYTES / 1024 / 1024}MB are not accepted; remove them or add them to .gitignore.`, { rejected: manifest.rejected });
253
+ }
254
+ async function listGitFiles(root) {
255
+ try {
256
+ const { stdout } = await execFileAsync$1("git", [
257
+ "ls-files",
258
+ "--cached",
259
+ "--others",
260
+ "--exclude-standard",
261
+ "-z"
262
+ ], {
263
+ cwd: root,
264
+ maxBuffer: 64 * 1024 * 1024
265
+ });
266
+ return stdout.split("\0").filter(Boolean);
267
+ } catch {
268
+ return null;
269
+ }
270
+ }
271
+ async function walk(root, relative) {
272
+ const entries = await readdir(path.join(root, relative), { withFileTypes: true });
273
+ const result = [];
274
+ for (const entry of entries) {
275
+ const child = relative ? `${relative}/${entry.name}` : entry.name;
276
+ if (entry.isDirectory()) {
277
+ if (EXCLUDED_DIRS.has(entry.name)) continue;
278
+ result.push(...await walk(root, child));
279
+ } else result.push(child);
280
+ }
281
+ return result;
282
+ }
283
+ /** 本地为准:远端多出来的删,哈希不同的传。远端被排除的路径(node_modules 等)不动。 */
284
+ function planSync(local, remote) {
285
+ const remoteByPath = new Map(remote.map((file) => [file.path, file.sha256]));
286
+ const localPaths = new Set(local.map((file) => file.path));
287
+ return {
288
+ upload: local.filter((file) => remoteByPath.get(file.path) !== file.sha256),
289
+ remove: remote.map((file) => file.path).filter((file) => !localPaths.has(file) && !isExcludedPath(file))
290
+ };
291
+ }
292
+ //#endregion
293
+ //#region src/work-with/project-state.ts
294
+ function findProjectRoot(start) {
295
+ let dir = path.resolve(start);
296
+ while (true) {
297
+ if (existsSync(path.join(dir, ".howone/cli.json"))) return dir;
298
+ const parent = path.dirname(dir);
299
+ if (parent === dir) return null;
300
+ dir = parent;
301
+ }
302
+ }
303
+ async function readProjectState(root) {
304
+ try {
305
+ return JSON.parse(await readFile(path.join(root, LOCAL_STATE_FILE), "utf-8"));
306
+ } catch (error) {
307
+ if (error.code === "ENOENT") return null;
308
+ throw error;
309
+ }
310
+ }
311
+ async function writeProjectState(root, state) {
312
+ const file = path.join(root, LOCAL_STATE_FILE);
313
+ await mkdir(path.dirname(file), { recursive: true });
314
+ await writeFile(file, `${JSON.stringify(state, null, 2)}\n`);
315
+ await ensureGitignored(root);
316
+ }
317
+ function newClientId() {
318
+ return randomUUID().replace(/-/g, "");
319
+ }
320
+ async function ensureGitignored(root) {
321
+ const gitignore = path.join(root, ".gitignore");
322
+ let content = "";
323
+ try {
324
+ content = await readFile(gitignore, "utf-8");
325
+ } catch (error) {
326
+ if (error.code !== "ENOENT") throw error;
327
+ }
328
+ if (content.split(/\r?\n/).some((line) => line.trim() === ".howone/cli.json")) return;
329
+ await appendFile(gitignore, `${content && !content.endsWith("\n") ? "\n" : ""}${LOCAL_STATE_FILE}\n`);
330
+ }
331
+ /**
332
+ * 找到要操作的 App 和本地目录:
333
+ * - 在 pull 下来的目录(或子目录)里,读 .howone/cli.json;
334
+ * - 给了 --app 而目录还没绑定时,就地绑定(没有基线版本,写操作要 --force 才放行)。
335
+ */
336
+ async function resolveProject(input) {
337
+ const root = findProjectRoot(input.cwd);
338
+ if (root) {
339
+ const state = await readProjectState(root);
340
+ if (state && (!input.app || input.app === state.app)) return {
341
+ root,
342
+ state
343
+ };
344
+ if (state && input.app && input.app !== state.app) throw new CliError("E_APP_MISMATCH", `This directory belongs to app ${state.app}, not ${input.app}. Run from another directory.`);
345
+ }
346
+ if (!input.app) throw new CliError("E_APP_REQUIRED", "No app here. Pass --app <app>, or run inside a directory created by `howone apps pull`.");
347
+ const target = path.resolve(input.cwd);
348
+ const state = {
349
+ app: input.app,
350
+ apiUrl: input.apiUrl,
351
+ clientId: newClientId(),
352
+ baseVersionId: null,
353
+ fenceToken: null
354
+ };
355
+ if (input.bindIfMissing) await writeProjectState(target, state);
356
+ return {
357
+ root: target,
358
+ state
359
+ };
360
+ }
361
+ //#endregion
362
+ //#region src/work-with/skill-install.ts
363
+ const SKILL_NAME = "howone";
364
+ const MARKER_FILE = ".howone-cli.json";
365
+ const TARGET_ROOTS = {
366
+ claude: () => path.join(os.homedir(), ".claude", "skills"),
367
+ codex: () => path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "skills")
368
+ };
369
+ function packageRoot() {
370
+ let dir = path.dirname(fileURLToPath(import.meta.url));
371
+ while (!existsSync(path.join(dir, "package.json"))) {
372
+ const parent = path.dirname(dir);
373
+ if (parent === dir) throw new Error("Cannot locate the howone package root.");
374
+ dir = parent;
375
+ }
376
+ return dir;
377
+ }
378
+ function skillSourceDirs() {
379
+ const root = packageRoot();
380
+ return {
381
+ workWith: path.join(root, "skills", SKILL_NAME),
382
+ coding: path.join(root, "templates", "vite", ".howone", "skills", SKILL_NAME)
383
+ };
384
+ }
385
+ function skillInstallDir(target) {
386
+ return path.join(TARGET_ROOTS[target](), SKILL_NAME);
387
+ }
388
+ /** 默认装 Claude Code;本机有 Codex 配置目录时一并装。 */
389
+ function defaultSkillTargets() {
390
+ const targets = ["claude"];
391
+ if (existsSync(path.dirname(TARGET_ROOTS.codex()))) targets.push("codex");
392
+ return targets;
393
+ }
394
+ async function installSkill(target, version) {
395
+ const dir = skillInstallDir(target);
396
+ const sources = skillSourceDirs();
397
+ await rm(dir, {
398
+ recursive: true,
399
+ force: true
400
+ });
401
+ await mkdir(dir, { recursive: true });
402
+ await cp(sources.workWith, dir, { recursive: true });
403
+ await cp(sources.coding, path.join(dir, "coding"), { recursive: true });
404
+ await writeFile(path.join(dir, MARKER_FILE), `${JSON.stringify({
405
+ version,
406
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
407
+ }, null, 2)}\n`);
408
+ return dir;
409
+ }
410
+ async function installedSkillVersion(target) {
411
+ try {
412
+ return JSON.parse(await readFile(path.join(skillInstallDir(target), MARKER_FILE), "utf-8")).version ?? null;
413
+ } catch {
414
+ return null;
415
+ }
416
+ }
417
+ /**
418
+ * 已经由 CLI 装过的 skill,版本和当前 CLI 不一致就原地覆盖,保证 skill 里写的命令
419
+ * 和装着的 CLI 对得上。没装过(没有标记文件)的位置不碰。
420
+ */
421
+ async function refreshInstalledSkills(version) {
422
+ const refreshed = [];
423
+ for (const target of Object.keys(TARGET_ROOTS)) {
424
+ const installed = await installedSkillVersion(target);
425
+ if (installed && installed !== version) {
426
+ await installSkill(target, version);
427
+ refreshed.push(target);
428
+ }
429
+ }
430
+ return refreshed;
431
+ }
432
+ async function uninstallSkill(target) {
433
+ if (!await installedSkillVersion(target)) return false;
434
+ await rm(skillInstallDir(target), {
435
+ recursive: true,
436
+ force: true
437
+ });
438
+ return true;
439
+ }
440
+ //#endregion
441
+ //#region src/work-with/sync.ts
442
+ const BATCH_MAX_BYTES = 16 * 1024 * 1024;
443
+ const BATCH_MAX_FILES = 400;
444
+ const appPath$1 = (app) => `/api/cli/v1/apps/${encodeURIComponent(app)}`;
445
+ async function fetchRemoteManifest(api, app) {
446
+ return api.request("GET", `${appPath$1(app)}/files`);
447
+ }
448
+ /** 远端独有的文件里,本地 .gitignore 忽略掉的那些不删(本地看不见不代表该删)。 */
449
+ async function dropLocallyIgnored(root, paths) {
450
+ if (!paths.length) return paths;
451
+ const result = await new Promise((resolve, reject) => {
452
+ const child = spawn("git", [
453
+ "check-ignore",
454
+ "--stdin",
455
+ "-z"
456
+ ], { cwd: root });
457
+ let stdout = "";
458
+ child.stdout.on("data", (data) => {
459
+ stdout += String(data);
460
+ });
461
+ child.on("error", reject);
462
+ child.on("close", (code) => resolve({
463
+ code,
464
+ stdout
465
+ }));
466
+ child.stdin.end(paths.join("\0"));
467
+ }).catch(() => ({
468
+ code: 128,
469
+ stdout: ""
470
+ }));
471
+ if (result.code !== 0) return paths;
472
+ const ignored = new Set(result.stdout.split("\0").filter(Boolean));
473
+ return paths.filter((file) => !ignored.has(file));
474
+ }
475
+ function chunk(items) {
476
+ const batches = [];
477
+ let current = [];
478
+ let bytes = 0;
479
+ for (const item of items) {
480
+ if (current.length && (bytes + item.size > BATCH_MAX_BYTES || current.length >= BATCH_MAX_FILES)) {
481
+ batches.push(current);
482
+ current = [];
483
+ bytes = 0;
484
+ }
485
+ current.push(item);
486
+ bytes += item.size;
487
+ }
488
+ if (current.length) batches.push(current);
489
+ return batches;
490
+ }
491
+ /**
492
+ * 把本地目录同步成沙箱的样子(本地为准)。remote 传入已知的远端状态可省一次远端清单;
493
+ * 返回同步后的远端状态,供 dev 模式下次增量比对。
494
+ */
495
+ async function syncToSandbox(input) {
496
+ const local = await buildLocalManifest(input.root);
497
+ assertNoRejected(local);
498
+ const remote = input.remote ?? (await fetchRemoteManifest(input.api, input.app)).files;
499
+ const plan = planSync(local.files, remote);
500
+ const remove = await dropLocallyIgnored(input.root, plan.remove);
501
+ let dependenciesChanged = false;
502
+ const batches = chunk(plan.upload);
503
+ for (const [index, batch] of batches.entries()) {
504
+ input.onProgress?.(`uploading ${batch.length} file(s) (${index + 1}/${batches.length})`);
505
+ const writes = await Promise.all(batch.map(async (file) => ({
506
+ path: file.path,
507
+ sha256: file.sha256,
508
+ contentBase64: (await readFile(path.join(input.root, file.path))).toString("base64")
509
+ })));
510
+ for (const write of writes) {
511
+ const actual = sha256(Buffer.from(write.contentBase64, "base64"));
512
+ if (actual !== write.sha256) write.sha256 = actual;
513
+ }
514
+ const result = await input.api.request("POST", `${appPath$1(input.app)}/sync`, { body: {
515
+ clientId: input.lock.clientId,
516
+ fenceToken: input.lock.fenceToken,
517
+ writes,
518
+ deletes: index === batches.length - 1 ? remove : []
519
+ } });
520
+ dependenciesChanged ||= result.dependenciesChanged;
521
+ }
522
+ if (!batches.length && remove.length) await input.api.request("POST", `${appPath$1(input.app)}/sync`, { body: {
523
+ clientId: input.lock.clientId,
524
+ fenceToken: input.lock.fenceToken,
525
+ writes: [],
526
+ deletes: remove
527
+ } });
528
+ const removed = new Set(remove);
529
+ const uploaded = new Map(plan.upload.map((file) => [file.path, file.sha256]));
530
+ const next = [...remote.filter((file) => !removed.has(file.path) && !uploaded.has(file.path)), ...plan.upload.map((file) => ({
531
+ path: file.path,
532
+ sha256: file.sha256
533
+ }))];
534
+ return {
535
+ summary: {
536
+ uploaded: plan.upload.length,
537
+ deleted: remove.length,
538
+ dependenciesChanged
539
+ },
540
+ remote: next
541
+ };
542
+ }
543
+ /** 把沙箱里的文件拉到本地目录(pull)。 */
544
+ async function pullFromSandbox(input) {
545
+ const manifest = await fetchRemoteManifest(input.api, input.app);
546
+ const batches = chunk(manifest.files);
547
+ let written = 0;
548
+ for (const [index, batch] of batches.entries()) {
549
+ input.onProgress?.(`downloading ${batch.length} file(s) (${index + 1}/${batches.length})`);
550
+ const { files } = await input.api.request("POST", `${appPath$1(input.app)}/files/read`, { body: { paths: batch.map((file) => file.path) } });
551
+ for (const file of files) {
552
+ const target = path.resolve(input.root, file.path);
553
+ if (!target.startsWith(`${path.resolve(input.root)}${path.sep}`)) throw new CliError("E_BAD_PATH", `Refusing to write outside the directory: ${file.path}`);
554
+ const content = Buffer.from(file.contentBase64, "base64");
555
+ if (sha256(content) !== file.sha256) throw new CliError("E_HASH_MISMATCH", `Corrupted download: ${file.path}`);
556
+ await mkdir(path.dirname(target), { recursive: true });
557
+ await writeFile(target, content);
558
+ written += 1;
559
+ }
560
+ }
561
+ return {
562
+ written,
563
+ baseVersion: manifest.baseVersion
564
+ };
565
+ }
566
+ /**
567
+ * 平台工具(ai-sync / schema-sync)在沙箱里生成的产物拉回本地:本地才是源头,
568
+ * 不拉回来下一次 push 就会把它们当成「本地删掉了」删掉。只拉 prefix 下内容不同的文件。
569
+ */
570
+ async function pullGenerated(input) {
571
+ const manifest = await fetchRemoteManifest(input.api, input.app);
572
+ const wanted = [];
573
+ for (const file of manifest.files) {
574
+ if (!file.path.startsWith(input.prefix)) continue;
575
+ let localHash = null;
576
+ try {
577
+ localHash = sha256(await readFile(path.join(input.root, file.path)));
578
+ } catch (error) {
579
+ if (error.code !== "ENOENT") throw error;
580
+ }
581
+ if (localHash !== file.sha256) wanted.push(file.path);
582
+ }
583
+ if (!wanted.length) return [];
584
+ const { files } = await input.api.request("POST", `${appPath$1(input.app)}/files/read`, { body: { paths: wanted } });
585
+ for (const file of files) {
586
+ const target = path.resolve(input.root, file.path);
587
+ if (!target.startsWith(`${path.resolve(input.root)}${path.sep}`)) throw new CliError("E_BAD_PATH", `Refusing to write outside the directory: ${file.path}`);
588
+ await mkdir(path.dirname(target), { recursive: true });
589
+ await writeFile(target, Buffer.from(file.contentBase64, "base64"));
590
+ }
591
+ return wanted;
592
+ }
593
+ //#endregion
594
+ //#region src/work-with/commands.ts
595
+ const appPath = (app) => `/api/cli/v1/apps/${encodeURIComponent(app)}`;
596
+ /** 结果:--json 时只往 stdout 打一份 JSON(给 agent 读);否则给人看的摘要。 */
597
+ function emit(options, result, human) {
598
+ if (options.json) {
599
+ console.log(JSON.stringify({
600
+ ok: true,
601
+ ...result
602
+ }, null, 2));
603
+ return;
604
+ }
605
+ human();
606
+ }
607
+ /** 过程信息一律走 stderr,不污染 stdout 上的 JSON。 */
608
+ function progress(options, message) {
609
+ if (options.json) console.error(JSON.stringify({ progress: message }));
610
+ else console.error(pc.dim(message));
611
+ }
612
+ function line(label, value) {
613
+ console.log(` ${pc.dim(label.padEnd(14))} ${value ?? pc.dim("—")}`);
614
+ }
615
+ function cwdOf(options) {
616
+ return path.resolve(options.cwd ?? process.cwd());
617
+ }
618
+ async function connect(options) {
619
+ return HowoneApi.connect(options);
620
+ }
621
+ function openBrowser(url) {
622
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
623
+ const args = process.platform === "win32" ? [
624
+ "/c",
625
+ "start",
626
+ "",
627
+ url
628
+ ] : [url];
629
+ try {
630
+ const child = spawn(command, args, {
631
+ stdio: "ignore",
632
+ detached: true
633
+ });
634
+ child.on("error", () => void 0);
635
+ child.unref();
636
+ } catch {}
637
+ }
638
+ async function runLogin(options) {
639
+ const connection = await resolveConnection({ apiUrl: options.apiUrl });
640
+ const api = new HowoneApi(connection.apiUrl, void 0);
641
+ const clientName = `${os.hostname()} (${process.platform})`;
642
+ const started = await api.request("POST", "/api/cli/v1/auth/device", {
643
+ body: { clientName },
644
+ anonymous: true
645
+ });
646
+ console.error([`${pc.bold("Confirm in your browser:")} ${pc.cyan(started.verificationUriComplete)}`, `${pc.dim("Code")} ${pc.bold(started.userCode)}`].join("\n"));
647
+ if (options.browser !== false) openBrowser(started.verificationUriComplete);
648
+ const deadline = Date.now() + started.expiresIn * 1e3;
649
+ while (Date.now() < deadline) {
650
+ await new Promise((resolve) => setTimeout(resolve, started.interval * 1e3));
651
+ try {
652
+ const granted = await api.request("POST", "/api/cli/v1/auth/token", {
653
+ body: { deviceCode: started.deviceCode },
654
+ anonymous: true
655
+ });
656
+ await writeCredentials({
657
+ apiUrl: connection.apiUrl,
658
+ token: granted.token,
659
+ tokenId: granted.tokenId,
660
+ user: granted.user,
661
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
662
+ });
663
+ const skills = options.skill === false ? [] : await Promise.all(defaultSkillTargets().map(async (target) => ({
664
+ target,
665
+ dir: await installSkill(target, options.version)
666
+ })));
667
+ emit(options, {
668
+ user: granted.user,
669
+ apiUrl: connection.apiUrl,
670
+ skills
671
+ }, () => {
672
+ console.log(`${pc.green("Logged in")} as ${pc.bold(granted.user.email ?? granted.user.id)}`);
673
+ for (const skill of skills) line(`skill (${skill.target})`, skill.dir);
674
+ });
675
+ return;
676
+ } catch (error) {
677
+ if (error instanceof CliError && error.code === "authorization_pending") continue;
678
+ if (error instanceof CliError && error.code === "access_denied") throw new CliError("E_LOGIN_DENIED", "Login was cancelled in the browser.");
679
+ if (error instanceof CliError && error.code === "expired_token") break;
680
+ throw error;
681
+ }
682
+ }
683
+ throw new CliError("E_LOGIN_EXPIRED", "The login code expired. Run `howone login` again.");
684
+ }
685
+ async function runLogout(options) {
686
+ const stored = await readCredentials();
687
+ if (stored) await new HowoneApi(stored.apiUrl, stored.token).request("DELETE", "/api/cli/v1/tokens/current").catch(() => void 0);
688
+ await deleteCredentials();
689
+ emit(options, { loggedOut: true }, () => console.log(pc.green("Logged out")));
690
+ }
691
+ async function runWhoami(options) {
692
+ const api = await connect(options);
693
+ const me = await api.request("GET", "/api/cli/v1/me");
694
+ emit(options, {
695
+ ...me,
696
+ apiUrl: api.apiUrl
697
+ }, () => {
698
+ line("user", me.user.email ?? me.user.id);
699
+ line("api", api.apiUrl);
700
+ if (me.token) line("scopes", me.token.scopes.join(", "));
701
+ });
702
+ }
703
+ async function runSetup(options, uninstall = false) {
704
+ const targets = options.target === "claude" || options.target === "codex" ? [options.target] : options.target ? (() => {
705
+ throw new CliError("E_BAD_TARGET", "--target must be claude or codex.");
706
+ })() : defaultSkillTargets();
707
+ if (uninstall) {
708
+ const removed = await Promise.all(targets.map(async (target) => ({
709
+ target,
710
+ removed: await uninstallSkill(target)
711
+ })));
712
+ emit(options, { removed }, () => {
713
+ for (const item of removed) line(item.target, item.removed ? "removed" : "not installed");
714
+ });
715
+ return;
716
+ }
717
+ const installed = await Promise.all(targets.map(async (target) => ({
718
+ target,
719
+ dir: await installSkill(target, options.version)
720
+ })));
721
+ emit(options, { installed }, () => {
722
+ for (const item of installed) line(item.target, item.dir);
723
+ });
724
+ }
725
+ async function runTokens(sub, args, options) {
726
+ const api = await connect(options);
727
+ if (!sub || sub === "list") {
728
+ const result = await api.request("GET", "/api/cli/v1/tokens");
729
+ emit(options, result, () => {
730
+ for (const token of result.tokens) console.log(` ${pc.bold(String(token.name))} ${pc.dim(String(token.id))} ${token.scopes.join(",")}`);
731
+ });
732
+ return;
733
+ }
734
+ if (sub === "create") {
735
+ const scopes = options.scopes?.split(",").map((scope) => scope.trim()).filter(Boolean);
736
+ const created = await api.request("POST", "/api/cli/v1/tokens", { body: {
737
+ name: options.name ?? args[0] ?? "CI token",
738
+ scopes,
739
+ expiresInDays: options.expiresDays
740
+ } });
741
+ emit(options, created, () => {
742
+ console.log(`${pc.green("Created")} ${pc.dim(created.id)} ${created.scopes.join(",")}`);
743
+ console.log(created.token);
744
+ console.error(pc.yellow("Shown once. Store it as HOWONE_API_TOKEN in your CI secrets."));
745
+ });
746
+ return;
747
+ }
748
+ if (sub === "revoke") {
749
+ if (!args[0]) throw new CliError("E_ARGUMENT_REQUIRED", "Token id is required.");
750
+ await api.request("DELETE", `/api/cli/v1/tokens/${encodeURIComponent(args[0])}`);
751
+ emit(options, { revoked: args[0] }, () => console.log(pc.green("Revoked")));
752
+ return;
753
+ }
754
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown tokens command: ${sub}`);
755
+ }
756
+ async function runApps(sub, args, options) {
757
+ const api = await connect(options);
758
+ if (!sub || sub === "list") {
759
+ const result = await api.request("GET", "/api/cli/v1/apps");
760
+ emit(options, result, () => {
761
+ if (!result.apps.length) console.log(pc.dim("No apps yet. Create one with `howone apps create <name>`."));
762
+ for (const app of result.apps) console.log(` ${pc.bold(String(app.shortId))} ${app.name}${app.productionUrl ? pc.dim(` ${app.productionUrl}`) : ""}`);
763
+ });
764
+ return;
765
+ }
766
+ if (sub === "create") {
767
+ const name = args.join(" ").trim() || options.name;
768
+ if (!name) throw new CliError("E_ARGUMENT_REQUIRED", "App name is required.");
769
+ const result = await api.request("POST", "/api/cli/v1/apps", { body: { name } });
770
+ const root = path.resolve(cwdOf(options), options.target ?? result.app.shortId);
771
+ if (!await isEmptyDir(root) && !options.force) throw new CliError("E_DIR_NOT_EMPTY", `${root} is not empty. Pass --target <dir> or --force.`, { app: result.app });
772
+ await scaffoldTemplate(root);
773
+ await writeProjectState(root, {
774
+ app: result.app.shortId,
775
+ apiUrl: api.apiUrl,
776
+ clientId: newClientId(),
777
+ baseVersionId: null,
778
+ fenceToken: null
779
+ });
780
+ emit(options, {
781
+ ...result,
782
+ dir: root
783
+ }, () => {
784
+ console.log(`${pc.green("Created")} ${pc.bold(result.app.shortId)} ${result.app.name} in ${pc.cyan(root)}`);
785
+ console.log(pc.dim(`Next: cd ${path.relative(process.cwd(), root) || "."} && howone push`));
786
+ });
787
+ return;
788
+ }
789
+ if (sub === "show") {
790
+ const app = args[0] ?? (await resolveProject({
791
+ cwd: cwdOf(options),
792
+ app: options.app,
793
+ apiUrl: api.apiUrl
794
+ })).state.app;
795
+ const { app: status } = await api.request("GET", appPath(app));
796
+ emit(options, { app: status }, () => printStatus(status));
797
+ return;
798
+ }
799
+ if (sub === "pull") {
800
+ await runPull(args[0] ?? options.app, args[1], options, api);
801
+ return;
802
+ }
803
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown apps command: ${sub}`);
804
+ }
805
+ function printStatus(status) {
806
+ console.log(`${pc.bold(status.name)} ${pc.dim(status.shortId)}`);
807
+ line("version", status.latestVersion ? `v${status.latestVersion.number}` : null);
808
+ line("preview", status.previewUrl);
809
+ line("production", status.productionUrl);
810
+ line("editing", status.editLock ? `locally (${status.editLock.clientName ?? "howone CLI"})` : "free");
811
+ }
812
+ /** Start an existing remote preview without requiring a local checkout or edit lock. */
813
+ async function runPreview(appArg, options) {
814
+ const api = await connect(options);
815
+ const result = await streamResult(api, `${appPath(appArg ?? options.app ?? (await resolveProject({
816
+ cwd: cwdOf(options),
817
+ apiUrl: api.apiUrl
818
+ })).state.app)}/preview/wake`, {}, options);
819
+ if (!result.ready || !result.previewUrl) throw new CliError("E_PREVIEW_FAILED", "The server did not return a ready preview URL.");
820
+ emit(options, result, () => line("preview", result.previewUrl));
821
+ }
822
+ async function scaffoldTemplate(root) {
823
+ const template = path.join(packageRoot(), "templates", "vite");
824
+ await cp(template, root, {
825
+ recursive: true,
826
+ filter: (source) => !path.relative(template, source).split(path.sep).includes("node_modules")
827
+ });
828
+ try {
829
+ await rename(path.join(root, "gitignore"), path.join(root, ".gitignore"));
830
+ } catch (error) {
831
+ if (error.code !== "ENOENT") throw error;
832
+ }
833
+ }
834
+ async function isEmptyDir(dir) {
835
+ try {
836
+ return (await readdir(dir)).length === 0;
837
+ } catch (error) {
838
+ if (error.code === "ENOENT") return true;
839
+ throw error;
840
+ }
841
+ }
842
+ async function runPull(app, dir, options, api) {
843
+ if (!app) throw new CliError("E_ARGUMENT_REQUIRED", "Usage: howone apps pull <app> [dir]");
844
+ const { app: status } = await api.request("GET", appPath(app));
845
+ const root = path.resolve(cwdOf(options), dir ?? status.shortId);
846
+ const existing = await readProjectState(root);
847
+ if (existing && existing.app !== status.shortId) throw new CliError("E_APP_MISMATCH", `${root} belongs to app ${existing.app}.`);
848
+ if (!existing && !await isEmptyDir(root) && !options.force) throw new CliError("E_DIR_NOT_EMPTY", `${root} is not empty. Use an empty directory, or pass --force.`);
849
+ const pulled = await pullFromSandbox({
850
+ api,
851
+ app: status.shortId,
852
+ root,
853
+ onProgress: (m) => progress(options, m)
854
+ });
855
+ await writeProjectState(root, {
856
+ app: status.shortId,
857
+ apiUrl: api.apiUrl,
858
+ clientId: existing?.clientId ?? newClientId(),
859
+ baseVersionId: pulled.baseVersion?.id ?? null,
860
+ fenceToken: existing?.fenceToken ?? null
861
+ });
862
+ emit(options, {
863
+ app: status.shortId,
864
+ dir: root,
865
+ files: pulled.written,
866
+ baseVersion: pulled.baseVersion
867
+ }, () => {
868
+ console.log(`${pc.green("Pulled")} ${pulled.written} file(s) into ${pc.cyan(root)}`);
869
+ if (!pulled.written) console.log(pc.dim("The app has no code yet — start writing, then `howone push`."));
870
+ });
871
+ }
872
+ async function runStatus(options) {
873
+ await runApps("show", [], options);
874
+ }
875
+ async function acquireLock(options, { bindIfMissing = true } = {}) {
876
+ const api = await connect(options);
877
+ const { root, state } = await resolveProject({
878
+ cwd: cwdOf(options),
879
+ app: options.app,
880
+ apiUrl: api.apiUrl,
881
+ bindIfMissing
882
+ });
883
+ if (!state.baseVersionId && !options.force) {
884
+ const { app: status } = await api.request("GET", appPath(state.app));
885
+ if (status.latestVersion) throw new CliError("E_STALE_BASE", "This directory was not pulled from the app, so pushing would overwrite it. Run `howone apps pull` first, or pass --force.");
886
+ }
887
+ const lock = await api.request("POST", `${appPath(state.app)}/lock`, { body: {
888
+ clientId: state.clientId,
889
+ clientName: `${os.hostname()} · ${path.basename(root)}`,
890
+ ...state.baseVersionId ? { baseVersionId: state.baseVersionId } : {},
891
+ ...options.force ? { force: true } : {}
892
+ } });
893
+ const next = {
894
+ ...state,
895
+ fenceToken: lock.fenceToken
896
+ };
897
+ await writeProjectState(root, next);
898
+ return {
899
+ api,
900
+ root,
901
+ state: next,
902
+ fenceToken: lock.fenceToken,
903
+ acquired: !lock.renewed
904
+ };
905
+ }
906
+ async function releaseLock(session) {
907
+ return session.api.request("DELETE", `${appPath(session.state.app)}/lock`, { body: {
908
+ clientId: session.state.clientId,
909
+ fenceToken: session.fenceToken
910
+ } });
911
+ }
912
+ async function runRelease(options) {
913
+ const api = await connect(options);
914
+ const { root, state } = await resolveProject({
915
+ cwd: cwdOf(options),
916
+ app: options.app,
917
+ apiUrl: api.apiUrl
918
+ });
919
+ if (state.fenceToken === null || state.fenceToken === void 0) {
920
+ emit(options, { released: false }, () => console.log(pc.dim("Not holding the edit lock.")));
921
+ return;
922
+ }
923
+ const result = await releaseLock({
924
+ api,
925
+ root,
926
+ state,
927
+ fenceToken: state.fenceToken,
928
+ acquired: false
929
+ });
930
+ await writeProjectState(root, {
931
+ ...state,
932
+ fenceToken: null
933
+ });
934
+ emit(options, result, () => {
935
+ console.log(pc.green("Released"));
936
+ if (result.sealError) console.error(pc.yellow(`Unsaved changes could not be sealed: ${result.sealError}`));
937
+ });
938
+ }
939
+ async function runSync(options) {
940
+ const session = await acquireLock(options);
941
+ const { summary } = await syncToSandbox({
942
+ api: session.api,
943
+ app: session.state.app,
944
+ root: session.root,
945
+ lock: {
946
+ clientId: session.state.clientId,
947
+ fenceToken: session.fenceToken
948
+ },
949
+ onProgress: (m) => progress(options, m)
950
+ });
951
+ emit(options, {
952
+ app: session.state.app,
953
+ ...summary
954
+ }, () => console.log(`${pc.green("Synced")} ${summary.uploaded} uploaded, ${summary.deleted} deleted`));
955
+ }
956
+ async function streamResult(api, apiPath, body, options) {
957
+ let result;
958
+ let failure;
959
+ await api.stream("POST", apiPath, { body }, (event) => {
960
+ if (event.event === "stage") progress(options, `${event.data.stage}…`);
961
+ else if (event.event === "warning") progress(options, `warning: ${event.data.message}`);
962
+ else if (event.event === "result") result = event.data;
963
+ else if (event.event === "error") failure = event.data;
964
+ });
965
+ if (failure) throw new CliError(failure.code, failure.message, failure.details);
966
+ if (result === void 0) throw new CliError("E_STREAM_ENDED", "The server closed the connection early.");
967
+ return result;
968
+ }
969
+ async function runPush(options) {
970
+ const session = await acquireLock(options);
971
+ const lock = {
972
+ clientId: session.state.clientId,
973
+ fenceToken: session.fenceToken
974
+ };
975
+ progress(options, "syncing…");
976
+ const { summary } = await syncToSandbox({
977
+ api: session.api,
978
+ app: session.state.app,
979
+ root: session.root,
980
+ lock,
981
+ onProgress: (m) => progress(options, m)
982
+ });
983
+ const result = await streamResult(session.api, `${appPath(session.state.app)}/push`, {
984
+ ...lock,
985
+ message: options.message,
986
+ build: options.build !== false
987
+ }, options);
988
+ await writeProjectState(session.root, {
989
+ ...session.state,
990
+ fenceToken: result.fenceToken,
991
+ baseVersionId: result.version?.id ?? session.state.baseVersionId ?? null
992
+ });
993
+ if (session.acquired && !options.keepLock) {
994
+ await releaseLock({
995
+ ...session,
996
+ fenceToken: result.fenceToken
997
+ });
998
+ await writeProjectState(session.root, {
999
+ ...session.state,
1000
+ fenceToken: null,
1001
+ baseVersionId: result.version?.id ?? session.state.baseVersionId ?? null
1002
+ });
1003
+ }
1004
+ if (!result.ok) throw new CliError("E_BUILD_FAILED", `Build failed at ${result.build?.step ?? "build"}.`, {
1005
+ version: result.version,
1006
+ previewUrl: result.previewUrl,
1007
+ build: result.build,
1008
+ synced: summary
1009
+ });
1010
+ emit(options, {
1011
+ app: session.state.app,
1012
+ synced: summary,
1013
+ ...result
1014
+ }, () => {
1015
+ console.log(result.status === "unchanged" ? pc.dim("No changes since the last version.") : `${pc.green("Pushed")} v${result.version?.number}`);
1016
+ line("preview", result.previewUrl);
1017
+ if (result.build) line("build", result.build.status);
1018
+ });
1019
+ }
1020
+ async function runPublish(versionArg, options) {
1021
+ const api = await connect(options);
1022
+ const { state } = await resolveProject({
1023
+ cwd: cwdOf(options),
1024
+ app: options.app,
1025
+ apiUrl: api.apiUrl
1026
+ });
1027
+ if (!options.yes) {
1028
+ if (options.json || !process.stdin.isTTY) throw new CliError("E_CONFIRMATION_REQUIRED", "Publishing goes live for real users. Re-run with --yes after the user agreed.");
1029
+ const answer = await confirm({ message: `Publish ${state.app}${versionArg ? ` v${versionArg}` : ""} to production?` });
1030
+ if (isCancel(answer) || !answer) throw new CliError("E_CANCELLED", "Cancelled.");
1031
+ }
1032
+ const result = await streamResult(api, `${appPath(state.app)}/publish`, {
1033
+ version: versionArg ?? "latest",
1034
+ requestId: newClientId()
1035
+ }, options);
1036
+ emit(options, {
1037
+ app: state.app,
1038
+ ...result
1039
+ }, () => {
1040
+ console.log(`${pc.green("Published")} ${pc.cyan(result.url)}`);
1041
+ });
1042
+ }
1043
+ async function runDev(options) {
1044
+ const session = await acquireLock(options);
1045
+ const lock = {
1046
+ clientId: session.state.clientId,
1047
+ fenceToken: session.fenceToken
1048
+ };
1049
+ const { api, root } = session;
1050
+ const app = session.state.app;
1051
+ let remote;
1052
+ const initial = await syncToSandbox({
1053
+ api,
1054
+ app,
1055
+ root,
1056
+ lock,
1057
+ onProgress: (m) => progress(options, m)
1058
+ });
1059
+ remote = initial.remote;
1060
+ const { previewUrl } = await api.request("POST", `${appPath(app)}/preview`, { body: lock });
1061
+ emit(options, {
1062
+ app,
1063
+ previewUrl,
1064
+ synced: initial.summary
1065
+ }, () => {
1066
+ console.log(`${pc.green("Live")} ${pc.cyan(previewUrl)}`);
1067
+ console.log(pc.dim("Saving a file updates the preview. Ctrl-C to stop (gives the app back)."));
1068
+ });
1069
+ let stopping = false;
1070
+ let syncing = null;
1071
+ let pending = false;
1072
+ let timer = null;
1073
+ const fail = async (error) => {
1074
+ stopping = true;
1075
+ watcher.close();
1076
+ clearInterval(heartbeat);
1077
+ const cliError = error instanceof CliError ? error : new CliError("E_UNEXPECTED", String(error));
1078
+ console.error(JSON.stringify({
1079
+ ok: false,
1080
+ error: {
1081
+ code: cliError.code,
1082
+ message: cliError.message
1083
+ }
1084
+ }));
1085
+ process.exit(1);
1086
+ };
1087
+ const runSyncOnce = async () => {
1088
+ if (syncing) {
1089
+ pending = true;
1090
+ return;
1091
+ }
1092
+ syncing = (async () => {
1093
+ do {
1094
+ pending = false;
1095
+ const next = await syncToSandbox({
1096
+ api,
1097
+ app,
1098
+ root,
1099
+ lock,
1100
+ remote
1101
+ });
1102
+ remote = next.remote;
1103
+ if (next.summary.uploaded || next.summary.deleted) progress(options, `synced ${next.summary.uploaded} up, ${next.summary.deleted} deleted`);
1104
+ if (next.summary.dependenciesChanged) progress(options, "dependencies changed — run `howone push` to reinstall and rebuild");
1105
+ } while (pending && !stopping);
1106
+ })().catch(fail).finally(() => {
1107
+ syncing = null;
1108
+ });
1109
+ };
1110
+ const watcher = watch(root, { recursive: true }, (_event, file) => {
1111
+ if (stopping || !file) return;
1112
+ const relative = String(file).split(path.sep).join("/");
1113
+ if (relative.startsWith(".git/") || relative.includes("node_modules/")) return;
1114
+ if (timer) clearTimeout(timer);
1115
+ timer = setTimeout(() => void runSyncOnce(), 300);
1116
+ });
1117
+ const heartbeat = setInterval(() => {
1118
+ api.request("POST", `${appPath(app)}/lock`, { body: { clientId: lock.clientId } }).catch(fail);
1119
+ }, 6e4);
1120
+ const stop = async () => {
1121
+ if (stopping) return;
1122
+ stopping = true;
1123
+ watcher.close();
1124
+ clearInterval(heartbeat);
1125
+ if (timer) clearTimeout(timer);
1126
+ await syncing;
1127
+ progress(options, "giving the app back…");
1128
+ const released = await releaseLock(session).catch((error) => ({ error: String(error) }));
1129
+ await writeProjectState(root, {
1130
+ ...session.state,
1131
+ fenceToken: null
1132
+ });
1133
+ emit(options, {
1134
+ stopped: true,
1135
+ released
1136
+ }, () => console.log(pc.green("Stopped")));
1137
+ process.exit(0);
1138
+ };
1139
+ process.on("SIGINT", () => void stop());
1140
+ process.on("SIGTERM", () => void stop());
1141
+ await new Promise(() => void 0);
1142
+ }
1143
+ async function readJsonInput(value, cwd) {
1144
+ if (!value) return {};
1145
+ const raw = value.trim();
1146
+ const content = raw.startsWith("{") || raw.startsWith("[") ? raw : await readFile(path.resolve(cwd, raw), "utf-8");
1147
+ try {
1148
+ return JSON.parse(content);
1149
+ } catch (error) {
1150
+ throw new CliError("E_INPUT_INVALID", `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
1151
+ }
1152
+ }
1153
+ async function readStdin() {
1154
+ const chunks = [];
1155
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
1156
+ return Buffer.concat(chunks).toString("utf-8").replace(/\r?\n$/, "");
1157
+ }
1158
+ async function runFunctions(sub, args, options) {
1159
+ const api = await connect(options);
1160
+ const { state } = await resolveProject({
1161
+ cwd: cwdOf(options),
1162
+ app: options.app,
1163
+ apiUrl: api.apiUrl
1164
+ });
1165
+ const base = `${appPath(state.app)}/functions`;
1166
+ if (!sub || sub === "list") {
1167
+ const result = await api.request("GET", base);
1168
+ emit(options, result, () => {
1169
+ if (!result.functions.length) console.log(pc.dim("No functions registered. Push an app with functions/<name>/."));
1170
+ for (const fn of result.functions) console.log(` ${pc.bold(fn.name)} ${pc.dim(`v${fn.version}`)}`);
1171
+ });
1172
+ return;
1173
+ }
1174
+ if (sub === "secrets") {
1175
+ const [action, name] = args;
1176
+ if (!action || action === "list") {
1177
+ const result = await api.request("GET", `${base}/secrets`);
1178
+ emit(options, result, () => {
1179
+ for (const secret of result.secrets) console.log(` ${secret.name} ${pc.dim(secret.updatedAt ?? "")}`);
1180
+ });
1181
+ return;
1182
+ }
1183
+ if (!name) throw new CliError("E_ARGUMENT_REQUIRED", "Secret name is required.");
1184
+ if (action === "set") {
1185
+ const value = options.valueStdin ? await readStdin() : options.value;
1186
+ if (!value) throw new CliError("E_ARGUMENT_REQUIRED", "Pass the value with --value-stdin (preferred) or --value.");
1187
+ await api.request("PUT", `${base}/secrets/${encodeURIComponent(name)}`, { body: { value } });
1188
+ emit(options, {
1189
+ name,
1190
+ saved: true
1191
+ }, () => console.log(`${pc.green("Saved")} ${name}`));
1192
+ return;
1193
+ }
1194
+ if (action === "delete") {
1195
+ await api.request("DELETE", `${base}/secrets/${encodeURIComponent(name)}`);
1196
+ emit(options, {
1197
+ name,
1198
+ deleted: true
1199
+ }, () => console.log(`${pc.green("Deleted")} ${name}`));
1200
+ return;
1201
+ }
1202
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown secrets command: ${action}`);
1203
+ }
1204
+ if (sub === "test") {
1205
+ const name = args[0];
1206
+ if (!name) throw new CliError("E_ARGUMENT_REQUIRED", "Function name is required.");
1207
+ const input = await readJsonInput(options.input, cwdOf(options));
1208
+ const result = await api.request("POST", `${base}/${encodeURIComponent(name)}/test`, { body: { input } });
1209
+ emit(options, result, () => console.log(JSON.stringify(result.result, null, 2)));
1210
+ return;
1211
+ }
1212
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown fn command: ${sub}`);
1213
+ }
1214
+ async function runSchema(sub, args, options) {
1215
+ const session = await acquireLock(options);
1216
+ const body = {
1217
+ clientId: session.state.clientId,
1218
+ fenceToken: session.fenceToken
1219
+ };
1220
+ if (!sub || sub === "get") {
1221
+ const result = await session.api.request("POST", `${appPath(session.state.app)}/schema`, { body });
1222
+ emit(options, result, () => console.log(JSON.stringify(result.schema, null, 2)));
1223
+ return;
1224
+ }
1225
+ if (sub === "apply") {
1226
+ const file = args[0] ?? options.input;
1227
+ if (!file) throw new CliError("E_ARGUMENT_REQUIRED", "Usage: howone schema apply <patch.json>");
1228
+ const patch = await readJsonInput(file, cwdOf(options));
1229
+ emit(options, await session.api.request("POST", `${appPath(session.state.app)}/schema`, { body: {
1230
+ ...body,
1231
+ patch,
1232
+ reason: options.reason,
1233
+ allowDestructive: options.allowDestructive === true
1234
+ } }), () => {
1235
+ console.log(pc.green("Applied to the draft version"));
1236
+ console.log(pc.dim("Run `howone push` to make it part of a version."));
1237
+ });
1238
+ return;
1239
+ }
1240
+ if (sub === "sync") {
1241
+ const result = await runTool(session, "schema-sync", {});
1242
+ const pulled = await pullGenerated({
1243
+ api: session.api,
1244
+ app: session.state.app,
1245
+ root: session.root,
1246
+ prefix: ".howone/"
1247
+ });
1248
+ emit(options, {
1249
+ result,
1250
+ pulled
1251
+ }, () => console.log(`${pc.green("Synced")} ${pulled.length} file(s) into .howone/`));
1252
+ return;
1253
+ }
1254
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown schema command: ${sub}`);
1255
+ }
1256
+ async function runTool(session, tool, input) {
1257
+ const { result } = await session.api.request("POST", `${appPath(session.state.app)}/tools/${tool}`, { body: {
1258
+ clientId: session.state.clientId,
1259
+ fenceToken: session.fenceToken,
1260
+ input
1261
+ } });
1262
+ const record = result && typeof result === "object" ? result : null;
1263
+ if (record && record.success === false) {
1264
+ const error = record.error ?? {};
1265
+ throw new CliError(record.requiresConfirmation ? "E_CONFIRMATION_REQUIRED" : "E_TOOL_FAILED", error.message ?? `${tool} failed.`, { result: record });
1266
+ }
1267
+ return result;
1268
+ }
1269
+ /** AI 能力契约(工作流的输入输出约定)。改完 ai sync 生成产物,再 workflows create/update 让 EAX 生成实现。 */
1270
+ async function runAi(sub, args, options) {
1271
+ const session = await acquireLock(options);
1272
+ if (!sub || sub === "get") {
1273
+ const result = await runTool(session, "ai-design", { type: "get_current_ai_capabilities" });
1274
+ emit(options, { result }, () => console.log(JSON.stringify(result, null, 2)));
1275
+ return;
1276
+ }
1277
+ if (sub === "apply") {
1278
+ const file = args[0] ?? options.input;
1279
+ if (!file) throw new CliError("E_ARGUMENT_REQUIRED", "Usage: howone ai apply <patch.json>");
1280
+ emit(options, { result: await runTool(session, "ai-design", {
1281
+ type: "apply_capability_patch",
1282
+ patch: await readJsonInput(file, cwdOf(options)),
1283
+ ...options.reason ? { reason: options.reason } : {}
1284
+ }) }, () => console.log(pc.green("Applied to the draft version")));
1285
+ return;
1286
+ }
1287
+ if (sub === "sync") {
1288
+ const versionId = aiVersionId(await runTool(session, "ai-design", { type: "get_current_ai_version" }));
1289
+ if (!versionId) throw new CliError("E_AI_VERSION_REQUIRED", "The current AI draft did not return a versionId. Run `howone ai get --json` and verify the App has an AI capability draft before syncing.");
1290
+ const result = await runTool(session, "ai-sync", { versionId });
1291
+ const pulled = await pullGenerated({
1292
+ api: session.api,
1293
+ app: session.state.app,
1294
+ root: session.root,
1295
+ prefix: ".howone/"
1296
+ });
1297
+ emit(options, {
1298
+ result,
1299
+ pulled
1300
+ }, () => console.log(`${pc.green("Synced")} ${pulled.length} file(s) into .howone/`));
1301
+ return;
1302
+ }
1303
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown ai command: ${sub}`);
1304
+ }
1305
+ function aiVersionId(value) {
1306
+ if (!value || typeof value !== "object") return void 0;
1307
+ const record = value;
1308
+ for (const candidate of [record, record.result]) {
1309
+ if (!candidate || typeof candidate !== "object") continue;
1310
+ const nested = candidate;
1311
+ for (const key of ["versionId", "currentVersionId"]) if (typeof nested[key] === "string" && nested[key].trim()) return nested[key].trim();
1312
+ }
1313
+ }
1314
+ async function runWorkflows(sub, args, options) {
1315
+ const api = await connect(options);
1316
+ if (!sub || sub === "list" || sub === "search") {
1317
+ const query = sub === "search" ? args.join(" ") : "";
1318
+ const result = await api.request("GET", "/api/cli/v1/workflows", { query: {
1319
+ q: query,
1320
+ fresh: options.fresh ? "1" : void 0
1321
+ } });
1322
+ emit(options, result, () => {
1323
+ if (!result.workflows.length) console.log(pc.dim("No matching workflows."));
1324
+ for (const workflow of result.workflows) console.log(` ${pc.bold(workflow.id)} ${workflow.name}${workflow.description ? pc.dim(` — ${workflow.description}`) : ""}`);
1325
+ for (const warning of result.warnings) console.error(pc.yellow(warning));
1326
+ });
1327
+ return;
1328
+ }
1329
+ if (sub === "create" || sub === "update") {
1330
+ const session = await acquireLock(options);
1331
+ const input = sub === "create" ? { capabilityNames: args } : { updates: [{
1332
+ capabilityName: args[0],
1333
+ updatePrompt: options.prompt
1334
+ }] };
1335
+ if (sub === "create" && !args.length) throw new CliError("E_ARGUMENT_REQUIRED", "Usage: howone workflows create <capability> [...]");
1336
+ if (sub === "update" && (!args[0] || !options.prompt)) throw new CliError("E_ARGUMENT_REQUIRED", "Usage: howone workflows update <capability> --prompt \"<change>\"");
1337
+ const result = await runTool(session, "ai-submit", input);
1338
+ const jobId = externalAiJobId(result);
1339
+ if (session.acquired && !options.keepLock) {
1340
+ await releaseLock(session);
1341
+ await writeProjectState(session.root, {
1342
+ ...session.state,
1343
+ fenceToken: null
1344
+ });
1345
+ }
1346
+ if (options.wait && jobId) {
1347
+ emit(options, {
1348
+ result,
1349
+ job: await waitForExternalAiJob(api, session.state.app, jobId, options)
1350
+ }, () => {
1351
+ console.log(pc.green("Workflow generation and Studio promotion completed."));
1352
+ console.log(pc.dim("Run `howone ai sync`, review the manifest, then push."));
1353
+ });
1354
+ return;
1355
+ }
1356
+ emit(options, { result }, () => {
1357
+ console.log(pc.green("Submitted to HowOne — the workflow is being generated."));
1358
+ if (jobId) console.log(pc.dim(`Track progress: howone workflows status ${jobId} --app ${session.state.app} --wait`));
1359
+ console.log(pc.dim("Run `howone ai sync` only after generation and Studio promotion finish."));
1360
+ });
1361
+ return;
1362
+ }
1363
+ if (sub === "status") {
1364
+ const jobId = args[0];
1365
+ const app = options.app;
1366
+ if (!jobId || !app) throw new CliError("E_ARGUMENT_REQUIRED", "Usage: howone workflows status <jobId> --app <app> [--wait]");
1367
+ const status = options.wait ? await waitForExternalAiJob(api, app, jobId, options) : await fetchExternalAiJobStatus(api, app, jobId);
1368
+ emit(options, { job: status }, () => printExternalAiJobStatus(status));
1369
+ return;
1370
+ }
1371
+ const ref = args[0];
1372
+ if (!ref?.includes("/")) throw new CliError("E_ARGUMENT_REQUIRED", "Workflow id looks like <app>/<workflow>.");
1373
+ const [app, ...rest] = ref.split("/");
1374
+ const workflowPath = `/api/cli/v1/workflows/${encodeURIComponent(app)}/${encodeURIComponent(rest.join("/"))}`;
1375
+ if (sub === "show") {
1376
+ const result = await api.request("GET", workflowPath);
1377
+ emit(options, result, () => console.log(JSON.stringify(result.workflow, null, 2)));
1378
+ return;
1379
+ }
1380
+ if (sub === "run") {
1381
+ const inputs = await readJsonInput(options.input, cwdOf(options));
1382
+ let output;
1383
+ let failure;
1384
+ await api.stream("POST", `${workflowPath}/run`, { body: { inputs } }, (event) => {
1385
+ const data = event.data && typeof event.data === "object" ? event.data : {};
1386
+ const kind = event.event !== "message" ? event.event : String(data.event ?? "message");
1387
+ if (kind === "progress" || kind === "run_start") progress(options, String(data.message ?? kind));
1388
+ else if (kind === "run_complete") output = data.message ?? data.output ?? data;
1389
+ else if (kind === "credit_insufficient") failure = {
1390
+ code: "E_INSUFFICIENT_CREDITS",
1391
+ message: "Not enough credits."
1392
+ };
1393
+ else if (kind === "run_error" || kind === "error") failure = {
1394
+ code: "E_WORKFLOW_FAILED",
1395
+ message: String(data.message ?? "Workflow failed.")
1396
+ };
1397
+ });
1398
+ if (failure) throw new CliError(failure.code, failure.message);
1399
+ if (options.output) {
1400
+ const { writeFile } = await import("node:fs/promises");
1401
+ await writeFile(path.resolve(cwdOf(options), options.output), `${JSON.stringify(output, null, 2)}\n`);
1402
+ }
1403
+ emit(options, {
1404
+ workflow: ref,
1405
+ output
1406
+ }, () => console.log(JSON.stringify(output, null, 2)));
1407
+ return;
1408
+ }
1409
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown workflows command: ${sub}`);
1410
+ }
1411
+ function externalAiJobId(result) {
1412
+ if (!result || typeof result !== "object") return void 0;
1413
+ const record = result;
1414
+ const job = record.job && typeof record.job === "object" ? record.job : void 0;
1415
+ for (const candidate of [record, job]) {
1416
+ if (!candidate) continue;
1417
+ for (const key of ["jobId", "eaxJobId"]) if (typeof candidate[key] === "string" && candidate[key]) return candidate[key];
1418
+ }
1419
+ }
1420
+ async function fetchExternalAiJobStatus(api, app, jobId) {
1421
+ return api.request("GET", `${appPath(app)}/external-ai-jobs/${encodeURIComponent(jobId)}`);
1422
+ }
1423
+ async function waitForExternalAiJob(api, app, jobId, options) {
1424
+ const timeoutMs = Math.max(1, options.timeout ?? 600) * 1e3;
1425
+ const intervalMs = Math.max(1, options.interval ?? 3) * 1e3;
1426
+ const deadline = Date.now() + timeoutMs;
1427
+ let lastStatus;
1428
+ while (Date.now() < deadline) {
1429
+ lastStatus = await fetchExternalAiJobStatus(api, app, jobId);
1430
+ if (lastStatus.status === "completed") return lastStatus;
1431
+ if ([
1432
+ "failed",
1433
+ "canceled",
1434
+ "timed_out"
1435
+ ].includes(lastStatus.status)) throw new CliError("E_EXTERNAL_AI_JOB_FAILED", lastStatus.message ?? `EAX job ${lastStatus.status}.`, { job: lastStatus });
1436
+ progress(options, `EAX ${jobId}: ${lastStatus.status}${lastStatus.promotionStatus ? `; Studio ${lastStatus.promotionStatus}` : ""}`);
1437
+ await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, Math.max(1, deadline - Date.now()))));
1438
+ }
1439
+ throw new CliError("E_EXTERNAL_AI_JOB_TIMEOUT", `EAX job is still ${lastStatus?.status ?? "pending"} after ${Math.floor(timeoutMs / 1e3)}s. Resume with: howone workflows status ${jobId} --app ${app} --wait`, { job: lastStatus ?? null });
1440
+ }
1441
+ function printExternalAiJobStatus(status) {
1442
+ console.log(`${pc.bold(status.jobId)} ${status.status}`);
1443
+ line("EAX", status.eaxStatus);
1444
+ line("Studio", status.promotionStatus);
1445
+ line("Release", status.releaseId);
1446
+ line("progress", status.progress ? `${status.progress.completed ?? 0}/${status.progress.total ?? "?"}` : null);
1447
+ if (status.message) console.log(` ${status.message}`);
1448
+ }
1449
+ //#endregion
1450
+ //#region src/index.ts
1451
+ const packageJson = createRequire(import.meta.url)("../package.json");
1452
+ const execFileAsync = promisify(execFile);
1453
+ const DEFAULT_PROJECT_NAME = "howone-app";
1454
+ const TEMPLATES = ["vite"];
1455
+ const TEMPLATE_ALIASES = { vite: "vite" };
1456
+ main().catch((error) => {
1457
+ handleFatalError(error, process.argv.includes("--json"));
1458
+ });
1459
+ async function main() {
1460
+ const command = parseCommand(process.argv.slice(2));
1461
+ if (command.options.version) {
1462
+ console.log(packageJson.version);
1463
+ return;
1464
+ }
1465
+ if (command.options.help || command.path.length === 0) {
1466
+ printHelp(command.path);
1467
+ return;
1468
+ }
1469
+ const [scope, subcommand, ...rest] = command.path;
1470
+ await refreshInstalledSkills(packageJson.version).catch((error) => {
1471
+ console.error(pc.yellow(`Could not refresh the howone skill: ${String(error)}`));
1472
+ });
1473
+ const workWith = {
1474
+ ...command.options,
1475
+ version: packageJson.version
1476
+ };
1477
+ const workWithCommand = scope ? {
1478
+ login: () => runLogin(workWith),
1479
+ logout: () => runLogout(workWith),
1480
+ whoami: () => runWhoami(workWith),
1481
+ setup: () => runSetup(workWith, subcommand === "remove"),
1482
+ tokens: () => runTokens(subcommand, rest, workWith),
1483
+ apps: () => runApps(subcommand, rest, workWith),
1484
+ app: () => runApps(subcommand, rest, workWith),
1485
+ status: () => runStatus(workWith),
1486
+ preview: () => runPreview(subcommand, workWith),
1487
+ dev: () => runDev(workWith),
1488
+ sync: () => runSync(workWith),
1489
+ push: () => runPush(workWith),
1490
+ release: () => runRelease(workWith),
1491
+ publish: () => runPublish(subcommand, workWith),
1492
+ fn: () => runFunctions(subcommand, rest, workWith),
1493
+ functions: () => runFunctions(subcommand, rest, workWith),
1494
+ schema: () => runSchema(subcommand, rest, workWith),
1495
+ ai: () => runAi(subcommand, rest, workWith),
1496
+ workflows: () => runWorkflows(subcommand, rest, workWith),
1497
+ workflow: () => runWorkflows(subcommand, rest, workWith)
1498
+ }[scope] : void 0;
1499
+ if (workWithCommand) {
1500
+ await workWithCommand();
1501
+ return;
1502
+ }
1503
+ if (isTemplateAlias(scope)) {
1504
+ await runInitApp(compact([subcommand, ...rest]), {
1505
+ ...command.options,
1506
+ template: resolveTemplateAlias(scope)
1507
+ });
1508
+ return;
1509
+ }
1510
+ if (scope === "init" || scope === "new") {
1511
+ await runInitApp(subcommand === "app" ? rest : compact([subcommand, ...rest]), command.options);
1512
+ return;
1513
+ }
1514
+ if (scope === "create") {
1515
+ await runCreatePlaceholder(command.options);
1516
+ return;
1517
+ }
1518
+ if (scope === "deploy") {
1519
+ await runDeploy(command.options);
1520
+ return;
1521
+ }
1522
+ if (scope === "capabilities" || scope === "capability" || scope === "caps") {
1523
+ await runCapabilitiesCommand(subcommand, rest, command.options);
1524
+ return;
1525
+ }
1526
+ if (scope === "skills" || scope === "skill") {
1527
+ await runSkillsCommand(subcommand, rest, command.options);
1528
+ return;
1529
+ }
1530
+ if (scope === "run") {
1531
+ await runCapabilityRun(compact([subcommand, ...rest]), command.options);
1532
+ return;
1533
+ }
1534
+ if (scope === "ai" && subcommand === "run") {
1535
+ await runAiRun(rest, command.options);
1536
+ return;
1537
+ }
1538
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown command: ${command.path.join(" ")}`);
1539
+ }
1540
+ function parseCommand(args) {
1541
+ const hasHelp = args.includes("--help") || args.includes("-h");
1542
+ const hasVersion = args.includes("--version") || args.includes("-v");
1543
+ const parsed = yargsParser(args, {
1544
+ alias: {
1545
+ h: "help",
1546
+ v: "version",
1547
+ t: "template",
1548
+ f: "force",
1549
+ y: "yes",
1550
+ m: "message"
1551
+ },
1552
+ boolean: [
1553
+ "help",
1554
+ "version",
1555
+ "vite",
1556
+ "force",
1557
+ "skip-install",
1558
+ "yes",
1559
+ "json",
1560
+ "stream",
1561
+ "value-stdin",
1562
+ "allow-destructive",
1563
+ "keep-lock",
1564
+ "build",
1565
+ "skill",
1566
+ "browser",
1567
+ "fresh",
1568
+ "wait"
1569
+ ],
1570
+ default: {
1571
+ build: true,
1572
+ skill: true,
1573
+ browser: true
1574
+ },
1575
+ string: [
1576
+ "template",
1577
+ "cwd",
1578
+ "scope",
1579
+ "input",
1580
+ "output",
1581
+ "prompt",
1582
+ "region",
1583
+ "api-url",
1584
+ "token",
1585
+ "status",
1586
+ "reason",
1587
+ "app",
1588
+ "message",
1589
+ "target",
1590
+ "value",
1591
+ "scopes",
1592
+ "name"
1593
+ ],
1594
+ number: [
1595
+ "limit",
1596
+ "expires-days",
1597
+ "timeout",
1598
+ "interval"
1599
+ ],
1600
+ configuration: { "camel-case-expansion": false }
1601
+ });
1602
+ return {
1603
+ path: parsed._.map(String),
1604
+ options: {
1605
+ template: typeof parsed.template === "string" ? parsed.template : void 0,
1606
+ vite: Boolean(parsed.vite),
1607
+ force: Boolean(parsed.force),
1608
+ skipInstall: Boolean(parsed["skip-install"]),
1609
+ yes: Boolean(parsed.yes),
1610
+ json: Boolean(parsed.json),
1611
+ cwd: typeof parsed.cwd === "string" ? parsed.cwd : void 0,
1612
+ scope: typeof parsed.scope === "string" ? parsed.scope : void 0,
1613
+ input: typeof parsed.input === "string" ? parsed.input : void 0,
1614
+ output: typeof parsed.output === "string" ? parsed.output : void 0,
1615
+ prompt: typeof parsed.prompt === "string" ? parsed.prompt : void 0,
1616
+ region: typeof parsed.region === "string" ? parsed.region : void 0,
1617
+ apiUrl: typeof parsed["api-url"] === "string" ? parsed["api-url"] : void 0,
1618
+ token: typeof parsed.token === "string" ? parsed.token : void 0,
1619
+ stream: Boolean(parsed.stream),
1620
+ status: typeof parsed.status === "string" ? parsed.status : void 0,
1621
+ limit: typeof parsed.limit === "number" && Number.isFinite(parsed.limit) ? parsed.limit : void 0,
1622
+ reason: typeof parsed.reason === "string" ? parsed.reason : void 0,
1623
+ app: typeof parsed.app === "string" ? parsed.app : void 0,
1624
+ message: typeof parsed.message === "string" ? parsed.message : void 0,
1625
+ target: typeof parsed.target === "string" ? parsed.target : void 0,
1626
+ value: typeof parsed.value === "string" ? parsed.value : void 0,
1627
+ valueStdin: Boolean(parsed["value-stdin"]),
1628
+ allowDestructive: Boolean(parsed["allow-destructive"]),
1629
+ keepLock: Boolean(parsed["keep-lock"]),
1630
+ build: parsed.build !== false,
1631
+ skill: parsed.skill !== false,
1632
+ browser: parsed.browser !== false,
1633
+ fresh: Boolean(parsed.fresh),
1634
+ wait: Boolean(parsed.wait),
1635
+ timeout: typeof parsed.timeout === "number" && Number.isFinite(parsed.timeout) ? parsed.timeout : void 0,
1636
+ interval: typeof parsed.interval === "number" && Number.isFinite(parsed.interval) ? parsed.interval : void 0,
1637
+ scopes: typeof parsed.scopes === "string" ? parsed.scopes : void 0,
1638
+ name: typeof parsed.name === "string" ? parsed.name : void 0,
1639
+ expiresDays: typeof parsed["expires-days"] === "number" && Number.isFinite(parsed["expires-days"]) ? parsed["expires-days"] : void 0,
1640
+ help: Boolean(parsed.help) || hasHelp,
1641
+ version: Boolean(parsed.version) || hasVersion
1642
+ }
1643
+ };
1644
+ }
1645
+ function compact(values) {
1646
+ return values.filter((value) => Boolean(value));
1647
+ }
1648
+ async function runInitApp(pathArgs, options) {
1649
+ const plan = await resolveCreatePlan(pathArgs, options, path.resolve(options.cwd ?? process.cwd()), process.stdout.isTTY && !options.yes && !options.json);
1650
+ const howoneContext = resolveHowoneCreateContext(options);
1651
+ if (options.json) {
1652
+ await createTemplate(plan, howoneContext, true);
1653
+ if (!options.skipInstall) await installTemplateDependencies(plan, true);
1654
+ } else {
1655
+ await say(pc.bold("HowOne"));
1656
+ await createTemplate(plan, howoneContext, false);
1657
+ if (!options.skipInstall) await installTemplateDependencies(plan, false);
1658
+ }
1659
+ const result = {
1660
+ ok: true,
1661
+ command: "init app",
1662
+ template: plan.template,
1663
+ projectName: plan.projectName,
1664
+ targetDir: plan.targetDir,
1665
+ packageManager: "bun",
1666
+ ...howoneContext ? { howone: {
1667
+ projectId: howoneContext.projectId,
1668
+ env: howoneContext.env,
1669
+ region: howoneContext.region,
1670
+ envFile: path.join(plan.targetDir, ".env")
1671
+ } } : {},
1672
+ nextSteps: [`cd ${formatPathForShell(path.relative(plan.cwd, plan.targetDir) || ".")}`, "bun run dev"]
1673
+ };
1674
+ if (options.json) {
1675
+ console.log(JSON.stringify(result, null, 2));
1676
+ return;
1677
+ }
1678
+ printCreateSuccess(plan, result);
1679
+ }
1680
+ async function runCreatePlaceholder(options) {
1681
+ const result = {
1682
+ ok: true,
1683
+ command: "create",
1684
+ status: "pending",
1685
+ message: "howone create is reserved for a future workflow."
1686
+ };
1687
+ if (options.json) {
1688
+ console.log(JSON.stringify(result, null, 2));
1689
+ return;
1690
+ }
1691
+ printPending("howone create", result.message ?? "howone create is reserved for a future workflow.");
1692
+ }
1693
+ async function runDeploy(options) {
1694
+ const result = {
1695
+ ok: true,
1696
+ command: "deploy",
1697
+ status: "pending",
1698
+ message: "howone deploy is not implemented yet."
1699
+ };
1700
+ if (options.json) {
1701
+ console.log(JSON.stringify(result, null, 2));
1702
+ return;
1703
+ }
1704
+ printPending("howone deploy", "Deploy is not implemented yet.");
1705
+ }
1706
+ async function runAiRun(pathArgs, options) {
1707
+ const aiId = pathArgs[0];
1708
+ const result = {
1709
+ ok: true,
1710
+ command: "ai run",
1711
+ status: "pending",
1712
+ message: aiId ? `howone ai run ${aiId} is not implemented yet.` : "howone ai run is not implemented yet."
1713
+ };
1714
+ if (options.json) {
1715
+ console.log(JSON.stringify(result, null, 2));
1716
+ return;
1717
+ }
1718
+ printPending("howone ai run", result.message ?? "AI run is not implemented yet.");
1719
+ }
1720
+ async function runCapabilitiesCommand(subcommand, pathArgs, options) {
1721
+ if (!subcommand || subcommand === "search") {
1722
+ const query = pathArgs.join(" ").trim();
1723
+ if (!query) throw new CliError("E_QUERY_REQUIRED", "Search query is required.");
1724
+ await runCapabilitySearch(query, options);
1725
+ return;
1726
+ }
1727
+ if (subcommand === "list") {
1728
+ await runCapabilityList(options);
1729
+ return;
1730
+ }
1731
+ if (subcommand === "inspect" || subcommand === "show") {
1732
+ const ref = pathArgs[0];
1733
+ if (!ref) throw new CliError("E_CAPABILITY_REF_REQUIRED", "Capability reference is required.");
1734
+ await runCapabilityInspect(ref, options);
1735
+ return;
1736
+ }
1737
+ if (subcommand === "proposals") {
1738
+ await runCapabilityProposals(options);
1739
+ return;
1740
+ }
1741
+ if (subcommand === "apply") {
1742
+ const proposalId = pathArgs[0];
1743
+ if (!proposalId) throw new CliError("E_PROPOSAL_ID_REQUIRED", "Capability proposal id is required.");
1744
+ await runCapabilityProposalAction("apply", proposalId, options);
1745
+ return;
1746
+ }
1747
+ if (subcommand === "reject") {
1748
+ const proposalId = pathArgs[0];
1749
+ if (!proposalId) throw new CliError("E_PROPOSAL_ID_REQUIRED", "Capability proposal id is required.");
1750
+ await runCapabilityProposalAction("reject", proposalId, options);
1751
+ return;
1752
+ }
1753
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown capabilities command: ${["capabilities", subcommand].join(" ")}`);
1754
+ }
1755
+ async function runSkillsCommand(subcommand, pathArgs, options) {
1756
+ const ref = pathArgs[0];
1757
+ if (subcommand === "export") {
1758
+ if (!ref) throw new CliError("E_SKILL_REF_REQUIRED", "Skill reference is required.");
1759
+ await runSkillProjection("export", ref, options);
1760
+ return;
1761
+ }
1762
+ if (subcommand === "install") {
1763
+ if (!ref) throw new CliError("E_SKILL_REF_REQUIRED", "Skill reference is required.");
1764
+ await runSkillProjection("install", ref, options);
1765
+ return;
1766
+ }
1767
+ if (subcommand === "publish") {
1768
+ if (!ref) throw new CliError("E_SKILL_REF_REQUIRED", "Skill reference is required.");
1769
+ await runSkillProjection("publish", ref, options);
1770
+ return;
1771
+ }
1772
+ throw new CliError("E_COMMAND_UNKNOWN", `Unknown skills command: ${["skills", subcommand].filter(Boolean).join(" ")}`);
1773
+ }
1774
+ async function runCapabilitySearch(query, options) {
1775
+ const params = new URLSearchParams({ q: query });
1776
+ if (options.scope) params.set("scope", options.scope);
1777
+ await printRegistryResult("capabilities search", await callHowoneRegistryApi(`/api/capabilities/search?${params}`, {
1778
+ options,
1779
+ requireAuth: options.scope !== "public"
1780
+ }), options);
1781
+ }
1782
+ async function runCapabilityList(options) {
1783
+ const params = new URLSearchParams();
1784
+ if (options.scope) params.set("scope", options.scope);
1785
+ await printRegistryResult("capabilities list", await callHowoneRegistryApi(`/api/capabilities${params.size ? `?${params}` : ""}`, {
1786
+ options,
1787
+ requireAuth: options.scope !== "public"
1788
+ }), options);
1789
+ }
1790
+ async function runCapabilityInspect(ref, options) {
1791
+ const result = await callHowoneRegistryApi(`/api/capabilities/${encodeURIComponent(ref)}`, {
1792
+ options,
1793
+ requireAuth: options.scope !== "public"
1794
+ });
1795
+ await printRegistryResult(`capabilities inspect ${ref}`, result, options);
1796
+ }
1797
+ async function runCapabilityProposals(options) {
1798
+ const params = new URLSearchParams();
1799
+ if (options.status) params.set("status", options.status);
1800
+ if (options.limit) params.set("limit", String(options.limit));
1801
+ await printRegistryResult("capabilities proposals", await callHowoneRegistryApi(`/api/capabilities/proposals${params.size ? `?${params}` : ""}`, {
1802
+ options,
1803
+ requireAuth: true
1804
+ }), options);
1805
+ }
1806
+ async function runCapabilityProposalAction(action, proposalId, options) {
1807
+ const result = await callHowoneRegistryApi(`/api/capabilities/proposals/${encodeURIComponent(proposalId)}/${action}`, {
1808
+ options,
1809
+ requireAuth: true,
1810
+ init: {
1811
+ method: "POST",
1812
+ headers: { "Content-Type": "application/json" },
1813
+ body: JSON.stringify(action === "reject" ? { reason: options.reason } : {})
1814
+ }
1815
+ });
1816
+ await printRegistryResult(`capabilities ${action} ${proposalId}`, result, options);
1817
+ }
1818
+ async function runCapabilityRun(pathArgs, options) {
1819
+ const actionRef = pathArgs[0];
1820
+ if (!actionRef && !options.prompt) throw new CliError("E_ACTION_REF_REQUIRED", "Capability action reference is required, or use --prompt for query-based routing.");
1821
+ const input = await readCapabilityRunInput(options);
1822
+ const body = {
1823
+ ...actionRef ? { actionRef } : {},
1824
+ ...options.prompt ? { prompt: options.prompt } : {},
1825
+ input,
1826
+ stream: Boolean(options.stream)
1827
+ };
1828
+ const result = await callHowoneRegistryApi("/api/capabilities/run", {
1829
+ options,
1830
+ requireAuth: true,
1831
+ init: {
1832
+ method: "POST",
1833
+ headers: { "Content-Type": "application/json" },
1834
+ body: JSON.stringify(body)
1835
+ }
1836
+ });
1837
+ await printRegistryResult(actionRef ? `run ${actionRef}` : "run query", result, options);
1838
+ }
1839
+ async function runSkillProjection(action, ref, options) {
1840
+ const method = action === "export" ? "GET" : "POST";
1841
+ const result = await callHowoneRegistryApi(`/api/capabilities/skills/${encodeURIComponent(ref)}/${action}`, {
1842
+ options,
1843
+ requireAuth: action !== "export",
1844
+ init: { method }
1845
+ });
1846
+ await printRegistryResult(`skills ${action} ${ref}`, result, options);
1847
+ }
1848
+ async function readCapabilityRunInput(options) {
1849
+ if (!options.input) return {};
1850
+ const raw = options.input.trim();
1851
+ const content = raw.startsWith("{") || raw.startsWith("[") ? raw : await readFile(path.resolve(options.cwd ?? process.cwd(), raw), "utf-8");
1852
+ try {
1853
+ const parsed = JSON.parse(content);
1854
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new CliError("E_INPUT_INVALID", "Capability input must be a JSON object.");
1855
+ return parsed;
1856
+ } catch (error) {
1857
+ if (error instanceof CliError) throw error;
1858
+ throw new CliError("E_INPUT_INVALID", error instanceof Error ? error.message : "Invalid JSON input.");
1859
+ }
1860
+ }
1861
+ async function callHowoneRegistryApi(apiPath, args) {
1862
+ const connection = await resolveConnection({
1863
+ apiUrl: args.options.apiUrl,
1864
+ token: args.options.token
1865
+ });
1866
+ const token = connection.token;
1867
+ if (args.requireAuth && !token) throw new CliError("E_AUTH_REQUIRED", "Not logged in. Run `howone login`, or set HOWONE_API_TOKEN, or pass --token to access private/workspace capabilities.");
1868
+ const url = `${connection.apiUrl}${apiPath.startsWith("/") ? apiPath : `/${apiPath}`}`;
1869
+ const headers = new Headers(args.init?.headers);
1870
+ if (token) headers.set("Authorization", `Bearer ${token}`);
1871
+ headers.set("Accept", args.options.stream ? "text/event-stream, application/json" : "application/json");
1872
+ const response = await fetch(url, {
1873
+ ...args.init,
1874
+ headers
1875
+ });
1876
+ const contentType = response.headers.get("content-type") ?? "";
1877
+ if (args.options.stream && contentType.includes("text/event-stream")) return readSseResponse(response);
1878
+ const text = await response.text();
1879
+ const body = text ? parseJsonOrText(text) : null;
1880
+ if (!response.ok) throw new CliError("E_API_REQUEST_FAILED", `HowOne API request failed: HTTP ${response.status}`, {
1881
+ status: response.status,
1882
+ body
1883
+ });
1884
+ return body;
1885
+ }
1886
+ async function readSseResponse(response) {
1887
+ if (!response.ok) throw new CliError("E_API_REQUEST_FAILED", `HowOne API request failed: HTTP ${response.status}`);
1888
+ if (!response.body) return {
1889
+ ok: true,
1890
+ events: []
1891
+ };
1892
+ const reader = response.body.getReader();
1893
+ const decoder = new TextDecoder();
1894
+ const events = [];
1895
+ let buffer = "";
1896
+ while (true) {
1897
+ const { value, done } = await reader.read();
1898
+ if (done) break;
1899
+ buffer += decoder.decode(value, { stream: true });
1900
+ let boundary = buffer.indexOf("\n\n");
1901
+ while (boundary >= 0) {
1902
+ const chunk = buffer.slice(0, boundary).trim();
1903
+ buffer = buffer.slice(boundary + 2);
1904
+ if (chunk) {
1905
+ events.push(chunk);
1906
+ console.log(chunk);
1907
+ }
1908
+ boundary = buffer.indexOf("\n\n");
1909
+ }
1910
+ }
1911
+ const tail = buffer.trim();
1912
+ if (tail) {
1913
+ events.push(tail);
1914
+ console.log(tail);
1915
+ }
1916
+ return {
1917
+ ok: true,
1918
+ events
1919
+ };
1920
+ }
1921
+ function parseJsonOrText(text) {
1922
+ try {
1923
+ return JSON.parse(text);
1924
+ } catch {
1925
+ return text;
1926
+ }
1927
+ }
1928
+ async function printRegistryResult(command, result, options) {
1929
+ if (options.output) await writeFile(path.resolve(options.cwd ?? process.cwd(), options.output), `${JSON.stringify(result, null, 2)}\n`, "utf-8");
1930
+ if (options.json || options.output) {
1931
+ if (!options.output) console.log(JSON.stringify(result, null, 2));
1932
+ return;
1933
+ }
1934
+ console.log(formatPanel(pc.bold(command), [formatRegistrySummary(result)]));
1935
+ }
1936
+ function formatRegistrySummary(result) {
1937
+ if (typeof result === "string") return result;
1938
+ if (!result || typeof result !== "object") return String(result);
1939
+ const record = result;
1940
+ const data = record.data ?? record.results ?? record.capabilities ?? record.actions;
1941
+ if (Array.isArray(data)) {
1942
+ if (!data.length) return "No capabilities found.";
1943
+ return data.slice(0, 12).map((item) => {
1944
+ if (!item || typeof item !== "object") return `- ${String(item)}`;
1945
+ const row = item;
1946
+ const name = row.name ?? row.title ?? row.slug ?? row.actionRef ?? row.proposalSlug ?? row.id ?? "capability";
1947
+ const description = row.description ?? row.summary ?? row.reason ?? row.status;
1948
+ return `- ${String(name)}${description ? `: ${String(description)}` : ""}`;
1949
+ }).join("\n");
1950
+ }
1951
+ const name = record.name ?? record.title ?? record.slug ?? record.actionRef ?? record.proposalSlug ?? record.id;
1952
+ const description = record.description ?? record.summary ?? record.reason ?? record.status;
1953
+ if (name || description) return [name ? String(name) : void 0, description ? String(description) : void 0].filter(Boolean).join("\n");
1954
+ return JSON.stringify(result, null, 2);
1955
+ }
1956
+ async function resolveCreatePlan(pathArgs, options, cwd, isInteractive) {
1957
+ const template = resolveTemplateOption(options);
1958
+ const projectName = pathArgs[0] === "template" ? pathArgs[1] : pathArgs[0];
1959
+ const resolvedTemplate = template ?? (isInteractive ? await promptTemplate() : void 0);
1960
+ if (!resolvedTemplate) throw new CliError("E_TEMPLATE_REQUIRED", "Missing template. Use --template vite.");
1961
+ const resolvedProjectName = projectName ?? (isInteractive ? await promptProjectName() : DEFAULT_PROJECT_NAME);
1962
+ validateProjectName(resolvedProjectName);
1963
+ const targetDir = path.resolve(cwd, resolvedProjectName);
1964
+ const force = Boolean(options.force);
1965
+ if (!force && await isNonEmptyDirectory(targetDir)) {
1966
+ const entries = await readdir(targetDir);
1967
+ if (!isInteractive) throw new CliError("E_TARGET_NOT_EMPTY", `Target directory already exists and is not empty: ${targetDir}`, {
1968
+ targetDir,
1969
+ entries: entries.slice(0, 20),
1970
+ retryWithForce: [
1971
+ "howone",
1972
+ "init",
1973
+ "app",
1974
+ resolvedProjectName,
1975
+ "--template",
1976
+ resolvedTemplate,
1977
+ "--cwd",
1978
+ cwd,
1979
+ "--force",
1980
+ "--yes",
1981
+ ...options.json ? ["--json"] : []
1982
+ ]
1983
+ });
1984
+ const shouldOverwrite = await confirm({
1985
+ message: `Directory "${path.relative(cwd, targetDir) || "."}" is not empty. Overwrite it?`,
1986
+ initialValue: false
1987
+ });
1988
+ if (isCancel(shouldOverwrite)) {
1989
+ cancel("Cancelled.");
1990
+ process.exit(0);
1991
+ }
1992
+ if (!shouldOverwrite) throw new CliError("E_CANCELLED", "Cancelled.");
1993
+ }
1994
+ await assertTargetWritable(targetDir);
1995
+ return {
1996
+ template: resolvedTemplate,
1997
+ projectName: resolvedProjectName,
1998
+ targetDir,
1999
+ force,
2000
+ cwd
2001
+ };
2002
+ }
2003
+ function resolveTemplateOption(options) {
2004
+ const flags = [options.template, options.vite ? "vite" : void 0].filter(Boolean);
2005
+ if (flags.length > 1) throw new CliError("E_TEMPLATE_CONFLICT", "Use only one template option.");
2006
+ const template = flags[0];
2007
+ if (!template) return void 0;
2008
+ if (!isTemplate(template)) throw new CliError("E_TEMPLATE_INVALID", `Unsupported template "${template}". Use vite.`);
2009
+ return template;
2010
+ }
2011
+ async function promptTemplate() {
2012
+ const value = await select({
2013
+ message: "Choose a template",
2014
+ options: [{
2015
+ value: "vite",
2016
+ label: "Vite React TypeScript",
2017
+ hint: "Fast SPA starter"
2018
+ }],
2019
+ initialValue: "vite"
2020
+ });
2021
+ if (isCancel(value)) {
2022
+ cancel("Cancelled.");
2023
+ process.exit(0);
2024
+ }
2025
+ if (!isTemplate(value)) throw new CliError("E_TEMPLATE_INVALID", `Unsupported template "${value}". Use vite.`);
2026
+ return value;
2027
+ }
2028
+ async function promptProjectName() {
2029
+ const value = await text({
2030
+ message: "Project name",
2031
+ placeholder: DEFAULT_PROJECT_NAME,
2032
+ defaultValue: DEFAULT_PROJECT_NAME,
2033
+ validate(value) {
2034
+ try {
2035
+ validateProjectName(value ?? "");
2036
+ return;
2037
+ } catch (error) {
2038
+ return error instanceof Error ? error.message : String(error);
2039
+ }
2040
+ }
2041
+ });
2042
+ if (isCancel(value)) {
2043
+ cancel("Cancelled.");
2044
+ process.exit(0);
2045
+ }
2046
+ return String(value || DEFAULT_PROJECT_NAME);
2047
+ }
2048
+ async function createTemplate(plan, howoneContext, json) {
2049
+ if (json) {
2050
+ await performCreateTemplate(plan, howoneContext);
2051
+ return;
2052
+ }
2053
+ await spinner({
2054
+ start: "Creating project",
2055
+ end: "Project created",
2056
+ while: () => performCreateTemplate(plan, howoneContext)
2057
+ });
2058
+ }
2059
+ async function installTemplateDependencies(plan, json) {
2060
+ const install = async () => {
2061
+ try {
2062
+ await execFileAsync("bun", ["install"], {
2063
+ cwd: plan.targetDir,
2064
+ maxBuffer: 10 * 1024 * 1024
2065
+ });
2066
+ } catch (error) {
2067
+ throw new CliError("E_DEP_INSTALL_FAILED", "Failed to install dependencies with bun.", error && typeof error === "object" ? {
2068
+ stdout: "stdout" in error ? String(error.stdout ?? "") : void 0,
2069
+ stderr: "stderr" in error ? String(error.stderr ?? "") : void 0
2070
+ } : void 0);
2071
+ }
2072
+ };
2073
+ if (json) {
2074
+ await install();
2075
+ return;
2076
+ }
2077
+ await spinner({
2078
+ start: "Installing dependencies with bun",
2079
+ end: "Dependencies installed",
2080
+ while: install
2081
+ });
2082
+ }
2083
+ async function performCreateTemplate(plan, howoneContext) {
2084
+ const templateDir = getTemplateDir(plan.template);
2085
+ if (plan.force && await pathExists(plan.targetDir)) await emptyDir(plan.targetDir);
2086
+ else await ensureDir(plan.targetDir);
2087
+ await copy(templateDir, plan.targetDir, {
2088
+ overwrite: true,
2089
+ errorOnExist: false,
2090
+ filter: (source) => {
2091
+ return !path.relative(templateDir, source).split(path.sep).includes("node_modules");
2092
+ }
2093
+ });
2094
+ await restoreGitignore(plan.targetDir);
2095
+ await writeHowoneEnvFile(plan, howoneContext);
2096
+ await assertTemplateCopied(plan);
2097
+ }
2098
+ function normalizeHowoneEnv(value) {
2099
+ const normalized = value?.trim().toLowerCase();
2100
+ if (!normalized) return "dev";
2101
+ if (normalized === "development") return "dev";
2102
+ if (normalized === "production") return "prod";
2103
+ if (normalized === "local" || normalized === "dev" || normalized === "prod") return normalized;
2104
+ return "dev";
2105
+ }
2106
+ function normalizeHowoneRegion(value) {
2107
+ const normalized = value?.trim().toLowerCase();
2108
+ if (normalized === "cn" || normalized === "china" || normalized === "mainland") return "cn";
2109
+ if (normalized === "global" || normalized === "intl" || normalized === "international") return "global";
2110
+ return "global";
2111
+ }
2112
+ function resolveHowoneCreateContext(options) {
2113
+ const projectId = process.env.HOWONE_PROJECT_ID?.trim();
2114
+ if (!projectId) return null;
2115
+ return {
2116
+ projectId,
2117
+ env: normalizeHowoneEnv(process.env.HOWONE_ENV ?? process.env.APP_ENV),
2118
+ region: normalizeHowoneRegion(options?.region ?? process.env.HOWONE_REGION)
2119
+ };
2120
+ }
2121
+ function getTemplateEnvEntries(context) {
2122
+ return [
2123
+ ["VITE_HOWONE_PROJECT_ID", context.projectId],
2124
+ ["VITE_HOWONE_ENV", context.env],
2125
+ ["VITE_HOWONE_REGION", context.region]
2126
+ ];
2127
+ }
2128
+ async function writeHowoneEnvFile(plan, howoneContext) {
2129
+ if (!howoneContext) return;
2130
+ const lines = getTemplateEnvEntries(howoneContext).map(([key, value]) => `${key}=${value}`);
2131
+ await writeFile(path.join(plan.targetDir, ".env"), [...lines, ""].join("\n"), "utf-8");
2132
+ }
2133
+ function getTemplateDir(template) {
2134
+ const currentFile = fileURLToPath(import.meta.url);
2135
+ const packageDir = path.resolve(path.dirname(currentFile), "..");
2136
+ return path.join(packageDir, "templates", template);
2137
+ }
2138
+ async function restoreGitignore(targetDir) {
2139
+ const source = path.join(targetDir, "gitignore");
2140
+ if (!await pathExists(source)) return;
2141
+ await rename(source, path.join(targetDir, ".gitignore"));
2142
+ }
2143
+ async function assertTemplateCopied(plan) {
2144
+ if (await pathExists(path.join(plan.targetDir, "package.json"))) return;
2145
+ throw new CliError("E_TEMPLATE_COPY_FAILED", `Template copy failed: ${plan.targetDir} is missing package.json`, {
2146
+ template: plan.template,
2147
+ targetDir: plan.targetDir
2148
+ });
2149
+ }
2150
+ async function assertTargetWritable(targetDir) {
2151
+ if (!await pathExists(targetDir)) return;
2152
+ if (!(await stat(targetDir)).isDirectory()) throw new CliError("E_TARGET_NOT_DIRECTORY", `Target exists and is not a directory: ${targetDir}`);
2153
+ }
2154
+ async function isNonEmptyDirectory(targetDir) {
2155
+ if (!await pathExists(targetDir)) return false;
2156
+ if (!(await stat(targetDir)).isDirectory()) return false;
2157
+ return (await readdir(targetDir)).length > 0;
2158
+ }
2159
+ function validateProjectName(projectName) {
2160
+ if (!projectName.trim()) throw new CliError("E_PROJECT_NAME_REQUIRED", "Project name is required.");
2161
+ const result = validatePackageName(path.basename(projectName));
2162
+ if (result.validForNewPackages) return;
2163
+ throw new CliError("E_PROJECT_NAME_INVALID", [...result.errors ?? [], ...result.warnings ?? []][0] ?? `Invalid project name: ${projectName}`);
2164
+ }
2165
+ function resolveTemplateAlias(value) {
2166
+ if (!value) return void 0;
2167
+ const normalized = TEMPLATE_ALIASES[value];
2168
+ return normalized && isTemplate(normalized) ? normalized : void 0;
2169
+ }
2170
+ function isTemplateAlias(value) {
2171
+ return Boolean(resolveTemplateAlias(value));
2172
+ }
2173
+ function isTemplate(value) {
2174
+ return typeof value === "string" && TEMPLATES.includes(value);
2175
+ }
2176
+ function formatPathForShell(value) {
2177
+ return value.includes(" ") ? JSON.stringify(value) : value;
2178
+ }
2179
+ function printHelp(pathArgs) {
2180
+ const topic = pathArgs.join(" ");
2181
+ if (pathArgs[0] === "preview") {
2182
+ console.log(formatPanel(pc.bold("HowOne preview"), [
2183
+ "Usage howone preview [app] [--app <app>] [--api-url <url>] [--json]",
2184
+ "Wake the sandbox and wait for the existing app preview to be ready.",
2185
+ "Uses CLI login. Does not pull or sync code, build, publish, or take an edit lock.",
2186
+ "Without an app argument, use --app or the current HowOne project directory."
2187
+ ]));
2188
+ return;
2189
+ }
2190
+ if (topic === "init" || topic === "init app" || topic === "new" || topic === "new app") {
2191
+ printInitHelp();
2192
+ return;
2193
+ }
2194
+ if (topic === "create") {
2195
+ printReservedHelp("howone create", "Reserved for a future create workflow.");
2196
+ return;
2197
+ }
2198
+ if (topic === "deploy") {
2199
+ printReservedHelp("howone deploy", "Deploy support is reserved and not implemented yet.");
2200
+ return;
2201
+ }
2202
+ if (topic === "capabilities" || topic === "capabilities search") {
2203
+ printCapabilitiesHelp();
2204
+ return;
2205
+ }
2206
+ if (topic === "skills") {
2207
+ printSkillsHelp();
2208
+ return;
2209
+ }
2210
+ if (topic === "run") {
2211
+ printRunHelp();
2212
+ return;
2213
+ }
2214
+ if (topic === "ai" || topic === "ai run") {
2215
+ printReservedHelp("howone ai run [aiId]", "AI run support is reserved and not implemented yet.");
2216
+ return;
2217
+ }
2218
+ printRootHelp();
2219
+ }
2220
+ function printRootHelp() {
2221
+ console.log(formatPanel(`${pc.bold("HowOne CLI")} ${pc.dim(`v${packageJson.version}`)}`, [
2222
+ `${pc.dim("Usage")} howone <command> [options]`,
2223
+ "",
2224
+ pc.bold("Account"),
2225
+ formatCommand("login", "Log in from the browser and install the howone skill"),
2226
+ formatCommand("logout", "Revoke this machine's token"),
2227
+ formatCommand("whoami", "Show the logged-in user"),
2228
+ formatCommand("setup [remove]", "Install (or remove) the skill for Claude Code / Codex"),
2229
+ formatCommand("tokens list|create|revoke", "Manage tokens for CI (HOWONE_API_TOKEN)"),
2230
+ "",
2231
+ pc.bold("Apps"),
2232
+ formatCommand("apps list|create|show", "Your apps"),
2233
+ formatCommand("apps pull <app> [dir]", "Download an app's code"),
2234
+ formatCommand("preview [app]", "Wake the sandbox and return a ready preview URL"),
2235
+ formatCommand("dev", "Live-sync this directory to the cloud preview"),
2236
+ formatCommand("push -m <message>", "Upload, seal a version, build, return the preview"),
2237
+ formatCommand("publish [version] --yes", "Publish to production"),
2238
+ formatCommand("status", "Version, preview, production, edit lock"),
2239
+ formatCommand("release", "Give the app back to the HowOne web app"),
2240
+ formatCommand("fn list|secrets|test", "Platform functions"),
2241
+ formatCommand("schema get|apply|sync", "Entity schema of the app"),
2242
+ formatCommand("ai get|apply|sync", "AI capability contracts (workflow inputs/outputs)"),
2243
+ "",
2244
+ pc.bold("Workflows"),
2245
+ formatCommand("workflows search <text>", "Find AI workflows you can run"),
2246
+ formatCommand("workflows show <app/id>", "Inputs and outputs of a workflow"),
2247
+ formatCommand("workflows status <jobId> --app <app>", "Check EAX generation and promotion progress"),
2248
+ formatCommand("workflows run <app/id>", "Run a workflow (--input json|file)"),
2249
+ formatCommand("workflows create <capability>", "Have HowOne generate a workflow for an AI capability"),
2250
+ formatCommand("workflows update <cap> --prompt", "Change a workflow's behaviour"),
2251
+ "",
2252
+ pc.bold("Templates & capabilities"),
2253
+ formatCommand("init app [name]", "Create an app from a template"),
2254
+ formatCommand("capabilities search <query>", "Search callable HowOne capabilities"),
2255
+ formatCommand("run <package.action>", "Run a callable capability action"),
2256
+ "",
2257
+ pc.bold("Options"),
2258
+ formatCommand("-h, --help", "Show help"),
2259
+ formatCommand("-v, --version", "Show version"),
2260
+ formatCommand("--app <app>", "Which app (default: the pulled directory you are in)"),
2261
+ formatCommand("--json", "Machine-readable output (for agents and CI)"),
2262
+ "",
2263
+ pc.bold("Examples"),
2264
+ ` ${pc.cyan("howone login")}`,
2265
+ ` ${pc.cyan("howone apps pull abc1234 ./my-app && cd my-app")}`,
2266
+ ` ${pc.cyan("howone push -m \"add charts\" --json")}`,
2267
+ ` ${pc.cyan("howone workflows search \"海报\" --json")}`
2268
+ ]));
2269
+ }
2270
+ function printInitHelp() {
2271
+ console.log(formatPanel(`${pc.bold("Create an app")}`, [
2272
+ `${pc.dim("Usage")} howone init app [name] [options]`,
2273
+ "",
2274
+ pc.bold("Options"),
2275
+ formatCommand("-t, --template <template>", "Template to use: vite"),
2276
+ formatCommand("--vite", "Shortcut for --template vite"),
2277
+ formatCommand("--region <cn|global>", "Override the HowOne deployment region"),
2278
+ formatCommand("-f, --force", "Overwrite an existing non-empty directory"),
2279
+ formatCommand("--skip-install", "Create the template without installing dependencies"),
2280
+ formatCommand("-y, --yes", "Disable prompts and accept defaults"),
2281
+ formatCommand("--json", "Print machine-readable JSON output"),
2282
+ formatCommand("--cwd <dir>", "Directory in which to create the app"),
2283
+ "",
2284
+ pc.bold("Examples"),
2285
+ ` ${pc.cyan("howone init app my-app --template vite")}`
2286
+ ]));
2287
+ }
2288
+ function printReservedHelp(command, description) {
2289
+ console.log(formatPanel(pc.bold(command), [
2290
+ description,
2291
+ "",
2292
+ `${pc.yellow("Pending")} This command is available as a stable placeholder.`
2293
+ ]));
2294
+ }
2295
+ function printCapabilitiesHelp() {
2296
+ console.log(formatPanel(`${pc.bold("HowOne capabilities")}`, [
2297
+ `${pc.dim("Usage")} howone capabilities <command> [options]`,
2298
+ "",
2299
+ pc.bold("Commands"),
2300
+ formatCommand("search <query>", "Search private, workspace, installed, or public capabilities"),
2301
+ formatCommand("list", "List capabilities in a scope"),
2302
+ formatCommand("inspect <ref>", "Inspect package/action schemas and runtime bindings"),
2303
+ formatCommand("proposals", "List generated proposals for the current user"),
2304
+ formatCommand("apply <proposalId>", "Apply a generated proposal to the registry"),
2305
+ formatCommand("reject <proposalId>", "Reject a generated proposal"),
2306
+ "",
2307
+ pc.bold("Options"),
2308
+ formatCommand("--scope <scope>", "private, workspace, installed, public, or global"),
2309
+ formatCommand("--status <status>", "Filter proposal list by status"),
2310
+ formatCommand("--limit <number>", "Limit result count"),
2311
+ formatCommand("--reason <text>", "Reason for rejecting a proposal"),
2312
+ formatCommand("--api-url <url>", "HowOne registry API origin"),
2313
+ formatCommand("--token <token>", "Agent API token; defaults to HOWONE_API_TOKEN"),
2314
+ formatCommand("--json", "Print machine-readable JSON output"),
2315
+ "",
2316
+ pc.bold("Examples"),
2317
+ ` ${pc.cyan("howone capabilities search \"海报生成\" --scope public")}`,
2318
+ ` ${pc.cyan("howone capabilities inspect poster-generator.createPoster")}`,
2319
+ ` ${pc.cyan("howone capabilities proposals --status pending_review")}`,
2320
+ ` ${pc.cyan("howone capabilities apply 00000000-0000-0000-0000-000000000000")}`
2321
+ ]));
2322
+ }
2323
+ function printRunHelp() {
2324
+ console.log(formatPanel(`${pc.bold("Run a capability")}`, [
2325
+ `${pc.dim("Usage")} howone run <package.action> [options]`,
2326
+ "",
2327
+ pc.bold("Options"),
2328
+ formatCommand("--input <json|file>", "JSON object or path to JSON input file"),
2329
+ formatCommand("--prompt <text>", "Natural-language query routed through the registry"),
2330
+ formatCommand("--output <file>", "Write JSON result to a file"),
2331
+ formatCommand("--stream", "Request SSE and print events as they arrive"),
2332
+ formatCommand("--api-url <url>", "HowOne registry API origin"),
2333
+ formatCommand("--token <token>", "Agent API token; defaults to HOWONE_API_TOKEN"),
2334
+ formatCommand("--json", "Print machine-readable JSON output"),
2335
+ "",
2336
+ pc.bold("Examples"),
2337
+ ` ${pc.cyan("howone run poster-generator.createPoster --input input.json")}`,
2338
+ ` ${pc.cyan("howone run --prompt \"帮我生成一张 AI 发布会海报\" --stream")}`
2339
+ ]));
2340
+ }
2341
+ function printSkillsHelp() {
2342
+ console.log(formatPanel(`${pc.bold("HowOne skill projections")}`, [
2343
+ `${pc.dim("Usage")} howone skills <command> <ref> [options]`,
2344
+ "",
2345
+ pc.bold("Commands"),
2346
+ formatCommand("export <ref>", "Export an agent-facing skill artifact"),
2347
+ formatCommand("install <ref>", "Install a public or workspace skill projection"),
2348
+ formatCommand("publish <ref>", "Request publication of a capability skill projection"),
2349
+ "",
2350
+ pc.bold("Options"),
2351
+ formatCommand("--api-url <url>", "HowOne registry API origin"),
2352
+ formatCommand("--token <token>", "Agent API token; defaults to HOWONE_API_TOKEN"),
2353
+ formatCommand("--json", "Print machine-readable JSON output"),
2354
+ "",
2355
+ pc.bold("Examples"),
2356
+ ` ${pc.cyan("howone skills export poster-generator")}`,
2357
+ ` ${pc.cyan("howone skills install poster-generator")}`
2358
+ ]));
2359
+ }
2360
+ function printPending(command, message) {
2361
+ console.log(formatPanel(pc.bold(command), [`${pc.yellow("Pending")} ${message}`]));
2362
+ }
2363
+ function printCreateSuccess(plan, result) {
2364
+ const relativeTarget = path.relative(plan.cwd, plan.targetDir) || ".";
2365
+ const lines = [`${pc.green("Created")} ${pc.bold(plan.template)} app in ${pc.cyan(relativeTarget)}`];
2366
+ if (result.howone) lines.push("", pc.bold("HowOne context"), formatCommand("project", result.howone.projectId), formatCommand("env", result.howone.env), formatCommand("file", path.relative(plan.cwd, result.howone.envFile) || ".env"));
2367
+ lines.push("", pc.bold("Next steps"), ...(result.nextSteps ?? []).map((step) => ` ${pc.cyan(step)}`));
2368
+ console.log(formatPanel(pc.bold("App ready"), lines));
2369
+ }
2370
+ function formatPanel(title, lines) {
2371
+ return [`${pc.green("◆")} ${title}`, ...lines.map((line) => line ? ` ${line}` : "")].join("\n");
2372
+ }
2373
+ function formatCommand(command, description) {
2374
+ return ` ${pc.cyan(command.padEnd(28))} ${description}`;
2375
+ }
2376
+ function handleFatalError(error, json) {
2377
+ const cliError = error instanceof CliError ? error : new CliError("E_UNEXPECTED", error instanceof Error ? error.message : String(error));
2378
+ printError(cliError, json);
2379
+ process.exit(cliError.code === "E_CANCELLED" ? 0 : 1);
2380
+ }
2381
+ function printError(error, json) {
2382
+ const payload = {
2383
+ ok: false,
2384
+ error: {
2385
+ code: error.code,
2386
+ message: error.message,
2387
+ ...error.details ? { details: error.details } : {}
2388
+ }
2389
+ };
2390
+ if (json) {
2391
+ console.error(JSON.stringify(payload, null, 2));
2392
+ return;
2393
+ }
2394
+ console.error(`${pc.red("Error")} ${error.message}`);
2395
+ }
2396
+ //#endregion
2397
+ export {};