@cloudflare/think 0.8.4 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,6 +27,35 @@ export class MyAgent extends Think<Env> {
27
27
 
28
28
  That's it. Think handles the WebSocket chat protocol, message persistence, the agentic loop, message sanitization, stream resumption, client tool support, and workspace file tools. Connect from the browser with `useAgentChat` from `@cloudflare/ai-chat`.
29
29
 
30
+ ## Think framework
31
+
32
+ The Think Vite plugin can generate the Worker entry, stable Durable Object
33
+ exports, friendly route helpers, and inferred Worker config from an `agents/`
34
+ directory:
35
+
36
+ ```ts
37
+ import { cloudflare } from "@cloudflare/vite-plugin";
38
+ import { think } from "@cloudflare/think/vite";
39
+ import { defineConfig } from "vite";
40
+
41
+ export default defineConfig({
42
+ plugins: [think(), cloudflare()]
43
+ });
44
+ ```
45
+
46
+ Use `main: "virtual:think/entry"` in framework projects. Top-level agents under
47
+ `agents/` get generated Durable Object bindings and migrations; nested
48
+ `agents/*/agents/*` entries are facet exports for `ctx.exports` and do not need
49
+ production Wrangler bindings or migrations. Apps with auth or custom routing can
50
+ add `src/server.ts`; the generated entry still wraps it and injects
51
+ `think.router` for manifest-aware routing.
52
+
53
+ The framework supports one sub-agent layer today. If you need nested sub-agents,
54
+ please reach out with your use case so we can design that model deliberately.
55
+
56
+ See the full Think framework docs in `docs/think/index.md` for conventions,
57
+ custom server handlers, diagnostics, and route-prefix configuration.
58
+
30
59
  ## Messengers
31
60
 
32
61
  Think can own messenger ingress directly. Declare providers with
@@ -296,12 +325,15 @@ Script execution requires a Worker Loader binding:
296
325
  | Export | Description |
297
326
  | --------------------------------------- | ------------------------------------------------------------- |
298
327
  | `@cloudflare/think` | `Think`, `Session`, `Workspace` — main class + re-exports |
328
+ | `@cloudflare/think/framework` | Framework manifest discovery and declarative `agent()` helper |
329
+ | `@cloudflare/think/server-entry` | Framework Worker entry helpers for custom server handlers |
299
330
  | `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
300
331
  | `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
301
332
  | `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
302
333
  | `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
303
334
  | `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
304
335
  | `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
336
+ | `@cloudflare/think/vite` | Think Vite plugin and generated Worker config helpers |
305
337
 
306
338
  ## Think
307
339
 
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,316 @@
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";
3
+ import { n as isThinkGeneratedFile, t as generateThinkTypes } from "../types-codegen-B6c5KpYH.js";
4
+ import { t as initCommand } from "../init-C9q1GbK-.js";
5
+ import { access, mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import yargs from "yargs";
8
+ import { hideBin } from "yargs/helpers";
9
+ import { spawn } from "node:child_process";
10
+ //#region src/cli/inspect.ts
11
+ async function inspectCommand(options) {
12
+ const root = path.resolve(options.root ?? process.cwd());
13
+ const project = await createThinkProject({
14
+ routePrefix: options.routePrefix,
15
+ allowNonVirtualMain: options.allowNonVirtualMain
16
+ }, root);
17
+ if (options.json) {
18
+ console.log(JSON.stringify({
19
+ root,
20
+ manifest: project.manifest,
21
+ workerConfig: project.workerConfig,
22
+ diagnostics: project.diagnostics,
23
+ wranglerConfig: {
24
+ path: project.wranglerConfig.path,
25
+ parsed: Boolean(project.wranglerConfig.config),
26
+ error: project.wranglerConfig.error
27
+ }
28
+ }, null, 2));
29
+ return;
30
+ }
31
+ const lines = [
32
+ "Think inspect",
33
+ `Root: ${root}`,
34
+ "",
35
+ ...summarizeThinkManifest(project.manifest),
36
+ "",
37
+ `Route prefix: ${project.manifest.routePrefix}`,
38
+ `App entry: ${project.manifest.appEntrypoint ?? "none"}`,
39
+ `Wrangler config: ${project.wranglerConfig.path ?? "not found"}`,
40
+ "",
41
+ "Features:",
42
+ ...formatFeatures(project.manifest),
43
+ "",
44
+ "Route surfaces:",
45
+ ...formatRouteSurfaces(project.manifest.routeSurfaces),
46
+ "",
47
+ "Schedules:",
48
+ ...formatNamedFacts(project.manifest.schedules),
49
+ "",
50
+ "Messengers:",
51
+ ...formatNamedFacts(project.manifest.messengers),
52
+ "",
53
+ "Tools:",
54
+ ...formatNamedFacts(project.manifest.tools),
55
+ "",
56
+ "Platform requirements:",
57
+ ...formatPlatformRequirements(project.manifest),
58
+ "",
59
+ "Expected top-level Durable Objects:",
60
+ ...formatBindings(project.manifest.bindings),
61
+ "",
62
+ "Diagnostics:",
63
+ ...formatDiagnostics(project.diagnostics)
64
+ ];
65
+ if (project.wranglerConfig.error) lines.push("", `[warning] ${project.wranglerConfig.error}`);
66
+ console.log(lines.join("\n"));
67
+ }
68
+ function formatBindings(bindings) {
69
+ if (bindings.length === 0) return ["- none"];
70
+ return bindings.map((binding) => `- ${binding.name} -> class ${binding.className}`);
71
+ }
72
+ function formatFeatures(manifest) {
73
+ if (manifest.features.length === 0) return ["- none"];
74
+ return manifest.agents.flatMap((agent) => {
75
+ if (agent.features.length === 0 && agent.env.length === 0) return [];
76
+ return [`- ${agent.id}: ${[agent.features.length ? `features ${agent.features.join(", ")}` : null, agent.env.length ? `env ${agent.env.join(", ")}` : null].filter(Boolean).join(" | ") || "none"}`];
77
+ });
78
+ }
79
+ function formatRouteSurfaces(surfaces) {
80
+ if (surfaces.length === 0) return ["- none"];
81
+ return surfaces.map((surface) => `- ${surface.kind} ${surface.id}: ${surface.pattern}${surface.requiredRunWorkerFirst ? " | requires run_worker_first" : ""}`);
82
+ }
83
+ function formatNamedFacts(facts) {
84
+ if (facts.length === 0) return ["- none"];
85
+ return facts.map((fact) => `- ${fact.id}${fact.agent ? ` | agent ${fact.agent}` : ""}${fact.sourcePath ? ` | ${fact.sourcePath}` : ""}`);
86
+ }
87
+ function formatPlatformRequirements(manifest) {
88
+ if (manifest.platformRequirements.length === 0) return ["- none"];
89
+ return manifest.platformRequirements.map((requirement) => `- ${requirement.kind} ${requirement.binding}${requirement.agent ? ` | agent ${requirement.agent}` : ""} | ${requirement.reason}`);
90
+ }
91
+ function formatDiagnostics(diagnostics) {
92
+ if (diagnostics.length === 0) return ["- none"];
93
+ return diagnostics.map((diagnostic) => `- ${severityLabel(diagnostic.severity)} [${diagnostic.code}] ${diagnostic.message}`);
94
+ }
95
+ function severityLabel(severity) {
96
+ return severity.toUpperCase();
97
+ }
98
+ //#endregion
99
+ //#region src/cli/types.ts
100
+ async function typesCommand(options) {
101
+ const root = path.resolve(options.root ?? process.cwd());
102
+ const typesFile = normalizePath(options.typesFile ?? "think.d.ts");
103
+ const wranglerEnvFile = normalizePath(options.wranglerEnvFile ?? "env.d.ts");
104
+ const files = await readProjectFiles(root, "agents");
105
+ const manifest = await resolveThinkManifest({
106
+ files,
107
+ routePrefix: options.routePrefix
108
+ }, root);
109
+ const wranglerConfig = await readWranglerConfig(root);
110
+ if (wranglerConfig.config) applyUserBindingNames(manifest, wranglerConfig.config);
111
+ if (options.all && !options.dryRun && !options.check) await runWranglerTypes(root, wranglerEnvFile, options.wranglerArgs ?? []);
112
+ const generated = generateThinkTypes(manifest, {
113
+ files,
114
+ typesFile
115
+ });
116
+ if (options.dryRun) {
117
+ console.log(["Think types would update:", ...generated.map((file) => `- ${file.path}`)].join("\n"));
118
+ return;
119
+ }
120
+ if (options.check) {
121
+ const stale = await findStaleFiles(root, generated);
122
+ if (stale.length > 0) throw new Error([
123
+ "Think generated types are out of date.",
124
+ "Run `think types` to update:",
125
+ ...stale.map((file) => `- ${file}`)
126
+ ].join("\n"));
127
+ console.log("Think generated types are up to date.");
128
+ return;
129
+ }
130
+ for (const file of generated) await writeGeneratedFile(root, file);
131
+ console.log(["Generated Think types:", ...generated.map((file) => `- ${file.path}`)].join("\n"));
132
+ }
133
+ async function findStaleFiles(root, files) {
134
+ const stale = [];
135
+ for (const file of files) {
136
+ const expected = await expectedFileContent(root, file);
137
+ if (await readTextIfExists(path.join(root, file.path)) !== expected) stale.push(file.path);
138
+ }
139
+ return stale;
140
+ }
141
+ async function writeGeneratedFile(root, file) {
142
+ const absolute = path.join(root, file.path);
143
+ const expected = await expectedFileContent(root, file);
144
+ await mkdir(path.dirname(absolute), { recursive: true });
145
+ await writeFile(absolute, expected, "utf8");
146
+ }
147
+ async function expectedFileContent(root, file) {
148
+ const current = await readTextIfExists(path.join(root, file.path));
149
+ if (current && !isThinkGeneratedFile(current)) throw new Error(`${file.path} already exists and is not Think-generated; pass a different output path or replace it with a Think-generated file.`);
150
+ return file.content;
151
+ }
152
+ async function readTextIfExists(file) {
153
+ try {
154
+ return await readFile(file, "utf8");
155
+ } catch (error) {
156
+ if (isMissingFileError(error)) return null;
157
+ throw error;
158
+ }
159
+ }
160
+ async function runWranglerTypes(root, envFile, passthroughArgs) {
161
+ const command = await resolveWranglerCommand(root);
162
+ const args = [
163
+ "types",
164
+ envFile,
165
+ ...defaultWranglerTypeArgs(passthroughArgs),
166
+ ...passthroughArgs
167
+ ];
168
+ await new Promise((resolve, reject) => {
169
+ const child = spawn(command, args, {
170
+ cwd: root,
171
+ stdio: "inherit"
172
+ });
173
+ child.on("error", (error) => {
174
+ reject(/* @__PURE__ */ new Error(`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}`));
175
+ });
176
+ child.on("exit", (code) => {
177
+ if (code === 0) {
178
+ resolve();
179
+ return;
180
+ }
181
+ reject(/* @__PURE__ */ new Error(`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.`));
182
+ });
183
+ });
184
+ }
185
+ function defaultWranglerTypeArgs(args) {
186
+ return args.some((arg) => arg === "--include-runtime" || arg.startsWith("--include-runtime=")) ? [] : ["--include-runtime", "false"];
187
+ }
188
+ async function resolveWranglerCommand(root) {
189
+ const executable = process.platform === "win32" ? "wrangler.cmd" : "wrangler";
190
+ const local = path.join(root, "node_modules", ".bin", executable);
191
+ try {
192
+ await access(local);
193
+ return local;
194
+ } catch {
195
+ return executable;
196
+ }
197
+ }
198
+ function normalizePath(file) {
199
+ return file.replace(/\\/g, "/").replace(/^\.?\//, "");
200
+ }
201
+ function isMissingFileError(error) {
202
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
203
+ }
204
+ //#endregion
205
+ //#region src/cli/create.ts
206
+ 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", {
208
+ type: "string",
209
+ describe: "Target directory to initialize. Omit to choose interactively."
210
+ }).option("root", {
211
+ type: "string",
212
+ describe: "Base directory for initialization",
213
+ default: process.cwd()
214
+ }).option("name", {
215
+ type: "string",
216
+ describe: "Package and Worker name for the generated app"
217
+ }).option("template", {
218
+ type: "string",
219
+ describe: "Starter template to scaffold (default: basic)"
220
+ }).option("ref", {
221
+ type: "string",
222
+ describe: "Git ref to fetch remote templates from"
223
+ }).option("yes", {
224
+ alias: "y",
225
+ type: "boolean",
226
+ describe: "Use defaults and skip prompts",
227
+ default: false
228
+ }).option("install", {
229
+ type: "boolean",
230
+ describe: "Run npm install after writing files",
231
+ default: true
232
+ }).option("dry-run", {
233
+ type: "boolean",
234
+ describe: "Print files that would be written without writing them",
235
+ default: false
236
+ }), async (args) => {
237
+ await initCommand({
238
+ root: args.root,
239
+ directory: args.directory,
240
+ name: args.name,
241
+ template: args.template,
242
+ ref: args.ref,
243
+ yes: args.yes,
244
+ install: args.install,
245
+ dryRun: args.dryRun
246
+ });
247
+ }).command("inspect", "Inspect the Think app manifest, routing, bindings, and diagnostics", (cmd) => cmd.option("root", {
248
+ type: "string",
249
+ describe: "Project root to inspect",
250
+ default: process.cwd()
251
+ }).option("json", {
252
+ type: "boolean",
253
+ describe: "Print machine-readable JSON output",
254
+ default: false
255
+ }).option("route-prefix", {
256
+ type: "string",
257
+ describe: "Override the Think route prefix"
258
+ }).option("allow-non-virtual-main", {
259
+ type: "boolean",
260
+ describe: "Do not report non-virtual Wrangler main as an error during inspection",
261
+ default: false
262
+ }), async (args) => {
263
+ await inspectCommand({
264
+ root: args.root,
265
+ json: args.json,
266
+ routePrefix: args.routePrefix,
267
+ allowNonVirtualMain: args.allowNonVirtualMain
268
+ });
269
+ }).command("types", "Generate Think TypeScript declarations", (cmd) => cmd.option("root", {
270
+ type: "string",
271
+ describe: "Project root to generate types for",
272
+ default: process.cwd()
273
+ }).option("types-file", {
274
+ type: "string",
275
+ describe: "Think declaration file to generate",
276
+ default: "think.d.ts"
277
+ }).option("all", {
278
+ type: "boolean",
279
+ describe: "Also run Wrangler type generation before Think typegen",
280
+ default: false
281
+ }).option("wrangler-env-file", {
282
+ type: "string",
283
+ describe: "Wrangler env declaration file to generate with --all",
284
+ default: "env.d.ts"
285
+ }).option("route-prefix", {
286
+ type: "string",
287
+ describe: "Override the Think route prefix"
288
+ }).option("dry-run", {
289
+ type: "boolean",
290
+ describe: "Print files that would be written without writing them",
291
+ default: false
292
+ }).option("check", {
293
+ type: "boolean",
294
+ describe: "Check generated Think types without modifying files",
295
+ default: false
296
+ }), async (args) => {
297
+ await typesCommand({
298
+ root: args.root,
299
+ typesFile: args.typesFile,
300
+ wranglerEnvFile: args.wranglerEnvFile,
301
+ routePrefix: args.routePrefix,
302
+ all: args.all,
303
+ dryRun: args.dryRun,
304
+ check: args.check,
305
+ wranglerArgs: Array.isArray(args["--"]) ? args["--"].map(String) : []
306
+ });
307
+ }).demandCommand(1, "Please provide a command").strict().help();
308
+ }
309
+ //#endregion
310
+ //#region src/cli/index.ts
311
+ console.warn("The `think` CLI is part of the experimental @cloudflare/think framework layer and may change or be removed in any release.");
312
+ createCli().parse();
313
+ //#endregion
314
+ export {};
315
+
316
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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":";;;;;;;;;;AAmBA,eAAsB,eACpB,SACe;CACf,MAAM,OAAO,KAAK,QAAQ,QAAQ,QAAQ,QAAQ,IAAI,CAAC;CACvD,MAAM,UAAU,MAAM,mBACpB;EACE,aAAa,QAAQ;EACrB,qBAAqB,QAAQ;CAC/B,GACA,IACF;CAEA,IAAI,QAAQ,MAAM;EAChB,QAAQ,IACN,KAAK,UACH;GACE;GACA,UAAU,QAAQ;GAClB,cAAc,QAAQ;GACtB,aAAa,QAAQ;GACrB,gBAAgB;IACd,MAAM,QAAQ,eAAe;IAC7B,QAAQ,QAAQ,QAAQ,eAAe,MAAM;IAC7C,OAAO,QAAQ,eAAe;GAChC;EACF,GACA,MACA,CACF,CACF;EACA;CACF;CAEA,MAAM,QAAQ;EACZ;EACA,SAAS;EACT;EACA,GAAG,uBAAuB,QAAQ,QAAQ;EAC1C;EACA,iBAAiB,QAAQ,SAAS;EAClC,cAAc,QAAQ,SAAS,iBAAiB;EAChD,oBAAoB,QAAQ,eAAe,QAAQ;EACnD;EACA;EACA,GAAG,eAAe,QAAQ,QAAQ;EAClC;EACA;EACA,GAAG,oBAAoB,QAAQ,SAAS,aAAa;EACrD;EACA;EACA,GAAG,iBAAiB,QAAQ,SAAS,SAAS;EAC9C;EACA;EACA,GAAG,iBAAiB,QAAQ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AAQ;EACd,MAAM;EACN,UAAU;EACV,SAAS,QAAQ,IAAI;CACvB,CAAC,CAAC,CACD,OAAO,cAAc;EACpB,MAAM;EACN,UAAU;EACV,SAAS;CACX,CAAC,CAAC,CACD,OAAO,OAAO;EACb,MAAM;EACN,UAAU;EACV,SAAS;CACX,CAAC,CAAC,CACD,OAAO,qBAAqB;EAC3B,MAAM;EACN,UAAU;EACV,SAAS;CACX,CAAC,CAAC,CACD,OAAO,gBAAgB;EACtB,MAAM;EACN,UAAU;CACZ,CAAC,CAAC,CACD,OAAO,WAAW;EACjB,MAAM;EACN,UAAU;EACV,SAAS;CACX,CAAC,CAAC,CACD,OAAO,SAAS;EACf,MAAM;EACN,UAAU;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"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,77 @@
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 ADDED
@@ -0,0 +1,8 @@
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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,140 @@
1
+ import { l as createThinkWorkerDefaults } from "./project-D1o1-3dN.js";
2
+ //#region src/framework/codegen.ts
3
+ function generateThinkAgentsModule(manifest) {
4
+ return [
5
+ manifest.agents.map((agent, index) => {
6
+ return `import * as AgentModule${index} from ${JSON.stringify(agent.importPath)};`;
7
+ }).join("\n"),
8
+ "",
9
+ runtimeHelpers,
10
+ "",
11
+ manifest.agents.map((agent, index) => {
12
+ return [`const AgentInfo${index} = __resolveThinkAgentModule(AgentModule${index}, ${JSON.stringify(agent.sourcePath)}, ${JSON.stringify(agent.className)});`, `const Agent${index} = AgentInfo${index}.agent;`].join("\n");
13
+ }).join("\n"),
14
+ manifest.agents.map((agent, index) => {
15
+ return `export { Agent${index} as ${agent.className} };`;
16
+ }).join("\n"),
17
+ `export const thinkAgentRegistry = [
18
+ ${manifest.agents.map((agent, index) => {
19
+ return ` { id: ${JSON.stringify(agent.id)}, className: ${JSON.stringify(agent.className)}, kind: ${JSON.stringify(agent.kind)}, parentId: ${JSON.stringify(agent.parentId)}, aliases: ${JSON.stringify(agent.aliases)}, exportName: AgentInfo${index}.exportName, sourcePath: ${JSON.stringify(agent.sourcePath)} }`;
20
+ }).join(",\n")}
21
+ ];`,
22
+ ""
23
+ ].filter((line) => line.length > 0).join("\n");
24
+ }
25
+ function generateThinkManifestModule(manifest) {
26
+ return `export default ${JSON.stringify(manifest, null, 2)};`;
27
+ }
28
+ function generateThinkConfigModule(manifest) {
29
+ return `export default ${JSON.stringify(createThinkWorkerDefaults(manifest), null, 2)};`;
30
+ }
31
+ function generateThinkRouterModule(manifest) {
32
+ return [
33
+ `import { createThinkRouter } from "@cloudflare/think/server-entry";`,
34
+ `import thinkManifest from "virtual:think/manifest";`,
35
+ `export { buildThinkAgentPath, createThinkRouter, parseThinkAgentPath, routeThinkRequest, resolveThinkAgentName, resolveThinkSubAgentName } from "@cloudflare/think/server-entry";`,
36
+ `export const thinkRouter = createThinkRouter({ routePrefix: ${JSON.stringify(manifest.routePrefix)}, manifest: thinkManifest });`,
37
+ ""
38
+ ].join("\n");
39
+ }
40
+ function generateThinkServerEntryModule() {
41
+ return [`export { buildThinkAgentPath, createThinkRouter, createThinkWorkerEntry, parseThinkAgentPath, routeThinkRequest } from "@cloudflare/think/server-entry";`, ""].join("\n");
42
+ }
43
+ function generateThinkEntry(manifest) {
44
+ return [
45
+ `export * from "virtual:think/agents";`,
46
+ `import { thinkRouter } from "virtual:think/router";`,
47
+ manifest.appEntrypoint ? `import appEntrypoint from ${JSON.stringify(`/${manifest.appEntrypoint}`)};` : `const appEntrypoint = null;`,
48
+ "",
49
+ "export default {",
50
+ " async fetch(request, env, ctx) {",
51
+ " if (appEntrypoint?.fetch) {",
52
+ " const response = await appEntrypoint.fetch(request, env, ctx, { router: thinkRouter });",
53
+ " if (response) return response;",
54
+ " }",
55
+ ` return (await thinkRouter.route(request, env, ctx)) ?? new Response('Not found', { status: 404 });`,
56
+ " }",
57
+ "};",
58
+ ""
59
+ ].filter((line) => line.length > 0).join("\n");
60
+ }
61
+ const runtimeHelpers = `
62
+ const THINK_AGENT_DEFINITION = Symbol.for("cloudflare.think.agent.definition");
63
+
64
+ function __resolveThinkAgentModule(module, sourcePath, className) {
65
+ const candidates = [];
66
+ if ("default" in module) candidates.push(["default", module.default]);
67
+ for (const [name, value] of Object.entries(module)) {
68
+ if (name !== "default") candidates.push([name, value]);
69
+ }
70
+
71
+ const valid = candidates.filter(([, value]) => __isThinkAgentExport(value));
72
+ if (valid.length === 0) {
73
+ const declarativeLike = candidates.find(([, value]) => __looksLikeInvalidThinkAgentDefinition(value));
74
+ const hint = declarativeLike
75
+ ? "A declarative agent export must be created with agent({ ... }) from @cloudflare/think/framework."
76
+ : "If this file only contains helper code, move it outside the /agents convention tree.";
77
+ throw new Error(
78
+ \`Invalid Think agent module: \${sourcePath}\\n\\n\` +
79
+ \`This file matches the /agents convention, but it does not export a Think agent.\\n\` +
80
+ \`Export a class that extends Agent/Think, or export default agent({ ... }).\\n\` +
81
+ hint
82
+ );
83
+ }
84
+
85
+ const selected = valid.find(([name]) => name === "default") ?? (valid.length === 1 ? valid[0] : null);
86
+ if (!selected) {
87
+ throw new Error(
88
+ \`Invalid Think agent module: \${sourcePath}\\n\\n\` +
89
+ \`This file exports multiple agent classes. Export one default agent or move helper classes outside /agents.\\n\` +
90
+ \`Only one Durable Object class can be generated for each convention path.\`
91
+ );
92
+ }
93
+
94
+ const value = selected[1];
95
+ const resolved = __isThinkAgentDefinition(value)
96
+ ? value.__toThinkClass(className)
97
+ : value;
98
+ try {
99
+ Object.defineProperty(resolved, "name", { value: className });
100
+ } catch {
101
+ // Best effort: class names are configurable for normal class declarations.
102
+ }
103
+ return { agent: resolved, exportName: selected[0] };
104
+ }
105
+
106
+ function __isThinkAgentExport(value) {
107
+ return __isThinkAgentDefinition(value) || __isAgentClass(value);
108
+ }
109
+
110
+ function __isThinkAgentDefinition(value) {
111
+ return Boolean(
112
+ value &&
113
+ typeof value === "object" &&
114
+ (value[THINK_AGENT_DEFINITION] === true ||
115
+ value.kind === "think-agent-definition") &&
116
+ typeof value.__toThinkClass === "function"
117
+ );
118
+ }
119
+
120
+ function __looksLikeInvalidThinkAgentDefinition(value) {
121
+ return Boolean(
122
+ value &&
123
+ typeof value === "object" &&
124
+ value.kind === "think-agent-definition" &&
125
+ typeof value.__toThinkClass !== "function"
126
+ );
127
+ }
128
+
129
+ function __isAgentClass(value) {
130
+ return Boolean(
131
+ typeof value === "function" &&
132
+ value.prototype &&
133
+ typeof value.prototype.fetch === "function"
134
+ );
135
+ }
136
+ `.trim();
137
+ //#endregion
138
+ export { generateThinkRouterModule as a, generateThinkManifestModule as i, generateThinkConfigModule as n, generateThinkServerEntryModule as o, generateThinkEntry as r, generateThinkAgentsModule as t };
139
+
140
+ //# sourceMappingURL=codegen-CauNNguA.js.map