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