@cloudflare/think 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +0 -6
  2. package/dist/{chat-sdk-D6cUghsQ.js → chat-sdk-Dm0R3pdR.js} +24 -1
  3. package/dist/{chat-sdk-D6cUghsQ.js.map → chat-sdk-Dm0R3pdR.js.map} +1 -1
  4. package/dist/cli/index.js +6 -15
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/{index-CR4-ffm_.d.ts → index-WF0HQmkk.d.ts} +153 -41
  7. package/dist/messengers/index.d.ts +1 -1
  8. package/dist/messengers/index.js +1 -1
  9. package/dist/messengers/telegram.d.ts +1 -1
  10. package/dist/messengers/telegram.js +1 -1
  11. package/dist/studio/assets/{angular-html-D27LthTc.js → angular-html--XgCyfPu.js} +1 -1
  12. package/dist/studio/assets/{angular-ts-DtNL2gQ7.js → angular-ts-Dt-feQIe.js} +1 -1
  13. package/dist/studio/assets/{apl-BgEcDqM0.js → apl-B7ymkyp4.js} +1 -1
  14. package/dist/studio/assets/{astro-CstbRF9e.js → astro-Ce5cw2JI.js} +1 -1
  15. package/dist/studio/assets/{blade-CLG-7epG.js → blade-DL-aXwjv.js} +1 -1
  16. package/dist/studio/assets/{c-CssQqwxO.js → c-CFfr09UF.js} +1 -1
  17. package/dist/studio/assets/{cobol-CjmzHCjg.js → cobol-Ba1f5ZqR.js} +1 -1
  18. package/dist/studio/assets/{coffee-B_rqYPkp.js → coffee-BG2_viYI.js} +1 -1
  19. package/dist/studio/assets/{cpp-5YyZJlb7.js → cpp-pU5HgBva.js} +1 -1
  20. package/dist/studio/assets/{crystal-D7uKze0i.js → crystal-Dlm_uR4r.js} +1 -1
  21. package/dist/studio/assets/{css-k9oPgg7G.js → css-tUC4TMTn.js} +1 -1
  22. package/dist/studio/assets/{edge-CGgsSt0x.js → edge-CQuSKMUt.js} +1 -1
  23. package/dist/studio/assets/{elixir-BX_d5Evo.js → elixir-BmIB-Wi1.js} +1 -1
  24. package/dist/studio/assets/{elm-DENxDm5e.js → elm-ByVNCtDB.js} +1 -1
  25. package/dist/studio/assets/{erb-DvYOup03.js → erb-DO4uDxTq.js} +1 -1
  26. package/dist/studio/assets/{git-rebase-BsAdTS5A.js → git-rebase-CT8LXapC.js} +1 -1
  27. package/dist/studio/assets/{glimmer-js-e0h98Z67.js → glimmer-js-DzIT0v-m.js} +1 -1
  28. package/dist/studio/assets/{glimmer-ts-C9s5Kv8m.js → glimmer-ts-znG2j9R4.js} +1 -1
  29. package/dist/studio/assets/{glsl-CCiyeTRs.js → glsl-C1p8U_gW.js} +1 -1
  30. package/dist/studio/assets/{graphql-BRtHwsqk.js → graphql-CFqegryf.js} +1 -1
  31. package/dist/studio/assets/{hack-Dnt0QXHh.js → hack-BfVsNhqs.js} +1 -1
  32. package/dist/studio/assets/{haml-EXGmzuB1.js → haml-DVcEksY5.js} +1 -1
  33. package/dist/studio/assets/{handlebars-CzyBIDJE.js → handlebars-DSWgWCJ4.js} +1 -1
  34. package/dist/studio/assets/{highlighted-body-OFNGDK62-CQUFKLNu.js → highlighted-body-OFNGDK62-BIm4UpTS.js} +1 -1
  35. package/dist/studio/assets/{html-BAT8b_VM.js → html-C-lP7-T4.js} +1 -1
  36. package/dist/studio/assets/{html-derivative-7tkS-r6F.js → html-derivative-ByukJopb.js} +1 -1
  37. package/dist/studio/assets/{http-Cgka02Qq.js → http-Bax2fYIk.js} +1 -1
  38. package/dist/studio/assets/{hurl-Cbkh8WEw.js → hurl-BrI2qfvy.js} +1 -1
  39. package/dist/studio/assets/{index-D6n8vpkp.js → index-DNSTOyBe.js} +5 -5
  40. package/dist/studio/assets/{java-DrRKiUno.js → java-ZiR-uym-.js} +1 -1
  41. package/dist/studio/assets/{javascript-9LAnHOxD.js → javascript-Dhhw85Vr.js} +1 -1
  42. package/dist/studio/assets/{jinja-CqRt4prs.js → jinja-DqSGkgE4.js} +1 -1
  43. package/dist/studio/assets/{jison-BX-IOQpJ.js → jison-CwQ0BO-q.js} +1 -1
  44. package/dist/studio/assets/{json-dOrE-En8.js → json-Je3YfUTE.js} +1 -1
  45. package/dist/studio/assets/{jsx-BSTPfqWX.js → jsx-Da-dLbW1.js} +1 -1
  46. package/dist/studio/assets/{julia-Dvz-BPmf.js → julia-CBJ0H-0z.js} +1 -1
  47. package/dist/studio/assets/{just-BHQm0Atq.js → just-CnuRC_nd.js} +1 -1
  48. package/dist/studio/assets/{latex-CxdhxuXv.js → latex-gZANCito.js} +1 -1
  49. package/dist/studio/assets/{liquid-D-hM-Q_F.js → liquid-0U9aXoFI.js} +1 -1
  50. package/dist/studio/assets/{lua-5qtqjLHq.js → lua-CX_TqMxt.js} +1 -1
  51. package/dist/studio/assets/{marko-5FJaM2co.js → marko-StSURz0o.js} +1 -1
  52. package/dist/studio/assets/{mdc-BhYW7lCG.js → mdc-CXZpf9k1.js} +1 -1
  53. package/dist/studio/assets/mermaid-GHXKKRXX-CqDQH2-r.js +1 -0
  54. package/dist/studio/assets/{nginx-rtAXrRye.js → nginx-3Q2L4366.js} +1 -1
  55. package/dist/studio/assets/{nim-DQSmaN9U.js → nim-CqX_5eXP.js} +1 -1
  56. package/dist/studio/assets/{perl-B54AdcaE.js → perl-CLOu1GnZ.js} +1 -1
  57. package/dist/studio/assets/{php-DpvTxCny.js → php-C1vkiu4h.js} +1 -1
  58. package/dist/studio/assets/{pug-Cyffw0Ho.js → pug-Cg3cFp5y.js} +1 -1
  59. package/dist/studio/assets/{qml-CxRetSkO.js → qml-DhKeHMwt.js} +1 -1
  60. package/dist/studio/assets/{r-CXWRxrXc.js → r--Lg2-Sir.js} +1 -1
  61. package/dist/studio/assets/{razor-BJzI-zc9.js → razor-Cjptf146.js} +1 -1
  62. package/dist/studio/assets/{regexp-dqxdfrnE.js → regexp-fS0DAwei.js} +1 -1
  63. package/dist/studio/assets/{rst-BW7eKYj4.js → rst-BBajBzk-.js} +1 -1
  64. package/dist/studio/assets/{ruby-D5Npyj8-.js → ruby-KvFedogM.js} +1 -1
  65. package/dist/studio/assets/{sas-DZLppjul.js → sas-D6p27LWr.js} +1 -1
  66. package/dist/studio/assets/{scss-CbqoxyAe.js → scss-6jXfJVsd.js} +1 -1
  67. package/dist/studio/assets/{shellscript-CFHqBeXu.js → shellscript-BK0Qbt1B.js} +1 -1
  68. package/dist/studio/assets/{shellsession-CbZDA4Bf.js → shellsession-BsXmVRU4.js} +1 -1
  69. package/dist/studio/assets/{soy-PImjtV58.js → soy-BKtGCXkJ.js} +1 -1
  70. package/dist/studio/assets/{sql-DhGo8urW.js → sql-vSUKslBj.js} +1 -1
  71. package/dist/studio/assets/{stata-CjHWbU2v.js → stata-BQ0iXcs9.js} +1 -1
  72. package/dist/studio/assets/{surrealql-o8Qr4t56.js → surrealql-v5pXHIwP.js} +1 -1
  73. package/dist/studio/assets/{svelte-DlSIyEV1.js → svelte-BMFjqgJb.js} +1 -1
  74. package/dist/studio/assets/{templ-qizfwU1w.js → templ-DYMTOmIJ.js} +1 -1
  75. package/dist/studio/assets/{tex-Ca7T661H.js → tex-BoQem9gj.js} +1 -1
  76. package/dist/studio/assets/{ts-tags-DUmjLkgl.js → ts-tags-Kp2pAlsd.js} +1 -1
  77. package/dist/studio/assets/{tsx-CfwgIqHW.js → tsx-DaB2J5uo.js} +1 -1
  78. package/dist/studio/assets/{twig-D7NAYUBY.js → twig-DohCGJPH.js} +1 -1
  79. package/dist/studio/assets/{typescript-Bbz9oX-P.js → typescript-BGG-5I-T.js} +1 -1
  80. package/dist/studio/assets/{vue-vYpz06zQ.js → vue-CCDLUl9R.js} +1 -1
  81. package/dist/studio/assets/{vue-html-CcxTb_Jn.js → vue-html-et9GYlaF.js} +1 -1
  82. package/dist/studio/assets/{vue-vine-DW4RqCKF.js → vue-vine-C561z6bx.js} +1 -1
  83. package/dist/studio/assets/{xml-R4LZ_u4f.js → xml-CJBA1ZPm.js} +1 -1
  84. package/dist/studio/assets/{xsl-CS-xzp3L.js → xsl-De-lf9XG.js} +1 -1
  85. package/dist/studio/assets/{yaml-CqDWbYXd.js → yaml-BcMKxf75.js} +1 -1
  86. package/dist/studio/index.html +1 -1
  87. package/dist/think.d.ts +2 -2
  88. package/dist/think.js +121 -31
  89. package/dist/think.js.map +1 -1
  90. package/dist/workflows.d.ts +1 -1
  91. package/docs/getting-started.md +11 -11
  92. package/docs/index.md +10 -13
  93. package/docs/lifecycle-hooks.md +14 -12
  94. package/package.json +7 -6
  95. package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["initCommand","scaffoldFromTemplate","readTextIfExists","initCommand"],"sources":["../../src/cli/init.ts","../../src/cli/inspect.ts","../../src/cli/target.ts","../../src/cli/connect.ts","../../src/cli/state.ts","../../src/cli/studio-config.ts","../../src/cli/studio.ts","../../src/cli/types.ts","../../src/cli/create.ts","../../src/cli/index.ts"],"sourcesContent":["import { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n fileExists,\n gitOutcomeMessage,\n initCommand as scaffoldFromTemplate,\n initializeGit,\n looksLikeThinkApp,\n packageName,\n readTextIfExists,\n runNpmInstall,\n type GitInitOutcome,\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 const gitOutcome = await initializeGit(root, {\n gitRunner: options.gitRunner,\n isInsideGitRepo: options.isInsideGitRepo\n });\n\n if (options.install ?? true) {\n await (options.installRunner ?? runNpmInstall)(root);\n }\n\n printSuccess(plan, skipped, options.install ?? true, gitOutcome);\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: \".gitignore\",\n content: gitignore()\n },\n {\n path: \".oxlintrc.json\",\n content: oxlintConfig()\n },\n {\n path: \".oxfmtrc.json\",\n content: oxfmtConfig()\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 \"Would initialize a git repository (skipped if already inside one).\",\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 gitOutcome: GitInitOutcome\n): void {\n const lines = [\n `Added Think to ${plan.root}.`,\n gitOutcomeMessage(gitOutcome),\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\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.202\",\n \"workers-ai-provider\": \"^3.2.1\"\n};\n\nexport const THIRD_PARTY_DEV_DEPENDENCIES: Record<string, string> = {\n \"@cloudflare/vite-plugin\": \"^1.42.3\",\n \"@cloudflare/workers-types\": \"^4.20260625.1\",\n oxfmt: \"^0.56.0\",\n oxlint: \"^1.71.0\",\n typescript: \"^6.0.3\",\n vite: \"^8.1.0\",\n wrangler: \"^4.105.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 format: \"oxfmt --write .\",\n \"format:check\": \"oxfmt --check .\",\n lint: \"oxlint .\",\n typecheck: \"tsc --noEmit\",\n check: \"npm run format:check && npm run lint && npm run typecheck\"\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.7-code\",',\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\n// Kept in sync with `think-starters/basic/.gitignore` (the canonical starter\n// ignore file) so scaffolded and augmented projects ignore the same set.\nfunction gitignore(): string {\n return `# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional stylelint cache\n.stylelintcache\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variable files\n.env\n.env.*\n!.env.example\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\nout\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n.output\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and not Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# vuepress v2.x temp directory\n.temp\n\n# Sveltekit cache directory\n.svelte-kit/\n\n# vitepress build output\n**/.vitepress/dist\n\n# vitepress cache directory\n**/.vitepress/cache\n\n# Docusaurus cache and generated files\n.docusaurus\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# Firebase cache directory\n.firebase/\n\n# TernJS port file\n.tern-port\n\n# Stores VSCode versions used for testing VSCode extensions\n.vscode-test\n\n# pnpm\n.pnpm-store\n\n# yarn v3\n.pnp.*\n.yarn/*\n!.yarn/patches\n!.yarn/plugins\n!.yarn/releases\n!.yarn/sdks\n!.yarn/versions\n\n# Vite files\nvite.config.js.timestamp-*\nvite.config.ts.timestamp-*\n.vite/\n\n\n.wrangler\n.dev.vars\n.DS_Store\n`;\n}\n\nfunction oxlintConfig(): string {\n return `${JSON.stringify(\n {\n $schema: \"./node_modules/oxlint/configuration_schema.json\",\n plugins: [\"react\", \"jsx-a11y\", \"typescript\"],\n categories: {\n correctness: \"error\"\n },\n rules: {\n \"no-explicit-any\": \"error\",\n \"typescript/no-deprecated\": \"warn\",\n \"react-hooks/exhaustive-deps\": \"warn\",\n \"no-unused-vars\": [\n \"error\",\n {\n argsIgnorePattern: \"^_\",\n varsIgnorePattern: \"^_\",\n caughtErrorsIgnorePattern: \"^_\"\n }\n ]\n },\n ignorePatterns: [\"**/env.d.ts\", \"**/think.d.ts\"]\n },\n null,\n 2\n )}\\n`;\n}\n\nfunction oxfmtConfig(): string {\n return `${JSON.stringify(\n {\n $schema: \"./node_modules/oxfmt/configuration_schema.json\",\n trailingComma: \"none\",\n printWidth: 80,\n experimentalSortPackageJson: false,\n ignorePatterns: [\"**/think.d.ts\"]\n },\n null,\n 2\n )}\\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","/**\n * Browser-safe, IO-free helpers for turning loose connection inputs (a remote\n * `url` or a local `host`, an agent id, an instance, a token, extra query\n * params) into the concrete `{ host, protocol, basePath, query }` an\n * `AgentClient`/`useAgent` needs.\n *\n * This module is deliberately dependency-free so it can be imported by both the\n * Node-side runtime CLI (`connect.ts`) and the browser Studio app. The\n * manifest-aware resolution (friendly agent ids/aliases) lives in `connect.ts`;\n * everything here is pure string math.\n */\n\n/**\n * Mirror the default `routeAgentRequest` segment derivation so a raw agent name\n * (e.g. a class name) maps to the same route the server exposes.\n */\nexport function camelCaseToKebabCase(str: string): string {\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/** Normalize a route prefix to a slash-free segment (default `agents`). */\nexport function normalizeRoutePrefix(routePrefix?: string): string {\n const trimmed = (routePrefix ?? \"/agents\").replace(/^\\/+|\\/+$/g, \"\");\n return trimmed || \"agents\";\n}\n\nexport interface DeriveWsTargetInput {\n /** Agent id/alias or raw route segment. */\n agent: string;\n /** Agent instance name. Defaults to `default`. */\n instance?: string;\n /** Remote origin, e.g. `https://app.example.com` (implies `wss`). */\n url?: string;\n /** Local host[:port]. Defaults to `localhost:5173` (Vite). */\n host?: string;\n /** Override the derived protocol. */\n protocol?: string;\n /** Bearer-style token sent as the `token` query param. */\n token?: string;\n /** Extra query params, either `key=value` strings or a record. */\n query?: string[] | Record<string, string>;\n /** Override the route prefix (default `agents`). */\n routePrefix?: string;\n /**\n * When `true`, `agent` is already a canonical route segment (e.g. a manifest\n * id resolved by the server) and is used verbatim (only URL-encoded).\n * Otherwise it is kebab-cased to match default `routeAgentRequest` behavior.\n */\n canonicalAgent?: boolean;\n}\n\nexport interface WsTarget {\n host: string;\n protocol: \"ws\" | \"wss\";\n /** URL pathname without a leading slash, suitable for `basePath`. */\n basePath: string;\n query: Record<string, string>;\n instance: string;\n /** The route segment used for the agent (canonical or kebab-cased). */\n segment: string;\n}\n\nfunction parseQuery(\n query: string[] | Record<string, string> | undefined,\n token: string | undefined\n): Record<string, string> {\n const result: Record<string, string> = {};\n if (token) result.token = token;\n if (!query) return result;\n if (Array.isArray(query)) {\n for (const pair of query) {\n const eq = pair.indexOf(\"=\");\n if (eq <= 0) {\n throw new Error(`Invalid query \"${pair}\" (expected key=value).`);\n }\n result[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return result;\n }\n for (const [key, value] of Object.entries(query)) {\n result[key] = value;\n }\n return result;\n}\n\n/**\n * Resolve host/protocol/basePath/query from loose inputs. Pure (no IO), so it\n * is safe in the browser and trivially unit-testable.\n */\nexport function deriveWsTarget(input: DeriveWsTargetInput): WsTarget {\n const instance = input.instance?.trim() || \"default\";\n const prefix = normalizeRoutePrefix(input.routePrefix);\n\n let host: string;\n let protocol: \"ws\" | \"wss\";\n if (input.url) {\n let origin: URL;\n try {\n origin = new URL(input.url);\n } catch {\n throw new Error(`Invalid url \"${input.url}\" (expected a full origin).`);\n }\n if (!origin.host) {\n throw new Error(\n `Invalid url \"${input.url}\" (missing host — include a scheme, e.g. https://host).`\n );\n }\n host = origin.host;\n protocol =\n input.protocol === \"ws\" || input.protocol === \"wss\"\n ? input.protocol\n : origin.protocol === \"https:\" || origin.protocol === \"wss:\"\n ? \"wss\"\n : \"ws\";\n } else {\n host = input.host?.trim() || \"localhost:5173\";\n protocol = input.protocol === \"wss\" ? \"wss\" : \"ws\";\n }\n\n const segment = input.canonicalAgent\n ? input.agent\n : camelCaseToKebabCase(input.agent);\n\n const basePath = [\n prefix,\n encodeURIComponent(segment),\n encodeURIComponent(instance)\n ].join(\"/\");\n\n return {\n host,\n protocol,\n basePath,\n query: parseQuery(input.query, input.token),\n instance,\n segment\n };\n}\n","import path from \"node:path\";\nimport { AgentClient } from \"agents/client\";\nimport type {\n ThinkFrameworkAgent,\n ThinkFrameworkManifest\n} from \"../framework/manifest\";\nimport { resolveThinkManifest } from \"../framework/project\";\nimport { deriveWsTarget } from \"./target\";\n\ntype ManifestAgents = Pick<ThinkFrameworkManifest, \"agents\">;\n\nfunction findTopLevelAgent(\n manifest: ManifestAgents,\n agent: string\n): ThinkFrameworkAgent | undefined {\n return manifest.agents.find(\n (entry) =>\n entry.kind === \"top-level\" &&\n (entry.id === agent ||\n entry.bindingName === agent ||\n entry.className === agent ||\n entry.aliases.includes(agent))\n );\n}\n\n/** Options shared by the runtime CLI commands (`chat` and `state`). */\nexport interface ConnectOptions {\n /** Manifest agent id/alias (e.g. `support`) or a raw route segment. */\n agent: string;\n /** Agent instance name. Defaults to `default`. */\n instance?: string;\n /** Remote origin, e.g. `https://app.example.com` (implies `wss`). */\n url?: string;\n /** Local host[:port]. Defaults to `localhost:5173` (Vite). */\n host?: string;\n /** Override the derived protocol. */\n protocol?: string;\n /** Bearer-style token sent as the `token` query param. */\n token?: string;\n /** Extra query params as `key=value` strings (repeatable). */\n query?: string[];\n /** Project root used to discover the Think manifest. Defaults to cwd. */\n root?: string;\n /** Override the Think route prefix. */\n routePrefix?: string;\n}\n\n/** A fully-resolved connection target — pure, derived without any IO. */\nexport interface ResolvedTarget {\n host: string;\n protocol: \"ws\" | \"wss\";\n /** URL pathname without a leading slash, suitable for `AgentClient.basePath`. */\n basePath: string;\n query: Record<string, string>;\n /** The agent identifier the user asked for (manifest id or raw segment). */\n agent: string;\n instance: string;\n /** Whether `agent` matched an entry in the supplied manifest. */\n matchedManifest: boolean;\n}\n\nexport interface ResolveTargetInput extends ConnectOptions {\n manifest?: ManifestAgents | null;\n}\n\n/**\n * Resolve target/URL/auth details from CLI options. Pure (no IO) so it can be\n * unit-tested with a synthetic manifest. The manifest, when supplied, lets the\n * CLI accept friendly agent ids/aliases and honor a custom route prefix; when\n * the agent isn't found we treat it as a literal route segment (kebab-cased to\n * match the default `routeAgentRequest` behavior) so the CLI also works against\n * an arbitrary deployed worker. The browser-safe URL/query math lives in\n * {@link deriveWsTarget}; this layer only adds manifest awareness.\n */\nexport function resolveTarget(input: ResolveTargetInput): ResolvedTarget {\n const topLevel = input.manifest\n ? findTopLevelAgent(input.manifest, input.agent)\n : undefined;\n const matchedManifest = topLevel !== undefined;\n\n // Manifest match → use the canonical route id (the server resolves ids,\n // aliases, binding names, and class names back to the agents class segment).\n // Otherwise treat the input as a literal segment, kebab-cased to match the\n // default `routeAgentRequest` behavior.\n const derived = deriveWsTarget({\n agent: topLevel ? topLevel.id : input.agent,\n canonicalAgent: topLevel !== undefined,\n instance: input.instance,\n url: input.url,\n host: input.host,\n protocol: input.protocol,\n token: input.token,\n query: input.query,\n routePrefix: input.routePrefix\n });\n\n return {\n host: derived.host,\n protocol: derived.protocol,\n basePath: derived.basePath,\n query: derived.query,\n agent: input.agent,\n instance: derived.instance,\n matchedManifest\n };\n}\n\nasync function loadManifest(\n root: string | undefined,\n routePrefix: string | undefined\n): Promise<ThinkFrameworkManifest | null> {\n try {\n return await resolveThinkManifest(\n { routePrefix },\n path.resolve(root ?? process.cwd())\n );\n } catch {\n // Best-effort: outside a Think project the manifest can't be discovered,\n // so the CLI falls back to treating the agent as a raw route segment.\n return null;\n }\n}\n\nexport interface ThinkConnection {\n client: AgentClient;\n target: ResolvedTarget;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;\n\n/**\n * Resolve once the client receives its identity handshake, or reject after\n * `timeoutMs` (covers unreachable hosts, which otherwise retry silently).\n */\nexport function waitForClientReady(\n client: AgentClient,\n timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n reject(\n new Error(\n `Timed out after ${timeoutMs}ms connecting to the agent. ` +\n \"Check the host/url, that the dev server or worker is running, and the token.\"\n )\n );\n }, timeoutMs);\n client.ready.then(\n () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve();\n },\n (error: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n );\n });\n}\n\n/**\n * Resolve a target (loading the local manifest when present) and open a\n * connected {@link AgentClient} backed by Node's global `WebSocket`.\n */\nexport async function connectToThinkAgent(\n options: ConnectOptions\n): Promise<ThinkConnection> {\n const WebSocketImpl = globalThis.WebSocket;\n if (typeof WebSocketImpl !== \"function\") {\n throw new Error(\n \"No global WebSocket found. The `think` runtime CLI requires Node.js 24+ \" +\n \"(which provides a built-in WebSocket).\"\n );\n }\n\n const manifest = await loadManifest(options.root, options.routePrefix);\n const target = resolveTarget({ ...options, manifest });\n\n const client = new AgentClient({\n agent: target.agent,\n name: target.instance,\n basePath: target.basePath,\n host: target.host,\n protocol: target.protocol,\n query: target.query,\n WebSocket: WebSocketImpl as unknown as typeof WebSocket\n });\n\n return { client, target };\n}\n","import type { UIMessage } from \"ai\";\nimport { CHAT_MESSAGE_TYPES } from \"agents/chat\";\nimport {\n type ConnectOptions,\n connectToThinkAgent,\n waitForClientReady\n} from \"./connect\";\n\n/** Minimal structural view of the socket the state snapshot needs. */\ninterface MessageSocket {\n addEventListener(\n type: \"message\",\n listener: (event: { data: unknown }) => void\n ): void;\n removeEventListener(\n type: \"message\",\n listener: (event: { data: unknown }) => void\n ): void;\n}\n\nexport type StateCommandOptions = ConnectOptions & {\n /** Emit a single machine-readable JSON object. */\n json?: boolean;\n /** Number of recent messages to include. Defaults to 10. */\n limit?: number;\n};\n\nconst SNAPSHOT_WAIT_MS = 1_000;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction messageText(message: UIMessage): string {\n let text = \"\";\n for (const part of message.parts) {\n if (part.type === \"text\") text += part.text;\n }\n return text;\n}\n\nexport async function stateCommand(\n options: StateCommandOptions\n): Promise<void> {\n const { client, target } = await connectToThinkAgent(options);\n const socket = client as unknown as MessageSocket;\n\n let messages: UIMessage[] = [];\n let gotSnapshot = false;\n const listener = (event: { data: unknown }) => {\n if (typeof event.data !== \"string\") return;\n let frame: Record<string, unknown>;\n try {\n frame = JSON.parse(event.data) as Record<string, unknown>;\n } catch {\n return;\n }\n if (\n frame.type === CHAT_MESSAGE_TYPES.CHAT_MESSAGES &&\n Array.isArray(frame.messages)\n ) {\n messages = frame.messages as UIMessage[];\n gotSnapshot = true;\n }\n };\n socket.addEventListener(\"message\", listener);\n\n try {\n await waitForClientReady(client);\n } catch (error) {\n socket.removeEventListener(\"message\", listener);\n client.close();\n throw error;\n }\n\n // Identity arrives with `ready`; the history snapshot and state broadcast\n // follow shortly after. Wait a beat for them (no server changes needed —\n // we only read connect-time frames).\n const deadline = Date.now() + SNAPSHOT_WAIT_MS;\n while (!gotSnapshot && Date.now() < deadline) {\n await delay(50);\n }\n socket.removeEventListener(\"message\", listener);\n\n const limit = options.limit ?? 10;\n const recent = limit > 0 ? messages.slice(-limit) : messages;\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n agent: client.agent,\n name: client.name,\n state: client.state ?? null,\n messages: recent\n },\n null,\n 2\n )\n );\n client.close();\n return;\n }\n\n const scheme = target.protocol === \"wss\" ? \"https\" : \"http\";\n const lines = [\n \"Think state\",\n `Endpoint: ${scheme}://${target.host}/${target.basePath}`,\n `Agent: ${client.agent}`,\n `Instance: ${client.name}`,\n \"\",\n \"State:\",\n client.state === undefined\n ? \"- none\"\n : indent(JSON.stringify(client.state, null, 2)),\n \"\",\n `Recent messages (${recent.length}):`,\n ...(recent.length === 0\n ? [\"- none\"]\n : recent.map((message) => {\n const text = messageText(message).trim();\n return `- ${message.role}: ${text || \"(no text)\"}`;\n }))\n ];\n console.log(lines.join(\"\\n\"));\n client.close();\n}\n\nfunction indent(value: string): string {\n return value\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n}\n","/**\n * Shared, dependency-free types and helpers for the `/__studio/config.json`\n * document the `think studio` launcher serves to the Studio SPA. Kept pure so\n * it is importable from both the Node launcher (`studio.ts`) and the browser\n * app (type-only) without dragging in any runtime dependency.\n */\n\n/** An agent the Studio connect view can offer as a picker option. */\nexport interface StudioAgentOption {\n /** Canonical route id (what the server resolves). */\n id: string;\n /** Human label for the picker (defaults to the id). */\n label: string;\n}\n\n/** The initial connection the launcher was pointed at. */\nexport interface StudioTarget {\n /** Remote origin, e.g. `https://app.example.com`. */\n url?: string;\n /** Local host[:port]. */\n host?: string;\n /** Override the derived protocol. */\n protocol?: \"ws\" | \"wss\";\n /** Auth token, sent as the `token` query param. */\n token?: string;\n /** Initial agent id/segment. */\n agent?: string;\n /** Initial instance name. */\n instance?: string;\n /** Route prefix (default `agents`). */\n routePrefix?: string;\n}\n\nexport interface StudioConfig {\n target: StudioTarget;\n /** Top-level agents discovered from the local manifest (empty for remote). */\n agents: StudioAgentOption[];\n}\n\n/** Minimal manifest shape needed to build the agent picker options. */\ninterface ManifestLike {\n agents: Array<{\n id: string;\n kind: string;\n bindingName?: string;\n }>;\n}\n\n/**\n * Build the `/__studio/config.json` payload from the resolved target and the\n * (optional) local manifest. Pure so it can be unit-tested directly.\n */\nexport function buildStudioConfig(input: {\n target: StudioTarget;\n manifest?: ManifestLike | null;\n}): StudioConfig {\n const agents: StudioAgentOption[] = (input.manifest?.agents ?? [])\n .filter((entry) => entry.kind === \"top-level\")\n .map((entry) => ({ id: entry.id, label: entry.bindingName || entry.id }));\n return { target: input.target, agents };\n}\n","import { spawn } from \"node:child_process\";\nimport { createReadStream } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { createServer } from \"node:http\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { resolveThinkManifest } from \"../framework/project\";\nimport {\n buildStudioConfig,\n type StudioConfig,\n type StudioTarget\n} from \"./studio-config\";\n\nexport interface StudioCommandOptions {\n /** Manifest agent id/alias or raw route segment to pre-fill the connect view. */\n agent?: string;\n /** Agent instance name to pre-fill. */\n instance?: string;\n /** Remote origin, e.g. `https://app.example.com`. */\n url?: string;\n /** Local host[:port]. */\n host?: string;\n /** Override the derived protocol. */\n protocol?: string;\n /** Auth token, forwarded to the connect view. */\n token?: string;\n /** Extra query params as `key=value` strings. */\n query?: string[];\n /** Project root used to discover the Think manifest. */\n root?: string;\n /** Override the Think route prefix. */\n routePrefix?: string;\n /** Port for the local Studio server. Defaults to 4321. */\n port?: number;\n /** Whether to open the browser automatically. Defaults to true. */\n open?: boolean;\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".ico\": \"image/x-icon\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".map\": \"application/json; charset=utf-8\"\n};\n\nfunction studioDistDir(): string {\n // At runtime this module lives in dist/cli; the built SPA is in dist/studio.\n return path.resolve(\n path.dirname(fileURLToPath(import.meta.url)),\n \"../studio\"\n );\n}\n\nasync function loadManifestAgents(\n root: string | undefined,\n routePrefix: string | undefined\n) {\n try {\n return await resolveThinkManifest(\n { routePrefix },\n path.resolve(root ?? process.cwd())\n );\n } catch {\n return null;\n }\n}\n\nfunction buildTarget(options: StudioCommandOptions): StudioTarget {\n const target: StudioTarget = {};\n if (options.url) target.url = options.url;\n if (options.host) target.host = options.host;\n if (options.protocol === \"ws\" || options.protocol === \"wss\") {\n target.protocol = options.protocol;\n }\n if (options.token) target.token = options.token;\n if (options.agent) target.agent = options.agent;\n if (options.instance) target.instance = options.instance;\n if (options.routePrefix) target.routePrefix = options.routePrefix;\n return target;\n}\n\nfunction openBrowser(url: string): void {\n const command =\n process.platform === \"darwin\"\n ? \"open\"\n : process.platform === \"win32\"\n ? \"start\"\n : \"xdg-open\";\n try {\n const child = spawn(command, [url], {\n stdio: \"ignore\",\n detached: true,\n shell: process.platform === \"win32\"\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // Best-effort — the URL is printed regardless.\n }\n}\n\n/** Resolve a file under `root`, guarding against path traversal. */\nfunction safeResolve(root: string, urlPath: string): string | null {\n let decoded: string;\n try {\n decoded = decodeURIComponent(urlPath.split(\"?\")[0]);\n } catch {\n // Malformed percent-encoding (e.g. `/%` or `/%zz`) makes decodeURIComponent\n // throw. Treat it as unresolvable (404) rather than letting the URIError\n // escape the request handler and crash the server.\n return null;\n }\n const resolved = path.resolve(root, `.${decoded}`);\n if (resolved !== root && !resolved.startsWith(root + path.sep)) return null;\n return resolved;\n}\n\nexport async function studioCommand(\n options: StudioCommandOptions\n): Promise<void> {\n const distDir = studioDistDir();\n try {\n await stat(path.join(distDir, \"index.html\"));\n } catch {\n throw new Error(\n `Think Studio assets were not found at ${distDir}. ` +\n \"Reinstall @cloudflare/think (the published package ships the prebuilt Studio), \" +\n \"or run the package build.\"\n );\n }\n\n const manifest = await loadManifestAgents(options.root, options.routePrefix);\n const config: StudioConfig = buildStudioConfig({\n target: buildTarget(options),\n manifest\n });\n const configJson = JSON.stringify(config);\n\n const server = createServer((req, res) => {\n const urlPath = req.url ?? \"/\";\n\n if (urlPath === \"/__studio/config.json\") {\n res.writeHead(200, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"cache-control\": \"no-store\"\n });\n res.end(configJson);\n return;\n }\n\n const rawPath = urlPath.split(\"?\")[0];\n const candidate =\n rawPath === \"/\"\n ? path.join(distDir, \"index.html\")\n : safeResolve(distDir, rawPath);\n\n const serve = (filePath: string) => {\n const ext = path.extname(filePath).toLowerCase();\n const stream = createReadStream(filePath);\n stream.on(\"error\", () => {\n // The stream can fail to open (file deleted after stat(), permissions)\n // or fault mid-read. Only send a 500 if we haven't already committed\n // the 200 status line; otherwise the headers are gone and the only\n // correct action is to tear down the (now-corrupt) response.\n if (res.headersSent) {\n res.destroy();\n } else {\n res.writeHead(500);\n res.end(\"Internal error\");\n }\n });\n // Defer the 200 until the file actually opens, so an open error can still\n // produce a clean 500 instead of throwing ERR_HTTP_HEADERS_SENT.\n stream.once(\"open\", () => {\n res.writeHead(200, {\n \"content-type\": CONTENT_TYPES[ext] ?? \"application/octet-stream\"\n });\n stream.pipe(res);\n });\n };\n\n if (!candidate) {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n\n stat(candidate)\n .then((s) => {\n if (s.isFile()) {\n serve(candidate);\n } else {\n // SPA fallback for directory/unknown routes.\n serve(path.join(distDir, \"index.html\"));\n }\n })\n .catch(() => serve(path.join(distDir, \"index.html\")));\n });\n\n const startPort = options.port ?? 4321;\n const port = await listen(server, startPort);\n const studioUrl = `http://localhost:${port}/`;\n\n console.log(`Think Studio running at ${studioUrl}`);\n console.log(\"Press Ctrl+C to stop.\");\n if (options.open !== false) openBrowser(studioUrl);\n\n await new Promise<void>((resolve) => {\n const shutdown = () => {\n server.close(() => resolve());\n };\n process.once(\"SIGINT\", shutdown);\n process.once(\"SIGTERM\", shutdown);\n });\n}\n\n/** Listen on `startPort`, advancing on EADDRINUSE up to 20 ports. */\nfunction listen(\n server: ReturnType<typeof createServer>,\n startPort: number\n): Promise<number> {\n return new Promise((resolve, reject) => {\n let attempt = 0;\n const tryPort = (port: number) => {\n const onError = (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" && attempt < 20) {\n attempt += 1;\n tryPort(port + 1);\n } else {\n reject(err);\n }\n };\n server.once(\"error\", onError);\n // Bind to loopback only: the config payload can carry an auth token, so\n // the launcher must not be reachable from other devices on the network.\n server.listen(port, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onError);\n const address = server.address();\n resolve(typeof address === \"object\" && address ? address.port : port);\n });\n };\n tryPort(startPort);\n });\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 type { Argv } from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { initCommand } from \"./init\";\nimport { inspectCommand } from \"./inspect\";\nimport { stateCommand } from \"./state\";\nimport { studioCommand } from \"./studio\";\nimport { typesCommand } from \"./types\";\n\nfunction connectionOptions<T>(cmd: Argv<T>) {\n return cmd\n .positional(\"agent\", {\n type: \"string\",\n describe: \"Agent id/alias (from the manifest) or a raw route segment\"\n })\n .positional(\"instance\", {\n type: \"string\",\n describe: \"Agent instance name\",\n default: \"default\"\n })\n .option(\"url\", {\n type: \"string\",\n describe: \"Remote origin, e.g. https://app.example.com (implies wss)\"\n })\n .option(\"host\", {\n type: \"string\",\n describe: \"Local host[:port] (default: localhost:5173)\"\n })\n .option(\"protocol\", {\n type: \"string\",\n choices: [\"ws\", \"wss\"] as const,\n describe: \"Override the WebSocket protocol\"\n })\n .option(\"token\", {\n type: \"string\",\n describe: \"Auth token, sent as the `token` query param\"\n })\n .option(\"query\", {\n type: \"string\",\n array: true,\n describe: \"Extra query params as key=value (repeatable)\"\n })\n .option(\"root\", {\n type: \"string\",\n describe: \"Project root used to discover the Think manifest\",\n default: process.cwd()\n })\n .option(\"route-prefix\", {\n type: \"string\",\n describe: \"Override the Think route prefix\"\n });\n}\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 (omit to choose)\"\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 .command(\n \"studio [agent] [instance]\",\n \"Launch Think Studio — a local web app to chat with and inspect a running Think instance (local or remote)\",\n (cmd) =>\n connectionOptions(cmd)\n .option(\"port\", {\n type: \"number\",\n describe: \"Port for the local Studio server\",\n default: 4321\n })\n .option(\"open\", {\n type: \"boolean\",\n describe: \"Open the browser automatically\",\n default: true\n }),\n async (args) => {\n await studioCommand({\n agent: args.agent as string | undefined,\n instance: args.instance,\n url: args.url,\n host: args.host,\n protocol: args.protocol,\n token: args.token,\n query: args.query,\n root: args.root,\n routePrefix: args.routePrefix,\n port: args.port,\n open: args.open\n });\n }\n )\n .command(\n \"state <agent> [instance]\",\n \"Print a running Think agent's identity, state, and recent history (read-only)\",\n (cmd) =>\n connectionOptions(cmd)\n .option(\"json\", {\n type: \"boolean\",\n describe: \"Print machine-readable JSON output\",\n default: false\n })\n .option(\"limit\", {\n type: \"number\",\n describe: \"Number of recent messages to include\",\n default: 10\n }),\n async (args) => {\n await stateCommand({\n agent: args.agent as string,\n instance: args.instance,\n url: args.url,\n host: args.host,\n protocol: args.protocol,\n token: args.token,\n query: args.query,\n root: args.root,\n routePrefix: args.routePrefix,\n json: args.json,\n limit: args.limit\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":";;;;;;;;;;;;;;;AAoCA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;AACF;;;;;;;;;;;AAYA,eAAsBA,cAAY,SAA4C;CAC5E,MAAM,WAAW,KAAK,QAAQ,QAAQ,QAAQ,QAAQ,IAAI,CAAC;CAC3D,MAAM,wBACJ,CAAC,QAAQ,aACR,MAAM,WAAW,KAAK,KAAK,UAAU,cAAc,CAAC;CAGvD,IAFoB,QAAQ,QAAQ,QAAQ,KAAK,CAAC,uBAEjC;EACf,MAAMC,YAAqB,OAAO;EAClC;CACF;CAEA,MAAM,uBAAuB,UAAU,OAAO;AAChD;AAEA,eAAe,uBACb,MACA,SACe;CACf,MAAM,cAAc,YAAY,QAAQ,QAAQ,KAAK,SAAS,IAAI,CAAC;CAEnE,IAAI,MAAM,kBAAkB,I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AiD;CACrD,qBAAqB;CACrB,QAAQ;AACV;AAOA,MAAa,2BAAmD;CAC9D,IAAI;CACJ,uBAAuB;AACzB;AAEA,MAAa,+BAAuD;CAClE,2BAA2B;CAC3B,6BAA6B;CAC7B,OAAO;CACP,QAAQ;CACR,YAAY;CACZ,MAAM;CACN,UAAU;AACZ;AAEA,SAAS,kBAAkB,aAA6B;CACtD,OAAO,GAAG,KAAK,UACb;EACE,MAAM;EACN,SAAS;EACT,MAAM;EACN,SAAS;GACP,KAAK;GACL,OAAO;GACP,QAAQ;GACR,OAAO;GACP,QAAQ;GACR,gBAAgB;GAChB,MAAM;GACN,WAAW;GACX,OAAO;EACT;EACA,cAAc;GACZ,GAAG;GACH,GAAG;EACL;EACA,iBAAiB,EACf,GAAG,6BACL;CACF,GACA,MACA,CACF,EAAE;AACJ;AAEA,SAAS,WAAW,aAAyC;CAI3D,OAAO;EACL;EACA;EACA;EACA;EACA;EACA,oBATmB,cACjB,mBAAmB,KAAK,UAAU,WAAW,EAAE,OAC/C,KAO+B;EACjC;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,cAAsB;CAC7B,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,qBAA6B;CACpC,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,WAAmB;CAC1B,OAAO,GAAG,KAAK,UACb;EACE,iBAAiB;GACf,QAAQ;GACR,QAAQ;GACR,kBAAkB;GAClB,QAAQ;GACR,sBAAsB;GACtB,OAAO,CAAC,2BAA2B;EACrC;EACA,SAAS;GAAC;G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AAS;CACX,CAAC,GACL,OAAO,SAAS;EACd,MAAM,cAAc;GAClB,OAAO,KAAK;GACZ,UAAU,KAAK;GACf,KAAK,KAAK;GACV,MAAM,KAAK;GACX,UAAU,KAAK;GACf,OAAO,KAAK;GACZ,OAAO,KAAK;GACZ,MAAM,KAAK;GACX,aAAa,KAAK;GAClB,MAAM,KAAK;GACX,MAAM,KAAK;EACb,CAAC;CACH,CACF,CAAC,CACA,QACC,4BACA,kFACC,QACC,kBAAkB,GAAG,CAAC,CACnB,OAAO,QAAQ;EACd,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,OAAO,KAAK;GACZ,UAAU,KAAK;GACf,KAAK,KAAK;GACV,MAAM,KAAK;GACX,UAAU,KAAK;GACf,OAAO,KAAK;GACZ,OAAO,KAAK;GACZ,MAAM,KAAK;GACX,aAAa,KAAK;GAClB,MAAM,KAAK;GACX,OAAO,KAAK;EACd,CAAC;CACH,CACF,CAAC,CACA,cAAc,GAAG,0BAA0B,CAAC,CAC5C,OAAO,CAAC,CACR,KAAK;AACV;;;AC3QA,QAAQ,KACN,4HAEF;AAEK,UAAU,CAAC,CAAC,MAAM"}
1
+ {"version":3,"file":"index.js","names":["initCommand","scaffoldFromTemplate","readTextIfExists","initCommand"],"sources":["../../src/cli/init.ts","../../src/cli/inspect.ts","../../src/cli/target.ts","../../src/cli/connect.ts","../../src/cli/state.ts","../../src/cli/studio-config.ts","../../src/cli/studio.ts","../../src/cli/types.ts","../../src/cli/create.ts","../../src/cli/index.ts"],"sourcesContent":["import { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n fileExists,\n gitOutcomeMessage,\n initCommand as scaffoldFromTemplate,\n initializeGit,\n looksLikeThinkApp,\n packageName,\n readTextIfExists,\n runNpmInstall,\n type GitInitOutcome,\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 const gitOutcome = await initializeGit(root, {\n gitRunner: options.gitRunner,\n isInsideGitRepo: options.isInsideGitRepo\n });\n\n if (options.install ?? true) {\n await (options.installRunner ?? runNpmInstall)(root);\n }\n\n printSuccess(plan, skipped, options.install ?? true, gitOutcome);\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: \".gitignore\",\n content: gitignore()\n },\n {\n path: \".oxlintrc.json\",\n content: oxlintConfig()\n },\n {\n path: \".oxfmtrc.json\",\n content: oxfmtConfig()\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 \"Would initialize a git repository (skipped if already inside one).\",\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 gitOutcome: GitInitOutcome\n): void {\n const lines = [\n `Added Think to ${plan.root}.`,\n gitOutcomeMessage(gitOutcome),\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\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`.\n// `workers-ai-provider` is intentionally NOT listed here: `@cloudflare/think`\n// depends on it directly and resolves string models through it, so scaffolded\n// projects get it transitively. Add it explicitly only if you import\n// `createWorkersAI` yourself.\nexport const THIRD_PARTY_DEPENDENCIES: Record<string, string> = {\n ai: \"^6.0.202\"\n};\n\nexport const THIRD_PARTY_DEV_DEPENDENCIES: Record<string, string> = {\n \"@cloudflare/vite-plugin\": \"^1.42.3\",\n \"@cloudflare/workers-types\": \"^4.20260629.1\",\n oxfmt: \"^0.56.0\",\n oxlint: \"^1.71.0\",\n typescript: \"^6.0.3\",\n vite: \"^8.1.0\",\n wrangler: \"^4.105.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 format: \"oxfmt --write .\",\n \"format:check\": \"oxfmt --check .\",\n lint: \"oxlint .\",\n typecheck: \"tsc --noEmit\",\n check: \"npm run format:check && npm run lint && npm run typecheck\"\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 bundledSkills from \"agents:skills\";`,\n \"\",\n \"export class Assistant extends Think<Env> {\",\n \" override getModel() {\",\n \" // Resolved via the built-in workers-ai-provider off env.AI. Use a\",\n ' // \"@cf/...\" id for Workers AI, or a \"provider/model\" slug like',\n ' // \"openai/gpt-5.5\" to route through AI Gateway.',\n ' return \"@cf/moonshotai/kimi-k2.7-code\";',\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\n// Kept in sync with `think-starters/basic/.gitignore` (the canonical starter\n// ignore file) so scaffolded and augmented projects ignore the same set.\nfunction gitignore(): string {\n return `# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional stylelint cache\n.stylelintcache\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variable files\n.env\n.env.*\n!.env.example\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\nout\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n.output\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and not Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# vuepress v2.x temp directory\n.temp\n\n# Sveltekit cache directory\n.svelte-kit/\n\n# vitepress build output\n**/.vitepress/dist\n\n# vitepress cache directory\n**/.vitepress/cache\n\n# Docusaurus cache and generated files\n.docusaurus\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# Firebase cache directory\n.firebase/\n\n# TernJS port file\n.tern-port\n\n# Stores VSCode versions used for testing VSCode extensions\n.vscode-test\n\n# pnpm\n.pnpm-store\n\n# yarn v3\n.pnp.*\n.yarn/*\n!.yarn/patches\n!.yarn/plugins\n!.yarn/releases\n!.yarn/sdks\n!.yarn/versions\n\n# Vite files\nvite.config.js.timestamp-*\nvite.config.ts.timestamp-*\n.vite/\n\n\n.wrangler\n.dev.vars\n.DS_Store\n`;\n}\n\nfunction oxlintConfig(): string {\n return `${JSON.stringify(\n {\n $schema: \"./node_modules/oxlint/configuration_schema.json\",\n plugins: [\"react\", \"jsx-a11y\", \"typescript\"],\n categories: {\n correctness: \"error\"\n },\n rules: {\n \"no-explicit-any\": \"error\",\n \"typescript/no-deprecated\": \"warn\",\n \"react-hooks/exhaustive-deps\": \"warn\",\n \"no-unused-vars\": [\n \"error\",\n {\n argsIgnorePattern: \"^_\",\n varsIgnorePattern: \"^_\",\n caughtErrorsIgnorePattern: \"^_\"\n }\n ]\n },\n ignorePatterns: [\"**/env.d.ts\", \"**/think.d.ts\"]\n },\n null,\n 2\n )}\\n`;\n}\n\nfunction oxfmtConfig(): string {\n return `${JSON.stringify(\n {\n $schema: \"./node_modules/oxfmt/configuration_schema.json\",\n trailingComma: \"none\",\n printWidth: 80,\n experimentalSortPackageJson: false,\n ignorePatterns: [\"**/think.d.ts\"]\n },\n null,\n 2\n )}\\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","/**\n * Browser-safe, IO-free helpers for turning loose connection inputs (a remote\n * `url` or a local `host`, an agent id, an instance, a token, extra query\n * params) into the concrete `{ host, protocol, basePath, query }` an\n * `AgentClient`/`useAgent` needs.\n *\n * This module is deliberately dependency-free so it can be imported by both the\n * Node-side runtime CLI (`connect.ts`) and the browser Studio app. The\n * manifest-aware resolution (friendly agent ids/aliases) lives in `connect.ts`;\n * everything here is pure string math.\n */\n\n/**\n * Mirror the default `routeAgentRequest` segment derivation so a raw agent name\n * (e.g. a class name) maps to the same route the server exposes.\n */\nexport function camelCaseToKebabCase(str: string): string {\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/** Normalize a route prefix to a slash-free segment (default `agents`). */\nexport function normalizeRoutePrefix(routePrefix?: string): string {\n const trimmed = (routePrefix ?? \"/agents\").replace(/^\\/+|\\/+$/g, \"\");\n return trimmed || \"agents\";\n}\n\nexport interface DeriveWsTargetInput {\n /** Agent id/alias or raw route segment. */\n agent: string;\n /** Agent instance name. Defaults to `default`. */\n instance?: string;\n /** Remote origin, e.g. `https://app.example.com` (implies `wss`). */\n url?: string;\n /** Local host[:port]. Defaults to `localhost:5173` (Vite). */\n host?: string;\n /** Override the derived protocol. */\n protocol?: string;\n /** Bearer-style token sent as the `token` query param. */\n token?: string;\n /** Extra query params, either `key=value` strings or a record. */\n query?: string[] | Record<string, string>;\n /** Override the route prefix (default `agents`). */\n routePrefix?: string;\n /**\n * When `true`, `agent` is already a canonical route segment (e.g. a manifest\n * id resolved by the server) and is used verbatim (only URL-encoded).\n * Otherwise it is kebab-cased to match default `routeAgentRequest` behavior.\n */\n canonicalAgent?: boolean;\n}\n\nexport interface WsTarget {\n host: string;\n protocol: \"ws\" | \"wss\";\n /** URL pathname without a leading slash, suitable for `basePath`. */\n basePath: string;\n query: Record<string, string>;\n instance: string;\n /** The route segment used for the agent (canonical or kebab-cased). */\n segment: string;\n}\n\nfunction parseQuery(\n query: string[] | Record<string, string> | undefined,\n token: string | undefined\n): Record<string, string> {\n const result: Record<string, string> = {};\n if (token) result.token = token;\n if (!query) return result;\n if (Array.isArray(query)) {\n for (const pair of query) {\n const eq = pair.indexOf(\"=\");\n if (eq <= 0) {\n throw new Error(`Invalid query \"${pair}\" (expected key=value).`);\n }\n result[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return result;\n }\n for (const [key, value] of Object.entries(query)) {\n result[key] = value;\n }\n return result;\n}\n\n/**\n * Resolve host/protocol/basePath/query from loose inputs. Pure (no IO), so it\n * is safe in the browser and trivially unit-testable.\n */\nexport function deriveWsTarget(input: DeriveWsTargetInput): WsTarget {\n const instance = input.instance?.trim() || \"default\";\n const prefix = normalizeRoutePrefix(input.routePrefix);\n\n let host: string;\n let protocol: \"ws\" | \"wss\";\n if (input.url) {\n let origin: URL;\n try {\n origin = new URL(input.url);\n } catch {\n throw new Error(`Invalid url \"${input.url}\" (expected a full origin).`);\n }\n if (!origin.host) {\n throw new Error(\n `Invalid url \"${input.url}\" (missing host — include a scheme, e.g. https://host).`\n );\n }\n host = origin.host;\n protocol =\n input.protocol === \"ws\" || input.protocol === \"wss\"\n ? input.protocol\n : origin.protocol === \"https:\" || origin.protocol === \"wss:\"\n ? \"wss\"\n : \"ws\";\n } else {\n host = input.host?.trim() || \"localhost:5173\";\n protocol = input.protocol === \"wss\" ? \"wss\" : \"ws\";\n }\n\n const segment = input.canonicalAgent\n ? input.agent\n : camelCaseToKebabCase(input.agent);\n\n const basePath = [\n prefix,\n encodeURIComponent(segment),\n encodeURIComponent(instance)\n ].join(\"/\");\n\n return {\n host,\n protocol,\n basePath,\n query: parseQuery(input.query, input.token),\n instance,\n segment\n };\n}\n","import path from \"node:path\";\nimport { AgentClient } from \"agents/client\";\nimport type {\n ThinkFrameworkAgent,\n ThinkFrameworkManifest\n} from \"../framework/manifest\";\nimport { resolveThinkManifest } from \"../framework/project\";\nimport { deriveWsTarget } from \"./target\";\n\ntype ManifestAgents = Pick<ThinkFrameworkManifest, \"agents\">;\n\nfunction findTopLevelAgent(\n manifest: ManifestAgents,\n agent: string\n): ThinkFrameworkAgent | undefined {\n return manifest.agents.find(\n (entry) =>\n entry.kind === \"top-level\" &&\n (entry.id === agent ||\n entry.bindingName === agent ||\n entry.className === agent ||\n entry.aliases.includes(agent))\n );\n}\n\n/** Options shared by the runtime CLI commands (`chat` and `state`). */\nexport interface ConnectOptions {\n /** Manifest agent id/alias (e.g. `support`) or a raw route segment. */\n agent: string;\n /** Agent instance name. Defaults to `default`. */\n instance?: string;\n /** Remote origin, e.g. `https://app.example.com` (implies `wss`). */\n url?: string;\n /** Local host[:port]. Defaults to `localhost:5173` (Vite). */\n host?: string;\n /** Override the derived protocol. */\n protocol?: string;\n /** Bearer-style token sent as the `token` query param. */\n token?: string;\n /** Extra query params as `key=value` strings (repeatable). */\n query?: string[];\n /** Project root used to discover the Think manifest. Defaults to cwd. */\n root?: string;\n /** Override the Think route prefix. */\n routePrefix?: string;\n}\n\n/** A fully-resolved connection target — pure, derived without any IO. */\nexport interface ResolvedTarget {\n host: string;\n protocol: \"ws\" | \"wss\";\n /** URL pathname without a leading slash, suitable for `AgentClient.basePath`. */\n basePath: string;\n query: Record<string, string>;\n /** The agent identifier the user asked for (manifest id or raw segment). */\n agent: string;\n instance: string;\n /** Whether `agent` matched an entry in the supplied manifest. */\n matchedManifest: boolean;\n}\n\nexport interface ResolveTargetInput extends ConnectOptions {\n manifest?: ManifestAgents | null;\n}\n\n/**\n * Resolve target/URL/auth details from CLI options. Pure (no IO) so it can be\n * unit-tested with a synthetic manifest. The manifest, when supplied, lets the\n * CLI accept friendly agent ids/aliases and honor a custom route prefix; when\n * the agent isn't found we treat it as a literal route segment (kebab-cased to\n * match the default `routeAgentRequest` behavior) so the CLI also works against\n * an arbitrary deployed worker. The browser-safe URL/query math lives in\n * {@link deriveWsTarget}; this layer only adds manifest awareness.\n */\nexport function resolveTarget(input: ResolveTargetInput): ResolvedTarget {\n const topLevel = input.manifest\n ? findTopLevelAgent(input.manifest, input.agent)\n : undefined;\n const matchedManifest = topLevel !== undefined;\n\n // Manifest match → use the canonical route id (the server resolves ids,\n // aliases, binding names, and class names back to the agents class segment).\n // Otherwise treat the input as a literal segment, kebab-cased to match the\n // default `routeAgentRequest` behavior.\n const derived = deriveWsTarget({\n agent: topLevel ? topLevel.id : input.agent,\n canonicalAgent: topLevel !== undefined,\n instance: input.instance,\n url: input.url,\n host: input.host,\n protocol: input.protocol,\n token: input.token,\n query: input.query,\n routePrefix: input.routePrefix\n });\n\n return {\n host: derived.host,\n protocol: derived.protocol,\n basePath: derived.basePath,\n query: derived.query,\n agent: input.agent,\n instance: derived.instance,\n matchedManifest\n };\n}\n\nasync function loadManifest(\n root: string | undefined,\n routePrefix: string | undefined\n): Promise<ThinkFrameworkManifest | null> {\n try {\n return await resolveThinkManifest(\n { routePrefix },\n path.resolve(root ?? process.cwd())\n );\n } catch {\n // Best-effort: outside a Think project the manifest can't be discovered,\n // so the CLI falls back to treating the agent as a raw route segment.\n return null;\n }\n}\n\nexport interface ThinkConnection {\n client: AgentClient;\n target: ResolvedTarget;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;\n\n/**\n * Resolve once the client receives its identity handshake, or reject after\n * `timeoutMs` (covers unreachable hosts, which otherwise retry silently).\n */\nexport function waitForClientReady(\n client: AgentClient,\n timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n reject(\n new Error(\n `Timed out after ${timeoutMs}ms connecting to the agent. ` +\n \"Check the host/url, that the dev server or worker is running, and the token.\"\n )\n );\n }, timeoutMs);\n client.ready.then(\n () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve();\n },\n (error: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n );\n });\n}\n\n/**\n * Resolve a target (loading the local manifest when present) and open a\n * connected {@link AgentClient} backed by Node's global `WebSocket`.\n */\nexport async function connectToThinkAgent(\n options: ConnectOptions\n): Promise<ThinkConnection> {\n const WebSocketImpl = globalThis.WebSocket;\n if (typeof WebSocketImpl !== \"function\") {\n throw new Error(\n \"No global WebSocket found. The `think` runtime CLI requires Node.js 24+ \" +\n \"(which provides a built-in WebSocket).\"\n );\n }\n\n const manifest = await loadManifest(options.root, options.routePrefix);\n const target = resolveTarget({ ...options, manifest });\n\n const client = new AgentClient({\n agent: target.agent,\n name: target.instance,\n basePath: target.basePath,\n host: target.host,\n protocol: target.protocol,\n query: target.query,\n WebSocket: WebSocketImpl as unknown as typeof WebSocket\n });\n\n return { client, target };\n}\n","import type { UIMessage } from \"ai\";\nimport { CHAT_MESSAGE_TYPES } from \"agents/chat\";\nimport {\n type ConnectOptions,\n connectToThinkAgent,\n waitForClientReady\n} from \"./connect\";\n\n/** Minimal structural view of the socket the state snapshot needs. */\ninterface MessageSocket {\n addEventListener(\n type: \"message\",\n listener: (event: { data: unknown }) => void\n ): void;\n removeEventListener(\n type: \"message\",\n listener: (event: { data: unknown }) => void\n ): void;\n}\n\nexport type StateCommandOptions = ConnectOptions & {\n /** Emit a single machine-readable JSON object. */\n json?: boolean;\n /** Number of recent messages to include. Defaults to 10. */\n limit?: number;\n};\n\nconst SNAPSHOT_WAIT_MS = 1_000;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction messageText(message: UIMessage): string {\n let text = \"\";\n for (const part of message.parts) {\n if (part.type === \"text\") text += part.text;\n }\n return text;\n}\n\nexport async function stateCommand(\n options: StateCommandOptions\n): Promise<void> {\n const { client, target } = await connectToThinkAgent(options);\n const socket = client as unknown as MessageSocket;\n\n let messages: UIMessage[] = [];\n let gotSnapshot = false;\n const listener = (event: { data: unknown }) => {\n if (typeof event.data !== \"string\") return;\n let frame: Record<string, unknown>;\n try {\n frame = JSON.parse(event.data) as Record<string, unknown>;\n } catch {\n return;\n }\n if (\n frame.type === CHAT_MESSAGE_TYPES.CHAT_MESSAGES &&\n Array.isArray(frame.messages)\n ) {\n messages = frame.messages as UIMessage[];\n gotSnapshot = true;\n }\n };\n socket.addEventListener(\"message\", listener);\n\n try {\n await waitForClientReady(client);\n } catch (error) {\n socket.removeEventListener(\"message\", listener);\n client.close();\n throw error;\n }\n\n // Identity arrives with `ready`; the history snapshot and state broadcast\n // follow shortly after. Wait a beat for them (no server changes needed —\n // we only read connect-time frames).\n const deadline = Date.now() + SNAPSHOT_WAIT_MS;\n while (!gotSnapshot && Date.now() < deadline) {\n await delay(50);\n }\n socket.removeEventListener(\"message\", listener);\n\n const limit = options.limit ?? 10;\n const recent = limit > 0 ? messages.slice(-limit) : messages;\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n agent: client.agent,\n name: client.name,\n state: client.state ?? null,\n messages: recent\n },\n null,\n 2\n )\n );\n client.close();\n return;\n }\n\n const scheme = target.protocol === \"wss\" ? \"https\" : \"http\";\n const lines = [\n \"Think state\",\n `Endpoint: ${scheme}://${target.host}/${target.basePath}`,\n `Agent: ${client.agent}`,\n `Instance: ${client.name}`,\n \"\",\n \"State:\",\n client.state === undefined\n ? \"- none\"\n : indent(JSON.stringify(client.state, null, 2)),\n \"\",\n `Recent messages (${recent.length}):`,\n ...(recent.length === 0\n ? [\"- none\"]\n : recent.map((message) => {\n const text = messageText(message).trim();\n return `- ${message.role}: ${text || \"(no text)\"}`;\n }))\n ];\n console.log(lines.join(\"\\n\"));\n client.close();\n}\n\nfunction indent(value: string): string {\n return value\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n}\n","/**\n * Shared, dependency-free types and helpers for the `/__studio/config.json`\n * document the `think studio` launcher serves to the Studio SPA. Kept pure so\n * it is importable from both the Node launcher (`studio.ts`) and the browser\n * app (type-only) without dragging in any runtime dependency.\n */\n\n/** An agent the Studio connect view can offer as a picker option. */\nexport interface StudioAgentOption {\n /** Canonical route id (what the server resolves). */\n id: string;\n /** Human label for the picker (defaults to the id). */\n label: string;\n}\n\n/** The initial connection the launcher was pointed at. */\nexport interface StudioTarget {\n /** Remote origin, e.g. `https://app.example.com`. */\n url?: string;\n /** Local host[:port]. */\n host?: string;\n /** Override the derived protocol. */\n protocol?: \"ws\" | \"wss\";\n /** Auth token, sent as the `token` query param. */\n token?: string;\n /** Initial agent id/segment. */\n agent?: string;\n /** Initial instance name. */\n instance?: string;\n /** Route prefix (default `agents`). */\n routePrefix?: string;\n}\n\nexport interface StudioConfig {\n target: StudioTarget;\n /** Top-level agents discovered from the local manifest (empty for remote). */\n agents: StudioAgentOption[];\n}\n\n/** Minimal manifest shape needed to build the agent picker options. */\ninterface ManifestLike {\n agents: Array<{\n id: string;\n kind: string;\n bindingName?: string;\n }>;\n}\n\n/**\n * Build the `/__studio/config.json` payload from the resolved target and the\n * (optional) local manifest. Pure so it can be unit-tested directly.\n */\nexport function buildStudioConfig(input: {\n target: StudioTarget;\n manifest?: ManifestLike | null;\n}): StudioConfig {\n const agents: StudioAgentOption[] = (input.manifest?.agents ?? [])\n .filter((entry) => entry.kind === \"top-level\")\n .map((entry) => ({ id: entry.id, label: entry.bindingName || entry.id }));\n return { target: input.target, agents };\n}\n","import { spawn } from \"node:child_process\";\nimport { createReadStream } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { createServer } from \"node:http\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { resolveThinkManifest } from \"../framework/project\";\nimport {\n buildStudioConfig,\n type StudioConfig,\n type StudioTarget\n} from \"./studio-config\";\n\nexport interface StudioCommandOptions {\n /** Manifest agent id/alias or raw route segment to pre-fill the connect view. */\n agent?: string;\n /** Agent instance name to pre-fill. */\n instance?: string;\n /** Remote origin, e.g. `https://app.example.com`. */\n url?: string;\n /** Local host[:port]. */\n host?: string;\n /** Override the derived protocol. */\n protocol?: string;\n /** Auth token, forwarded to the connect view. */\n token?: string;\n /** Extra query params as `key=value` strings. */\n query?: string[];\n /** Project root used to discover the Think manifest. */\n root?: string;\n /** Override the Think route prefix. */\n routePrefix?: string;\n /** Port for the local Studio server. Defaults to 4321. */\n port?: number;\n /** Whether to open the browser automatically. Defaults to true. */\n open?: boolean;\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".ico\": \"image/x-icon\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".map\": \"application/json; charset=utf-8\"\n};\n\nfunction studioDistDir(): string {\n // At runtime this module lives in dist/cli; the built SPA is in dist/studio.\n return path.resolve(\n path.dirname(fileURLToPath(import.meta.url)),\n \"../studio\"\n );\n}\n\nasync function loadManifestAgents(\n root: string | undefined,\n routePrefix: string | undefined\n) {\n try {\n return await resolveThinkManifest(\n { routePrefix },\n path.resolve(root ?? process.cwd())\n );\n } catch {\n return null;\n }\n}\n\nfunction buildTarget(options: StudioCommandOptions): StudioTarget {\n const target: StudioTarget = {};\n if (options.url) target.url = options.url;\n if (options.host) target.host = options.host;\n if (options.protocol === \"ws\" || options.protocol === \"wss\") {\n target.protocol = options.protocol;\n }\n if (options.token) target.token = options.token;\n if (options.agent) target.agent = options.agent;\n if (options.instance) target.instance = options.instance;\n if (options.routePrefix) target.routePrefix = options.routePrefix;\n return target;\n}\n\nfunction openBrowser(url: string): void {\n const command =\n process.platform === \"darwin\"\n ? \"open\"\n : process.platform === \"win32\"\n ? \"start\"\n : \"xdg-open\";\n try {\n const child = spawn(command, [url], {\n stdio: \"ignore\",\n detached: true,\n shell: process.platform === \"win32\"\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // Best-effort — the URL is printed regardless.\n }\n}\n\n/** Resolve a file under `root`, guarding against path traversal. */\nfunction safeResolve(root: string, urlPath: string): string | null {\n let decoded: string;\n try {\n decoded = decodeURIComponent(urlPath.split(\"?\")[0]);\n } catch {\n // Malformed percent-encoding (e.g. `/%` or `/%zz`) makes decodeURIComponent\n // throw. Treat it as unresolvable (404) rather than letting the URIError\n // escape the request handler and crash the server.\n return null;\n }\n const resolved = path.resolve(root, `.${decoded}`);\n if (resolved !== root && !resolved.startsWith(root + path.sep)) return null;\n return resolved;\n}\n\nexport async function studioCommand(\n options: StudioCommandOptions\n): Promise<void> {\n const distDir = studioDistDir();\n try {\n await stat(path.join(distDir, \"index.html\"));\n } catch {\n throw new Error(\n `Think Studio assets were not found at ${distDir}. ` +\n \"Reinstall @cloudflare/think (the published package ships the prebuilt Studio), \" +\n \"or run the package build.\"\n );\n }\n\n const manifest = await loadManifestAgents(options.root, options.routePrefix);\n const config: StudioConfig = buildStudioConfig({\n target: buildTarget(options),\n manifest\n });\n const configJson = JSON.stringify(config);\n\n const server = createServer((req, res) => {\n const urlPath = req.url ?? \"/\";\n\n if (urlPath === \"/__studio/config.json\") {\n res.writeHead(200, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"cache-control\": \"no-store\"\n });\n res.end(configJson);\n return;\n }\n\n const rawPath = urlPath.split(\"?\")[0];\n const candidate =\n rawPath === \"/\"\n ? path.join(distDir, \"index.html\")\n : safeResolve(distDir, rawPath);\n\n const serve = (filePath: string) => {\n const ext = path.extname(filePath).toLowerCase();\n const stream = createReadStream(filePath);\n stream.on(\"error\", () => {\n // The stream can fail to open (file deleted after stat(), permissions)\n // or fault mid-read. Only send a 500 if we haven't already committed\n // the 200 status line; otherwise the headers are gone and the only\n // correct action is to tear down the (now-corrupt) response.\n if (res.headersSent) {\n res.destroy();\n } else {\n res.writeHead(500);\n res.end(\"Internal error\");\n }\n });\n // Defer the 200 until the file actually opens, so an open error can still\n // produce a clean 500 instead of throwing ERR_HTTP_HEADERS_SENT.\n stream.once(\"open\", () => {\n res.writeHead(200, {\n \"content-type\": CONTENT_TYPES[ext] ?? \"application/octet-stream\"\n });\n stream.pipe(res);\n });\n };\n\n if (!candidate) {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n\n stat(candidate)\n .then((s) => {\n if (s.isFile()) {\n serve(candidate);\n } else {\n // SPA fallback for directory/unknown routes.\n serve(path.join(distDir, \"index.html\"));\n }\n })\n .catch(() => serve(path.join(distDir, \"index.html\")));\n });\n\n const startPort = options.port ?? 4321;\n const port = await listen(server, startPort);\n const studioUrl = `http://localhost:${port}/`;\n\n console.log(`Think Studio running at ${studioUrl}`);\n console.log(\"Press Ctrl+C to stop.\");\n if (options.open !== false) openBrowser(studioUrl);\n\n await new Promise<void>((resolve) => {\n const shutdown = () => {\n server.close(() => resolve());\n };\n process.once(\"SIGINT\", shutdown);\n process.once(\"SIGTERM\", shutdown);\n });\n}\n\n/** Listen on `startPort`, advancing on EADDRINUSE up to 20 ports. */\nfunction listen(\n server: ReturnType<typeof createServer>,\n startPort: number\n): Promise<number> {\n return new Promise((resolve, reject) => {\n let attempt = 0;\n const tryPort = (port: number) => {\n const onError = (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" && attempt < 20) {\n attempt += 1;\n tryPort(port + 1);\n } else {\n reject(err);\n }\n };\n server.once(\"error\", onError);\n // Bind to loopback only: the config payload can carry an auth token, so\n // the launcher must not be reachable from other devices on the network.\n server.listen(port, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onError);\n const address = server.address();\n resolve(typeof address === \"object\" && address ? address.port : port);\n });\n };\n tryPort(startPort);\n });\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 type { Argv } from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { initCommand } from \"./init\";\nimport { inspectCommand } from \"./inspect\";\nimport { stateCommand } from \"./state\";\nimport { studioCommand } from \"./studio\";\nimport { typesCommand } from \"./types\";\n\nfunction connectionOptions<T>(cmd: Argv<T>) {\n return cmd\n .positional(\"agent\", {\n type: \"string\",\n describe: \"Agent id/alias (from the manifest) or a raw route segment\"\n })\n .positional(\"instance\", {\n type: \"string\",\n describe: \"Agent instance name\",\n default: \"default\"\n })\n .option(\"url\", {\n type: \"string\",\n describe: \"Remote origin, e.g. https://app.example.com (implies wss)\"\n })\n .option(\"host\", {\n type: \"string\",\n describe: \"Local host[:port] (default: localhost:5173)\"\n })\n .option(\"protocol\", {\n type: \"string\",\n choices: [\"ws\", \"wss\"] as const,\n describe: \"Override the WebSocket protocol\"\n })\n .option(\"token\", {\n type: \"string\",\n describe: \"Auth token, sent as the `token` query param\"\n })\n .option(\"query\", {\n type: \"string\",\n array: true,\n describe: \"Extra query params as key=value (repeatable)\"\n })\n .option(\"root\", {\n type: \"string\",\n describe: \"Project root used to discover the Think manifest\",\n default: process.cwd()\n })\n .option(\"route-prefix\", {\n type: \"string\",\n describe: \"Override the Think route prefix\"\n });\n}\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 (omit to choose)\"\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 .command(\n \"studio [agent] [instance]\",\n \"Launch Think Studio — a local web app to chat with and inspect a running Think instance (local or remote)\",\n (cmd) =>\n connectionOptions(cmd)\n .option(\"port\", {\n type: \"number\",\n describe: \"Port for the local Studio server\",\n default: 4321\n })\n .option(\"open\", {\n type: \"boolean\",\n describe: \"Open the browser automatically\",\n default: true\n }),\n async (args) => {\n await studioCommand({\n agent: args.agent as string | undefined,\n instance: args.instance,\n url: args.url,\n host: args.host,\n protocol: args.protocol,\n token: args.token,\n query: args.query,\n root: args.root,\n routePrefix: args.routePrefix,\n port: args.port,\n open: args.open\n });\n }\n )\n .command(\n \"state <agent> [instance]\",\n \"Print a running Think agent's identity, state, and recent history (read-only)\",\n (cmd) =>\n connectionOptions(cmd)\n .option(\"json\", {\n type: \"boolean\",\n describe: \"Print machine-readable JSON output\",\n default: false\n })\n .option(\"limit\", {\n type: \"number\",\n describe: \"Number of recent messages to include\",\n default: 10\n }),\n async (args) => {\n await stateCommand({\n agent: args.agent as string,\n instance: args.instance,\n url: args.url,\n host: args.host,\n protocol: args.protocol,\n token: args.token,\n query: args.query,\n root: args.root,\n routePrefix: args.routePrefix,\n json: args.json,\n limit: args.limit\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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