@popmelt.com/core 0.7.5 → 0.7.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-entry.mjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +24 -24
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/{server-5IM3W4KN.mjs → server-O4KGZLHM.mjs} +1 -1
- package/dist/server.mjs +1 -1
- package/package.json +1 -1
package/dist/bridge-entry.mjs
CHANGED
|
@@ -328,7 +328,7 @@ url = "${s}"
|
|
|
328
328
|
`)}function cn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function ln(s,t,n,e){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=t.find(c=>c.role==="human"&&c.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),t.length>0){o.push(""),o.push("## Conversation History");let c=0;for(let a of t)a.role==="human"?(c++,a.replyToQuestion?(o.push(`### Round ${c} (human) \u2014 reply`),o.push(`"${a.replyToQuestion}"`)):(o.push(`### Round ${c} (human)`),a.feedbackSummary&&o.push(`Annotations: ${a.feedbackSummary}`))):a.question?(o.push(`### Round ${c} (assistant) \u2014 question`),o.push(`"${a.question}"`)):(o.push(`### Round ${c} (assistant)`),a.responseText&&o.push(`Response: ${a.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e&&e.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let c of e)o.push(`Attached image: use the Read tool to view the image at: ${c}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
|
|
329
329
|
`)}function no(s){if(typeof s!="object"||s===null)return!1;let t=s;return(t.breadth==="instance"||t.breadth==="pattern")&&(t.target==="element"||t.target==="component"||t.target==="token")}function so(s){if(typeof s!="object"||s===null||typeof s.annotationId!="string"||s.status!=="resolved"&&s.status!=="needs_review"||typeof s.summary!="string")return!1;let t=s;for(let n of["declaredScope","inferredScope","finalScope"])if(t[n]!==void 0&&t[n]!==null&&!no(t[n]))return!1;return!0}function dn(s){let t=s.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!t||!t[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(so):[]}catch{return[]}}function un(s){let t=s.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!t?.[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(e=>{if(typeof e!="object"||e===null)return!1;let o=e;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as oo}from"child_process";import{readdir as ro,readFile as io,stat as ao}from"fs/promises";import{homedir as Ce}from"os";import{join as me}from"path";var Ye=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static"},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static"}],$e=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],_e={id:"",label:"Default",source:"cli"},co=/^\s*-\s+"([^"]+)"/;function lo(s){let t=[],n=!1;for(let e of s.split(`
|
|
330
330
|
`)){if(/^\s*`model`:/.test(e)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(e))break;if(!n)continue;let o=e.match(co);if(!o?.[1])continue;let i=o[1];t.push({id:i,label:ht(i),source:"cli"})}return Ke([_e,...t])}function uo(s){let t=JSON.parse(s);return(Array.isArray(t.models)?t.models:[]).filter(e=>e.visibility===void 0||e.visibility==="list").sort((e,o)=>{let i=typeof e.priority=="number"?e.priority:Number.MAX_SAFE_INTEGER,c=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-c}).flatMap(e=>{let o=typeof e.slug=="string"?e.slug:typeof e.id=="string"?e.id:"";if(!o)return[];let i=typeof e.display_name=="string"&&e.display_name.trim()?e.display_name.trim():ht(o);return[{id:o,label:i,source:"cli"}]})}function po(s){let t=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Ke(t.map(n=>({id:n,label:ht(n),source:"cli"})))}function ht(s){if(!s)return"Default";let t={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=s.replace(/-\d{8,}$/,"");if(t[s])return t[s];if(t[n])return t[n];let e=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(e){let i=e[1]==="sonnet"?"Sonn":go(e[1]),c=e[2]&&e[3]?` ${e[2]}.${e[3]}`:"";return`${i}${c}${e[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function pn(s="copilot"){let t=await qe(s,["help","config"]),n=lo(t);return n.length>1?n:[_e]}async function fn(s="codex"){let t=await qe(s,["debug","models"]).catch(async()=>{let e=process.env.CODEX_HOME||me(Ce(),".codex");return mn(me(e,"models_cache.json"))}),n=uo(t);return n.length>0?Ke([...n,...$e]):$e}async function hn(s="claude"){let t=me(Ce(),".claude"),n=[me(Ce(),".claude","stats-cache.json"),me(Ce(),".claude","settings.json"),me(Ce(),".claude.json"),me(t,"cache","changelog.md")],[e,o,i]=await Promise.all([qe(s,["--help"]).catch(()=>""),qe(s,["--version"]).catch(()=>""),fo(t).catch(()=>[])]),c=mo([...n,...i]),a=await Promise.all(c.map(P=>mn(P).catch(()=>""))),m=po([e,o,...a].join(`
|
|
331
|
-
`));return Ke([...Ye,...m])}function qe(s,t,n=5e3){return new Promise((e,o)=>{oo(s,t,{encoding:"utf-8",timeout:n},(i,c)=>{if(i){o(i);return}e(c)})})}async function mn(s){return io(s,"utf-8")}async function fo(s){let t=[me(s,"projects"),me(s,"telemetry")],n=[];for(let e of t)await gn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function gn(s,t,n){if(n<0)return;let e;try{e=await ro(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=me(s,o.name);if(o.isDirectory()){await gn(i,t,n-1);return}if(!(!o.isFile()||!ho(o.name)))try{let c=await ao(i);if(c.size>2e6)return;t.push({path:i,mtimeMs:c.mtimeMs})}catch{}}))}function ho(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Ke(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function mo(s){return[...new Set(s)]}function go(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Qe=class{constructor(t=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,n){n?this.activeProcesses.set(t,n):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,n,e){let o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let c=n<0?e.events:e.events.filter(a=>a.seq>n);return{jobId:t,events:c,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[n]+=e}getAccumulated(t){return this.accumulators.get(t)??null}scheduleBufferCleanup(t){let n=this.cleanupTimers.get(t);n&&clearTimeout(n);let e=setTimeout(()=>{this.eventBuffers.delete(t),this.accumulators.delete(t),this.cleanupTimers.delete(t)},6e4);this.cleanupTimers.set(t,e)}cancelJob(t){let n=this.activeProcesses.get(t),e=this.activeJobs.get(t);return!n||!e?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let n of t)this.cancelJob(n);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}async destroyAsync(t=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let e of n)try{e.kill("SIGTERM")}catch{}await Promise.all(n.map(e=>new Promise(o=>{let i=!1,c=()=>{i||(i=!0,o())};e.on("exit",c),e.on("error",c),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(c,500)}},t)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0,threadId:t.threadId},t.id,t.sourceId),this.processor(t).catch(n=>{t.status="error",t.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},t.id,t.sourceId)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.scheduleBufferCleanup(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as vo,readFile as yo,writeFile as wo}from"fs/promises";import{dirname as So,join as bo}from"path";var xo={version:1,threads:{}},Ve=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=bo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await yo(this.filePath,"utf-8"),n=JSON.parse(t);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...xo,threads:{}},this.cache}async getThread(t){return(await this.load()).threads[t]??null}async findContinuationThread(t){if(t.length===0)return null;let n=await this.load(),e=new Set(t);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(c=>e.has(c)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];if(!o)return;let i=new Set(o.elementIdentifiers);for(let c of n)i.has(c)||o.elementIdentifiers.push(c);o.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).map(o=>{let c=o.messages.find(a=>a.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:c,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(t,n=6){let e=await this.getThread(t);return!e||e.messages.length===0?[]:e.messages.length<=n?e.messages:[e.messages[0],...e.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await vo(So(this.filePath),{recursive:!0}),await wo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var vn="0.7.
|
|
331
|
+
`));return Ke([...Ye,...m])}function qe(s,t,n=5e3){return new Promise((e,o)=>{oo(s,t,{encoding:"utf-8",timeout:n},(i,c)=>{if(i){o(i);return}e(c)})})}async function mn(s){return io(s,"utf-8")}async function fo(s){let t=[me(s,"projects"),me(s,"telemetry")],n=[];for(let e of t)await gn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function gn(s,t,n){if(n<0)return;let e;try{e=await ro(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=me(s,o.name);if(o.isDirectory()){await gn(i,t,n-1);return}if(!(!o.isFile()||!ho(o.name)))try{let c=await ao(i);if(c.size>2e6)return;t.push({path:i,mtimeMs:c.mtimeMs})}catch{}}))}function ho(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Ke(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function mo(s){return[...new Set(s)]}function go(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Qe=class{constructor(t=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,n){n?this.activeProcesses.set(t,n):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,n,e){let o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let c=n<0?e.events:e.events.filter(a=>a.seq>n);return{jobId:t,events:c,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[n]+=e}getAccumulated(t){return this.accumulators.get(t)??null}scheduleBufferCleanup(t){let n=this.cleanupTimers.get(t);n&&clearTimeout(n);let e=setTimeout(()=>{this.eventBuffers.delete(t),this.accumulators.delete(t),this.cleanupTimers.delete(t)},6e4);this.cleanupTimers.set(t,e)}cancelJob(t){let n=this.activeProcesses.get(t),e=this.activeJobs.get(t);return!n||!e?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let n of t)this.cancelJob(n);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}async destroyAsync(t=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let e of n)try{e.kill("SIGTERM")}catch{}await Promise.all(n.map(e=>new Promise(o=>{let i=!1,c=()=>{i||(i=!0,o())};e.on("exit",c),e.on("error",c),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(c,500)}},t)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0,threadId:t.threadId},t.id,t.sourceId),this.processor(t).catch(n=>{t.status="error",t.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},t.id,t.sourceId)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.scheduleBufferCleanup(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as vo,readFile as yo,writeFile as wo}from"fs/promises";import{dirname as So,join as bo}from"path";var xo={version:1,threads:{}},Ve=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=bo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await yo(this.filePath,"utf-8"),n=JSON.parse(t);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...xo,threads:{}},this.cache}async getThread(t){return(await this.load()).threads[t]??null}async findContinuationThread(t){if(t.length===0)return null;let n=await this.load(),e=new Set(t);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(c=>e.has(c)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];if(!o)return;let i=new Set(o.elementIdentifiers);for(let c of n)i.has(c)||o.elementIdentifiers.push(c);o.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).map(o=>{let c=o.messages.find(a=>a.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:c,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(t,n=6){let e=await this.getThread(t);return!e||e.messages.length===0?[]:e.messages.length<=n?e.messages:[e.messages[0],...e.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await vo(So(this.filePath),{recursive:!0}),await wo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var vn="0.7.7";var $o=1111,_o=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Oo=1800*1e3,Ao=3600*1e3;function kn(s){if(!s)return!1;try{let t=new URL(s);return t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="::1"||t.hostname==="[::1]"}catch{return!1}}function Do(s){let t=[];for(let n of s)if(n.type==="delta"){let e=n.text;if(!e)continue;let o=t[t.length-1];o&&o.kind==="text"?o.text+=e:t.push({kind:"text",text:e})}else if(n.type==="tool_use"){let e=n.tool||"",o=n.file??void 0,i=n.content??void 0,c=o?o.split("/").pop()??o:void 0,a;switch(e){case"Read":a=c?`Reading ${c}`:"Reading file";break;case"Edit":a=c?`Editing ${c}`:"Editing file";break;case"Write":a=c?`Writing ${c}`:"Writing file";break;case"Bash":a=i?i.split(`
|
|
332
332
|
`)[0].trim().slice(0,60):"Running command";break;case"Glob":a="Searching files";break;case"Grep":a="Searching code";break;case"WebFetch":a="Fetching page";break;case"WebSearch":a="Searching web";break;default:a=e?`Using ${e}`:"tool";break}let m=o??i??void 0,P=t[t.length-1];P&&P.kind==="tool_group"&&P.tool===e?P.items.push({label:a,detail:m}):t.push({kind:"tool_group",tool:e,items:[{label:a,detail:m}]})}return t}function No(s,t){let n=s.headers.origin;kn(n)&&(t.setHeader("Access-Control-Allow-Origin",n),t.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function y(s,t,n){s.writeHead(t,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function Jo(s,t){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||t.searchParams.get("projectId")||null}function Fo(s,t){if(!s)return t;let n=s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return t;let[,e,o,i]=n;return`\x1B[38;2;${parseInt(e,16)};${parseInt(o,16)};${parseInt(i,16)}m${t}\x1B[0m`}function gt(s,t){try{s.res.write(`event: ${t.type}
|
|
333
333
|
data: ${JSON.stringify(t)}
|
|
334
334
|
|
package/dist/cli.mjs
CHANGED
|
@@ -329,7 +329,7 @@ url = "${s}"
|
|
|
329
329
|
`)}function dn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function un(s,t,n,e){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=t.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),t.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let c of t)c.role==="human"?(a++,c.replyToQuestion?(o.push(`### Round ${a} (human) \u2014 reply`),o.push(`"${c.replyToQuestion}"`)):(o.push(`### Round ${a} (human)`),c.feedbackSummary&&o.push(`Annotations: ${c.feedbackSummary}`))):c.question?(o.push(`### Round ${a} (assistant) \u2014 question`),o.push(`"${c.question}"`)):(o.push(`### Round ${a} (assistant)`),c.responseText&&o.push(`Response: ${c.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e&&e.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of e)o.push(`Attached image: use the Read tool to view the image at: ${a}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
|
|
330
330
|
`)}function Vs(s){if(typeof s!="object"||s===null)return!1;let t=s;return(t.breadth==="instance"||t.breadth==="pattern")&&(t.target==="element"||t.target==="component"||t.target==="token")}function Zs(s){if(typeof s!="object"||s===null||typeof s.annotationId!="string"||s.status!=="resolved"&&s.status!=="needs_review"||typeof s.summary!="string")return!1;let t=s;for(let n of["declaredScope","inferredScope","finalScope"])if(t[n]!==void 0&&t[n]!==null&&!Vs(t[n]))return!1;return!0}function pn(s){let t=s.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!t||!t[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(Zs):[]}catch{return[]}}function fn(s){let t=s.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!t?.[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(e=>{if(typeof e!="object"||e===null)return!1;let o=e;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as eo}from"child_process";import{readdir as to,readFile as no,stat as so}from"fs/promises";import{homedir as $e}from"os";import{join as ge}from"path";var Ke=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static"},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static"}],_e=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],Oe={id:"",label:"Default",source:"cli"},oo=/^\s*-\s+"([^"]+)"/;function ro(s){let t=[],n=!1;for(let e of s.split(`
|
|
331
331
|
`)){if(/^\s*`model`:/.test(e)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(e))break;if(!n)continue;let o=e.match(oo);if(!o?.[1])continue;let i=o[1];t.push({id:i,label:mt(i),source:"cli"})}return Qe([Oe,...t])}function io(s){let t=JSON.parse(s);return(Array.isArray(t.models)?t.models:[]).filter(e=>e.visibility===void 0||e.visibility==="list").sort((e,o)=>{let i=typeof e.priority=="number"?e.priority:Number.MAX_SAFE_INTEGER,a=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-a}).flatMap(e=>{let o=typeof e.slug=="string"?e.slug:typeof e.id=="string"?e.id:"";if(!o)return[];let i=typeof e.display_name=="string"&&e.display_name.trim()?e.display_name.trim():mt(o);return[{id:o,label:i,source:"cli"}]})}function ao(s){let t=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Qe(t.map(n=>({id:n,label:mt(n),source:"cli"})))}function mt(s){if(!s)return"Default";let t={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=s.replace(/-\d{8,}$/,"");if(t[s])return t[s];if(t[n])return t[n];let e=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(e){let i=e[1]==="sonnet"?"Sonn":po(e[1]),a=e[2]&&e[3]?` ${e[2]}.${e[3]}`:"";return`${i}${a}${e[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function hn(s="copilot"){let t=await Ye(s,["help","config"]),n=ro(t);return n.length>1?n:[Oe]}async function mn(s="codex"){let t=await Ye(s,["debug","models"]).catch(async()=>{let e=process.env.CODEX_HOME||ge($e(),".codex");return vn(ge(e,"models_cache.json"))}),n=io(t);return n.length>0?Qe([...n,..._e]):_e}async function gn(s="claude"){let t=ge($e(),".claude"),n=[ge($e(),".claude","stats-cache.json"),ge($e(),".claude","settings.json"),ge($e(),".claude.json"),ge(t,"cache","changelog.md")],[e,o,i]=await Promise.all([Ye(s,["--help"]).catch(()=>""),Ye(s,["--version"]).catch(()=>""),co(t).catch(()=>[])]),a=uo([...n,...i]),c=await Promise.all(a.map(P=>vn(P).catch(()=>""))),m=ao([e,o,...c].join(`
|
|
332
|
-
`));return Qe([...Ke,...m])}function Ye(s,t,n=5e3){return new Promise((e,o)=>{eo(s,t,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}e(a)})})}async function vn(s){return no(s,"utf-8")}async function co(s){let t=[ge(s,"projects"),ge(s,"telemetry")],n=[];for(let e of t)await yn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function yn(s,t,n){if(n<0)return;let e;try{e=await to(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=ge(s,o.name);if(o.isDirectory()){await yn(i,t,n-1);return}if(!(!o.isFile()||!lo(o.name)))try{let a=await so(i);if(a.size>2e6)return;t.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function lo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Qe(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function uo(s){return[...new Set(s)]}function po(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Ve=class{constructor(t=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,n){n?this.activeProcesses.set(t,n):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,n,e){let o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let a=n<0?e.events:e.events.filter(c=>c.seq>n);return{jobId:t,events:a,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[n]+=e}getAccumulated(t){return this.accumulators.get(t)??null}scheduleBufferCleanup(t){let n=this.cleanupTimers.get(t);n&&clearTimeout(n);let e=setTimeout(()=>{this.eventBuffers.delete(t),this.accumulators.delete(t),this.cleanupTimers.delete(t)},6e4);this.cleanupTimers.set(t,e)}cancelJob(t){let n=this.activeProcesses.get(t),e=this.activeJobs.get(t);return!n||!e?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let n of t)this.cancelJob(n);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}async destroyAsync(t=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let e of n)try{e.kill("SIGTERM")}catch{}await Promise.all(n.map(e=>new Promise(o=>{let i=!1,a=()=>{i||(i=!0,o())};e.on("exit",a),e.on("error",a),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(a,500)}},t)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0,threadId:t.threadId},t.id,t.sourceId),this.processor(t).catch(n=>{t.status="error",t.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},t.id,t.sourceId)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.scheduleBufferCleanup(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as fo,readFile as ho,writeFile as mo}from"fs/promises";import{dirname as go,join as vo}from"path";var yo={version:1,threads:{}},Ze=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=vo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await ho(this.filePath,"utf-8"),n=JSON.parse(t);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...yo,threads:{}},this.cache}async getThread(t){return(await this.load()).threads[t]??null}async findContinuationThread(t){if(t.length===0)return null;let n=await this.load(),e=new Set(t);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>e.has(a)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).map(o=>{let a=o.messages.find(c=>c.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(t,n=6){let e=await this.getThread(t);return!e||e.messages.length===0?[]:e.messages.length<=n?e.messages:[e.messages[0],...e.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await fo(go(this.filePath),{recursive:!0}),await mo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var wn="0.7.
|
|
332
|
+
`));return Qe([...Ke,...m])}function Ye(s,t,n=5e3){return new Promise((e,o)=>{eo(s,t,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}e(a)})})}async function vn(s){return no(s,"utf-8")}async function co(s){let t=[ge(s,"projects"),ge(s,"telemetry")],n=[];for(let e of t)await yn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function yn(s,t,n){if(n<0)return;let e;try{e=await to(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=ge(s,o.name);if(o.isDirectory()){await yn(i,t,n-1);return}if(!(!o.isFile()||!lo(o.name)))try{let a=await so(i);if(a.size>2e6)return;t.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function lo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Qe(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function uo(s){return[...new Set(s)]}function po(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Ve=class{constructor(t=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,n){n?this.activeProcesses.set(t,n):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,n,e){let o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let a=n<0?e.events:e.events.filter(c=>c.seq>n);return{jobId:t,events:a,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[n]+=e}getAccumulated(t){return this.accumulators.get(t)??null}scheduleBufferCleanup(t){let n=this.cleanupTimers.get(t);n&&clearTimeout(n);let e=setTimeout(()=>{this.eventBuffers.delete(t),this.accumulators.delete(t),this.cleanupTimers.delete(t)},6e4);this.cleanupTimers.set(t,e)}cancelJob(t){let n=this.activeProcesses.get(t),e=this.activeJobs.get(t);return!n||!e?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let n of t)this.cancelJob(n);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}async destroyAsync(t=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let e of n)try{e.kill("SIGTERM")}catch{}await Promise.all(n.map(e=>new Promise(o=>{let i=!1,a=()=>{i||(i=!0,o())};e.on("exit",a),e.on("error",a),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(a,500)}},t)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0,threadId:t.threadId},t.id,t.sourceId),this.processor(t).catch(n=>{t.status="error",t.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},t.id,t.sourceId)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.scheduleBufferCleanup(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as fo,readFile as ho,writeFile as mo}from"fs/promises";import{dirname as go,join as vo}from"path";var yo={version:1,threads:{}},Ze=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=vo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await ho(this.filePath,"utf-8"),n=JSON.parse(t);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...yo,threads:{}},this.cache}async getThread(t){return(await this.load()).threads[t]??null}async findContinuationThread(t){if(t.length===0)return null;let n=await this.load(),e=new Set(t);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>e.has(a)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).map(o=>{let a=o.messages.find(c=>c.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(t,n=6){let e=await this.getThread(t);return!e||e.messages.length===0?[]:e.messages.length<=n?e.messages:[e.messages[0],...e.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await fo(go(this.filePath),{recursive:!0}),await mo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var wn="0.7.7";var Io=1111,To=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Mo=1800*1e3,Co=3600*1e3;function En(s){if(!s)return!1;try{let t=new URL(s);return t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="::1"||t.hostname==="[::1]"}catch{return!1}}function $o(s){let t=[];for(let n of s)if(n.type==="delta"){let e=n.text;if(!e)continue;let o=t[t.length-1];o&&o.kind==="text"?o.text+=e:t.push({kind:"text",text:e})}else if(n.type==="tool_use"){let e=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,c;switch(e){case"Read":c=a?`Reading ${a}`:"Reading file";break;case"Edit":c=a?`Editing ${a}`:"Editing file";break;case"Write":c=a?`Writing ${a}`:"Writing file";break;case"Bash":c=i?i.split(`
|
|
333
333
|
`)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=e?`Using ${e}`:"tool";break}let m=o??i??void 0,P=t[t.length-1];P&&P.kind==="tool_group"&&P.tool===e?P.items.push({label:c,detail:m}):t.push({kind:"tool_group",tool:e,items:[{label:c,detail:m}]})}return t}function _o(s,t){let n=s.headers.origin;En(n)&&(t.setHeader("Access-Control-Allow-Origin",n),t.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function y(s,t,n){s.writeHead(t,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function Oo(s,t){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||t.searchParams.get("projectId")||null}function Ao(s,t){if(!s)return t;let n=s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return t;let[,e,o,i]=n;return`\x1B[38;2;${parseInt(e,16)};${parseInt(o,16)};${parseInt(i,16)}m${t}\x1B[0m`}function vt(s,t){try{s.res.write(`event: ${t.type}
|
|
334
334
|
data: ${JSON.stringify(t)}
|
|
335
335
|
|