tripo-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +105 -0
  2. package/dist/ai/experts.js +115 -0
  3. package/dist/ai/llm.js +88 -0
  4. package/dist/ai/plan-card.js +79 -0
  5. package/dist/ai/wizard.js +105 -0
  6. package/dist/cli.js +7 -0
  7. package/dist/commands/account.js +27 -0
  8. package/dist/commands/ai.js +114 -0
  9. package/dist/commands/batch.js +148 -0
  10. package/dist/commands/completion.js +84 -0
  11. package/dist/commands/config-cmd.js +84 -0
  12. package/dist/commands/docs.js +30 -0
  13. package/dist/commands/doctor.js +102 -0
  14. package/dist/commands/generate.js +81 -0
  15. package/dist/commands/home.js +68 -0
  16. package/dist/commands/login.js +309 -0
  17. package/dist/commands/make.js +142 -0
  18. package/dist/commands/mcp.js +194 -0
  19. package/dist/commands/process-groups.js +166 -0
  20. package/dist/commands/shared.js +75 -0
  21. package/dist/commands/task.js +128 -0
  22. package/dist/commands/topup.js +61 -0
  23. package/dist/commands/view.js +97 -0
  24. package/dist/config/config.js +99 -0
  25. package/dist/config/context.js +44 -0
  26. package/dist/config/history.js +104 -0
  27. package/dist/core/client.js +129 -0
  28. package/dist/core/device-auth.js +141 -0
  29. package/dist/core/download.js +107 -0
  30. package/dist/core/errors.js +64 -0
  31. package/dist/core/output.js +72 -0
  32. package/dist/core/region.js +45 -0
  33. package/dist/core/requests.js +197 -0
  34. package/dist/core/task-service.js +167 -0
  35. package/dist/core/upload.js +42 -0
  36. package/dist/core/viewer-assets.js +24 -0
  37. package/dist/core/viewer.js +59 -0
  38. package/dist/core/watch.js +42 -0
  39. package/dist/i18n.js +19 -0
  40. package/dist/knowledge/chains.js +157 -0
  41. package/dist/knowledge/error-catalog.js +91 -0
  42. package/dist/knowledge/models.js +158 -0
  43. package/dist/knowledge/params.js +203 -0
  44. package/dist/knowledge/scenarios.js +112 -0
  45. package/dist/pipeline/make.js +233 -0
  46. package/dist/pipeline/runner.js +73 -0
  47. package/dist/pipeline/stdin.js +40 -0
  48. package/dist/program.js +147 -0
  49. package/dist/src/ai/experts.js +115 -0
  50. package/dist/src/ai/llm.js +88 -0
  51. package/dist/src/ai/plan-card.js +79 -0
  52. package/dist/src/ai/wizard.js +104 -0
  53. package/dist/src/cli.js +7 -0
  54. package/dist/src/commands/account.js +27 -0
  55. package/dist/src/commands/ai.js +113 -0
  56. package/dist/src/commands/batch.js +148 -0
  57. package/dist/src/commands/completion.js +84 -0
  58. package/dist/src/commands/config-cmd.js +84 -0
  59. package/dist/src/commands/docs.js +30 -0
  60. package/dist/src/commands/doctor.js +94 -0
  61. package/dist/src/commands/generate.js +81 -0
  62. package/dist/src/commands/home.js +68 -0
  63. package/dist/src/commands/login.js +225 -0
  64. package/dist/src/commands/make.js +142 -0
  65. package/dist/src/commands/mcp.js +194 -0
  66. package/dist/src/commands/process-groups.js +164 -0
  67. package/dist/src/commands/shared.js +75 -0
  68. package/dist/src/commands/task.js +127 -0
  69. package/dist/src/commands/topup.js +61 -0
  70. package/dist/src/commands/view.js +97 -0
  71. package/dist/src/config/config.js +79 -0
  72. package/dist/src/config/context.js +44 -0
  73. package/dist/src/config/history.js +104 -0
  74. package/dist/src/core/client.js +120 -0
  75. package/dist/src/core/download.js +107 -0
  76. package/dist/src/core/errors.js +64 -0
  77. package/dist/src/core/output.js +72 -0
  78. package/dist/src/core/requests.js +169 -0
  79. package/dist/src/core/task-service.js +161 -0
  80. package/dist/src/core/upload.js +36 -0
  81. package/dist/src/core/viewer-assets.js +24 -0
  82. package/dist/src/core/viewer.js +59 -0
  83. package/dist/src/core/watch.js +41 -0
  84. package/dist/src/i18n.js +19 -0
  85. package/dist/src/knowledge/chains.js +152 -0
  86. package/dist/src/knowledge/error-catalog.js +91 -0
  87. package/dist/src/knowledge/models.js +110 -0
  88. package/dist/src/knowledge/params.js +174 -0
  89. package/dist/src/knowledge/scenarios.js +112 -0
  90. package/dist/src/pipeline/make.js +233 -0
  91. package/dist/src/pipeline/runner.js +73 -0
  92. package/dist/src/pipeline/stdin.js +40 -0
  93. package/dist/src/program.js +147 -0
  94. package/dist/src/types.js +2 -0
  95. package/dist/src/util/input-detect.js +92 -0
  96. package/dist/src/util/notify.js +17 -0
  97. package/dist/src/util/open.js +18 -0
  98. package/dist/src/util/spinner.js +62 -0
  99. package/dist/src/util/term-image.js +28 -0
  100. package/dist/src/version.js +10 -0
  101. package/dist/types.js +2 -0
  102. package/dist/util/input-detect.js +93 -0
  103. package/dist/util/notify.js +17 -0
  104. package/dist/util/open.js +18 -0
  105. package/dist/util/spinner.js +62 -0
  106. package/dist/util/term-image.js +28 -0
  107. package/dist/version.js +10 -0
  108. package/package.json +63 -0
  109. package/skill/SKILL.md +70 -0
  110. package/skill/commands/account.md +41 -0
  111. package/skill/commands/batch.md +33 -0
  112. package/skill/commands/generate.md +34 -0
  113. package/skill/commands/make.md +47 -0
  114. package/skill/commands/process.md +50 -0
  115. package/skill/commands/task.md +27 -0
  116. package/skill/commands/view.md +25 -0
  117. package/skill/common-errors.md +38 -0
  118. package/skill/examples/animation.md +33 -0
  119. package/skill/examples/ar-web.md +23 -0
  120. package/skill/examples/film.md +22 -0
  121. package/skill/examples/game-asset.md +35 -0
  122. package/skill/examples/pipes.md +39 -0
  123. package/skill/examples/print.md +31 -0
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Multi-expert agent orchestration (conversation mode).
3
+ *
4
+ * Producer (router) → domain specialist(s) → plan card. The LLM only parses
5
+ * intent and phrases advice; every decision it may make is constrained to the
6
+ * knowledge base (scenario ids, step names, parameter windows), and the
7
+ * result is re-validated locally before anything is spent.
8
+ */
9
+ import { getLocale, t, tList } from '../i18n.js';
10
+ import { parseThenExpression, validateChain, STEPS } from '../knowledge/chains.js';
11
+ import { chooseModel, detectLowPolyIntent } from '../knowledge/models.js';
12
+ import { getScenario, SCENARIOS } from '../knowledge/scenarios.js';
13
+ import { chatJson } from './llm.js';
14
+ const SCENARIO_TABLE = SCENARIOS.map((s) => `- ${s.id}: ${s.description.en} | model=${s.model} | chain=${s.chain.map((c) => c.step).join('→') || 'none'} | deliver=${s.deliverables.join('/')}`).join('\n');
15
+ const STEP_TABLE = STEPS.map((s) => s.name).join(', ');
16
+ const PRODUCER_SYSTEM = `You are the producer/router of the Tripo 3D generation CLI.
17
+ Classify the user's request into exactly one scenario and extract a clean English 3D generation prompt.
18
+
19
+ Scenarios:
20
+ ${SCENARIO_TABLE}
21
+
22
+ Rules:
23
+ - "prompt" must describe the object to generate (translate to English, keep it concrete, <= 200 chars).
24
+ - Set "face_limit" only when the user states a face/polygon budget.
25
+ - Set "needs_animation" true only when the user wants skeleton/animations.
26
+ - If one critical piece of information is missing and materially changes the plan, set "question" (one short question in the user's language). Otherwise omit it.
27
+ Respond with JSON only: {"scenario","prompt","face_limit","needs_animation","question","notes"}`;
28
+ const SPECIALIST_PROMPTS = {
29
+ 'game-mobile': `You are a senior game technical artist (mobile). Budgets: 500–20000 faces, 1–2K textures, clean topology, FBX/GLB delivery. P1 model is used (no quad/parts/geometry_quality).`,
30
+ 'game-pc': `You are a senior game technical artist (PC/console). PBR detailed textures, optional decimate for LODs (bake=true), FBX delivery with engine presets.`,
31
+ film: `You are a film/offline-rendering artist. quad=true subdivision-friendly topology (FBX output), geometry_quality=detailed, texture_quality=detailed, 4K textures, USD/OBJ handoff via convert.`,
32
+ print: `You are a 3D-printing engineer. Geometry only (texture=false,pbr=false), watertight meshes, flatten_bottom for FDM, STL or colored 3MF via convert, real-world sizing via scale_factor/auto_size.`,
33
+ 'ar-web': `You are a realtime AR/Web 3D engineer. Keep faces <= 20000 via decimate, 2K textures, deliver GLB + USDZ (iOS QuickLook).`,
34
+ anim: `You are a character animation TD. Chain: rig-check → rig (rig-v2.0, spec tripo|mixamo) → retarget (<=5 preset animations, billed per animation). Mixamo/Unity Humanoid → spec=mixamo.`,
35
+ toy: `You are a stylized collectible designer. P1 low-poly or stylize steps (lego/voxel/voronoi/minecraft). STL via convert for physical prints.`,
36
+ };
37
+ function specialistSystem(scenarioId) {
38
+ const persona = SPECIALIST_PROMPTS[scenarioId] ?? SPECIALIST_PROMPTS['game-mobile'];
39
+ return `${persona}
40
+ You fine-tune a Tripo generation plan. You may adjust generation params and the processing chain.
41
+ Valid chain steps: ${STEP_TABLE}. Chain syntax: "step:key=value,step2" (e.g. "texture,rig,convert:format=FBX").
42
+ Constraints: pbr=>texture; generate_parts excludes texture/pbr/quad; P1 face_limit 48-20000 and forbids quad/smart_low_poly/generate_parts/geometry_quality; retarget <= 5 animations.
43
+ Respond with JSON only: {"params":{...},"chain":"...","notes":["short practical notes in ${getLocale() === 'zh' ? 'Chinese' : 'English'}"]}. Omit fields you don't want to change.`;
44
+ }
45
+ /**
46
+ * Run the expert pipeline. `askUser` is called when the producer needs one
47
+ * clarification (interactive mode only); return undefined to skip.
48
+ */
49
+ export async function buildExpertPlan(request, askUser) {
50
+ const messages = [
51
+ { role: 'system', content: PRODUCER_SYSTEM },
52
+ { role: 'user', content: request },
53
+ ];
54
+ let producer = await chatJson(messages);
55
+ if (producer.question && askUser) {
56
+ const answer = await askUser(producer.question);
57
+ if (answer) {
58
+ messages.push({ role: 'assistant', content: JSON.stringify(producer) });
59
+ messages.push({ role: 'user', content: `Additional info: ${answer}. Re-classify with the complete picture; do not ask again.` });
60
+ producer = await chatJson(messages);
61
+ }
62
+ }
63
+ const scenario = getScenario(producer.scenario) ?? getScenario('game-mobile');
64
+ const specialist = await chatJson([
65
+ { role: 'system', content: specialistSystem(scenario.id) },
66
+ {
67
+ role: 'user',
68
+ content: `User request: ${request}\nPrompt: ${producer.prompt}\nBase plan: model=${scenario.model} params=${JSON.stringify(scenario.genParams)} chain=${scenario.chain.map((c) => c.step).join('→') || 'none'}\nneeds_animation=${producer.needs_animation ?? false} face_limit=${producer.face_limit ?? 'default'}`,
69
+ },
70
+ ]).catch(() => ({}));
71
+ // Merge + re-validate everything the LLM produced.
72
+ const params = { ...scenario.genParams, ...(specialist.params ?? {}) };
73
+ if (producer.face_limit)
74
+ params.face_limit = producer.face_limit;
75
+ let chain = scenario.chain;
76
+ if (specialist.chain) {
77
+ try {
78
+ chain = parseThenExpression(specialist.chain);
79
+ }
80
+ catch {
81
+ chain = scenario.chain; // discard invalid expert chain, keep the preset
82
+ }
83
+ }
84
+ if (producer.needs_animation && !chain.some((s) => s.step === 'rig')) {
85
+ chain = [
86
+ ...chain.filter((s) => s.step !== 'convert'),
87
+ { step: 'rig-check', args: {} },
88
+ { step: 'rig', args: { model: 'rig-v2.0' } },
89
+ { step: 'retarget', args: { animations: ['preset:idle', 'preset:walk'] } },
90
+ ];
91
+ }
92
+ const choice = chooseModel({
93
+ explicit: scenario.model,
94
+ faceLimit: typeof params.face_limit === 'number' ? params.face_limit : undefined,
95
+ lowPoly: detectLowPolyIntent(request),
96
+ });
97
+ try {
98
+ validateChain(chain, 'text_to_model');
99
+ }
100
+ catch {
101
+ chain = scenario.chain;
102
+ }
103
+ const card = {
104
+ inputSummary: producer.prompt,
105
+ scenario: scenario.id,
106
+ model: choice.model,
107
+ modelReason: t({ zh: '制片人路由 + 场景预设', en: 'producer routing + scenario preset' }),
108
+ genParams: params,
109
+ chain,
110
+ deliverables: scenario.deliverables,
111
+ notes: tList(scenario.notes),
112
+ expertNotes: [...(producer.notes ?? []), ...(specialist.notes ?? [])],
113
+ };
114
+ return { card, scenarioId: scenario.id, prompt: producer.prompt, chain, params };
115
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * BYO-LLM client: any OpenAI-compatible /chat/completions endpoint.
3
+ * Configure via `tripo config set llm.base_url/llm.api_key/llm.model`
4
+ * or env TRIPO_LLM_BASE_URL / TRIPO_LLM_API_KEY / TRIPO_LLM_MODEL.
5
+ */
6
+ import { loadConfig } from '../config/config.js';
7
+ import { CliError } from '../core/errors.js';
8
+ import { EXIT } from '../knowledge/error-catalog.js';
9
+ export function resolveLlmConfig() {
10
+ const env = {
11
+ base_url: process.env.TRIPO_LLM_BASE_URL,
12
+ api_key: process.env.TRIPO_LLM_API_KEY,
13
+ model: process.env.TRIPO_LLM_MODEL,
14
+ };
15
+ if (env.base_url && env.model)
16
+ return { base_url: env.base_url, api_key: env.api_key, model: env.model };
17
+ const config = loadConfig().llm;
18
+ if (config?.base_url && config.model)
19
+ return config;
20
+ return undefined;
21
+ }
22
+ export async function chatCompletion(messages, options = {}) {
23
+ const config = resolveLlmConfig();
24
+ if (!config)
25
+ throw new CliError('no LLM configured', EXIT.USAGE);
26
+ const url = `${config.base_url.replace(/\/$/, '')}/chat/completions`;
27
+ const controller = new AbortController();
28
+ const timer = setTimeout(() => controller.abort(), 60_000);
29
+ let response;
30
+ try {
31
+ response = await fetch(url, {
32
+ method: 'POST',
33
+ headers: {
34
+ 'Content-Type': 'application/json',
35
+ ...(config.api_key ? { Authorization: `Bearer ${config.api_key}` } : {}),
36
+ },
37
+ body: JSON.stringify({
38
+ model: config.model,
39
+ messages,
40
+ temperature: 0.2,
41
+ ...(options.json ? { response_format: { type: 'json_object' } } : {}),
42
+ }),
43
+ signal: controller.signal,
44
+ });
45
+ }
46
+ catch (err) {
47
+ throw new CliError(`LLM request failed: ${err instanceof Error ? err.message : String(err)}`, EXIT.NETWORK);
48
+ }
49
+ finally {
50
+ clearTimeout(timer);
51
+ }
52
+ if (!response.ok) {
53
+ const body = await response.text().catch(() => '');
54
+ throw new CliError(`LLM endpoint returned HTTP ${response.status}: ${body.slice(0, 300)}`, EXIT.NETWORK);
55
+ }
56
+ const data = (await response.json());
57
+ const content = data.choices?.[0]?.message?.content;
58
+ if (!content)
59
+ throw new CliError('LLM returned an empty response', EXIT.NETWORK);
60
+ return content;
61
+ }
62
+ /** Chat expecting a JSON object back; tolerates markdown fences. */
63
+ export async function chatJson(messages) {
64
+ const raw = await chatCompletion(messages, { json: true }).catch(async (err) => {
65
+ // Some endpoints reject response_format; retry without it.
66
+ if (err instanceof CliError && err.exitCode === EXIT.NETWORK) {
67
+ return chatCompletion(messages, { json: false });
68
+ }
69
+ throw err;
70
+ });
71
+ return extractJson(raw);
72
+ }
73
+ export function extractJson(raw) {
74
+ const trimmed = raw.trim();
75
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(trimmed);
76
+ const candidate = fenced ? fenced[1] : trimmed;
77
+ const start = candidate.indexOf('{');
78
+ const end = candidate.lastIndexOf('}');
79
+ if (start === -1 || end === -1 || end < start) {
80
+ throw new CliError(`LLM did not return JSON: ${raw.slice(0, 200)}`, EXIT.NETWORK);
81
+ }
82
+ try {
83
+ return JSON.parse(candidate.slice(start, end + 1));
84
+ }
85
+ catch {
86
+ throw new CliError(`LLM returned invalid JSON: ${candidate.slice(0, 200)}`, EXIT.NETWORK);
87
+ }
88
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The plan card: one shared "here is what I will do and what it costs"
3
+ * confirmation format used by both the wizard (zero-LLM) and the expert
4
+ * conversation mode. Decisions come from the knowledge base either way.
5
+ */
6
+ import pc from 'picocolors';
7
+ import { t } from '../i18n.js';
8
+ import { getScenario } from '../knowledge/scenarios.js';
9
+ /** Cost-impact annotations derived from the parameter set. */
10
+ export function costNotes(card) {
11
+ const notes = [];
12
+ const params = card.genParams;
13
+ if (params.texture === false) {
14
+ notes.push(t({ zh: '白模生成:不消耗贴图积分', en: 'bare geometry: no texture credits' }));
15
+ }
16
+ if (params.texture_quality === 'detailed' || params.texture_quality === 'extreme') {
17
+ notes.push(t({ zh: `贴图质量 ${params.texture_quality}:价签更高`, en: `texture_quality ${params.texture_quality}: higher price tier` }));
18
+ }
19
+ if (params.geometry_quality === 'detailed') {
20
+ notes.push(t({ zh: 'geometry detailed(Ultra):加收 HD credit', en: 'geometry detailed (Ultra): extra HD credit' }));
21
+ }
22
+ if (params.quad === true) {
23
+ notes.push(t({ zh: 'quad 四边面:价签更高,输出 FBX', en: 'quad topology: higher price tier, FBX output' }));
24
+ }
25
+ if (params.generate_parts === true) {
26
+ notes.push(t({ zh: '分件生成:价签更高,出裸几何', en: 'part generation: higher price tier, bare geometry' }));
27
+ }
28
+ for (const step of card.chain) {
29
+ if (step.step === 'convert' && Object.keys(step.args).length > 1) {
30
+ notes.push(t({ zh: 'convert 非默认参数:按 complex 价签计费', en: 'non-default convert options bill as complex convert' }));
31
+ }
32
+ if (step.step === 'retarget') {
33
+ const count = Array.isArray(step.args.animations) ? step.args.animations.length : 1;
34
+ notes.push(t({ zh: `retarget ${count} 条动画:按条计费`, en: `retarget ${count} animation(s): billed per animation` }));
35
+ }
36
+ }
37
+ return notes;
38
+ }
39
+ /** Render the card for terminal display (stderr). */
40
+ export function renderPlanCard(card) {
41
+ const scenario = card.scenario ? getScenario(card.scenario) : undefined;
42
+ const lines = [];
43
+ const title = t({ zh: '方案卡', en: 'Plan' });
44
+ lines.push(pc.bold(`── ${title} ──────────────────────────`));
45
+ lines.push(`${t({ zh: '输入', en: 'input' })}: ${card.inputSummary}`);
46
+ if (scenario)
47
+ lines.push(`${t({ zh: '场景', en: 'scenario' })}: ${scenario.id} (${t(scenario.label)})`);
48
+ if (card.model) {
49
+ lines.push(`${t({ zh: '模型', en: 'model' })}: ${card.model}${card.modelReason ? pc.dim(` — ${card.modelReason}`) : ''}`);
50
+ }
51
+ const params = Object.entries(card.genParams);
52
+ if (params.length > 0) {
53
+ lines.push(`${t({ zh: '参数', en: 'params' })}: ${params.map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(' ')}`);
54
+ }
55
+ if (card.chain.length > 0) {
56
+ const chainStr = card.chain
57
+ .map((s) => (Object.keys(s.args).length > 0 ? `${s.step}(${Object.entries(s.args).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(',')})` : s.step))
58
+ .join(' → ');
59
+ lines.push(`${t({ zh: '加工链', en: 'chain' })}: ${chainStr}`);
60
+ }
61
+ if (card.deliverables.length > 0) {
62
+ lines.push(`${t({ zh: '交付物', en: 'deliverables' })}: ${card.deliverables.join(', ')}`);
63
+ }
64
+ const cost = costNotes(card);
65
+ if (cost.length > 0) {
66
+ lines.push(`${t({ zh: '成本影响', en: 'cost impact' })}:`);
67
+ for (const note of cost)
68
+ lines.push(` · ${note}`);
69
+ }
70
+ for (const note of card.notes)
71
+ lines.push(pc.dim(` ${note}`));
72
+ if (card.expertNotes && card.expertNotes.length > 0) {
73
+ lines.push(`${t({ zh: '专家意见', en: 'expert notes' })}:`);
74
+ for (const note of card.expertNotes)
75
+ lines.push(` · ${note}`);
76
+ }
77
+ lines.push(pc.bold('──────────────────────────────────'));
78
+ return lines.join('\n');
79
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Wizard mode (zero-LLM): 3–4 multiple-choice questions drive the same
3
+ * knowledge-base decision tree that experts use. Every user gets 80% of the
4
+ * intelligence with no LLM configured.
5
+ */
6
+ import * as p from '@clack/prompts';
7
+ import { CliError, UsageError } from '../core/errors.js';
8
+ import { isInteractive } from '../core/output.js';
9
+ import { t, tList } from '../i18n.js';
10
+ import { EXIT } from '../knowledge/error-catalog.js';
11
+ import { getScenario, SCENARIOS } from '../knowledge/scenarios.js';
12
+ export async function runWizard(initialPrompt) {
13
+ if (!isInteractive()) {
14
+ throw new UsageError(t({
15
+ zh: '向导需要交互终端;无头环境请直接用 tripo make --for <场景> 或配置 LLM 后用 tripo ai --yes',
16
+ en: 'the wizard needs an interactive terminal; headless callers should use "tripo make --for <scenario>" instead',
17
+ }));
18
+ }
19
+ p.intro('tripo ai');
20
+ let prompt = initialPrompt?.trim() ?? '';
21
+ if (!prompt) {
22
+ const answer = await p.text({
23
+ message: t({ zh: '想做个什么?一句话描述(或图片路径)', en: 'What do you want to make? one sentence (or an image path)' }),
24
+ validate: (v) => (v && v.trim().length > 0 ? undefined : t({ zh: '说点什么吧', en: 'say something' })),
25
+ });
26
+ if (p.isCancel(answer))
27
+ throw new CliError('cancelled', EXIT.FATAL);
28
+ prompt = answer.trim();
29
+ }
30
+ const scenarioAnswer = await p.select({
31
+ message: t({ zh: '用在什么地方?', en: 'What is it for?' }),
32
+ options: SCENARIOS.map((s) => ({ value: s.id, label: `${t(s.label)} — ${t(s.description)}` })),
33
+ });
34
+ if (p.isCancel(scenarioAnswer))
35
+ throw new CliError('cancelled', EXIT.FATAL);
36
+ const scenario = getScenario(scenarioAnswer);
37
+ let engine;
38
+ if (scenarioAnswer === 'game-mobile' || scenarioAnswer === 'game-pc') {
39
+ const engineAnswer = await p.select({
40
+ message: t({ zh: '目标引擎/软件?', en: 'Target engine/software?' }),
41
+ options: [
42
+ { value: 'unity', label: 'Unity' },
43
+ { value: 'unreal', label: 'Unreal' },
44
+ { value: 'blender', label: 'Blender' },
45
+ { value: 'any', label: t({ zh: '不确定/通用', en: 'not sure / generic' }) },
46
+ ],
47
+ });
48
+ if (p.isCancel(engineAnswer))
49
+ throw new CliError('cancelled', EXIT.FATAL);
50
+ engine = engineAnswer;
51
+ }
52
+ let animations = false;
53
+ if (scenarioAnswer !== 'print' && scenarioAnswer !== 'film') {
54
+ const animAnswer = await p.confirm({
55
+ message: t({ zh: '需要骨骼/动画吗?', en: 'Do you need a skeleton / animations?' }),
56
+ initialValue: scenarioAnswer === 'anim',
57
+ });
58
+ if (p.isCancel(animAnswer))
59
+ throw new CliError('cancelled', EXIT.FATAL);
60
+ animations = animAnswer;
61
+ }
62
+ const { chain, notes } = adjustChain(scenario.id, engine, animations);
63
+ const card = {
64
+ inputSummary: prompt,
65
+ scenario: scenario.id,
66
+ model: scenario.model,
67
+ modelReason: t({ zh: '场景预设', en: 'scenario preset' }),
68
+ genParams: scenario.genParams,
69
+ chain,
70
+ deliverables: scenario.deliverables,
71
+ notes: [...tList(scenario.notes), ...notes],
72
+ };
73
+ return { card, options: { prompt, scenario: scenario.id, chain } };
74
+ }
75
+ /** Engine/animation adjustments on top of the scenario chain. */
76
+ export function adjustChain(scenarioId, engine, animations) {
77
+ const scenario = getScenario(scenarioId);
78
+ let chain = scenario.chain.map((s) => ({ step: s.step, args: { ...s.args } }));
79
+ const notes = [];
80
+ if (animations && !chain.some((s) => s.step === 'rig')) {
81
+ const rigArgs = { model: 'rig-v2.0', out_format: 'fbx' };
82
+ if (engine === 'unity') {
83
+ rigArgs.spec = 'mixamo';
84
+ notes.push(t({ zh: 'Unity Humanoid → spec=mixamo', en: 'Unity Humanoid → spec=mixamo' }));
85
+ }
86
+ chain = [
87
+ ...chain.filter((s) => s.step !== 'convert'),
88
+ { step: 'rig-check', args: {} },
89
+ { step: 'rig', args: rigArgs },
90
+ { step: 'retarget', args: { animations: ['preset:idle', 'preset:walk'], out_format: 'fbx' } },
91
+ ];
92
+ notes.push(t({ zh: '动画链输出 FBX(骨骼+动画)', en: 'animation chain outputs FBX (skeleton + animations)' }));
93
+ }
94
+ if (engine && !animations) {
95
+ const convert = chain.find((s) => s.step === 'convert');
96
+ if (convert && convert.args.format === 'FBX') {
97
+ if (engine === 'blender')
98
+ convert.args.fbx_preset = 'blender';
99
+ if (engine === 'unreal' || engine === 'unity')
100
+ convert.args.export_orientation = '+x';
101
+ }
102
+ }
103
+ return { chain, notes };
104
+ }
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from './program.js';
3
+ process.on('SIGINT', () => {
4
+ process.stderr.write('\n');
5
+ process.exit(130);
6
+ });
7
+ void runCli(process.argv);
@@ -0,0 +1,27 @@
1
+ /** `tripo balance` / `tripo usage` — account visibility. */
2
+ import { TripoClient } from '../core/client.js';
3
+ import { emitResult } from '../core/output.js';
4
+ import { t } from '../i18n.js';
5
+ export function registerAccountCommands(program) {
6
+ program
7
+ .command('balance')
8
+ .description('show available and frozen credits')
9
+ .action(async () => {
10
+ const data = await new TripoClient().getBalance();
11
+ emitResult(data, t({
12
+ zh: `余额 ${data.balance} 积分(冻结 ${data.frozen})`,
13
+ en: `balance: ${data.balance} credits (${data.frozen} frozen)`,
14
+ }));
15
+ });
16
+ program
17
+ .command('usage')
18
+ .description('recent task credit usage')
19
+ .option('--limit <n>', 'max rows to show', (v) => Number(v), 20)
20
+ .action(async (opts) => {
21
+ const items = (await new TripoClient().getUsage()).slice(0, opts.limit);
22
+ const human = items
23
+ .map((i) => `${(i.created_at ?? '').slice(0, 19).padEnd(20)} ${i.type.padEnd(24)} ${String(i.credits_consumed ?? 0).padStart(6)} cr ${i.task_id}`)
24
+ .join('\n');
25
+ emitResult(items, human || t({ zh: '暂无用量记录', en: 'no usage yet' }));
26
+ });
27
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * `tripo ai` — dual mode:
3
+ * wizard (default without an LLM): knowledge-base decision-tree Q&A
4
+ * conversation (with an LLM configured): producer + specialist agents
5
+ * Both produce the same plan card; confirmed plans execute through the same
6
+ * deterministic engine as `tripo make`.
7
+ */
8
+ import * as p from '@clack/prompts';
9
+ import { resolveReference } from '../config/history.js';
10
+ import { CliError } from '../core/errors.js';
11
+ import { isInteractive, isYes, log, warn } from '../core/output.js';
12
+ import { t } from '../i18n.js';
13
+ import { EXIT } from '../knowledge/error-catalog.js';
14
+ import { executeMake, planMake } from '../pipeline/make.js';
15
+ import { renderPlanCard } from '../ai/plan-card.js';
16
+ import { resolveLlmConfig } from '../ai/llm.js';
17
+ import { buildExpertPlan } from '../ai/experts.js';
18
+ import { runWizard } from '../ai/wizard.js';
19
+ import { emitMakeOutcome } from './make.js';
20
+ import { newClient, withTaskOptions } from './shared.js';
21
+ export function registerAiCommand(program) {
22
+ const cmd = program
23
+ .command('ai')
24
+ .description('describe what you want in natural language; experts plan it, you confirm, it runs')
25
+ .argument('[request...]', 'e.g. "给我的手游做一个低模骑士,要跑步动画"')
26
+ .option('--wizard', 'force wizard mode even when an LLM is configured');
27
+ withTaskOptions(cmd);
28
+ cmd.action(async (request, flags) => {
29
+ const text = expandHistoryRefs(request.join(' ').trim());
30
+ const llm = resolveLlmConfig();
31
+ let card;
32
+ let makeOptions;
33
+ if (llm && !flags.wizard && text) {
34
+ log(t({ zh: `对话模式(${llm.model})…`, en: `conversation mode (${llm.model})…` }));
35
+ try {
36
+ const plan = await buildExpertPlan(text, isInteractive() ? askUser : undefined);
37
+ card = plan.card;
38
+ makeOptions = {
39
+ inputs: [plan.prompt],
40
+ scenario: plan.scenarioId,
41
+ chain: plan.chain,
42
+ params: plan.params,
43
+ name: flags.name,
44
+ outDir: flags.out,
45
+ notify: flags.notify,
46
+ timeoutMs: flags.timeout ? flags.timeout * 1000 : undefined,
47
+ };
48
+ }
49
+ catch (err) {
50
+ warn(t({
51
+ zh: `LLM 编排失败(${err instanceof Error ? err.message : err}),回落到向导模式`,
52
+ en: `LLM planning failed (${err instanceof Error ? err.message : err}); falling back to the wizard`,
53
+ }));
54
+ const wizard = await runWizard(text);
55
+ card = wizard.card;
56
+ makeOptions = wizardToOptions(wizard.options, flags);
57
+ }
58
+ }
59
+ else {
60
+ if (llm === undefined && text && !isInteractive()) {
61
+ throw new CliError(t({
62
+ zh: '无 LLM 配置时 tripo ai 需要交互终端;无头环境请用 tripo make --for <场景>(或配置 llm.base_url/llm.model)',
63
+ en: 'without an LLM, "tripo ai" needs an interactive terminal; headless callers should use "tripo make --for <scenario>" (or configure llm.base_url/llm.model)',
64
+ }), EXIT.USAGE);
65
+ }
66
+ const wizard = await runWizard(text || undefined);
67
+ card = wizard.card;
68
+ makeOptions = wizardToOptions(wizard.options, flags);
69
+ }
70
+ process.stderr.write(renderPlanCard(card) + '\n');
71
+ if (!isYes()) {
72
+ const go = await p.confirm({ message: t({ zh: '按方案执行?', en: 'Run this plan?' }) });
73
+ if (p.isCancel(go) || !go) {
74
+ log(t({ zh: '已取消,未消耗积分', en: 'cancelled; no credits spent' }));
75
+ return;
76
+ }
77
+ }
78
+ const client = newClient();
79
+ const plan = await planMake(client, makeOptions);
80
+ const outcome = await executeMake(client, plan, makeOptions);
81
+ emitMakeOutcome({ results: [outcome.primary], chainResults: outcome.chainResults, stoppedEarly: outcome.stoppedEarly });
82
+ });
83
+ }
84
+ function wizardToOptions(options, flags) {
85
+ return {
86
+ inputs: [options.prompt],
87
+ scenario: options.scenario,
88
+ chain: options.chain,
89
+ params: flags.param,
90
+ name: flags.name,
91
+ outDir: flags.out,
92
+ notify: flags.notify,
93
+ timeoutMs: flags.timeout ? flags.timeout * 1000 : undefined,
94
+ };
95
+ }
96
+ async function askUser(question) {
97
+ const answer = await p.text({ message: question });
98
+ if (p.isCancel(answer))
99
+ return undefined;
100
+ return answer;
101
+ }
102
+ /** Replace @task-name references in a prompt with their task ids. */
103
+ export function expandHistoryRefs(text) {
104
+ return text.replace(/@[\w\u4e00-\u9fff-]+/g, (ref) => {
105
+ try {
106
+ const entry = resolveReference(ref);
107
+ return entry ? entry.task_id : ref;
108
+ }
109
+ catch {
110
+ return ref; // ambiguity is reported when the value is actually used
111
+ }
112
+ });
113
+ }