@cloudflare/think 0.8.6 → 0.8.7

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/dist/cli/index.js CHANGED
@@ -1,12 +1,342 @@
1
1
  #!/usr/bin/env node
2
- import { a as readWranglerConfig, i as readProjectFiles, m as summarizeThinkManifest, n as createThinkProject, o as resolveThinkManifest, t as applyUserBindingNames } from "../project-D1o1-3dN.js";
2
+ import { a as readWranglerConfig, c as createThinkWorkerConfig, h as discoverThinkApp, i as readProjectFiles, m as summarizeThinkManifest, n as createThinkProject, o as resolveThinkManifest, t as applyUserBindingNames } from "../project-D1o1-3dN.js";
3
3
  import { n as isThinkGeneratedFile, t as generateThinkTypes } from "../types-codegen-B6c5KpYH.js";
4
- import { t as initCommand } from "../init-C9q1GbK-.js";
5
4
  import { access, mkdir, readFile, writeFile } from "node:fs/promises";
6
5
  import path from "node:path";
7
6
  import yargs from "yargs";
8
7
  import { hideBin } from "yargs/helpers";
9
8
  import { spawn } from "node:child_process";
9
+ import { initCommand, looksLikeThinkApp } from "create-think";
10
+ //#region src/cli/init.ts
11
+ const VITE_CONFIG_FILES = [
12
+ "vite.config.ts",
13
+ "vite.config.mts",
14
+ "vite.config.js",
15
+ "vite.config.mjs"
16
+ ];
17
+ /**
18
+ * `think init` has two modes:
19
+ *
20
+ * - New project: when a `--template` is given, or when the command is run
21
+ * outside an existing npm project. Delegates to `create-think`, which fetches
22
+ * a complete starter template (no framework dependency required at runtime).
23
+ * - Augment in place: when run inside an existing npm project with no
24
+ * `--template`. Adds Think framework files (agent, Vite/Wrangler config,
25
+ * generated types) and merges dependencies into the current project.
26
+ */
27
+ async function initCommand$1(options) {
28
+ const baseRoot = path.resolve(options.root ?? process.cwd());
29
+ const insideExistingProject = !options.directory && await fileExists(path.join(baseRoot, "package.json"));
30
+ if (Boolean(options.template) || !insideExistingProject) {
31
+ await initCommand(options);
32
+ return;
33
+ }
34
+ await augmentExistingProject(baseRoot, options);
35
+ }
36
+ async function augmentExistingProject(root, options) {
37
+ const projectName = packageName(options.name ?? path.basename(root));
38
+ if (await looksLikeThinkApp(root)) {
39
+ console.log(["This already looks like a Think app.", "Try `think inspect` to review the manifest or `think types` to refresh generated declarations."].join("\n"));
40
+ return;
41
+ }
42
+ const migrationReason = await unsafeMigrationReason(root);
43
+ if (migrationReason) throw new Error([
44
+ "This directory already has Vite or Wrangler configuration, so `think init` will not migrate it automatically yet.",
45
+ migrationReason,
46
+ "Start a new Think app with `npm create think`, or add `@cloudflare/think/vite` and Think framework files manually."
47
+ ].join("\n"));
48
+ const plan = await createInitPlan({
49
+ root,
50
+ projectName,
51
+ routePrefix: options.routePrefix
52
+ });
53
+ const skipped = await existingPlanFiles(plan);
54
+ if (options.dryRun) {
55
+ printDryRun(plan, skipped, options.install ?? true);
56
+ return;
57
+ }
58
+ await writePlannedFiles(plan, skipped);
59
+ if (options.install ?? true) await (options.installRunner ?? runNpmInstall)(root);
60
+ printSuccess(plan, skipped, options.install ?? true);
61
+ }
62
+ async function createInitPlan(options) {
63
+ const sourceFiles = {
64
+ "agents/assistant/agent.ts": agentSource(),
65
+ "agents/assistant/skills/project-helper/SKILL.md": starterSkillSource()
66
+ };
67
+ const manifest = discoverThinkApp({
68
+ root: options.root,
69
+ routePrefix: options.routePrefix,
70
+ files: sourceFiles
71
+ });
72
+ const workerConfig = createThinkWorkerConfig(manifest, {
73
+ name: options.projectName,
74
+ routePrefix: options.routePrefix
75
+ });
76
+ workerConfig.ai = { binding: "AI" };
77
+ workerConfig.worker_loaders = [{ binding: "LOADER" }];
78
+ const typeFiles = generateThinkTypes(manifest, {
79
+ files: sourceFiles,
80
+ typesFile: "think.d.ts"
81
+ });
82
+ return {
83
+ root: options.root,
84
+ projectName: options.projectName,
85
+ packageJsonPath: "package.json",
86
+ files: [
87
+ {
88
+ path: "package.json",
89
+ content: packageJsonSource(options.projectName),
90
+ merge: "package-json"
91
+ },
92
+ {
93
+ path: "vite.config.ts",
94
+ content: viteConfig(options.routePrefix)
95
+ },
96
+ {
97
+ path: "wrangler.jsonc",
98
+ content: `${JSON.stringify(workerConfig, null, 2)}\n`
99
+ },
100
+ {
101
+ path: "tsconfig.json",
102
+ content: tsconfig()
103
+ },
104
+ {
105
+ path: "agents/assistant/agent.ts",
106
+ content: sourceFiles["agents/assistant/agent.ts"]
107
+ },
108
+ {
109
+ path: "agents/assistant/skills/project-helper/SKILL.md",
110
+ content: sourceFiles["agents/assistant/skills/project-helper/SKILL.md"]
111
+ },
112
+ ...typeFiles
113
+ ]
114
+ };
115
+ }
116
+ async function existingPlanFiles(plan) {
117
+ const existing = /* @__PURE__ */ new Set();
118
+ for (const file of plan.files) {
119
+ if (file.merge === "package-json") continue;
120
+ if (await fileExists(path.join(plan.root, file.path))) existing.add(file.path);
121
+ }
122
+ return existing;
123
+ }
124
+ async function writePlannedFiles(plan, skip) {
125
+ await mkdir(plan.root, { recursive: true });
126
+ for (const file of plan.files) {
127
+ if (skip.has(file.path)) continue;
128
+ const absolute = path.join(plan.root, file.path);
129
+ await mkdir(path.dirname(absolute), { recursive: true });
130
+ await writeFile(absolute, file.merge === "package-json" ? await mergePackageJson(absolute, file.content) : file.content, "utf8");
131
+ }
132
+ }
133
+ async function mergePackageJson(absolutePath, generatedContent) {
134
+ const generated = JSON.parse(generatedContent);
135
+ const existingSource = await readTextIfExists$1(absolutePath);
136
+ if (!existingSource) return generatedContent;
137
+ const existing = JSON.parse(existingSource);
138
+ return `${JSON.stringify(mergePackageJsonData(existing, generated), null, 2)}\n`;
139
+ }
140
+ function mergePackageJsonData(existing, generated) {
141
+ return {
142
+ ...generated,
143
+ ...existing,
144
+ type: generated.type ?? existing.type,
145
+ scripts: {
146
+ ...generated.scripts,
147
+ ...existing.scripts
148
+ },
149
+ dependencies: {
150
+ ...generated.dependencies,
151
+ ...existing.dependencies
152
+ },
153
+ devDependencies: {
154
+ ...generated.devDependencies,
155
+ ...existing.devDependencies
156
+ }
157
+ };
158
+ }
159
+ async function unsafeMigrationReason(root) {
160
+ for (const file of [
161
+ ...VITE_CONFIG_FILES,
162
+ "wrangler.jsonc",
163
+ "wrangler.json",
164
+ "wrangler.toml"
165
+ ]) if (await fileExists(path.join(root, file))) return `Found existing ${file}.`;
166
+ return null;
167
+ }
168
+ function printDryRun(plan, skipped, install) {
169
+ const lines = ["Think init would add to the current project:", ...plan.files.filter((file) => !skipped.has(file.path)).map((file) => `- ${file.path}`)];
170
+ if (skipped.size > 0) lines.push("", "Would keep your existing files (left unchanged):", ...[...skipped].map((file) => `- ${file}`));
171
+ lines.push(install ? "Would run: npm install" : "Would skip dependency install.");
172
+ console.log(lines.join("\n"));
173
+ }
174
+ function printSuccess(plan, skipped, install) {
175
+ const lines = [`Added Think to ${plan.root}.`, install ? "Installed npm dependencies." : "Skipped npm install."];
176
+ if (skipped.size > 0) lines.push("", "Kept your existing files (not overwritten):", ...[...skipped].map((file) => `- ${file}`), "Reconcile them with Think's expected setup if the app does not build.");
177
+ lines.push("", "Next steps:", "- Edit agents/assistant/agent.ts to customize the model, prompt, skills, and schedules", "- npm run dev", "- npm run types", "- npm run deploy");
178
+ console.log(lines.join("\n"));
179
+ }
180
+ async function runNpmInstall(root) {
181
+ await new Promise((resolve, reject) => {
182
+ const child = spawn("npm", ["install"], {
183
+ cwd: root,
184
+ stdio: "inherit",
185
+ shell: process.platform === "win32"
186
+ });
187
+ child.on("error", reject);
188
+ child.on("exit", (code) => {
189
+ if (code === 0) {
190
+ resolve();
191
+ return;
192
+ }
193
+ reject(/* @__PURE__ */ new Error(`npm install failed with exit code ${code ?? "unknown"}.`));
194
+ });
195
+ });
196
+ }
197
+ const FRAMEWORK_DEPENDENCIES = {
198
+ "@cloudflare/think": "latest",
199
+ agents: "latest"
200
+ };
201
+ const THIRD_PARTY_DEPENDENCIES = {
202
+ ai: "^6.0.196",
203
+ "workers-ai-provider": "^3.1.14"
204
+ };
205
+ const THIRD_PARTY_DEV_DEPENDENCIES = {
206
+ "@cloudflare/vite-plugin": "^1.39.2",
207
+ "@cloudflare/workers-types": "^4.20260604.1",
208
+ typescript: "^6.0.3",
209
+ vite: "^8.0.16",
210
+ wrangler: "^4.97.0"
211
+ };
212
+ function packageJsonSource(projectName) {
213
+ return `${JSON.stringify({
214
+ name: projectName,
215
+ private: true,
216
+ type: "module",
217
+ scripts: {
218
+ dev: "vite dev",
219
+ build: "vite build",
220
+ deploy: "vite build && wrangler deploy",
221
+ types: "think types --all"
222
+ },
223
+ dependencies: {
224
+ ...FRAMEWORK_DEPENDENCIES,
225
+ ...THIRD_PARTY_DEPENDENCIES
226
+ },
227
+ devDependencies: { ...THIRD_PARTY_DEV_DEPENDENCIES }
228
+ }, null, 2)}\n`;
229
+ }
230
+ function viteConfig(routePrefix) {
231
+ return [
232
+ `import { cloudflare } from "@cloudflare/vite-plugin";`,
233
+ `import { think } from "@cloudflare/think/vite";`,
234
+ `import { defineConfig } from "vite";`,
235
+ "",
236
+ "export default defineConfig({",
237
+ ` plugins: [think${routePrefix ? `({ routePrefix: ${JSON.stringify(routePrefix)} })` : "()"}, cloudflare()]`,
238
+ "});",
239
+ ""
240
+ ].join("\n");
241
+ }
242
+ function agentSource() {
243
+ return [
244
+ `import { Think, skills } from "@cloudflare/think";`,
245
+ `import { createWorkersAI } from "workers-ai-provider";`,
246
+ `import bundledSkills from "agents:skills";`,
247
+ "",
248
+ "type Env = Cloudflare.Env & {",
249
+ " AI: Ai;",
250
+ " LOADER: WorkerLoader;",
251
+ "};",
252
+ "",
253
+ "export class Assistant extends Think<Env> {",
254
+ " override getModel() {",
255
+ " return createWorkersAI({ binding: this.env.AI })(",
256
+ " \"@cf/moonshotai/kimi-k2.6\",",
257
+ " { sessionAffinity: this.sessionAffinity }",
258
+ " );",
259
+ " }",
260
+ "",
261
+ " override getSystemPrompt() {",
262
+ " return \"You are a helpful assistant. Keep answers clear, practical, and concise.\";",
263
+ " }",
264
+ "",
265
+ " override getSkills() {",
266
+ " return [bundledSkills];",
267
+ " }",
268
+ "",
269
+ " override getSkillScriptRunner() {",
270
+ " return skills.runner({",
271
+ " loader: this.env.LOADER,",
272
+ " workspaceInstance: this.workspace",
273
+ " });",
274
+ " }",
275
+ "}",
276
+ ""
277
+ ].join("\n");
278
+ }
279
+ function starterSkillSource() {
280
+ return [
281
+ "---",
282
+ "name: project-helper",
283
+ "description: Help users plan and explain small project changes. Use when the user asks for implementation guidance, debugging steps, or a concise project plan.",
284
+ "---",
285
+ "",
286
+ "# Project Helper",
287
+ "",
288
+ "Use this skill to give practical, action-oriented project help.",
289
+ "",
290
+ "## Instructions",
291
+ "",
292
+ "1. Restate the user's goal in one sentence.",
293
+ "2. Identify the smallest useful next step.",
294
+ "3. Call out any important risk or missing context.",
295
+ "4. Keep the answer concise and easy to act on.",
296
+ ""
297
+ ].join("\n");
298
+ }
299
+ function tsconfig() {
300
+ return `${JSON.stringify({
301
+ compilerOptions: {
302
+ target: "ES2021",
303
+ module: "ES2022",
304
+ moduleResolution: "bundler",
305
+ strict: true,
306
+ verbatimModuleSyntax: true,
307
+ types: ["@cloudflare/workers-types"]
308
+ },
309
+ include: [
310
+ "agents",
311
+ "think.d.ts",
312
+ "vite.config.ts"
313
+ ]
314
+ }, null, 2)}\n`;
315
+ }
316
+ function packageName(name) {
317
+ return name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").replace(/^[._]+/, "") || "think-agent";
318
+ }
319
+ async function readTextIfExists$1(file) {
320
+ try {
321
+ return await readFile(file, "utf8");
322
+ } catch (error) {
323
+ if (isMissingFileError$1(error)) return null;
324
+ throw error;
325
+ }
326
+ }
327
+ async function fileExists(file) {
328
+ try {
329
+ await access(file);
330
+ return true;
331
+ } catch (error) {
332
+ if (isMissingFileError$1(error)) return false;
333
+ throw error;
334
+ }
335
+ }
336
+ function isMissingFileError$1(error) {
337
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
338
+ }
339
+ //#endregion
10
340
  //#region src/cli/inspect.ts
11
341
  async function inspectCommand(options) {
12
342
  const root = path.resolve(options.root ?? process.cwd());
@@ -204,7 +534,7 @@ function isMissingFileError(error) {
204
534
  //#endregion
205
535
  //#region src/cli/create.ts
206
536
  function createCli(argv = process.argv) {
207
- return yargs(hideBin(argv)).parserConfiguration({ "populate--": true }).scriptName("think").usage("$0 <command> [options]").command("init [directory]", "Create a new Think app from a starter template", (cmd) => cmd.positional("directory", {
537
+ return yargs(hideBin(argv)).parserConfiguration({ "populate--": true }).scriptName("think").usage("$0 <command> [options]").command("init [directory]", "Scaffold a new Think app from a starter template, or add Think to the current project", (cmd) => cmd.positional("directory", {
208
538
  type: "string",
209
539
  describe: "Target directory to initialize. Omit to choose interactively."
210
540
  }).option("root", {
@@ -220,6 +550,9 @@ function createCli(argv = process.argv) {
220
550
  }).option("ref", {
221
551
  type: "string",
222
552
  describe: "Git ref to fetch remote templates from"
553
+ }).option("route-prefix", {
554
+ type: "string",
555
+ describe: "Think route prefix when adding Think to an existing project"
223
556
  }).option("yes", {
224
557
  alias: "y",
225
558
  type: "boolean",
@@ -234,12 +567,13 @@ function createCli(argv = process.argv) {
234
567
  describe: "Print files that would be written without writing them",
235
568
  default: false
236
569
  }), async (args) => {
237
- await initCommand({
570
+ await initCommand$1({
238
571
  root: args.root,
239
572
  directory: args.directory,
240
573
  name: args.name,
241
574
  template: args.template,
242
575
  ref: args.ref,
576
+ routePrefix: args.routePrefix,
243
577
  yes: args.yes,
244
578
  install: args.install,
245
579
  dryRun: args.dryRun
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/inspect.ts","../../src/cli/types.ts","../../src/cli/create.ts","../../src/cli/index.ts"],"sourcesContent":["import path from \"node:path\";\nimport {\n summarizeThinkManifest,\n type ThinkConfigSeverity,\n type ThinkWorkerConfigDiagnostic\n} from \"../framework/config\";\nimport type {\n ThinkFrameworkManifest,\n ThinkFrameworkRouteSurface\n} from \"../framework/manifest\";\nimport { createThinkProject } from \"../framework/project\";\n\nexport interface InspectCommandOptions {\n root?: string;\n json?: boolean;\n routePrefix?: string;\n allowNonVirtualMain?: boolean;\n}\n\nexport async function inspectCommand(\n options: InspectCommandOptions\n): Promise<void> {\n const root = path.resolve(options.root ?? process.cwd());\n const project = await createThinkProject(\n {\n routePrefix: options.routePrefix,\n allowNonVirtualMain: options.allowNonVirtualMain\n },\n root\n );\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n root,\n manifest: project.manifest,\n workerConfig: project.workerConfig,\n diagnostics: project.diagnostics,\n wranglerConfig: {\n path: project.wranglerConfig.path,\n parsed: Boolean(project.wranglerConfig.config),\n error: project.wranglerConfig.error\n }\n },\n null,\n 2\n )\n );\n return;\n }\n\n const lines = [\n \"Think inspect\",\n `Root: ${root}`,\n \"\",\n ...summarizeThinkManifest(project.manifest),\n \"\",\n `Route prefix: ${project.manifest.routePrefix}`,\n `App entry: ${project.manifest.appEntrypoint ?? \"none\"}`,\n `Wrangler config: ${project.wranglerConfig.path ?? \"not found\"}`,\n \"\",\n \"Features:\",\n ...formatFeatures(project.manifest),\n \"\",\n \"Route surfaces:\",\n ...formatRouteSurfaces(project.manifest.routeSurfaces),\n \"\",\n \"Schedules:\",\n ...formatNamedFacts(project.manifest.schedules),\n \"\",\n \"Messengers:\",\n ...formatNamedFacts(project.manifest.messengers),\n \"\",\n \"Tools:\",\n ...formatNamedFacts(project.manifest.tools),\n \"\",\n \"Platform requirements:\",\n ...formatPlatformRequirements(project.manifest),\n \"\",\n \"Expected top-level Durable Objects:\",\n ...formatBindings(project.manifest.bindings),\n \"\",\n \"Diagnostics:\",\n ...formatDiagnostics(project.diagnostics)\n ];\n\n if (project.wranglerConfig.error) {\n lines.push(\"\", `[warning] ${project.wranglerConfig.error}`);\n }\n\n console.log(lines.join(\"\\n\"));\n}\n\nfunction formatBindings(\n bindings: Array<{ name: string; className: string }>\n): string[] {\n if (bindings.length === 0) return [\"- none\"];\n return bindings.map(\n (binding) => `- ${binding.name} -> class ${binding.className}`\n );\n}\n\nfunction formatFeatures(manifest: ThinkFrameworkManifest): string[] {\n if (manifest.features.length === 0) return [\"- none\"];\n return manifest.agents.flatMap((agent) => {\n if (agent.features.length === 0 && agent.env.length === 0) return [];\n return [\n `- ${agent.id}: ${\n [\n agent.features.length\n ? `features ${agent.features.join(\", \")}`\n : null,\n agent.env.length ? `env ${agent.env.join(\", \")}` : null\n ]\n .filter(Boolean)\n .join(\" | \") || \"none\"\n }`\n ];\n });\n}\n\nfunction formatRouteSurfaces(surfaces: ThinkFrameworkRouteSurface[]): string[] {\n if (surfaces.length === 0) return [\"- none\"];\n return surfaces.map(\n (surface) =>\n `- ${surface.kind} ${surface.id}: ${surface.pattern}${\n surface.requiredRunWorkerFirst ? \" | requires run_worker_first\" : \"\"\n }`\n );\n}\n\nfunction formatNamedFacts(\n facts: Array<{ id: string; agent?: string; sourcePath?: string }>\n): string[] {\n if (facts.length === 0) return [\"- none\"];\n return facts.map(\n (fact) =>\n `- ${fact.id}${fact.agent ? ` | agent ${fact.agent}` : \"\"}${\n fact.sourcePath ? ` | ${fact.sourcePath}` : \"\"\n }`\n );\n}\n\nfunction formatPlatformRequirements(\n manifest: ThinkFrameworkManifest\n): string[] {\n if (manifest.platformRequirements.length === 0) return [\"- none\"];\n return manifest.platformRequirements.map(\n (requirement) =>\n `- ${requirement.kind} ${requirement.binding}${\n requirement.agent ? ` | agent ${requirement.agent}` : \"\"\n } | ${requirement.reason}`\n );\n}\n\nfunction formatDiagnostics(\n diagnostics: ThinkWorkerConfigDiagnostic[]\n): string[] {\n if (diagnostics.length === 0) return [\"- none\"];\n return diagnostics.map(\n (diagnostic) =>\n `- ${severityLabel(diagnostic.severity)} [${diagnostic.code}] ${diagnostic.message}`\n );\n}\n\nfunction severityLabel(severity: ThinkConfigSeverity): string {\n return severity.toUpperCase();\n}\n","import { spawn } from \"node:child_process\";\nimport { access, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n applyUserBindingNames,\n readProjectFiles,\n readWranglerConfig,\n resolveThinkManifest\n} from \"../framework/project\";\nimport {\n generateThinkTypes,\n isThinkGeneratedFile,\n type ThinkGeneratedFile\n} from \"../framework/types-codegen\";\n\nexport interface TypesCommandOptions {\n root?: string;\n typesFile?: string;\n wranglerEnvFile?: string;\n routePrefix?: string;\n all?: boolean;\n dryRun?: boolean;\n check?: boolean;\n wranglerArgs?: string[];\n}\n\nexport async function typesCommand(\n options: TypesCommandOptions\n): Promise<void> {\n const root = path.resolve(options.root ?? process.cwd());\n const typesFile = normalizePath(options.typesFile ?? \"think.d.ts\");\n const wranglerEnvFile = normalizePath(options.wranglerEnvFile ?? \"env.d.ts\");\n\n const files = await readProjectFiles(root, \"agents\");\n const manifest = await resolveThinkManifest(\n {\n files,\n routePrefix: options.routePrefix\n },\n root\n );\n const wranglerConfig = await readWranglerConfig(root);\n if (wranglerConfig.config) {\n applyUserBindingNames(manifest, wranglerConfig.config);\n }\n\n if (options.all && !options.dryRun && !options.check) {\n await runWranglerTypes(root, wranglerEnvFile, options.wranglerArgs ?? []);\n }\n\n const generated = generateThinkTypes(manifest, {\n files,\n typesFile\n });\n\n if (options.dryRun) {\n console.log(\n [\n \"Think types would update:\",\n ...generated.map((file) => `- ${file.path}`)\n ].join(\"\\n\")\n );\n return;\n }\n\n if (options.check) {\n const stale = await findStaleFiles(root, generated);\n if (stale.length > 0) {\n throw new Error(\n [\n \"Think generated types are out of date.\",\n \"Run `think types` to update:\",\n ...stale.map((file) => `- ${file}`)\n ].join(\"\\n\")\n );\n }\n console.log(\"Think generated types are up to date.\");\n return;\n }\n\n for (const file of generated) {\n await writeGeneratedFile(root, file);\n }\n\n console.log(\n [\n \"Generated Think types:\",\n ...generated.map((file) => `- ${file.path}`)\n ].join(\"\\n\")\n );\n}\n\nasync function findStaleFiles(\n root: string,\n files: ThinkGeneratedFile[]\n): Promise<string[]> {\n const stale: string[] = [];\n for (const file of files) {\n const expected = await expectedFileContent(root, file);\n const current = await readTextIfExists(path.join(root, file.path));\n if (current !== expected) stale.push(file.path);\n }\n return stale;\n}\n\nasync function writeGeneratedFile(\n root: string,\n file: ThinkGeneratedFile\n): Promise<void> {\n const absolute = path.join(root, file.path);\n const expected = await expectedFileContent(root, file);\n await mkdir(path.dirname(absolute), { recursive: true });\n await writeFile(absolute, expected, \"utf8\");\n}\n\nasync function expectedFileContent(\n root: string,\n file: ThinkGeneratedFile\n): Promise<string> {\n const current = await readTextIfExists(path.join(root, file.path));\n if (current && !isThinkGeneratedFile(current)) {\n throw new Error(\n `${file.path} already exists and is not Think-generated; pass a different output path or replace it with a Think-generated file.`\n );\n }\n return file.content;\n}\n\nasync function readTextIfExists(file: string): Promise<string | null> {\n try {\n return await readFile(file, \"utf8\");\n } catch (error) {\n if (isMissingFileError(error)) return null;\n throw error;\n }\n}\n\nasync function runWranglerTypes(\n root: string,\n envFile: string,\n passthroughArgs: string[]\n): Promise<void> {\n const command = await resolveWranglerCommand(root);\n const args = [\n \"types\",\n envFile,\n ...defaultWranglerTypeArgs(passthroughArgs),\n ...passthroughArgs\n ];\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: root,\n stdio: \"inherit\"\n });\n child.on(\"error\", (error) => {\n reject(\n new Error(\n `Could not run Wrangler to generate platform types. Install wrangler in this project, or run \\`think types\\` without --all to generate only Think declarations.\\n\\n${error.message}`\n )\n );\n });\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(\n `Wrangler type generation failed with exit code ${code ?? \"unknown\"}. Fix the Wrangler error above, or run \\`think types\\` without --all if you intentionally want only Think declarations.`\n )\n );\n });\n });\n}\n\nfunction defaultWranglerTypeArgs(args: string[]): string[] {\n return args.some(\n (arg) => arg === \"--include-runtime\" || arg.startsWith(\"--include-runtime=\")\n )\n ? []\n : [\"--include-runtime\", \"false\"];\n}\n\nasync function resolveWranglerCommand(root: string): Promise<string> {\n const executable = process.platform === \"win32\" ? \"wrangler.cmd\" : \"wrangler\";\n const local = path.join(root, \"node_modules\", \".bin\", executable);\n try {\n await access(local);\n return local;\n } catch {\n return executable;\n }\n}\n\nfunction normalizePath(file: string): string {\n return file.replace(/\\\\/g, \"/\").replace(/^\\.?\\//, \"\");\n}\n\nfunction isMissingFileError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === \"ENOENT\"\n );\n}\n","import yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { initCommand } from \"./init\";\nimport { inspectCommand } from \"./inspect\";\nimport { typesCommand } from \"./types\";\n\nexport function createCli(argv = process.argv) {\n return yargs(hideBin(argv))\n .parserConfiguration({ \"populate--\": true })\n .scriptName(\"think\")\n .usage(\"$0 <command> [options]\")\n .command(\n \"init [directory]\",\n \"Create a new Think app from a starter template\",\n (cmd) =>\n cmd\n .positional(\"directory\", {\n type: \"string\",\n describe:\n \"Target directory to initialize. Omit to choose interactively.\"\n })\n .option(\"root\", {\n type: \"string\",\n describe: \"Base directory for initialization\",\n default: process.cwd()\n })\n .option(\"name\", {\n type: \"string\",\n describe: \"Package and Worker name for the generated app\"\n })\n .option(\"template\", {\n type: \"string\",\n describe: \"Starter template to scaffold (default: basic)\"\n })\n .option(\"ref\", {\n type: \"string\",\n describe: \"Git ref to fetch remote templates from\"\n })\n .option(\"yes\", {\n alias: \"y\",\n type: \"boolean\",\n describe: \"Use defaults and skip prompts\",\n default: false\n })\n .option(\"install\", {\n type: \"boolean\",\n describe: \"Run npm install after writing files\",\n default: true\n })\n .option(\"dry-run\", {\n type: \"boolean\",\n describe: \"Print files that would be written without writing them\",\n default: false\n }),\n async (args) => {\n await initCommand({\n root: args.root,\n directory: args.directory,\n name: args.name,\n template: args.template,\n ref: args.ref,\n yes: args.yes,\n install: args.install,\n dryRun: args.dryRun\n });\n }\n )\n .command(\n \"inspect\",\n \"Inspect the Think app manifest, routing, bindings, and diagnostics\",\n (cmd) =>\n cmd\n .option(\"root\", {\n type: \"string\",\n describe: \"Project root to inspect\",\n default: process.cwd()\n })\n .option(\"json\", {\n type: \"boolean\",\n describe: \"Print machine-readable JSON output\",\n default: false\n })\n .option(\"route-prefix\", {\n type: \"string\",\n describe: \"Override the Think route prefix\"\n })\n .option(\"allow-non-virtual-main\", {\n type: \"boolean\",\n describe:\n \"Do not report non-virtual Wrangler main as an error during inspection\",\n default: false\n }),\n async (args) => {\n await inspectCommand({\n root: args.root,\n json: args.json,\n routePrefix: args.routePrefix,\n allowNonVirtualMain: args.allowNonVirtualMain\n });\n }\n )\n .command(\n \"types\",\n \"Generate Think TypeScript declarations\",\n (cmd) =>\n cmd\n .option(\"root\", {\n type: \"string\",\n describe: \"Project root to generate types for\",\n default: process.cwd()\n })\n .option(\"types-file\", {\n type: \"string\",\n describe: \"Think declaration file to generate\",\n default: \"think.d.ts\"\n })\n .option(\"all\", {\n type: \"boolean\",\n describe: \"Also run Wrangler type generation before Think typegen\",\n default: false\n })\n .option(\"wrangler-env-file\", {\n type: \"string\",\n describe: \"Wrangler env declaration file to generate with --all\",\n default: \"env.d.ts\"\n })\n .option(\"route-prefix\", {\n type: \"string\",\n describe: \"Override the Think route prefix\"\n })\n .option(\"dry-run\", {\n type: \"boolean\",\n describe: \"Print files that would be written without writing them\",\n default: false\n })\n .option(\"check\", {\n type: \"boolean\",\n describe: \"Check generated Think types without modifying files\",\n default: false\n }),\n async (args) => {\n await typesCommand({\n root: args.root,\n typesFile: args.typesFile,\n wranglerEnvFile: args.wranglerEnvFile,\n routePrefix: args.routePrefix,\n all: args.all,\n dryRun: args.dryRun,\n check: args.check,\n wranglerArgs: Array.isArray(args[\"--\"]) ? args[\"--\"].map(String) : []\n });\n }\n )\n .demandCommand(1, \"Please provide a command\")\n .strict()\n .help();\n}\n","#!/usr/bin/env node\n\nimport { createCli } from \"./create\";\n\nconsole.warn(\n \"The `think` CLI is part of the experimental @cloudflare/think framework \" +\n \"layer and may change or be removed in any release.\"\n);\n\nvoid createCli().parse();\n"],"mappings":";;;;;;;;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U;EACV,SAAS;CACX,CAAC,GACL,OAAO,SAAS;EACd,MAAM,aAAa;GACjB,MAAM,KAAK;GACX,WAAW,KAAK;GAChB,iBAAiB,KAAK;GACtB,aAAa,KAAK;GAClB,KAAK,KAAK;GACV,QAAQ,KAAK;GACb,OAAO,KAAK;GACZ,cAAc,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,IAAI,MAAM,IAAI,CAAC;EACtE,CAAC;CACH,CACF,CAAC,CACA,cAAc,GAAG,0BAA0B,CAAC,CAC5C,OAAO,CAAC,CACR,KAAK;AACV;;;ACxJA,QAAQ,KACN,4HAEF;AAEK,UAAU,CAAC,CAAC,MAAM"}
1
+ {"version":3,"file":"index.js","names":["initCommand","scaffoldFromTemplate","readTextIfExists","isMissingFileError","initCommand"],"sources":["../../src/cli/init.ts","../../src/cli/inspect.ts","../../src/cli/types.ts","../../src/cli/create.ts","../../src/cli/index.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { access, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n initCommand as scaffoldFromTemplate,\n looksLikeThinkApp,\n type InitCommandOptions as TemplateInitOptions\n} from \"create-think\";\nimport { createThinkWorkerConfig } from \"../framework/config\";\nimport { discoverThinkApp } from \"../framework/discovery\";\nimport { generateThinkTypes } from \"../framework/types-codegen\";\n\nexport interface InitCommandOptions extends TemplateInitOptions {\n /** Think route prefix, used when augmenting an existing project. */\n routePrefix?: string;\n}\n\ninterface PlannedFile {\n path: string;\n content: string;\n merge?: \"package-json\";\n}\n\ninterface InitPlan {\n root: string;\n projectName: string;\n files: PlannedFile[];\n packageJsonPath: string;\n}\n\nconst VITE_CONFIG_FILES = [\n \"vite.config.ts\",\n \"vite.config.mts\",\n \"vite.config.js\",\n \"vite.config.mjs\"\n];\n\n/**\n * `think init` has two modes:\n *\n * - New project: when a `--template` is given, or when the command is run\n * outside an existing npm project. Delegates to `create-think`, which fetches\n * a complete starter template (no framework dependency required at runtime).\n * - Augment in place: when run inside an existing npm project with no\n * `--template`. Adds Think framework files (agent, Vite/Wrangler config,\n * generated types) and merges dependencies into the current project.\n */\nexport async function initCommand(options: InitCommandOptions): Promise<void> {\n const baseRoot = path.resolve(options.root ?? process.cwd());\n const insideExistingProject =\n !options.directory &&\n (await fileExists(path.join(baseRoot, \"package.json\")));\n const useTemplate = Boolean(options.template) || !insideExistingProject;\n\n if (useTemplate) {\n await scaffoldFromTemplate(options);\n return;\n }\n\n await augmentExistingProject(baseRoot, options);\n}\n\nasync function augmentExistingProject(\n root: string,\n options: InitCommandOptions\n): Promise<void> {\n const projectName = packageName(options.name ?? path.basename(root));\n\n if (await looksLikeThinkApp(root)) {\n console.log(\n [\n \"This already looks like a Think app.\",\n \"Try `think inspect` to review the manifest or `think types` to refresh generated declarations.\"\n ].join(\"\\n\")\n );\n return;\n }\n\n const migrationReason = await unsafeMigrationReason(root);\n if (migrationReason) {\n throw new Error(\n [\n \"This directory already has Vite or Wrangler configuration, so `think init` will not migrate it automatically yet.\",\n migrationReason,\n \"Start a new Think app with `npm create think`, or add `@cloudflare/think/vite` and Think framework files manually.\"\n ].join(\"\\n\")\n );\n }\n\n const plan = await createInitPlan({\n root,\n projectName,\n routePrefix: options.routePrefix\n });\n\n // Anything the user already owns (e.g. an existing tsconfig.json) is kept as-is\n // rather than aborting the whole command. Vite/Wrangler config is handled by\n // the migration guard above, so the rest is safe to skip and report.\n const skipped = await existingPlanFiles(plan);\n\n if (options.dryRun) {\n printDryRun(plan, skipped, options.install ?? true);\n return;\n }\n\n await writePlannedFiles(plan, skipped);\n\n if (options.install ?? true) {\n await (options.installRunner ?? runNpmInstall)(root);\n }\n\n printSuccess(plan, skipped, options.install ?? true);\n}\n\nasync function createInitPlan(options: {\n root: string;\n projectName: string;\n routePrefix?: string;\n}): Promise<InitPlan> {\n const sourceFiles = {\n \"agents/assistant/agent.ts\": agentSource(),\n \"agents/assistant/skills/project-helper/SKILL.md\": starterSkillSource()\n };\n const manifest = discoverThinkApp({\n root: options.root,\n routePrefix: options.routePrefix,\n files: sourceFiles\n });\n const workerConfig = createThinkWorkerConfig(manifest, {\n name: options.projectName,\n routePrefix: options.routePrefix\n });\n workerConfig.ai = { binding: \"AI\" };\n workerConfig.worker_loaders = [{ binding: \"LOADER\" }];\n const typeFiles = generateThinkTypes(manifest, {\n files: sourceFiles,\n typesFile: \"think.d.ts\"\n });\n\n return {\n root: options.root,\n projectName: options.projectName,\n packageJsonPath: \"package.json\",\n files: [\n {\n path: \"package.json\",\n content: packageJsonSource(options.projectName),\n merge: \"package-json\"\n },\n {\n path: \"vite.config.ts\",\n content: viteConfig(options.routePrefix)\n },\n {\n path: \"wrangler.jsonc\",\n content: `${JSON.stringify(workerConfig, null, 2)}\\n`\n },\n {\n path: \"tsconfig.json\",\n content: tsconfig()\n },\n {\n path: \"agents/assistant/agent.ts\",\n content: sourceFiles[\"agents/assistant/agent.ts\"]\n },\n {\n path: \"agents/assistant/skills/project-helper/SKILL.md\",\n content: sourceFiles[\"agents/assistant/skills/project-helper/SKILL.md\"]\n },\n ...typeFiles\n ]\n };\n}\n\nasync function existingPlanFiles(plan: InitPlan): Promise<Set<string>> {\n const existing = new Set<string>();\n for (const file of plan.files) {\n // package.json is always merged, never overwritten, so it is never skipped.\n if (file.merge === \"package-json\") continue;\n if (await fileExists(path.join(plan.root, file.path))) {\n existing.add(file.path);\n }\n }\n return existing;\n}\n\nasync function writePlannedFiles(\n plan: InitPlan,\n skip: Set<string>\n): Promise<void> {\n await mkdir(plan.root, { recursive: true });\n for (const file of plan.files) {\n if (skip.has(file.path)) continue;\n const absolute = path.join(plan.root, file.path);\n await mkdir(path.dirname(absolute), { recursive: true });\n const content =\n file.merge === \"package-json\"\n ? await mergePackageJson(absolute, file.content)\n : file.content;\n await writeFile(absolute, content, \"utf8\");\n }\n}\n\nasync function mergePackageJson(\n absolutePath: string,\n generatedContent: string\n): Promise<string> {\n const generated = JSON.parse(generatedContent) as PackageJson;\n const existingSource = await readTextIfExists(absolutePath);\n if (!existingSource) return generatedContent;\n const existing = JSON.parse(existingSource) as PackageJson;\n return `${JSON.stringify(mergePackageJsonData(existing, generated), null, 2)}\\n`;\n}\n\nfunction mergePackageJsonData(\n existing: PackageJson,\n generated: PackageJson\n): PackageJson {\n return {\n ...generated,\n ...existing,\n // Think + Vite require ES modules, so the framework's `type` wins even if the\n // existing project was CommonJS (or omitted `type`).\n type: generated.type ?? existing.type,\n scripts: {\n ...generated.scripts,\n ...existing.scripts\n },\n dependencies: {\n ...generated.dependencies,\n ...existing.dependencies\n },\n devDependencies: {\n ...generated.devDependencies,\n ...existing.devDependencies\n }\n };\n}\n\nasync function unsafeMigrationReason(root: string): Promise<string | null> {\n for (const file of [\n ...VITE_CONFIG_FILES,\n \"wrangler.jsonc\",\n \"wrangler.json\",\n \"wrangler.toml\"\n ]) {\n if (await fileExists(path.join(root, file))) {\n return `Found existing ${file}.`;\n }\n }\n return null;\n}\n\nfunction printDryRun(\n plan: InitPlan,\n skipped: Set<string>,\n install: boolean\n): void {\n const lines = [\n \"Think init would add to the current project:\",\n ...plan.files\n .filter((file) => !skipped.has(file.path))\n .map((file) => `- ${file.path}`)\n ];\n if (skipped.size > 0) {\n lines.push(\n \"\",\n \"Would keep your existing files (left unchanged):\",\n ...[...skipped].map((file) => `- ${file}`)\n );\n }\n lines.push(\n install ? \"Would run: npm install\" : \"Would skip dependency install.\"\n );\n console.log(lines.join(\"\\n\"));\n}\n\nfunction printSuccess(\n plan: InitPlan,\n skipped: Set<string>,\n install: boolean\n): void {\n const lines = [\n `Added Think to ${plan.root}.`,\n install ? \"Installed npm dependencies.\" : \"Skipped npm install.\"\n ];\n if (skipped.size > 0) {\n lines.push(\n \"\",\n \"Kept your existing files (not overwritten):\",\n ...[...skipped].map((file) => `- ${file}`),\n \"Reconcile them with Think's expected setup if the app does not build.\"\n );\n }\n lines.push(\n \"\",\n \"Next steps:\",\n \"- Edit agents/assistant/agent.ts to customize the model, prompt, skills, and schedules\",\n \"- npm run dev\",\n \"- npm run types\",\n \"- npm run deploy\"\n );\n console.log(lines.join(\"\\n\"));\n}\n\nasync function runNpmInstall(root: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n const child = spawn(\"npm\", [\"install\"], {\n cwd: root,\n stdio: \"inherit\",\n // On Windows `npm` resolves to `npm.cmd`, which Node's spawn won't find\n // without a shell.\n shell: process.platform === \"win32\"\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(`npm install failed with exit code ${code ?? \"unknown\"}.`)\n );\n });\n });\n}\n\n// In-repo packages float to `latest`: they release in tandem from this\n// monorepo via changesets, so a fresh project always gets the newest matching\n// set.\nconst FRAMEWORK_DEPENDENCIES: Record<string, string> = {\n \"@cloudflare/think\": \"latest\",\n agents: \"latest\"\n};\n\n// Third-party packages are NOT released in tandem with us, so they are pinned\n// to the exact ranges the starter templates are tested against (see\n// `think-starters/basic/package.json`). This avoids fresh projects pulling an\n// untested major (e.g. a new `vite`/`ai`/`wrangler`). Kept in sync with the\n// starter by a test in `src/cli-tests/cli.test.ts`.\nexport const THIRD_PARTY_DEPENDENCIES: Record<string, string> = {\n ai: \"^6.0.196\",\n \"workers-ai-provider\": \"^3.1.14\"\n};\n\nexport const THIRD_PARTY_DEV_DEPENDENCIES: Record<string, string> = {\n \"@cloudflare/vite-plugin\": \"^1.39.2\",\n \"@cloudflare/workers-types\": \"^4.20260604.1\",\n typescript: \"^6.0.3\",\n vite: \"^8.0.16\",\n wrangler: \"^4.97.0\"\n};\n\nfunction packageJsonSource(projectName: string): string {\n return `${JSON.stringify(\n {\n name: projectName,\n private: true,\n type: \"module\",\n scripts: {\n dev: \"vite dev\",\n build: \"vite build\",\n deploy: \"vite build && wrangler deploy\",\n types: \"think types --all\"\n },\n dependencies: {\n ...FRAMEWORK_DEPENDENCIES,\n ...THIRD_PARTY_DEPENDENCIES\n },\n devDependencies: {\n ...THIRD_PARTY_DEV_DEPENDENCIES\n }\n },\n null,\n 2\n )}\\n`;\n}\n\nfunction viteConfig(routePrefix: string | undefined): string {\n const thinkOptions = routePrefix\n ? `({ routePrefix: ${JSON.stringify(routePrefix)} })`\n : \"()\";\n return [\n `import { cloudflare } from \"@cloudflare/vite-plugin\";`,\n `import { think } from \"@cloudflare/think/vite\";`,\n `import { defineConfig } from \"vite\";`,\n \"\",\n \"export default defineConfig({\",\n ` plugins: [think${thinkOptions}, cloudflare()]`,\n \"});\",\n \"\"\n ].join(\"\\n\");\n}\n\nfunction agentSource(): string {\n return [\n `import { Think, skills } from \"@cloudflare/think\";`,\n `import { createWorkersAI } from \"workers-ai-provider\";`,\n `import bundledSkills from \"agents:skills\";`,\n \"\",\n \"type Env = Cloudflare.Env & {\",\n \" AI: Ai;\",\n \" LOADER: WorkerLoader;\",\n \"};\",\n \"\",\n \"export class Assistant extends Think<Env> {\",\n \" override getModel() {\",\n \" return createWorkersAI({ binding: this.env.AI })(\",\n ' \"@cf/moonshotai/kimi-k2.6\",',\n \" { sessionAffinity: this.sessionAffinity }\",\n \" );\",\n \" }\",\n \"\",\n \" override getSystemPrompt() {\",\n ' return \"You are a helpful assistant. Keep answers clear, practical, and concise.\";',\n \" }\",\n \"\",\n \" override getSkills() {\",\n \" return [bundledSkills];\",\n \" }\",\n \"\",\n \" override getSkillScriptRunner() {\",\n \" return skills.runner({\",\n \" loader: this.env.LOADER,\",\n \" workspaceInstance: this.workspace\",\n \" });\",\n \" }\",\n \"}\",\n \"\"\n ].join(\"\\n\");\n}\n\nfunction starterSkillSource(): string {\n return [\n \"---\",\n \"name: project-helper\",\n \"description: Help users plan and explain small project changes. Use when the user asks for implementation guidance, debugging steps, or a concise project plan.\",\n \"---\",\n \"\",\n \"# Project Helper\",\n \"\",\n \"Use this skill to give practical, action-oriented project help.\",\n \"\",\n \"## Instructions\",\n \"\",\n \"1. Restate the user's goal in one sentence.\",\n \"2. Identify the smallest useful next step.\",\n \"3. Call out any important risk or missing context.\",\n \"4. Keep the answer concise and easy to act on.\",\n \"\"\n ].join(\"\\n\");\n}\n\nfunction tsconfig(): string {\n return `${JSON.stringify(\n {\n compilerOptions: {\n target: \"ES2021\",\n module: \"ES2022\",\n moduleResolution: \"bundler\",\n strict: true,\n verbatimModuleSyntax: true,\n types: [\"@cloudflare/workers-types\"]\n },\n include: [\"agents\", \"think.d.ts\", \"vite.config.ts\"]\n },\n null,\n 2\n )}\\n`;\n}\n\nfunction packageName(name: string): string {\n return (\n name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/^[._]+/, \"\") || \"think-agent\"\n );\n}\n\nasync function readTextIfExists(file: string): Promise<string | null> {\n try {\n return await readFile(file, \"utf8\");\n } catch (error) {\n if (isMissingFileError(error)) return null;\n throw error;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n await access(file);\n return true;\n } catch (error) {\n if (isMissingFileError(error)) return false;\n throw error;\n }\n}\n\nfunction isMissingFileError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === \"ENOENT\"\n );\n}\n\ninterface PackageJson {\n name?: string;\n private?: boolean;\n type?: string;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n [key: string]: unknown;\n}\n","import path from \"node:path\";\nimport {\n summarizeThinkManifest,\n type ThinkConfigSeverity,\n type ThinkWorkerConfigDiagnostic\n} from \"../framework/config\";\nimport type {\n ThinkFrameworkManifest,\n ThinkFrameworkRouteSurface\n} from \"../framework/manifest\";\nimport { createThinkProject } from \"../framework/project\";\n\nexport interface InspectCommandOptions {\n root?: string;\n json?: boolean;\n routePrefix?: string;\n allowNonVirtualMain?: boolean;\n}\n\nexport async function inspectCommand(\n options: InspectCommandOptions\n): Promise<void> {\n const root = path.resolve(options.root ?? process.cwd());\n const project = await createThinkProject(\n {\n routePrefix: options.routePrefix,\n allowNonVirtualMain: options.allowNonVirtualMain\n },\n root\n );\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n root,\n manifest: project.manifest,\n workerConfig: project.workerConfig,\n diagnostics: project.diagnostics,\n wranglerConfig: {\n path: project.wranglerConfig.path,\n parsed: Boolean(project.wranglerConfig.config),\n error: project.wranglerConfig.error\n }\n },\n null,\n 2\n )\n );\n return;\n }\n\n const lines = [\n \"Think inspect\",\n `Root: ${root}`,\n \"\",\n ...summarizeThinkManifest(project.manifest),\n \"\",\n `Route prefix: ${project.manifest.routePrefix}`,\n `App entry: ${project.manifest.appEntrypoint ?? \"none\"}`,\n `Wrangler config: ${project.wranglerConfig.path ?? \"not found\"}`,\n \"\",\n \"Features:\",\n ...formatFeatures(project.manifest),\n \"\",\n \"Route surfaces:\",\n ...formatRouteSurfaces(project.manifest.routeSurfaces),\n \"\",\n \"Schedules:\",\n ...formatNamedFacts(project.manifest.schedules),\n \"\",\n \"Messengers:\",\n ...formatNamedFacts(project.manifest.messengers),\n \"\",\n \"Tools:\",\n ...formatNamedFacts(project.manifest.tools),\n \"\",\n \"Platform requirements:\",\n ...formatPlatformRequirements(project.manifest),\n \"\",\n \"Expected top-level Durable Objects:\",\n ...formatBindings(project.manifest.bindings),\n \"\",\n \"Diagnostics:\",\n ...formatDiagnostics(project.diagnostics)\n ];\n\n if (project.wranglerConfig.error) {\n lines.push(\"\", `[warning] ${project.wranglerConfig.error}`);\n }\n\n console.log(lines.join(\"\\n\"));\n}\n\nfunction formatBindings(\n bindings: Array<{ name: string; className: string }>\n): string[] {\n if (bindings.length === 0) return [\"- none\"];\n return bindings.map(\n (binding) => `- ${binding.name} -> class ${binding.className}`\n );\n}\n\nfunction formatFeatures(manifest: ThinkFrameworkManifest): string[] {\n if (manifest.features.length === 0) return [\"- none\"];\n return manifest.agents.flatMap((agent) => {\n if (agent.features.length === 0 && agent.env.length === 0) return [];\n return [\n `- ${agent.id}: ${\n [\n agent.features.length\n ? `features ${agent.features.join(\", \")}`\n : null,\n agent.env.length ? `env ${agent.env.join(\", \")}` : null\n ]\n .filter(Boolean)\n .join(\" | \") || \"none\"\n }`\n ];\n });\n}\n\nfunction formatRouteSurfaces(surfaces: ThinkFrameworkRouteSurface[]): string[] {\n if (surfaces.length === 0) return [\"- none\"];\n return surfaces.map(\n (surface) =>\n `- ${surface.kind} ${surface.id}: ${surface.pattern}${\n surface.requiredRunWorkerFirst ? \" | requires run_worker_first\" : \"\"\n }`\n );\n}\n\nfunction formatNamedFacts(\n facts: Array<{ id: string; agent?: string; sourcePath?: string }>\n): string[] {\n if (facts.length === 0) return [\"- none\"];\n return facts.map(\n (fact) =>\n `- ${fact.id}${fact.agent ? ` | agent ${fact.agent}` : \"\"}${\n fact.sourcePath ? ` | ${fact.sourcePath}` : \"\"\n }`\n );\n}\n\nfunction formatPlatformRequirements(\n manifest: ThinkFrameworkManifest\n): string[] {\n if (manifest.platformRequirements.length === 0) return [\"- none\"];\n return manifest.platformRequirements.map(\n (requirement) =>\n `- ${requirement.kind} ${requirement.binding}${\n requirement.agent ? ` | agent ${requirement.agent}` : \"\"\n } | ${requirement.reason}`\n );\n}\n\nfunction formatDiagnostics(\n diagnostics: ThinkWorkerConfigDiagnostic[]\n): string[] {\n if (diagnostics.length === 0) return [\"- none\"];\n return diagnostics.map(\n (diagnostic) =>\n `- ${severityLabel(diagnostic.severity)} [${diagnostic.code}] ${diagnostic.message}`\n );\n}\n\nfunction severityLabel(severity: ThinkConfigSeverity): string {\n return severity.toUpperCase();\n}\n","import { spawn } from \"node:child_process\";\nimport { access, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n applyUserBindingNames,\n readProjectFiles,\n readWranglerConfig,\n resolveThinkManifest\n} from \"../framework/project\";\nimport {\n generateThinkTypes,\n isThinkGeneratedFile,\n type ThinkGeneratedFile\n} from \"../framework/types-codegen\";\n\nexport interface TypesCommandOptions {\n root?: string;\n typesFile?: string;\n wranglerEnvFile?: string;\n routePrefix?: string;\n all?: boolean;\n dryRun?: boolean;\n check?: boolean;\n wranglerArgs?: string[];\n}\n\nexport async function typesCommand(\n options: TypesCommandOptions\n): Promise<void> {\n const root = path.resolve(options.root ?? process.cwd());\n const typesFile = normalizePath(options.typesFile ?? \"think.d.ts\");\n const wranglerEnvFile = normalizePath(options.wranglerEnvFile ?? \"env.d.ts\");\n\n const files = await readProjectFiles(root, \"agents\");\n const manifest = await resolveThinkManifest(\n {\n files,\n routePrefix: options.routePrefix\n },\n root\n );\n const wranglerConfig = await readWranglerConfig(root);\n if (wranglerConfig.config) {\n applyUserBindingNames(manifest, wranglerConfig.config);\n }\n\n if (options.all && !options.dryRun && !options.check) {\n await runWranglerTypes(root, wranglerEnvFile, options.wranglerArgs ?? []);\n }\n\n const generated = generateThinkTypes(manifest, {\n files,\n typesFile\n });\n\n if (options.dryRun) {\n console.log(\n [\n \"Think types would update:\",\n ...generated.map((file) => `- ${file.path}`)\n ].join(\"\\n\")\n );\n return;\n }\n\n if (options.check) {\n const stale = await findStaleFiles(root, generated);\n if (stale.length > 0) {\n throw new Error(\n [\n \"Think generated types are out of date.\",\n \"Run `think types` to update:\",\n ...stale.map((file) => `- ${file}`)\n ].join(\"\\n\")\n );\n }\n console.log(\"Think generated types are up to date.\");\n return;\n }\n\n for (const file of generated) {\n await writeGeneratedFile(root, file);\n }\n\n console.log(\n [\n \"Generated Think types:\",\n ...generated.map((file) => `- ${file.path}`)\n ].join(\"\\n\")\n );\n}\n\nasync function findStaleFiles(\n root: string,\n files: ThinkGeneratedFile[]\n): Promise<string[]> {\n const stale: string[] = [];\n for (const file of files) {\n const expected = await expectedFileContent(root, file);\n const current = await readTextIfExists(path.join(root, file.path));\n if (current !== expected) stale.push(file.path);\n }\n return stale;\n}\n\nasync function writeGeneratedFile(\n root: string,\n file: ThinkGeneratedFile\n): Promise<void> {\n const absolute = path.join(root, file.path);\n const expected = await expectedFileContent(root, file);\n await mkdir(path.dirname(absolute), { recursive: true });\n await writeFile(absolute, expected, \"utf8\");\n}\n\nasync function expectedFileContent(\n root: string,\n file: ThinkGeneratedFile\n): Promise<string> {\n const current = await readTextIfExists(path.join(root, file.path));\n if (current && !isThinkGeneratedFile(current)) {\n throw new Error(\n `${file.path} already exists and is not Think-generated; pass a different output path or replace it with a Think-generated file.`\n );\n }\n return file.content;\n}\n\nasync function readTextIfExists(file: string): Promise<string | null> {\n try {\n return await readFile(file, \"utf8\");\n } catch (error) {\n if (isMissingFileError(error)) return null;\n throw error;\n }\n}\n\nasync function runWranglerTypes(\n root: string,\n envFile: string,\n passthroughArgs: string[]\n): Promise<void> {\n const command = await resolveWranglerCommand(root);\n const args = [\n \"types\",\n envFile,\n ...defaultWranglerTypeArgs(passthroughArgs),\n ...passthroughArgs\n ];\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: root,\n stdio: \"inherit\"\n });\n child.on(\"error\", (error) => {\n reject(\n new Error(\n `Could not run Wrangler to generate platform types. Install wrangler in this project, or run \\`think types\\` without --all to generate only Think declarations.\\n\\n${error.message}`\n )\n );\n });\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(\n `Wrangler type generation failed with exit code ${code ?? \"unknown\"}. Fix the Wrangler error above, or run \\`think types\\` without --all if you intentionally want only Think declarations.`\n )\n );\n });\n });\n}\n\nfunction defaultWranglerTypeArgs(args: string[]): string[] {\n return args.some(\n (arg) => arg === \"--include-runtime\" || arg.startsWith(\"--include-runtime=\")\n )\n ? []\n : [\"--include-runtime\", \"false\"];\n}\n\nasync function resolveWranglerCommand(root: string): Promise<string> {\n const executable = process.platform === \"win32\" ? \"wrangler.cmd\" : \"wrangler\";\n const local = path.join(root, \"node_modules\", \".bin\", executable);\n try {\n await access(local);\n return local;\n } catch {\n return executable;\n }\n}\n\nfunction normalizePath(file: string): string {\n return file.replace(/\\\\/g, \"/\").replace(/^\\.?\\//, \"\");\n}\n\nfunction isMissingFileError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === \"ENOENT\"\n );\n}\n","import yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { initCommand } from \"./init\";\nimport { inspectCommand } from \"./inspect\";\nimport { typesCommand } from \"./types\";\n\nexport function createCli(argv = process.argv) {\n return yargs(hideBin(argv))\n .parserConfiguration({ \"populate--\": true })\n .scriptName(\"think\")\n .usage(\"$0 <command> [options]\")\n .command(\n \"init [directory]\",\n \"Scaffold a new Think app from a starter template, or add Think to the current project\",\n (cmd) =>\n cmd\n .positional(\"directory\", {\n type: \"string\",\n describe:\n \"Target directory to initialize. Omit to choose interactively.\"\n })\n .option(\"root\", {\n type: \"string\",\n describe: \"Base directory for initialization\",\n default: process.cwd()\n })\n .option(\"name\", {\n type: \"string\",\n describe: \"Package and Worker name for the generated app\"\n })\n .option(\"template\", {\n type: \"string\",\n describe: \"Starter template to scaffold (default: basic)\"\n })\n .option(\"ref\", {\n type: \"string\",\n describe: \"Git ref to fetch remote templates from\"\n })\n .option(\"route-prefix\", {\n type: \"string\",\n describe:\n \"Think route prefix when adding Think to an existing project\"\n })\n .option(\"yes\", {\n alias: \"y\",\n type: \"boolean\",\n describe: \"Use defaults and skip prompts\",\n default: false\n })\n .option(\"install\", {\n type: \"boolean\",\n describe: \"Run npm install after writing files\",\n default: true\n })\n .option(\"dry-run\", {\n type: \"boolean\",\n describe: \"Print files that would be written without writing them\",\n default: false\n }),\n async (args) => {\n await initCommand({\n root: args.root,\n directory: args.directory,\n name: args.name,\n template: args.template,\n ref: args.ref,\n routePrefix: args.routePrefix,\n yes: args.yes,\n install: args.install,\n dryRun: args.dryRun\n });\n }\n )\n .command(\n \"inspect\",\n \"Inspect the Think app manifest, routing, bindings, and diagnostics\",\n (cmd) =>\n cmd\n .option(\"root\", {\n type: \"string\",\n describe: \"Project root to inspect\",\n default: process.cwd()\n })\n .option(\"json\", {\n type: \"boolean\",\n describe: \"Print machine-readable JSON output\",\n default: false\n })\n .option(\"route-prefix\", {\n type: \"string\",\n describe: \"Override the Think route prefix\"\n })\n .option(\"allow-non-virtual-main\", {\n type: \"boolean\",\n describe:\n \"Do not report non-virtual Wrangler main as an error during inspection\",\n default: false\n }),\n async (args) => {\n await inspectCommand({\n root: args.root,\n json: args.json,\n routePrefix: args.routePrefix,\n allowNonVirtualMain: args.allowNonVirtualMain\n });\n }\n )\n .command(\n \"types\",\n \"Generate Think TypeScript declarations\",\n (cmd) =>\n cmd\n .option(\"root\", {\n type: \"string\",\n describe: \"Project root to generate types for\",\n default: process.cwd()\n })\n .option(\"types-file\", {\n type: \"string\",\n describe: \"Think declaration file to generate\",\n default: \"think.d.ts\"\n })\n .option(\"all\", {\n type: \"boolean\",\n describe: \"Also run Wrangler type generation before Think typegen\",\n default: false\n })\n .option(\"wrangler-env-file\", {\n type: \"string\",\n describe: \"Wrangler env declaration file to generate with --all\",\n default: \"env.d.ts\"\n })\n .option(\"route-prefix\", {\n type: \"string\",\n describe: \"Override the Think route prefix\"\n })\n .option(\"dry-run\", {\n type: \"boolean\",\n describe: \"Print files that would be written without writing them\",\n default: false\n })\n .option(\"check\", {\n type: \"boolean\",\n describe: \"Check generated Think types without modifying files\",\n default: false\n }),\n async (args) => {\n await typesCommand({\n root: args.root,\n typesFile: args.typesFile,\n wranglerEnvFile: args.wranglerEnvFile,\n routePrefix: args.routePrefix,\n all: args.all,\n dryRun: args.dryRun,\n check: args.check,\n wranglerArgs: Array.isArray(args[\"--\"]) ? args[\"--\"].map(String) : []\n });\n }\n )\n .demandCommand(1, \"Please provide a command\")\n .strict()\n .help();\n}\n","#!/usr/bin/env node\n\nimport { createCli } from \"./create\";\n\nconsole.warn(\n \"The `think` CLI is part of the experimental @cloudflare/think framework \" +\n \"layer and may change or be removed in any release.\"\n);\n\nvoid createCli().parse();\n"],"mappings":";;;;;;;;;;AA8BA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;AACF;;;;;;;;;;;AAYA,eAAsBA,cAAY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KAAK;GAChB,iBAAiB,KAAK;GACtB,aAAa,KAAK;GAClB,KAAK,KAAK;GACV,QAAQ,KAAK;GACb,OAAO,KAAK;GACZ,cAAc,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,IAAI,MAAM,IAAI,CAAC;EACtE,CAAC;CACH,CACF,CAAC,CACA,cAAc,GAAG,0BAA0B,CAAC,CAC5C,OAAO,CAAC,CACR,KAAK;AACV;;;AC9JA,QAAQ,KACN,4HAEF;AAEK,UAAU,CAAC,CAAC,MAAM"}
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "tools"
10
10
  ],
11
11
  "type": "module",
12
- "version": "0.8.6",
12
+ "version": "0.8.7",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/think",
@@ -28,6 +28,7 @@
28
28
  "@cloudflare/shell": "^0.3.9",
29
29
  "aywson": "^0.0.16",
30
30
  "chat": "^4.30.0",
31
+ "create-think": "^0.0.3",
31
32
  "just-bash": "^3.0.1",
32
33
  "smol-toml": "^1.6.1",
33
34
  "yargs": "^18.0.0"
@@ -107,10 +108,6 @@
107
108
  "./vite": {
108
109
  "types": "./dist/vite.d.ts",
109
110
  "import": "./dist/vite.js"
110
- },
111
- "./cli": {
112
- "types": "./dist/cli.d.ts",
113
- "import": "./dist/cli.js"
114
111
  }
115
112
  },
116
113
  "files": [
package/dist/cli.d.ts DELETED
@@ -1,77 +0,0 @@
1
- //#region src/cli/templates.d.ts
2
- /**
3
- * The starter templates shipped in the repo's top-level `think-starters/`
4
- * directory. The first entry is the default used when `--template` is omitted.
5
- */
6
- declare const THINK_TEMPLATES: readonly [
7
- {
8
- readonly name: "basic";
9
- readonly description: "Minimal Think chat agent with a small React chat UI.";
10
- },
11
- {
12
- readonly name: "personal-assistant";
13
- readonly description: "Assistant with persistent memory (configureSession) and scheduled tasks.";
14
- },
15
- {
16
- readonly name: "coding-agent";
17
- readonly description: "Coding agent with workspace file tools and a coding skill.";
18
- },
19
- {
20
- readonly name: "customer-support";
21
- readonly description: "Support agent with custom tools and an escalation skill.";
22
- }
23
- ];
24
- type ThinkTemplateName = (typeof THINK_TEMPLATES)[number]["name"];
25
- declare const DEFAULT_TEMPLATE: ThinkTemplateName;
26
- interface TemplateFetchRequest {
27
- template: string;
28
- ref: string;
29
- dest: string;
30
- }
31
- type TemplateFetcher = (request: TemplateFetchRequest) => Promise<void>;
32
- declare function isKnownTemplate(name: string): name is ThinkTemplateName;
33
- declare function resolveTemplateName(name: string | undefined): string;
34
- declare function formatTemplateList(): string;
35
- //#endregion
36
- //#region src/cli/init.d.ts
37
- interface InitCommandOptions {
38
- root?: string;
39
- directory?: string;
40
- name?: string;
41
- /** Starter template to scaffold. Defaults to `basic`. */
42
- template?: string;
43
- /** Git ref passed to the remote template fetcher. Defaults to `main`. */
44
- ref?: string;
45
- yes?: boolean;
46
- install?: boolean;
47
- dryRun?: boolean;
48
- /** Local templates directory override (used in-repo and by tests). */
49
- templatesDir?: string;
50
- /**
51
- * Fetches a template from a remote source (e.g. degit). Injected by
52
- * `create-think`. When omitted, only local templates can be scaffolded.
53
- */
54
- fetchTemplate?: TemplateFetcher;
55
- promptTargetDirectory?: (defaultDirectory: string) => Promise<string>;
56
- installRunner?: (root: string) => Promise<void>;
57
- }
58
- declare function initCommand(options: InitCommandOptions): Promise<void>;
59
- //#endregion
60
- //#region src/cli.d.ts
61
- /** The GitHub repo path that hosts the starter templates for remote fetches. */
62
- declare const THINK_TEMPLATES_REPO = "cloudflare/agents/think-starters";
63
- //#endregion
64
- export {
65
- DEFAULT_TEMPLATE,
66
- type InitCommandOptions,
67
- THINK_TEMPLATES,
68
- THINK_TEMPLATES_REPO,
69
- type TemplateFetchRequest,
70
- type TemplateFetcher,
71
- type ThinkTemplateName,
72
- formatTemplateList,
73
- initCommand,
74
- isKnownTemplate,
75
- resolveTemplateName
76
- };
77
- //# sourceMappingURL=cli.d.ts.map
package/dist/cli.js DELETED
@@ -1,8 +0,0 @@
1
- import { a as isKnownTemplate, i as formatTemplateList, n as DEFAULT_TEMPLATE, o as resolveTemplateName, r as THINK_TEMPLATES, t as initCommand } from "./init-C9q1GbK-.js";
2
- //#region src/cli.ts
3
- /** The GitHub repo path that hosts the starter templates for remote fetches. */
4
- const THINK_TEMPLATES_REPO = "cloudflare/agents/think-starters";
5
- //#endregion
6
- export { DEFAULT_TEMPLATE, THINK_TEMPLATES, THINK_TEMPLATES_REPO, formatTemplateList, initCommand, isKnownTemplate, resolveTemplateName };
7
-
8
- //# sourceMappingURL=cli.js.map
package/dist/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["// Programmatic entry point for the Think CLI.\n//\n// This is consumed by the `create-think` package so it can reuse the exact\n// scaffolding logic behind `think init`, while injecting its own remote\n// template fetcher (degit). It intentionally has no side effects on import\n// (unlike `./cli/index.ts`, which is the executable bin).\n\nexport { initCommand, type InitCommandOptions } from \"./cli/init\";\nexport {\n DEFAULT_TEMPLATE,\n formatTemplateList,\n isKnownTemplate,\n resolveTemplateName,\n THINK_TEMPLATES,\n type TemplateFetcher,\n type TemplateFetchRequest,\n type ThinkTemplateName\n} from \"./cli/templates\";\n\n/** The GitHub repo path that hosts the starter templates for remote fetches. */\nexport const THINK_TEMPLATES_REPO = \"cloudflare/agents/think-starters\";\n"],"mappings":";;;AAoBA,MAAa,uBAAuB"}
@@ -1,361 +0,0 @@
1
- import { access, cp, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import { spawn } from "node:child_process";
4
- import { createInterface } from "node:readline/promises";
5
- import { stdin, stdout } from "node:process";
6
- import { fileURLToPath } from "node:url";
7
- //#region src/cli/templates.ts
8
- /**
9
- * The starter templates shipped in the repo's top-level `think-starters/`
10
- * directory. The first entry is the default used when `--template` is omitted.
11
- */
12
- const THINK_TEMPLATES = [
13
- {
14
- name: "basic",
15
- description: "Minimal Think chat agent with a small React chat UI."
16
- },
17
- {
18
- name: "personal-assistant",
19
- description: "Assistant with persistent memory (configureSession) and scheduled tasks."
20
- },
21
- {
22
- name: "coding-agent",
23
- description: "Coding agent with workspace file tools and a coding skill."
24
- },
25
- {
26
- name: "customer-support",
27
- description: "Support agent with custom tools and an escalation skill."
28
- }
29
- ];
30
- const DEFAULT_TEMPLATE = THINK_TEMPLATES[0].name;
31
- /** Files/directories that are never copied from a local workspace template. */
32
- const LOCAL_COPY_IGNORE = new Set([
33
- "node_modules",
34
- "dist",
35
- ".wrangler",
36
- ".turbo",
37
- ".dev.vars",
38
- ".env"
39
- ]);
40
- function isKnownTemplate(name) {
41
- return THINK_TEMPLATES.some((template) => template.name === name);
42
- }
43
- function resolveTemplateName(name) {
44
- const resolved = (name ?? DEFAULT_TEMPLATE).trim();
45
- if (!isKnownTemplate(resolved)) throw new Error([
46
- `Unknown template: ${resolved}`,
47
- "Available templates:",
48
- ...THINK_TEMPLATES.map((t) => `- ${t.name} — ${t.description}`)
49
- ].join("\n"));
50
- return resolved;
51
- }
52
- function formatTemplateList() {
53
- return THINK_TEMPLATES.map((t) => `- ${t.name} — ${t.description}`).join("\n");
54
- }
55
- /**
56
- * Locate the in-repo `think-starters/` directory by walking up from this
57
- * module. Only matches inside the monorepo (identified by a sibling
58
- * `pnpm-workspace.yaml`), so a published package never accidentally copies
59
- * from an unrelated `think-starters` folder on the user's machine.
60
- */
61
- async function findLocalTemplatesRoot(template) {
62
- let dir = path.dirname(fileURLToPath(import.meta.url));
63
- for (let depth = 0; depth < 8; depth++) {
64
- const candidate = path.join(dir, "think-starters");
65
- if (await isDirectory(path.join(dir, ".git")) || await fileExists$1(path.join(dir, "pnpm-workspace.yaml"))) {
66
- if (await isDirectory(path.join(candidate, template))) return candidate;
67
- }
68
- const parent = path.dirname(dir);
69
- if (parent === dir) break;
70
- dir = parent;
71
- }
72
- return null;
73
- }
74
- /**
75
- * Copy a local template directory into the destination, skipping build
76
- * artifacts and local secrets.
77
- */
78
- async function copyLocalTemplate(templateDir, dest) {
79
- await cp(templateDir, dest, {
80
- recursive: true,
81
- filter: (source) => {
82
- const base = path.basename(source);
83
- return !LOCAL_COPY_IGNORE.has(base);
84
- }
85
- });
86
- }
87
- /**
88
- * Wrangler config filenames, in the order `wrangler` itself resolves them.
89
- */
90
- const WRANGLER_CONFIG_FILES = [
91
- "wrangler.jsonc",
92
- "wrangler.json",
93
- "wrangler.toml"
94
- ];
95
- /**
96
- * After a template is fetched, set the project name (in both `package.json` and
97
- * the Wrangler config's `name`) and rewrite any `workspace:*` dependencies
98
- * (used so templates build inside the monorepo) to published version ranges so
99
- * the project installs standalone.
100
- */
101
- async function finalizeTemplate(dest, projectName) {
102
- await finalizePackageJson(dest, projectName);
103
- await finalizeWranglerName(dest, projectName);
104
- }
105
- async function finalizePackageJson(dest, projectName) {
106
- const packageJsonPath = path.join(dest, "package.json");
107
- const source = await readFile(packageJsonPath, "utf8").catch(() => null);
108
- if (!source) return;
109
- const pkg = JSON.parse(source);
110
- pkg.name = projectName;
111
- for (const field of [
112
- "dependencies",
113
- "devDependencies",
114
- "peerDependencies"
115
- ]) {
116
- const deps = pkg[field];
117
- if (deps && typeof deps === "object") rewriteWorkspaceVersions(deps);
118
- }
119
- await writeFile(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`, "utf8");
120
- }
121
- /**
122
- * Update the Worker `name` in the template's Wrangler config so each scaffolded
123
- * app deploys under its own name instead of the shared template name. Done with
124
- * a targeted replacement of the first `name` field so JSONC comments and
125
- * formatting are preserved.
126
- */
127
- async function finalizeWranglerName(dest, projectName) {
128
- for (const file of WRANGLER_CONFIG_FILES) {
129
- const configPath = path.join(dest, file);
130
- const source = await readFile(configPath, "utf8").catch(() => null);
131
- if (source === null) continue;
132
- const updated = file.endsWith(".toml") ? source.replace(/^(\s*name\s*=\s*")[^"]*(")/m, `$1${projectName}$2`) : source.replace(/("name"\s*:\s*")[^"]*(")/, `$1${projectName}$2`);
133
- if (updated !== source) await writeFile(configPath, updated, "utf8");
134
- return;
135
- }
136
- }
137
- function rewriteWorkspaceVersions(deps) {
138
- for (const [name, version] of Object.entries(deps)) if (typeof version === "string" && version.startsWith("workspace:")) deps[name] = "latest";
139
- }
140
- async function isDirectory(target) {
141
- try {
142
- return (await stat(target)).isDirectory();
143
- } catch {
144
- return false;
145
- }
146
- }
147
- async function fileExists$1(target) {
148
- try {
149
- await stat(target);
150
- return true;
151
- } catch {
152
- return false;
153
- }
154
- }
155
- async function localTemplateExists(root, template) {
156
- return isDirectory(path.join(root, template));
157
- }
158
- //#endregion
159
- //#region src/cli/init.ts
160
- const SAFE_EMPTY_DIRECTORY_ENTRIES = new Set([".git", ".DS_Store"]);
161
- const DEFAULT_TEMPLATE_REF = "main";
162
- const VITE_CONFIG_FILES = [
163
- "vite.config.ts",
164
- "vite.config.mts",
165
- "vite.config.js",
166
- "vite.config.mjs"
167
- ];
168
- const ADJECTIVES = [
169
- "bright",
170
- "calm",
171
- "clever",
172
- "gentle",
173
- "quiet",
174
- "rapid",
175
- "steady",
176
- "sunny"
177
- ];
178
- const NOUNS = [
179
- "agent",
180
- "brook",
181
- "comet",
182
- "harbor",
183
- "meadow",
184
- "river",
185
- "signal",
186
- "spark"
187
- ];
188
- async function initCommand(options) {
189
- const baseRoot = path.resolve(options.root ?? process.cwd());
190
- const template = resolveTemplateName(options.template);
191
- const selectedDirectory = await selectTargetDirectory(options, await uniqueDefaultDirectory(baseRoot));
192
- const targetRoot = resolveTargetRoot(baseRoot, selectedDirectory);
193
- const projectName = packageName(options.name ?? path.basename(targetRoot));
194
- if (await looksLikeThinkApp(targetRoot)) {
195
- console.log(["This already looks like a Think app.", "Try `think inspect` to review the manifest or `think types` to refresh generated declarations."].join("\n"));
196
- return;
197
- }
198
- await assertSafeTargetDirectory(targetRoot, selectedDirectory);
199
- if (options.dryRun) {
200
- console.log([`Think init would create a "${template}" app in ${targetRoot}.`, options.install ?? true ? "Would run: npm install" : "Would skip dependency install."].join("\n"));
201
- return;
202
- }
203
- await mkdir(targetRoot, { recursive: true });
204
- await fetchTemplate(template, targetRoot, options);
205
- await finalizeTemplate(targetRoot, projectName);
206
- if (options.install ?? true) await (options.installRunner ?? runNpmInstall)(targetRoot);
207
- printSuccess(targetRoot, selectedDirectory, template, options.install ?? true);
208
- }
209
- async function fetchTemplate(template, targetRoot, options) {
210
- const localRoot = options.templatesDir ?? await findLocalTemplatesRoot(template);
211
- if (localRoot && await localTemplateExists(localRoot, template)) {
212
- await copyLocalTemplate(path.join(localRoot, template), targetRoot);
213
- return;
214
- }
215
- if (options.fetchTemplate) {
216
- await options.fetchTemplate({
217
- template,
218
- ref: options.ref ?? DEFAULT_TEMPLATE_REF,
219
- dest: targetRoot
220
- });
221
- return;
222
- }
223
- throw new Error([
224
- "Could not find Think starter templates locally, and no remote fetcher is configured.",
225
- "Run `npm create think` to scaffold a Think app.",
226
- "",
227
- "Available templates:",
228
- formatTemplateList()
229
- ].join("\n"));
230
- }
231
- async function selectTargetDirectory(options, defaultDirectory) {
232
- if (options.directory) return normalizeTargetDirectory(options.directory);
233
- if (options.yes) return defaultDirectory;
234
- return normalizeTargetDirectory(await (options.promptTargetDirectory ?? promptTargetDirectory)(defaultDirectory) || defaultDirectory);
235
- }
236
- async function promptTargetDirectory(defaultDirectory) {
237
- const rl = createInterface({
238
- input: stdin,
239
- output: stdout
240
- });
241
- try {
242
- return await rl.question(`Where should Think create your app? (${defaultDirectory}) `);
243
- } finally {
244
- rl.close();
245
- }
246
- }
247
- async function uniqueDefaultDirectory(root) {
248
- for (let index = 0; index < 24; index++) {
249
- const candidate = randomProjectDirectory();
250
- if (!await fileExists(path.join(root, candidate))) return candidate;
251
- }
252
- return `think-agent-${Date.now().toString(36)}`;
253
- }
254
- function randomProjectDirectory() {
255
- return `think-agent-${ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)]}-${NOUNS[Math.floor(Math.random() * NOUNS.length)]}`;
256
- }
257
- function normalizeTargetDirectory(directory) {
258
- const normalized = directory.trim();
259
- if (!normalized) throw new Error("Target directory cannot be empty.");
260
- if (path.isAbsolute(normalized)) throw new Error("Target directory must be relative to the project root.");
261
- return normalized;
262
- }
263
- function resolveTargetRoot(baseRoot, selectedDirectory) {
264
- const targetRoot = path.resolve(baseRoot, selectedDirectory);
265
- const relative = path.relative(baseRoot, targetRoot);
266
- if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("Target directory must stay inside the project root.");
267
- return targetRoot;
268
- }
269
- async function assertSafeTargetDirectory(root, selectedDirectory) {
270
- const entries = await readDirectoryEntries(root);
271
- if (entries.length === 0) return;
272
- if (selectedDirectory === "." && entries.every((entry) => SAFE_EMPTY_DIRECTORY_ENTRIES.has(entry))) return;
273
- throw new Error("Target directory is not empty. Choose a new or empty folder for the new Think app.");
274
- }
275
- async function looksLikeThinkApp(root) {
276
- let hasThinkDependency = false;
277
- const packageSource = await readTextIfExists(path.join(root, "package.json"));
278
- if (packageSource) try {
279
- const packageJson = JSON.parse(packageSource);
280
- hasThinkDependency = Boolean(packageJson.dependencies?.["@cloudflare/think"] || packageJson.devDependencies?.["@cloudflare/think"]);
281
- } catch {
282
- hasThinkDependency = false;
283
- }
284
- if ((await readFirstExistingText(VITE_CONFIG_FILES.map((file) => path.join(root, file))))?.includes("@cloudflare/think/vite")) return true;
285
- if ((await readFirstExistingText([
286
- "wrangler.jsonc",
287
- "wrangler.json",
288
- "wrangler.toml"
289
- ].map((file) => path.join(root, file))))?.includes("virtual:think/entry")) return true;
290
- return hasThinkDependency && await fileExists(path.join(root, "agents"));
291
- }
292
- function printSuccess(root, selectedDirectory, template, install) {
293
- const lines = [
294
- `Created a "${template}" Think app in ${root}.`,
295
- install ? "Installed npm dependencies." : "Skipped npm install.",
296
- "",
297
- "Next steps:"
298
- ];
299
- if (selectedDirectory !== ".") lines.push(`- cd ${selectedDirectory}`);
300
- lines.push("- Edit the agent in agents/ to customize the model, prompt, tools, and skills", "- npm run dev", "- npm run types", "- npm run deploy");
301
- console.log(lines.join("\n"));
302
- }
303
- async function runNpmInstall(root) {
304
- await new Promise((resolve, reject) => {
305
- const child = spawn("npm", ["install"], {
306
- cwd: root,
307
- stdio: "inherit",
308
- shell: process.platform === "win32"
309
- });
310
- child.on("error", reject);
311
- child.on("exit", (code) => {
312
- if (code === 0) {
313
- resolve();
314
- return;
315
- }
316
- reject(/* @__PURE__ */ new Error(`npm install failed with exit code ${code ?? "unknown"}.`));
317
- });
318
- });
319
- }
320
- function packageName(name) {
321
- return name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").replace(/^[._]+/, "") || "think-agent";
322
- }
323
- async function readDirectoryEntries(root) {
324
- try {
325
- return await readdir(root);
326
- } catch (error) {
327
- if (isMissingFileError(error)) return [];
328
- throw error;
329
- }
330
- }
331
- async function readTextIfExists(file) {
332
- try {
333
- return await readFile(file, "utf8");
334
- } catch (error) {
335
- if (isMissingFileError(error)) return null;
336
- throw error;
337
- }
338
- }
339
- async function readFirstExistingText(files) {
340
- for (const file of files) {
341
- const source = await readTextIfExists(file);
342
- if (source !== null) return source;
343
- }
344
- return null;
345
- }
346
- async function fileExists(file) {
347
- try {
348
- await access(file);
349
- return true;
350
- } catch (error) {
351
- if (isMissingFileError(error)) return false;
352
- throw error;
353
- }
354
- }
355
- function isMissingFileError(error) {
356
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
357
- }
358
- //#endregion
359
- export { isKnownTemplate as a, formatTemplateList as i, DEFAULT_TEMPLATE as n, resolveTemplateName as o, THINK_TEMPLATES as r, initCommand as t };
360
-
361
- //# sourceMappingURL=init-C9q1GbK-.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"init-C9q1GbK-.js","names":["fileExists"],"sources":["../src/cli/templates.ts","../src/cli/init.ts"],"sourcesContent":["import { cp, readFile, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * The starter templates shipped in the repo's top-level `think-starters/`\n * directory. The first entry is the default used when `--template` is omitted.\n */\nexport const THINK_TEMPLATES = [\n {\n name: \"basic\",\n description: \"Minimal Think chat agent with a small React chat UI.\"\n },\n {\n name: \"personal-assistant\",\n description:\n \"Assistant with persistent memory (configureSession) and scheduled tasks.\"\n },\n {\n name: \"coding-agent\",\n description: \"Coding agent with workspace file tools and a coding skill.\"\n },\n {\n name: \"customer-support\",\n description: \"Support agent with custom tools and an escalation skill.\"\n }\n] as const;\n\nexport type ThinkTemplateName = (typeof THINK_TEMPLATES)[number][\"name\"];\n\nexport const DEFAULT_TEMPLATE: ThinkTemplateName = THINK_TEMPLATES[0].name;\n\n/** Files/directories that are never copied from a local workspace template. */\nconst LOCAL_COPY_IGNORE = new Set([\n \"node_modules\",\n \"dist\",\n \".wrangler\",\n \".turbo\",\n \".dev.vars\",\n \".env\"\n]);\n\nexport interface TemplateFetchRequest {\n template: string;\n ref: string;\n dest: string;\n}\n\nexport type TemplateFetcher = (request: TemplateFetchRequest) => Promise<void>;\n\nexport function isKnownTemplate(name: string): name is ThinkTemplateName {\n return THINK_TEMPLATES.some((template) => template.name === name);\n}\n\nexport function resolveTemplateName(name: string | undefined): string {\n const resolved = (name ?? DEFAULT_TEMPLATE).trim();\n if (!isKnownTemplate(resolved)) {\n throw new Error(\n [\n `Unknown template: ${resolved}`,\n \"Available templates:\",\n ...THINK_TEMPLATES.map((t) => `- ${t.name} — ${t.description}`)\n ].join(\"\\n\")\n );\n }\n return resolved;\n}\n\nexport function formatTemplateList(): string {\n return THINK_TEMPLATES.map((t) => `- ${t.name} — ${t.description}`).join(\n \"\\n\"\n );\n}\n\n/**\n * Locate the in-repo `think-starters/` directory by walking up from this\n * module. Only matches inside the monorepo (identified by a sibling\n * `pnpm-workspace.yaml`), so a published package never accidentally copies\n * from an unrelated `think-starters` folder on the user's machine.\n */\nexport async function findLocalTemplatesRoot(\n template: string\n): Promise<string | null> {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n for (let depth = 0; depth < 8; depth++) {\n const candidate = path.join(dir, \"think-starters\");\n if (\n (await isDirectory(path.join(dir, \".git\"))) ||\n (await fileExists(path.join(dir, \"pnpm-workspace.yaml\")))\n ) {\n if (await isDirectory(path.join(candidate, template))) {\n return candidate;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/**\n * Copy a local template directory into the destination, skipping build\n * artifacts and local secrets.\n */\nexport async function copyLocalTemplate(\n templateDir: string,\n dest: string\n): Promise<void> {\n await cp(templateDir, dest, {\n recursive: true,\n filter: (source) => {\n const base = path.basename(source);\n return !LOCAL_COPY_IGNORE.has(base);\n }\n });\n}\n\n/**\n * Wrangler config filenames, in the order `wrangler` itself resolves them.\n */\nconst WRANGLER_CONFIG_FILES = [\n \"wrangler.jsonc\",\n \"wrangler.json\",\n \"wrangler.toml\"\n];\n\n/**\n * After a template is fetched, set the project name (in both `package.json` and\n * the Wrangler config's `name`) and rewrite any `workspace:*` dependencies\n * (used so templates build inside the monorepo) to published version ranges so\n * the project installs standalone.\n */\nexport async function finalizeTemplate(\n dest: string,\n projectName: string\n): Promise<void> {\n await finalizePackageJson(dest, projectName);\n await finalizeWranglerName(dest, projectName);\n}\n\nasync function finalizePackageJson(\n dest: string,\n projectName: string\n): Promise<void> {\n const packageJsonPath = path.join(dest, \"package.json\");\n const source = await readFile(packageJsonPath, \"utf8\").catch(() => null);\n if (!source) return;\n const pkg = JSON.parse(source) as Record<string, unknown>;\n pkg.name = projectName;\n for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n const deps = pkg[field];\n if (deps && typeof deps === \"object\") {\n rewriteWorkspaceVersions(deps as Record<string, string>);\n }\n }\n await writeFile(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\\n`, \"utf8\");\n}\n\n/**\n * Update the Worker `name` in the template's Wrangler config so each scaffolded\n * app deploys under its own name instead of the shared template name. Done with\n * a targeted replacement of the first `name` field so JSONC comments and\n * formatting are preserved.\n */\nasync function finalizeWranglerName(\n dest: string,\n projectName: string\n): Promise<void> {\n for (const file of WRANGLER_CONFIG_FILES) {\n const configPath = path.join(dest, file);\n const source = await readFile(configPath, \"utf8\").catch(() => null);\n if (source === null) continue;\n const updated = file.endsWith(\".toml\")\n ? source.replace(/^(\\s*name\\s*=\\s*\")[^\"]*(\")/m, `$1${projectName}$2`)\n : source.replace(/(\"name\"\\s*:\\s*\")[^\"]*(\")/, `$1${projectName}$2`);\n if (updated !== source) {\n await writeFile(configPath, updated, \"utf8\");\n }\n return;\n }\n}\n\nfunction rewriteWorkspaceVersions(deps: Record<string, string>): void {\n for (const [name, version] of Object.entries(deps)) {\n if (typeof version === \"string\" && version.startsWith(\"workspace:\")) {\n deps[name] = \"latest\";\n }\n }\n}\n\nasync function isDirectory(target: string): Promise<boolean> {\n try {\n return (await stat(target)).isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function fileExists(target: string): Promise<boolean> {\n try {\n await stat(target);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function localTemplateExists(\n root: string,\n template: string\n): Promise<boolean> {\n return isDirectory(path.join(root, template));\n}\n","import { spawn } from \"node:child_process\";\nimport { createInterface } from \"node:readline/promises\";\nimport { stdin as input, stdout as output } from \"node:process\";\nimport { access, mkdir, readdir, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n copyLocalTemplate,\n finalizeTemplate,\n findLocalTemplatesRoot,\n formatTemplateList,\n localTemplateExists,\n resolveTemplateName,\n type TemplateFetcher\n} from \"./templates\";\n\nexport interface InitCommandOptions {\n root?: string;\n directory?: string;\n name?: string;\n /** Starter template to scaffold. Defaults to `basic`. */\n template?: string;\n /** Git ref passed to the remote template fetcher. Defaults to `main`. */\n ref?: string;\n yes?: boolean;\n install?: boolean;\n dryRun?: boolean;\n /** Local templates directory override (used in-repo and by tests). */\n templatesDir?: string;\n /**\n * Fetches a template from a remote source (e.g. degit). Injected by\n * `create-think`. When omitted, only local templates can be scaffolded.\n */\n fetchTemplate?: TemplateFetcher;\n promptTargetDirectory?: (defaultDirectory: string) => Promise<string>;\n installRunner?: (root: string) => Promise<void>;\n}\n\nconst SAFE_EMPTY_DIRECTORY_ENTRIES = new Set([\".git\", \".DS_Store\"]);\nconst DEFAULT_TEMPLATE_REF = \"main\";\nconst VITE_CONFIG_FILES = [\n \"vite.config.ts\",\n \"vite.config.mts\",\n \"vite.config.js\",\n \"vite.config.mjs\"\n];\n\nconst ADJECTIVES = [\n \"bright\",\n \"calm\",\n \"clever\",\n \"gentle\",\n \"quiet\",\n \"rapid\",\n \"steady\",\n \"sunny\"\n];\n\nconst NOUNS = [\n \"agent\",\n \"brook\",\n \"comet\",\n \"harbor\",\n \"meadow\",\n \"river\",\n \"signal\",\n \"spark\"\n];\n\nexport async function initCommand(options: InitCommandOptions): Promise<void> {\n const baseRoot = path.resolve(options.root ?? process.cwd());\n const template = resolveTemplateName(options.template);\n const defaultDirectory = await uniqueDefaultDirectory(baseRoot);\n const selectedDirectory = await selectTargetDirectory(\n options,\n defaultDirectory\n );\n const targetRoot = resolveTargetRoot(baseRoot, selectedDirectory);\n const projectName = packageName(options.name ?? path.basename(targetRoot));\n\n const existingThinkApp = await looksLikeThinkApp(targetRoot);\n if (existingThinkApp) {\n console.log(\n [\n \"This already looks like a Think app.\",\n \"Try `think inspect` to review the manifest or `think types` to refresh generated declarations.\"\n ].join(\"\\n\")\n );\n return;\n }\n\n await assertSafeTargetDirectory(targetRoot, selectedDirectory);\n\n if (options.dryRun) {\n console.log(\n [\n `Think init would create a \"${template}\" app in ${targetRoot}.`,\n (options.install ?? true)\n ? \"Would run: npm install\"\n : \"Would skip dependency install.\"\n ].join(\"\\n\")\n );\n return;\n }\n\n await mkdir(targetRoot, { recursive: true });\n await fetchTemplate(template, targetRoot, options);\n await finalizeTemplate(targetRoot, projectName);\n\n if (options.install ?? true) {\n await (options.installRunner ?? runNpmInstall)(targetRoot);\n }\n\n printSuccess(\n targetRoot,\n selectedDirectory,\n template,\n options.install ?? true\n );\n}\n\nasync function fetchTemplate(\n template: string,\n targetRoot: string,\n options: InitCommandOptions\n): Promise<void> {\n const localRoot =\n options.templatesDir ?? (await findLocalTemplatesRoot(template));\n if (localRoot && (await localTemplateExists(localRoot, template))) {\n await copyLocalTemplate(path.join(localRoot, template), targetRoot);\n return;\n }\n if (options.fetchTemplate) {\n await options.fetchTemplate({\n template,\n ref: options.ref ?? DEFAULT_TEMPLATE_REF,\n dest: targetRoot\n });\n return;\n }\n throw new Error(\n [\n \"Could not find Think starter templates locally, and no remote fetcher is configured.\",\n \"Run `npm create think` to scaffold a Think app.\",\n \"\",\n \"Available templates:\",\n formatTemplateList()\n ].join(\"\\n\")\n );\n}\n\nasync function selectTargetDirectory(\n options: InitCommandOptions,\n defaultDirectory: string\n): Promise<string> {\n if (options.directory) return normalizeTargetDirectory(options.directory);\n if (options.yes) return defaultDirectory;\n const target = await (options.promptTargetDirectory ?? promptTargetDirectory)(\n defaultDirectory\n );\n return normalizeTargetDirectory(target || defaultDirectory);\n}\n\nasync function promptTargetDirectory(\n defaultDirectory: string\n): Promise<string> {\n const rl = createInterface({ input, output });\n try {\n return await rl.question(\n `Where should Think create your app? (${defaultDirectory}) `\n );\n } finally {\n rl.close();\n }\n}\n\nasync function uniqueDefaultDirectory(root: string): Promise<string> {\n for (let index = 0; index < 24; index++) {\n const candidate = randomProjectDirectory();\n if (!(await fileExists(path.join(root, candidate)))) return candidate;\n }\n return `think-agent-${Date.now().toString(36)}`;\n}\n\nfunction randomProjectDirectory(): string {\n const adjective = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)];\n const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)];\n return `think-agent-${adjective}-${noun}`;\n}\n\nfunction normalizeTargetDirectory(directory: string): string {\n const normalized = directory.trim();\n if (!normalized) throw new Error(\"Target directory cannot be empty.\");\n if (path.isAbsolute(normalized)) {\n throw new Error(\"Target directory must be relative to the project root.\");\n }\n return normalized;\n}\n\nfunction resolveTargetRoot(\n baseRoot: string,\n selectedDirectory: string\n): string {\n const targetRoot = path.resolve(baseRoot, selectedDirectory);\n const relative = path.relative(baseRoot, targetRoot);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(\"Target directory must stay inside the project root.\");\n }\n return targetRoot;\n}\n\nasync function assertSafeTargetDirectory(\n root: string,\n selectedDirectory: string\n): Promise<void> {\n const entries = await readDirectoryEntries(root);\n if (entries.length === 0) return;\n if (\n selectedDirectory === \".\" &&\n entries.every((entry) => SAFE_EMPTY_DIRECTORY_ENTRIES.has(entry))\n ) {\n return;\n }\n throw new Error(\n \"Target directory is not empty. Choose a new or empty folder for the new Think app.\"\n );\n}\n\nasync function looksLikeThinkApp(root: string): Promise<boolean> {\n let hasThinkDependency = false;\n const packageSource = await readTextIfExists(path.join(root, \"package.json\"));\n if (packageSource) {\n try {\n const packageJson = JSON.parse(packageSource) as PackageJson;\n hasThinkDependency = Boolean(\n packageJson.dependencies?.[\"@cloudflare/think\"] ||\n packageJson.devDependencies?.[\"@cloudflare/think\"]\n );\n } catch {\n hasThinkDependency = false;\n }\n }\n const viteConfig = await readFirstExistingText(\n VITE_CONFIG_FILES.map((file) => path.join(root, file))\n );\n if (viteConfig?.includes(\"@cloudflare/think/vite\")) return true;\n const wranglerConfig = await readFirstExistingText(\n [\"wrangler.jsonc\", \"wrangler.json\", \"wrangler.toml\"].map((file) =>\n path.join(root, file)\n )\n );\n if (wranglerConfig?.includes(\"virtual:think/entry\")) return true;\n return hasThinkDependency && (await fileExists(path.join(root, \"agents\")));\n}\n\nfunction printSuccess(\n root: string,\n selectedDirectory: string,\n template: string,\n install: boolean\n): void {\n const lines = [\n `Created a \"${template}\" Think app in ${root}.`,\n install ? \"Installed npm dependencies.\" : \"Skipped npm install.\",\n \"\",\n \"Next steps:\"\n ];\n if (selectedDirectory !== \".\") {\n lines.push(`- cd ${selectedDirectory}`);\n }\n lines.push(\n \"- Edit the agent in agents/ to customize the model, prompt, tools, and skills\",\n \"- npm run dev\",\n \"- npm run types\",\n \"- npm run deploy\"\n );\n console.log(lines.join(\"\\n\"));\n}\n\nasync function runNpmInstall(root: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n const child = spawn(\"npm\", [\"install\"], {\n cwd: root,\n stdio: \"inherit\",\n // On Windows `npm` resolves to `npm.cmd`, which Node's spawn won't find\n // without a shell.\n shell: process.platform === \"win32\"\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(`npm install failed with exit code ${code ?? \"unknown\"}.`)\n );\n });\n });\n}\n\nfunction packageName(name: string): string {\n return (\n name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/^[._]+/, \"\") || \"think-agent\"\n );\n}\n\nasync function readDirectoryEntries(root: string): Promise<string[]> {\n try {\n return await readdir(root);\n } catch (error) {\n if (isMissingFileError(error)) return [];\n throw error;\n }\n}\n\nasync function readTextIfExists(file: string): Promise<string | null> {\n try {\n return await readFile(file, \"utf8\");\n } catch (error) {\n if (isMissingFileError(error)) return null;\n throw error;\n }\n}\n\nasync function readFirstExistingText(files: string[]): Promise<string | null> {\n for (const file of files) {\n const source = await readTextIfExists(file);\n if (source !== null) return source;\n }\n return null;\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n await access(file);\n return true;\n } catch (error) {\n if (isMissingFileError(error)) return false;\n throw error;\n }\n}\n\nfunction isMissingFileError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === \"ENOENT\"\n );\n}\n\ninterface PackageJson {\n name?: string;\n private?: boolean;\n type?: string;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n [key: string]: unknown;\n}\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,kBAAkB;CAC7B;EACE,MAAM;EACN,aAAa;CACf;CACA;EACE,MAAM;EACN,aACE;CACJ;C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