create.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import type { TuiSubmitPrompt } from "@zcode/tui";
  2. import {
  3. formatAvailableCommandNames,
  4. listCustomCommandsForHelp,
  5. } from "../command-center-custom.js";
  6. import { formatNewSessionResult, formatResumeResult } from "./formatters.js";
  7. import { handleCustomCommand } from "./handlers/custom.js";
  8. import { handleDwfCommand } from "./handlers/dwf.js";
  9. import { handleEffortCommand } from "./handlers/effort.js";
  10. import { handleExpertCommand } from "./handlers/expert.js";
  11. import { handleLocaleCommand } from "./handlers/locale.js";
  12. import { handleMcpCommand } from "./handlers/mcp.js";
  13. import { handleModeCommand } from "./handlers/mode.js";
  14. import { handleModelCommand } from "./handlers/model.js";
  15. import { handlePluginsCommand } from "./handlers/plugins.js";
  16. import { handleSkillListCommand } from "./handlers/skill.js";
  17. import { handleTargetCommand } from "./handlers/goal.js";
  18. import { recordSlashCommandInHistory } from "./history.js";
  19. import { attachCurrentSessionMetadata, normalizeTuiPromptInput } from "./metadata.js";
  20. import { buildCheckpointSelection, buildSessionSelection } from "./selections.js";
  21. import {
  22. AVAILABLE_COMMANDS,
  23. buildManualSkillPrompt,
  24. formatSlashCommandHelp,
  25. parseSlashCommand,
  26. } from "./slash-commands.js";
  27. import {
  28. buildLoginSelection,
  29. emitLoginAuthorizeMessage,
  30. formatLoginResult,
  31. formatProviderSetupResult,
  32. loginSetupResponse,
  33. parseApiKeyLoginArgs,
  34. } from "./login-flow.js";
  35. import { loginRequiredResponse } from "../tui-login-state.js";
  36. import type { CommandCenterDeps } from "./types.js";
  37. export function createCommandCenter(deps: CommandCenterDeps): TuiSubmitPrompt {
  38. return async (input, options) => {
  39. const promptInput = normalizeTuiPromptInput(input);
  40. const command = parseSlashCommand(promptInput.text);
  41. const hasAttachments = (promptInput.attachments?.length ?? 0) > 0;
  42. if (!command) {
  43. if (await isLoginRequired(deps)) {
  44. return {
  45. loginRequired: true,
  46. mode: deps.getMode?.(),
  47. response: loginRequiredResponse(deps.getLocale?.()),
  48. };
  49. }
  50. const app = await deps.getApp();
  51. return attachCurrentSessionMetadata(await app.submitPrompt(input, options), deps, app);
  52. }
  53. if (hasAttachments) {
  54. return {
  55. mode: deps.getMode?.(),
  56. response: "Image attachments are only supported for normal prompts.",
  57. };
  58. }
  59. if (command.type === "unknown") {
  60. const customResult = await handleCustomCommand(command.rawName, command.args, deps, options);
  61. if (customResult) {
  62. await recordSlashCommandInHistory(deps, promptInput.text, command);
  63. return customResult;
  64. }
  65. const customCommands = await listCustomCommandsForHelp(deps);
  66. return {
  67. mode: deps.getMode?.(),
  68. response: `Unknown command: /${command.rawName}. Available commands: ${formatAvailableCommandNames(AVAILABLE_COMMANDS, customCommands)}.`,
  69. };
  70. }
  71. const result = await (async () => {
  72. if (command.name === "help") {
  73. const customCommands = await listCustomCommandsForHelp(deps);
  74. return {
  75. mode: deps.getMode?.(),
  76. response: formatSlashCommandHelp(command.args, customCommands),
  77. };
  78. }
  79. if (command.name === "login") {
  80. if (command.args.length === 0) {
  81. return {
  82. loginRequired: await isLoginRequired(deps),
  83. mode: deps.getMode?.(),
  84. response: loginSetupResponse(deps.getLocale?.()),
  85. selection: buildLoginSelection(deps.getLocale?.()),
  86. };
  87. }
  88. if (command.args === "zai-coding-plan") {
  89. if (!deps.login) {
  90. return {
  91. mode: deps.getMode?.(),
  92. response: "Z.AI Coding Plan login is not available in this client.",
  93. };
  94. }
  95. return {
  96. loginRequired: false,
  97. mode: deps.getMode?.(),
  98. response: formatLoginResult(
  99. await deps.login({
  100. abortSignal: options.abortSignal,
  101. onAuthorizeUrl: async (data) => {
  102. await emitLoginAuthorizeMessage(
  103. options,
  104. data.authorize_url,
  105. "Z.AI",
  106. await deps.getApp(),
  107. );
  108. },
  109. }),
  110. ),
  111. };
  112. }
  113. if (command.args === "bigmodel-coding-plan") {
  114. if (!deps.loginBigmodel) {
  115. return {
  116. mode: deps.getMode?.(),
  117. response: "BigModel Coding Plan login is not available in this client.",
  118. };
  119. }
  120. return {
  121. loginRequired: false,
  122. mode: deps.getMode?.(),
  123. response: formatProviderSetupResult(
  124. await deps.loginBigmodel({
  125. abortSignal: options.abortSignal,
  126. onAuthorizeUrl: async (data) => {
  127. await emitLoginAuthorizeMessage(
  128. options,
  129. data.authorize_url,
  130. "BigModel",
  131. await deps.getApp(),
  132. );
  133. },
  134. }),
  135. ),
  136. };
  137. }
  138. const apiKeyCommand = parseApiKeyLoginArgs(command.args);
  139. if (apiKeyCommand) {
  140. if (!deps.configureApiKey) {
  141. return {
  142. mode: deps.getMode?.(),
  143. response: "Manual API key setup is not available in this client.",
  144. };
  145. }
  146. if (!apiKeyCommand.apiKey) {
  147. return {
  148. loginRequired: await isLoginRequired(deps),
  149. mode: deps.getMode?.(),
  150. response: `Usage: /login ${apiKeyCommand.kind} <api-key>`,
  151. };
  152. }
  153. return {
  154. loginRequired: false,
  155. mode: deps.getMode?.(),
  156. response: formatProviderSetupResult(
  157. await deps.configureApiKey({
  158. apiKey: apiKeyCommand.apiKey,
  159. providerId: apiKeyCommand.providerId,
  160. }),
  161. ),
  162. };
  163. }
  164. return {
  165. mode: deps.getMode?.(),
  166. response:
  167. "Usage: /login [zai-coding-plan|bigmodel-coding-plan|zai-coding-plan-api-key <api-key>|bigmodel-coding-plan-api-key <api-key>]",
  168. };
  169. }
  170. if (command.name === "logout") {
  171. if (command.args.length > 0) {
  172. return {
  173. mode: deps.getMode?.(),
  174. response: "Usage: /logout",
  175. };
  176. }
  177. if (!deps.logout) {
  178. return {
  179. mode: deps.getMode?.(),
  180. response: "Logout is not available in this client.",
  181. };
  182. }
  183. const result = await deps.logout();
  184. return {
  185. mode: deps.getMode?.(),
  186. response: `Logged out from Coding Plan accounts. Credentials: ${result.credentialsPath}`,
  187. };
  188. }
  189. if (command.name === "compact") {
  190. const app = await deps.getApp();
  191. const prompt = command.args ? `/compact ${command.args}` : "/compact";
  192. return attachCurrentSessionMetadata(await app.submitPrompt(prompt, options), deps, app);
  193. }
  194. if (command.name === "init") {
  195. const app = await deps.getApp();
  196. const prompt = command.args ? `/init ${command.args}` : "/init";
  197. // TUI 已知 slash command 若没有显式分支,会落到文件末尾的
  198. // resume 兜底。/init 是普通 prompt command,必须交给 app.submitPrompt
  199. // 进入 bootstrap resolver,才能和 app --stdio 复用同一套展开逻辑。
  200. return attachCurrentSessionMetadata(await app.submitPrompt(prompt, options), deps, app);
  201. }
  202. if (command.name === "workflow") {
  203. const app = await deps.getApp();
  204. const prompt = command.args ? `/workflow ${command.args}` : "/workflow";
  205. // 与 /init 同款:原文交给 app.submitPrompt,由 bootstrap 的 builtin resolver 展开成
  206. // 「先加载 dynamic-workflows 技能,再写脚本调 CreateWorkflow」的提示词。
  207. return attachCurrentSessionMetadata(await app.submitPrompt(prompt, options), deps, app);
  208. }
  209. if (command.name === "expert") {
  210. return handleExpertCommand(command.args, deps, options);
  211. }
  212. if (command.name === "effort") {
  213. return handleEffortCommand(command.args, deps);
  214. }
  215. if (command.name === "dwf") {
  216. return handleDwfCommand(command.args, deps);
  217. }
  218. if (command.name === "rewind") {
  219. const app = await deps.getApp();
  220. if (command.args.length === 0 && app.listCheckpoints) {
  221. return {
  222. mode: deps.getMode?.(),
  223. response: "Select a checkpoint to rewind.",
  224. selection: buildCheckpointSelection("rewind", await app.listCheckpoints({ limit: 50 })),
  225. };
  226. }
  227. const prompt = command.args ? `/rewind ${command.args}` : "/rewind";
  228. return attachCurrentSessionMetadata(await app.submitPrompt(prompt, options), deps, app);
  229. }
  230. if (command.name === "fork") {
  231. if (command.args.length === 0) {
  232. const app = await deps.getApp();
  233. if (app.listCheckpoints) {
  234. return {
  235. mode: deps.getMode?.(),
  236. response: "Select a checkpoint to fork.",
  237. selection: buildCheckpointSelection("fork", await app.listCheckpoints({ limit: 50 })),
  238. };
  239. }
  240. }
  241. const targetCheckpointId = parseForkTarget(command.args);
  242. if (deps.forkApp) {
  243. const result = await deps.forkApp(targetCheckpointId);
  244. return {
  245. mode: deps.getMode?.(),
  246. response: result.response,
  247. traceId: undefined,
  248. };
  249. }
  250. const app = await deps.getApp();
  251. const prompt = targetCheckpointId ? `/fork ${targetCheckpointId}` : "/fork latest";
  252. return attachCurrentSessionMetadata(await app.submitPrompt(prompt, options), deps, app);
  253. }
  254. if (command.name === "mode") {
  255. return handleModeCommand(command.args, deps);
  256. }
  257. if (command.name === "locale") {
  258. return handleLocaleCommand(command.args, deps);
  259. }
  260. if (command.name === "mcp") {
  261. return handleMcpCommand(command.args, deps);
  262. }
  263. if (command.name === "plugins") {
  264. return handlePluginsCommand(command.args, deps);
  265. }
  266. if (command.name === "model") {
  267. return handleModelCommand(command.args, deps, promptInput.modelSelection);
  268. }
  269. if (command.name === "goal") {
  270. return handleTargetCommand(command.args, deps, options);
  271. }
  272. if (command.name === "new") {
  273. if (command.args.length > 0) {
  274. return {
  275. mode: deps.getMode?.(),
  276. response: "Usage: /new",
  277. };
  278. }
  279. if (!deps.newApp) {
  280. return {
  281. mode: deps.getMode?.(),
  282. response: "Creating a new session is not available in this client.",
  283. };
  284. }
  285. const app = await deps.newApp();
  286. return {
  287. mode: deps.getMode?.(),
  288. locale: app.getLocale?.(),
  289. model: app.getModel?.(),
  290. theme: app.getTheme?.(),
  291. resetSessionProjection: true,
  292. response: formatNewSessionResult(app.sessionId),
  293. sessionId: app.sessionId,
  294. thoughtLevel: app.getThoughtLevel?.(),
  295. traceId: app.traceId,
  296. };
  297. }
  298. if (command.name === "skill") {
  299. if (!command.skillName) {
  300. return handleSkillListCommand(deps);
  301. }
  302. const app = await deps.getApp();
  303. return attachCurrentSessionMetadata(
  304. await app.submitPrompt(buildManualSkillPrompt(command.skillName, command.task), options),
  305. deps,
  306. app,
  307. );
  308. }
  309. if (
  310. command.name === "resume" &&
  311. command.args.length === 0 &&
  312. command.rawName === "resume" &&
  313. deps.listSessions
  314. ) {
  315. return {
  316. mode: deps.getMode?.(),
  317. response: "Select a session to resume.",
  318. selection: buildSessionSelection(await deps.listSessions()),
  319. };
  320. }
  321. const app = await deps.resumeApp(command.args || undefined);
  322. const result = await app.resume({
  323. onEvent: options.onEvent,
  324. });
  325. const restoredMessages = app.loadSessionTranscript
  326. ? await app.loadSessionTranscript()
  327. : undefined;
  328. return {
  329. mode: deps.getMode?.(),
  330. locale: app.getLocale?.(),
  331. model: app.getModel?.(),
  332. theme: app.getTheme?.(),
  333. ...(restoredMessages !== undefined
  334. ? {
  335. resetSessionProjection: true,
  336. restoredMessages,
  337. }
  338. : {}),
  339. response: formatResumeResult(app.sessionId, result),
  340. thoughtLevel: app.getThoughtLevel?.(),
  341. traceId: result.traceId ?? app.traceId,
  342. };
  343. })();
  344. await recordSlashCommandInHistory(deps, promptInput.text, command);
  345. return result;
  346. };
  347. }
  348. function parseForkTarget(args: string): string | undefined {
  349. const trimmed = args.trim();
  350. if (trimmed.length === 0 || trimmed === "latest") return undefined;
  351. return trimmed;
  352. }
  353. async function isLoginRequired(deps: CommandCenterDeps): Promise<boolean> {
  354. if (!deps.hasSelectableModels) return false;
  355. try {
  356. return !(await deps.hasSelectableModels());
  357. } catch {
  358. return false;
  359. }
  360. }