import"../../errors-pXKbCKbL.js";import"../../editor-BmJI32_P.js";import{i as e,t}from"../../runner-DYk4q6mP.js";import"../../fsStore-BzLA1cBc.js";import"../../base-xqced3zT.js";import"../../config-Bphz_1Sc.js";import"../../template-Cpbt9qy8.js";import{t as n}from"../../xling-DyktHkvX.js";import"../../providerRegistry-DXZVv1rc.js";import"../../client-CG1X3JM2.js";import{n as r,t as i}from"../../types-D9R5QJnK.js";import{n as a}from"../../router-Dq8YoWty.js";import{Args as o,Command as s,Flags as c}from"@oclif/core";import*as l from"node:fs";import*as u from"node:readline";import*as d from"node:tty";var f=class f extends s{static description=`Execute a prompt via xling providers or hand off to codex exec / claude -p with yolo`;static examples=[{description:`Simple prompt`,command:`<%= config.bin %> <%= command.id %> "Explain quantum computing"`},{description:`Specify model`,command:`<%= config.bin %> <%= command.id %> --model gpt-4-turbo "Write a poem"`},{description:`Read from file`,command:`<%= config.bin %> <%= command.id %> -f README.md "Summarize this"`},{description:`Read from stdin`,command:`git diff | <%= config.bin %> <%= command.id %> --stdin "Review this diff"`},{description:`JSON output`,command:`<%= config.bin %> <%= command.id %> --json "What is 2+2?"`},{description:`Directly run codex exec (bypass xling providers)`,command:`<%= config.bin %> <%= command.id %> --tool codex "Summarize this repo"`},{description:`Use Claude Code CLI with yolo by default`,command:`<%= config.bin %> <%= command.id %> --tool claude "Review this diff"`},{description:`Shorthand for Codex backend (matches x command flag)`,command:`<%= config.bin %> <%= command.id %> -t codex "Hello"`},{description:`Use Gemini CLI headless prompt`,command:`<%= config.bin %> <%= command.id %> -t gemini "Summarize this diff"`}];static flags={tool:c.string({description:`Choose backend: xling router (default) or call codex/claude/gemini CLI directly`,options:[`xling`,`codex`,`claude`,`gemini`],required:!1,default:`xling`,char:`t`}),yolo:c.boolean({description:`Use yolo flags when calling codex/claude/gemini directly (skip permission prompts)`,required:!1,default:!0,allowNo:!0}),model:c.string({char:`m`,description:`Model to use (defaults to configured defaultModel)`,required:!1}),prompt:c.string({char:`p`,description:`Prompt text (alternative to positional arg)`,required:!1}),system:c.string({char:`s`,description:`System prompt`,required:!1}),file:c.string({char:`f`,description:`Read additional context from file`,required:!1,multiple:!0}),stdin:c.boolean({description:`Read prompt from stdin`,required:!1,default:!1}),temperature:c.string({char:`T`,description:`Temperature (0.0-2.0)`,required:!1}),"max-tokens":c.integer({description:`Maximum tokens to generate`,required:!1}),json:c.boolean({description:`Output as JSON`,required:!1,default:!1}),stream:c.boolean({description:`Stream output (default: true)`,required:!1,default:!0,allowNo:!0}),interactive:c.boolean({char:`i`,description:`Enter interactive chat mode after first response`,required:!1,default:!1})};static args={prompt:o.string({description:`The prompt text`,required:!1})};async run(){let{args:e,flags:t}=await this.parse(f),n=t.tool??`xling`,o=t.yolo!==!1;try{let r=await this.#s(e,t);if(r.trim()||this.error(`No prompt provided. Use argument, --prompt, --file, or --stdin`),n!==`xling`){this.#t(n,t),await this.#n(n,r,o,t);return}this.#e();let i={prompt:r,model:t.model,system:t.system,temperature:t.temperature?parseFloat(t.temperature):void 0,maxTokens:t[`max-tokens`],stream:t.stream},s=await a(),c,l,u;if(t.stream&&!t.json){let e=await s.executeStream(i);c=await this.#o(e);let n=await e.usage;l=n?{promptTokens:n.inputTokens??0,completionTokens:n.outputTokens??0,totalTokens:n.totalTokens??0}:void 0,u={provider:`streaming`,model:t.model||`default`}}else{let e=await s.execute(i);c=e.content,l=e.usage,u={provider:e.provider,model:e.model},t.json?this.log(JSON.stringify(e,null,2)):this.log(e.content)}!t.json&&l&&u&&this.log(`\n[${u.provider}/${u.model}] ${l.totalTokens} tokens (${l.promptTokens} prompt + ${l.completionTokens} completion)`);let d=this.#r(t),f=d;!d&&!t.json&&process.stdout.isTTY&&(f=await this.#i()),f&&await this.#a(r,c,t,s)}catch(e){e instanceof r?this.error(e.message):e instanceof i?this.error(`All providers failed:\n${e.errors.map(e=>`  ${e.provider}: ${e.error.message}`).join(`
`)}`):this.error(e.message)}}#e(){let e=new n().resolvePath(`user`);l.existsSync(e.replace(`~`,process.env.HOME||``))||this.error(`Configuration not found at ${e}\n\nPlease create a configuration file with at least one provider.\nExample:\n{\n  "prompt": {\n    "providers": [\n      {\n        "name": "openai",\n        "baseUrl": "https://api.openai.com/v1",\n        "apiKey": "sk-...",\n        "models": ["gpt-4", "gpt-4-turbo"]\n      }\n    ],\n    "defaultModel": "gpt-4"\n  }\n}`)}#t(e,t){t.interactive&&this.error(`Interactive mode is not supported when using --tool codex/claude/gemini. Remove --interactive or use the default xling router.`);let n=[];t.json&&n.push(`--json`),t.model&&e!==`gemini`&&n.push(`--model`),t.system&&n.push(`--system`),t.temperature!==void 0&&n.push(`--temperature`),t[`max-tokens`]!==void 0&&n.push(`--max-tokens`),t.stream===!1&&n.push(`--no-stream`),n.length>0&&this.warn(`Ignoring ${n.join(`, `)} when using direct CLI backend; codex/claude will apply their own defaults.`)}async#n(n,r,i,a){let o=n===`codex`?`codex`:n===`gemini`?`gemini`:`claude`;await t(o)||this.error(`Tool "${o}" is not installed or not found in PATH. Please install it before using --tool ${n}.`);let s=n===`codex`?[`exec`,r]:[`-p`,r];n===`gemini`&&a.model&&s.unshift(`-m`,a.model);let c={executable:o,baseArgs:s,yoloArgs:n===`codex`?i?[`--dangerously-bypass-approvals-and-sandbox`]:void 0:n===`gemini`?i?[`-y`]:void 0:i?[`--dangerously-skip-permissions`]:void 0};this.log(`[backend: ${n}] ${i?`yolo on`:`yolo off`} — handing output to ${o}`),await e(c)}#r(e){return e.interactive?!0:(process.stdout.isTTY&&process.stdin.isTTY,!1)}async#i(){return new Promise(e=>{let t=!1;try{let n=l.openSync(`/dev/tty`,`r+`),r=new d.ReadStream(n),i=new d.WriteStream(n),a=u.createInterface({input:r,output:i});a.question(`
Continue conversation? (y/N): `,o=>{t=!0;let s=o.trim().toLowerCase(),c=s===`y`||s===`yes`;c||(i??process.stdout).write(`
Okay, not continuing the conversation.
`),a.close(),r.destroy(),i.destroy(),l.closeSync(n),e(c)}),setTimeout(()=>{t||(a.close(),r.destroy(),i.destroy(),l.closeSync(n),process.stdout.write(`
No response received. Ending conversation prompt.
`),e(!1))},1e4)}catch{this.log(`Skipping interactive follow-up (TTY not available).`),e(!1)}})}async#a(e,t,n,r){let i=[];n.system&&i.push({role:`system`,content:n.system}),i.push({role:`user`,content:e}),i.push({role:`assistant`,content:t}),this.log(`
--- Interactive mode (type 'exit', 'quit', or press Ctrl+D to end) ---
`);try{let e,t=null,a=null,o=null,s=!1,c,f=()=>{if(c&&`setRawMode`in c)try{c.setRawMode(s)}catch{}if(a)try{a.destroy()}catch{}if(o)try{o.destroy()}catch{}if(t!==null)try{l.closeSync(t)}catch{}};process.stdin.isTTY?(c=process.stdin,s=process.stdin.isRaw||!1,s||process.stdin.setRawMode(!0),e=u.createInterface({input:process.stdin,output:process.stdout,prompt:`> `})):(t=l.openSync(`/dev/tty`,`r+`),a=new d.ReadStream(t),o=new d.WriteStream(t),c=a,s=a.isRaw||!1,s||a.setRawMode(!0),e=u.createInterface({input:a,output:o,prompt:`> `}));let p=o||process.stdout;e.prompt(),e.on(`line`,async t=>{let a=t.trim();if([`exit`,`quit`,`q`].includes(a.toLowerCase())){e.close();return}if(!a){e.prompt();return}i.push({role:`user`,content:a});try{let t={messages:i,model:n.model,temperature:n.temperature?parseFloat(n.temperature):void 0,maxTokens:n[`max-tokens`],stream:!0},a=await r.executeStream(t),o=await this.#o(a,p);i.push({role:`assistant`,content:o}),e.prompt()}catch(t){p.write(`\n[Error] ${t.message}\n\n`),e.prompt()}}),e.on(`close`,()=>{f(),this.log(`
Goodbye!`),process.exit(0)}),e.on(`SIGINT`,()=>{p.write(`

Interrupted. Type 'exit' to quit or continue chatting.
`),e.prompt()});let m=()=>{f(),process.exit(0)};process.once(`SIGTERM`,m),process.once(`SIGINT`,m)}catch(e){this.error(`Cannot enter interactive mode: ${e.message}`)}}async#o(e,t=process.stdout){let n=``;t.write(`
`);for await(let r of e.textStream)t.write(r),n+=r,`flush`in t&&typeof t.flush==`function`&&t.flush();return t.write(`
`),n}async#s(e,t){let n=[];if(e.prompt&&n.push(e.prompt),t.prompt&&n.push(t.prompt),t.file&&t.file.length>0)for(let e of t.file)try{let t=l.readFileSync(e,`utf-8`);n.push(`\n--- File: ${e} ---\n${t}`)}catch(t){this.warn(`Failed to read file ${e}: ${t.message}`)}if(t.stdin){let e=await this.#c();e&&n.push(e)}return n.join(`
`).trim()}async#c(){return new Promise(e=>{let t=[];process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{t.push(e.toString())}),process.stdin.on(`end`,()=>{e(t.join(``))}),process.stdin.isTTY&&e(``)})}};export{f as default};