@duckmind/dm-darwin-x64 0.49.9 → 0.50.9
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/dm +0 -0
- package/extensions/.dm-extensions.json +4 -185
- package/extensions/dm-cliproxy/index.js +2 -2
- package/extensions/dm-cliproxy/scripts/check-config-migration.js +8 -10
- package/extensions/dm-cliproxy/src/apply.js +1 -1
- package/extensions/dm-cliproxy/src/cache.js +1 -1
- package/extensions/dm-cliproxy/src/commands.js +2 -2
- package/extensions/dm-cliproxy/src/config.js +2 -2
- package/extensions/dm-cliproxy/src/fetch-models.js +1 -1
- package/extensions/dm-cliproxy/src/fetch-usage.js +1 -1
- package/extensions/dm-cliproxy/src/ui-hub/hub.js +2 -2
- package/extensions/dm-cliproxy/src/ui-hub/index.js +2 -2
- package/extensions/dm-cliproxy/src/ui-hub/view-diagnostics.js +1 -1
- package/extensions/dm-cliproxy/src/ui-hub/view-usage.js +1 -1
- package/extensions/dm-cliproxy/src/ui-setup.js +2 -2
- package/extensions/dm-cliproxy/src/usage-shared-cache.js +1 -1
- package/extensions/dm-image2/index.js +7 -7
- package/extensions/dm-image2/src/image-lib.mjs +1 -1
- package/package.json +1 -1
- package/CHANGELOG.md +0 -4796
- package/extensions/dm-ask-user/index.js +0 -10
- package/extensions/dm-ask-user/package.json +0 -18
- package/extensions/dm-cli-anything/index.js +0 -5
- package/extensions/dm-cli-anything/package.json +0 -22
- package/extensions/dm-cli-anything/skills/cli-anything/SKILL.md +0 -21
- package/extensions/dm-cli-anything/vendor/public_registry.json +0 -367
- package/extensions/dm-cli-anything/vendor/registry.json +0 -1232
- package/extensions/dm-grill-me/index.js +0 -174
- package/extensions/dm-grill-me/package.json +0 -23
- package/extensions/dm-tasks/package.json +0 -20
- package/extensions/dm-tasks/src/auto-clear.js +0 -1
- package/extensions/dm-tasks/src/index.js +0 -212
- package/extensions/dm-tasks/src/process-tracker.js +0 -1
- package/extensions/dm-tasks/src/task-store.js +0 -1
- package/extensions/dm-tasks/src/tasks-config.js +0 -1
- package/extensions/dm-tasks/src/types.js +0 -0
- package/extensions/dm-tasks/src/ui/settings-menu.js +0 -1
- package/extensions/dm-tasks/src/ui/task-widget.js +0 -1
|
@@ -3,6 +3,6 @@ import{randomUUID as l}from"node:crypto";import{existsSync as F,mkdirSync as x,r
|
|
|
3
3
|
`)}function t(Z,$){let H=b[$]??b[A];return[Z,`Target aspect ratio: ${$}.`,`Compose for roughly ${H.width}x${H.height} output.`,"Generate the final answer by calling the image_generation tool.","If the prompt is a portrait or public person, keep it respectful and presentation-ready."].join(`
|
|
4
4
|
`)}function EZ(Z){let $=String(Z??"").trim();if(!$)throw Error("Codex returned an empty image response.");let H=$.match(/!\[[^\]]*]\((data:image\/svg\+xml[^)]+)\)/i);if(H?.[1]){let Q=H[1],z=Q.indexOf(",");if(z!==-1)return decodeURIComponent(Q.slice(z+1)).trim()}let W=$.match(/data:image\/svg\+xml[^,]*,(.+)$/is);if(W?.[1])return decodeURIComponent(W[1]).trim();let Y=$.match(/```(?:svg)?\s*([\s\S]*?)```/i)?.[1]?.trim();if(Y?.startsWith("<svg"))return Y;let J=$.match(/<svg[\s\S]*<\/svg>/i);if(J?.[0])return J[0].trim();throw Error(`Expected SVG markup from Codex, received: ${$.slice(0,240)}`)}async function c(Z,$,H){let W=LZ(H,y),X;try{X=await fetch(QZ,{method:"POST",signal:W.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${$.accessToken}`,Accept:"text/event-stream","Cache-Control":"no-cache",originator:"Codex Desktop","User-Agent":"Codex Desktop/26.212.1823 (darwin; arm64)","ChatGPT-Account-Id":$.accountId},body:JSON.stringify(Z)})}catch(K){if(W.cleanup(),C(K)||W.signal.aborted)throw w();throw K}if(!X.ok){W.cleanup();let K=await X.text().catch(()=>"");throw Error(`Codex image request failed: HTTP ${X.status} ${K.slice(0,240)}`)}if(!X.body)throw W.cleanup(),Error("Codex image request returned no response body.");let Y=new TextDecoder,J=X.body.getReader(),Q="",z=null,q=[],B="",G,N=[],U=()=>{if(!z||q.length===0)return z=null,q=[],!1;let K=JSON.parse(q.join(`
|
|
5
5
|
`));if(z==="response.output_text.delta"&&typeof K.delta==="string")B+=K.delta;if(z==="response.output_item.done"&&K.item&&typeof K.item==="object")N.push(K.item);if(z==="response.completed"||z==="response.done")return G=K.response?.id??G,z=null,q=[],!0;if(z==="response.failed"||z==="response.incomplete"){let j=K.response?.error?.message||K.response?.incomplete_details?.reason||"Codex image request did not complete.";throw Error(String(j))}return z=null,q=[],!1};try{while(!0){k(W.signal);let{value:K,done:j}=await J.read();Q+=Y.decode(K??new Uint8Array,{stream:!j});while(!0){let O=Q.indexOf(`
|
|
6
|
-
`);if(O===-1)break;let V=Q.slice(0,O);if(Q=Q.slice(O+1),V.endsWith("\r"))V=V.slice(0,-1);if(!V){if(U())return{assistantText:B.trim(),outputItems:N,responseId:G};continue}if(V.startsWith("event: "))z=V.slice(7).trim();else if(V.startsWith("data: "))q.push(V.slice(6))}if(j)break}if(q.length>0)U();return{assistantText:B.trim(),outputItems:N,responseId:G}}catch(K){if(await J.cancel().catch(()=>{}),C(K)||W.signal.aborted)throw w();throw K}finally{W.cleanup(),J.releaseLock()}}function IZ(Z,$,H){switch($){case"global":return f(L(n(),"generated-images"));case"custom":if(!H||!String(H).trim())throw Error("save=custom requires saveDir.");return f(String(H).trim());case"project":default:return f(Z,".dm","generated-images")}}function xZ(Z,$,H,W){let X=W||`run-${l().slice(0,8)}`;return f("/tmp","dm-imagen-runs",X)}function h(Z,$){x(R(Z),{recursive:!0}),d(Z,$,"utf-8")}function g(Z,$){x(R(Z),{recursive:!0}),d(Z,$)}function RZ(Z,$){let H=JZ("sips",["-s","format","png",Z,"--out",$],{encoding:"utf-8"});if(H.status===0&&F($))return;let W=(H.stderr||H.stdout||`exit ${H.status??"unknown"}`).trim();throw Error(`Failed to convert SVG to PNG via sips: ${W}`)}function e(Z,$="png"){let H=String(Z??"").trim();if(!H)throw Error("image_generation.result is empty");let W=H,X="";if(H.startsWith("data:")){let Q=H.indexOf(",");if(Q===-1)throw Error("image_generation.result data URL is malformed");let z=H.slice(5,Q);X=String(z.split(";",1)[0]??"").trim(),W=H.slice(Q+1)}let Y=Buffer.from(W,"base64");if(!Y.length)throw Error("image_generation.result decoded to empty bytes");let J=String($||"png").trim().toLowerCase().replace(/^\./,"")||"png";if(X==="image/jpeg")J="jpg";else if(X==="image/webp")J="webp";else if(X==="image/gif")J="gif";else if(X==="image/png")J="png";return{bytes:Y,mimeType:X||(J==="jpg"?"image/jpeg":`image/${J}`),extension:J}}function AZ(Z){return String(Z??"").trim().replace(/^['"]|['"]$/g,"")}function PZ(Z){if(!Z||!F(Z))return;try{for(let $ of S(Z,"utf-8").split(/\r?\n/)){let H=$.trim();if(!H||H.startsWith("#")||!H.includes("="))continue;if(H.startsWith("export "))H=H.slice(7).trim();let[W,...X]=H.split("="),Y=W.trim(),J=AZ(X.join("="));if((Y==="OPENROUTER_API_KEY"||Y==="OPENROUTER_KEY")&&J)return{apiKey:J,source:`config:${Z}`}}}catch{return}return}function u(Z){let $=[],H=f(Z||process.cwd());while(!0){$.push(L(H,"config","openrouter.cnf"));let W=R(H);if(W===H)break;H=W}return $}function yZ(Z){let $=process.env.OPENROUTER_API_KEY||process.env.OPENROUTER_KEY;if($)return{apiKey:$,source:"env:OPENROUTER_API_KEY"};let H=[...u(Z),...u(process.cwd()),L(p(),".dm","openrouter.cnf"),L(p(),".config","dm","openrouter.cnf")],W=new Set;for(let X of H){if(W.has(X))continue;W.add(X);let Y=PZ(X);if(Y)return Y}return}async function vZ(Z){let $=Z?.modelRegistry;if(!$||typeof $!=="object")return;if(typeof $.getApiKeyForProvider==="function")for(let Y of["openrouter","duckmind"]){let J=await $.getApiKeyForProvider(Y);if(typeof J==="string"&&J.trim())return{apiKey:J.trim(),source:`model-registry:${Y}`}}if(typeof $.getApiKeyAndHeaders!=="function")return;let H=[],W=new Set,X=(Y)=>{if(!Y||typeof Y!=="object")return;let J=String(Y.provider??"").toLowerCase();if(J!=="openrouter"&&J!=="duckmind")return;let Q=String(Y.id??Y.modelId??""),z=`${J}/${Q}`;if(W.has(z))return;W.add(z),H.push(Y)};if(X(Z?.model),typeof $.find==="function")X($.find("openrouter",I)),X($.find("openrouter","@preset/free"));if(typeof $.getAvailable==="function")for(let Y of $.getAvailable())X(Y);for(let Y of H){let J=await $.getApiKeyAndHeaders(Y);if(J?.ok&&typeof J.apiKey==="string"&&J.apiKey.trim())return{apiKey:J.apiKey.trim(),source:`model-registry:${Y.provider}/${Y.id??Y.modelId??""}`}}return}async function hZ(Z,$){return await vZ($)??yZ(Z)}function gZ(Z){let $=Z?.content;if(typeof $==="string")return $.trim();if(!Array.isArray($))return"";return $.map((H)=>{if(!H||typeof H!=="object")return"";return typeof H.text==="string"?H.text:""}).join("").trim()}function pZ(Z){for(let $ of Array.isArray(Z?.choices)?Z.choices:[]){let H=$?.message;for(let W of Array.isArray(H?.images)?H.images:[]){let X=W?.image_url,Y=typeof X==="string"?X:X?.url??W?.url;if(typeof Y==="string"&&Y.trim())return Y.trim()}for(let W of Array.isArray(H?.content)?H.content:[]){let X=W?.image_url,Y=typeof X==="string"?X:X?.url??W?.url;if(typeof Y==="string"&&Y.trim())return Y.trim()}}return""}async function mZ({prompt:Z,aspectRatio:$,outputFormat:H,model:W,outputRoot:X,baseName:Y,cwd:J,signal:Q,runtimeAuthContext:z}){if(H!=="png")throw Error("DuckMind image2 currently supports PNG output only.");if(typeof fetch!=="function")throw Error("DuckMind image2 requires a runtime with global fetch support.");let q=await hZ(J,z);if(!q?.apiKey)throw Error("Missing DuckMind API key for image2. Set OPENROUTER_API_KEY, paste a DuckMind API key via /login, or provide a local DuckMind
|
|
6
|
+
`);if(O===-1)break;let V=Q.slice(0,O);if(Q=Q.slice(O+1),V.endsWith("\r"))V=V.slice(0,-1);if(!V){if(U())return{assistantText:B.trim(),outputItems:N,responseId:G};continue}if(V.startsWith("event: "))z=V.slice(7).trim();else if(V.startsWith("data: "))q.push(V.slice(6))}if(j)break}if(q.length>0)U();return{assistantText:B.trim(),outputItems:N,responseId:G}}catch(K){if(await J.cancel().catch(()=>{}),C(K)||W.signal.aborted)throw w();throw K}finally{W.cleanup(),J.releaseLock()}}function IZ(Z,$,H){switch($){case"global":return f(L(n(),"generated-images"));case"custom":if(!H||!String(H).trim())throw Error("save=custom requires saveDir.");return f(String(H).trim());case"project":default:return f(Z,".dm","generated-images")}}function xZ(Z,$,H,W){let X=W||`run-${l().slice(0,8)}`;return f("/tmp","dm-imagen-runs",X)}function h(Z,$){x(R(Z),{recursive:!0}),d(Z,$,"utf-8")}function g(Z,$){x(R(Z),{recursive:!0}),d(Z,$)}function RZ(Z,$){let H=JZ("sips",["-s","format","png",Z,"--out",$],{encoding:"utf-8"});if(H.status===0&&F($))return;let W=(H.stderr||H.stdout||`exit ${H.status??"unknown"}`).trim();throw Error(`Failed to convert SVG to PNG via sips: ${W}`)}function e(Z,$="png"){let H=String(Z??"").trim();if(!H)throw Error("image_generation.result is empty");let W=H,X="";if(H.startsWith("data:")){let Q=H.indexOf(",");if(Q===-1)throw Error("image_generation.result data URL is malformed");let z=H.slice(5,Q);X=String(z.split(";",1)[0]??"").trim(),W=H.slice(Q+1)}let Y=Buffer.from(W,"base64");if(!Y.length)throw Error("image_generation.result decoded to empty bytes");let J=String($||"png").trim().toLowerCase().replace(/^\./,"")||"png";if(X==="image/jpeg")J="jpg";else if(X==="image/webp")J="webp";else if(X==="image/gif")J="gif";else if(X==="image/png")J="png";return{bytes:Y,mimeType:X||(J==="jpg"?"image/jpeg":`image/${J}`),extension:J}}function AZ(Z){return String(Z??"").trim().replace(/^['"]|['"]$/g,"")}function PZ(Z){if(!Z||!F(Z))return;try{for(let $ of S(Z,"utf-8").split(/\r?\n/)){let H=$.trim();if(!H||H.startsWith("#")||!H.includes("="))continue;if(H.startsWith("export "))H=H.slice(7).trim();let[W,...X]=H.split("="),Y=W.trim(),J=AZ(X.join("="));if((Y==="OPENROUTER_API_KEY"||Y==="OPENROUTER_KEY")&&J)return{apiKey:J,source:`config:${Z}`}}}catch{return}return}function u(Z){let $=[],H=f(Z||process.cwd());while(!0){$.push(L(H,"config","openrouter.cnf"));let W=R(H);if(W===H)break;H=W}return $}function yZ(Z){let $=process.env.OPENROUTER_API_KEY||process.env.OPENROUTER_KEY;if($)return{apiKey:$,source:"env:OPENROUTER_API_KEY"};let H=[...u(Z),...u(process.cwd()),L(p(),".dm","openrouter.cnf"),L(p(),".config","dm","openrouter.cnf")],W=new Set;for(let X of H){if(W.has(X))continue;W.add(X);let Y=PZ(X);if(Y)return Y}return}async function vZ(Z){let $=Z?.modelRegistry;if(!$||typeof $!=="object")return;if(typeof $.getApiKeyForProvider==="function")for(let Y of["openrouter","duckmind"]){let J=await $.getApiKeyForProvider(Y);if(typeof J==="string"&&J.trim())return{apiKey:J.trim(),source:`model-registry:${Y}`}}if(typeof $.getApiKeyAndHeaders!=="function")return;let H=[],W=new Set,X=(Y)=>{if(!Y||typeof Y!=="object")return;let J=String(Y.provider??"").toLowerCase();if(J!=="openrouter"&&J!=="duckmind")return;let Q=String(Y.id??Y.modelId??""),z=`${J}/${Q}`;if(W.has(z))return;W.add(z),H.push(Y)};if(X(Z?.model),typeof $.find==="function")X($.find("openrouter",I)),X($.find("openrouter","@preset/free"));if(typeof $.getAvailable==="function")for(let Y of $.getAvailable())X(Y);for(let Y of H){let J=await $.getApiKeyAndHeaders(Y);if(J?.ok&&typeof J.apiKey==="string"&&J.apiKey.trim())return{apiKey:J.apiKey.trim(),source:`model-registry:${Y.provider}/${Y.id??Y.modelId??""}`}}return}async function hZ(Z,$){return await vZ($)??yZ(Z)}function gZ(Z){let $=Z?.content;if(typeof $==="string")return $.trim();if(!Array.isArray($))return"";return $.map((H)=>{if(!H||typeof H!=="object")return"";return typeof H.text==="string"?H.text:""}).join("").trim()}function pZ(Z){for(let $ of Array.isArray(Z?.choices)?Z.choices:[]){let H=$?.message;for(let W of Array.isArray(H?.images)?H.images:[]){let X=W?.image_url,Y=typeof X==="string"?X:X?.url??W?.url;if(typeof Y==="string"&&Y.trim())return Y.trim()}for(let W of Array.isArray(H?.content)?H.content:[]){let X=W?.image_url,Y=typeof X==="string"?X:X?.url??W?.url;if(typeof Y==="string"&&Y.trim())return Y.trim()}}return""}async function mZ({prompt:Z,aspectRatio:$,outputFormat:H,model:W,outputRoot:X,baseName:Y,cwd:J,signal:Q,runtimeAuthContext:z}){if(H!=="png")throw Error("DuckMind image2 currently supports PNG output only.");if(typeof fetch!=="function")throw Error("DuckMind image2 requires a runtime with global fetch support.");let q=await hZ(J,z);if(!q?.apiKey)throw Error("Missing DuckMind API key for image2. Set OPENROUTER_API_KEY, paste a DuckMind API key via /login, or provide a local DuckMind image service config.");let B={model:W,modalities:["image","text"],messages:[{role:"user",content:[{type:"text",text:t(Z,$)}]}]},G=await fetch(zZ,{method:"POST",headers:{Authorization:`Bearer ${q.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(B),signal:Q}),N=await G.text(),U;try{U=N?JSON.parse(N):{}}catch{U={}}if(!G.ok){let _=U?.error?.message||U?.message||N.slice(0,400)||G.statusText;throw Error(`DuckMind image_generation failed (${G.status}): ${_}`)}let K=pZ(U);if(!K)throw Error("DuckMind image_generation returned no image data.");let j=e(K,H),O=L(X,`${Y}.${j.extension}`);g(O,j.bytes);let V=U?.choices?.[0]?.message;return{status:"ok",imagePath:O,svgPath:"",imageBase64:j.bytes.toString("base64"),mimeType:j.mimeType,prompt:Z,aspectRatio:$,model:W,source:q.source,responseId:typeof U?.id==="string"?U.id:"",revisedPrompt:"",backendMode:"openrouter-image-generation",requestedBackend:"openrouter:image2",authSource:q.source,assistantText:gZ(V),openRouterModel:typeof U?.model==="string"?U.model:""}}function cZ(Z){return Array.isArray(Z)?Z.filter(($)=>$&&typeof $==="object"&&$.type==="image_generation_call"):[]}function uZ(){let Z=a();return{tokens:{access_token:Z.accessToken,account_id:Z.accountId}}}function lZ(Z){let $=L(Z,"auth.json");return h($,JSON.stringify(uZ(),null,2)+`
|
|
7
7
|
`),$}function ZZ(){let Z=[],$=new Set;for(let[H,W]of[["env:auth_file",process.env.auth_file],["env:M_AUTH_FILE",process.env.M_AUTH_FILE]]){if(typeof W!=="string"||!W.trim())continue;let X=f(W);if(!F(X)||$.has(X))continue;$.add(X),Z.push({kind:"file",authSource:H,authFile:X})}return Z}function $Z(){let Z=v(r("auth.json"));if(!Z||typeof Z!=="object")return[];return Object.keys(Z).filter(($)=>$==="openai-codex"||/^openai-codex-account-\d+$/.test($)).sort(($,H)=>{if($==="openai-codex")return-1;if(H==="openai-codex")return 1;return $.localeCompare(H,void 0,{numeric:!0})}).map(($)=>{let H=Z[$],W=typeof H?.access==="string"?H.access:"",X=typeof H?.accountId==="string"?H.accountId:typeof H?.account_id==="string"?H.account_id:"";if(!W||!X)return;return{kind:"managed",authSource:`auth.json:${$}`,email:typeof H?.email==="string"?H.email:$,authData:{tokens:{access_token:W,account_id:X}}}}).filter(Boolean)}function dZ(Z,$){let H=[],W=new Set,X=(Q,z)=>{let q=z?.tokens?.access_token,B=z?.tokens?.account_id;if(typeof q!=="string"||!q.trim())return;if(typeof B!=="string"||!B.trim())return;let G=`inline:${Q}:${B}`;if(W.has(G))return;W.add(G),H.push({kind:"managed",authSource:Q,email:Q,authData:z})},Y=(Q,z)=>{if(!z)return;let q=f(z);if(!F(q))return;let B=`file:${q}`;if(W.has(B))return;W.add(B),H.push({kind:"file",authSource:Q,authFile:q})},J=$?.liveCodexCredentials;if(J?.accessToken&&J?.accountId)X(J.source||"model-registry",{tokens:{access_token:J.accessToken,account_id:J.accountId}});for(let Q of ZZ())Y(Q.authSource,Q.authFile);for(let Q of $Z()){let z=`managed:${Q.email}`;if(W.has(z))continue;W.add(z),H.push(Q)}if(H.length===0)H.push({kind:"file",authSource:"dm-auth-shim",authFile:lZ(Z)});return H}function nZ(Z){let H=v(Z)?.tokens,W=typeof H?.access_token==="string"?H.access_token.trim():"",X=typeof H?.account_id==="string"?H.account_id.trim():"";if(!W||!X)return;return{accessToken:W,accountId:X,email:void 0,source:Z}}function iZ(Z){let $=Z?.tokens,H=typeof $?.access_token==="string"?$.access_token.trim():"",W=typeof $?.account_id==="string"?$.account_id.trim():"";if(!H||!W)return;return{accessToken:H,accountId:W,email:void 0,source:"managed-inline"}}function sZ(){for(let Z of ZZ()){let $=nZ(Z.authFile);if($)return{...$,source:Z.authSource}}for(let Z of $Z()){let $=iZ(Z.authData);if($)return{...$,source:Z.authSource}}return a()}function HZ(Z){return String(Z??"").split(/\r?\n/).map(($)=>$.trim()).filter(Boolean).map(($)=>f($))}function oZ(Z){if(!F(Z))return[];return S(Z,"utf-8").split(/\r?\n/).map(($)=>$.trim()).filter(Boolean).map(($)=>{try{return JSON.parse($)}catch{return null}}).filter(Boolean)}function rZ(Z){let $=oZ(Z),H="",W="";for(let X of $)if(X?.type==="image_generation_call"&&typeof X.saved_path==="string"&&X.saved_path){if(H=X.saved_path,typeof X.revised_prompt==="string"&&X.revised_prompt)W=X.revised_prompt}return{savedPath:H,revisedPrompt:W}}async function aZ({prompt:Z,aspectRatio:$,model:H,outputFormat:W,cwd:X,signal:Y,sessionRoot:J,candidate:Q,index:z}){let q=L(J,`session-${z}.jsonl`),B=Q.authFile;if(Q.kind==="managed")B=L(J,`auth-${z}.json`),h(B,JSON.stringify(Q.authData,null,2)+`
|
|
8
8
|
`);let G={...process.env,PYTHONPATH:s+(process.env.PYTHONPATH?`:${process.env.PYTHONPATH}`:""),auth_file:B,model:H,quiet:"1",no_session_lock:"1",session:`new:${q}`},N=y;return await new Promise((U,K)=>{let j=!1,O="",V="",_=YZ("python3",[P,CZ(Z,$)],{cwd:X,env:G,stdio:["ignore","pipe","pipe"]}),T=setTimeout(()=>{_.kill("SIGTERM")},N),M=()=>{_.kill("SIGTERM")};Y?.addEventListener("abort",M,{once:!0}),_.stdout.on("data",(D)=>{O+=D.toString("utf-8")}),_.stderr.on("data",(D)=>{V+=D.toString("utf-8")}),_.on("error",(D)=>{if(j)return;j=!0,clearTimeout(T),Y?.removeEventListener("abort",M),K(D)}),_.on("close",(D,WZ)=>{if(j)return;if(j=!0,clearTimeout(T),Y?.removeEventListener("abort",M),Y?.aborted){K(w());return}if(WZ==="SIGTERM"){K(Error(`imagen.py timed out after ${Math.round(N/1000)}s`));return}if(D!==0){K(Error(V.trim()||O.trim()||`imagen.py exited ${D}`));return}U({stdout:O,stderr:V,sessionFile:q,sessionRoot:J,authSource:Q.authSource})})})}async function tZ({prompt:Z,aspectRatio:$,model:H,outputFormat:W,cwd:X,save:Y,saveDir:J,signal:Q,runId:z,runtimeAuthContext:q}){if(W!=="png")throw Error("The bundled imagen.py lane only supports PNG output.");if(!F(P))throw Error(`Bundled imagen.py is missing: ${P}`);let B=xZ(X,Y,J,z);x(B,{recursive:!0});let G=dZ(B,q),N=[];for(let[U,K]of G.entries())try{let j=await aZ({prompt:Z,aspectRatio:$,model:H,outputFormat:W,cwd:X,signal:Q,sessionRoot:B,candidate:K,index:U});if(HZ(j.stdout).length>0)return j;N.push(`${K.authSource}: no saved image path`)}catch(j){if(C(j))throw j;N.push(`${K.authSource}: ${j instanceof Error?j.message:String(j)}`)}throw Error(`imagen.py candidates exhausted: ${N.slice(-5).join(" | ")}`)}function eZ(Z,$,H){let W=f(Z);if(!F(W))throw Error(`imagen.py reported a missing artifact: ${W}`);let X=W.split(".").pop()||"png",Y=L($,`${H}.${X}`);return g(Y,S(W)),Y}async function Z0({prompt:Z,aspectRatio:$,outputFormat:H,model:W,outputRoot:X,baseName:Y,credentials:J,signal:Q,imagenError:z,requestedBackend:q}){let B="",G="",N="",U="image/png";try{if(H==="png"){let V=await c({model:W,instructions:bZ(),input:[{type:"message",role:"user",content:[{type:"input_text",text:t(Z,$)}]}],reasoning:{effort:"medium",summary:"detailed"},tools:[{type:"image_generation",output_format:"png"}],tool_choice:"auto",parallel_tool_calls:!1,store:!1,stream:!0,include:["reasoning.encrypted_content"]},J,Q),_=cZ(V.outputItems);if(_.length>0){let T=_[0],M=e(T.result,"png");return G=L(X,`${Y}.${M.extension}`),g(G,M.bytes),N=S(G).toString("base64"),{status:"ok",imagePath:G,svgPath:"",imageBase64:N,mimeType:M.mimeType,prompt:Z,aspectRatio:$,model:W,source:J.source,responseId:V.responseId,revisedPrompt:typeof T.revised_prompt==="string"?T.revised_prompt:"",backendMode:"native-image-generation",requestedBackend:q,imagenError:z,assistantText:V.assistantText}}}let{assistantText:K,responseId:j}=await c({model:W,instructions:wZ(),input:[{type:"message",role:"user",content:[{type:"input_text",text:kZ(Z,$)}]}],reasoning:{effort:"medium",summary:"detailed"},tool_choice:"auto",parallel_tool_calls:!1,store:!1,stream:!0,include:["reasoning.encrypted_content"]},J,Q);k(Q);let O=EZ(K);if(B=L(X,`${Y}.svg`),h(B,O),G=B,U="image/svg+xml",H==="png"){let V=L(X,`${Y}.png`);k(Q),RZ(B,V),k(Q),G=V,N=S(V).toString("base64"),U="image/png"}return{status:"ok",imagePath:G,svgPath:B,imageBase64:N,mimeType:U,prompt:Z,aspectRatio:$,model:W,source:J.source,responseId:j,backendMode:"svg-fallback",requestedBackend:q,imagenError:z,assistantText:K}}catch(K){if(C(K))for(let j of[G,B]){if(!j||!F(j))continue;try{XZ(j)}catch{}}throw K}}async function z0(Z,$,H,W=void 0){let X=String(Z.prompt??"").trim();if(!X)throw Error("image_generation.prompt is required.");k(H);let Y=UZ(Z.aspectRatio),J=NZ(Z.outputFormat),Q=o(Z.model),z=IZ($,Z.save??"project",Z.saveDir);x(z,{recursive:!0});let q=new Date().toISOString().replace(/[:.]/g,"-"),B=BZ(X),G=`image-${q}-${B}-${l().slice(0,8)}`;if(OZ(Q))return await mZ({prompt:X,aspectRatio:Y,outputFormat:J,model:Q,outputRoot:z,baseName:G,cwd:$,signal:H,runtimeAuthContext:W});let N=await SZ(W),U=N??sZ();try{let K=DZ();if(K>0)await MZ(K,H);let j="",O=_Z();if(J==="png"){try{let V=await tZ({prompt:X,aspectRatio:Y,model:Q,outputFormat:J,cwd:$,save:Z.save??"project",saveDir:Z.saveDir,signal:H,runId:G,runtimeAuthContext:N?{liveCodexCredentials:N}:W}),_=HZ(V.stdout);if(_.length>0){let T=rZ(V.sessionFile),M=eZ(T.savedPath||_[0],z,G),D=S(M).toString("base64");return{status:"ok",imagePath:M,svgPath:"",imageBase64:D,mimeType:"image/png",prompt:X,aspectRatio:Y,model:Q,source:U.source,responseId:"",revisedPrompt:T.revisedPrompt||"",backendMode:"imagen-py",requestedBackend:"imagen-py",authSource:V.authSource,assistantText:String(V.stderr??"").trim(),sessionFile:V.sessionFile,imagenSavedPaths:_}}j=`imagen.py produced no saved image path. stderr=${V.stderr.trim().slice(0,400)}`}catch(V){if(C(V))throw V;j=V instanceof Error?V.message:String(V)}if(!O)throw Error(`Bundled imagen.py is required for PNG image_generation, but it failed: ${j}. Provide a healthy DM Codex credential source or set ${i}=1 only for emergency legacy fallback debugging.`)}return await Z0({prompt:X,aspectRatio:Y,outputFormat:J,model:Q,outputRoot:z,baseName:G,credentials:U,signal:H,imagenError:j,requestedBackend:"legacy-fallback"})}catch(K){if(C(K))throw K;throw K}}export{MZ as sleepWithSignal,NZ as resolveOutputFormat,SZ as resolveLiveSessionCodexCredentials,o as resolveImageGenerationModel,sZ as resolveCustomFallbackCredentials,UZ as normalizeAspectRatio,a as loadActiveCodexCredentials,Q0 as isManagedCodexAccountUsable,_Z as isLegacyFallbackEnabled,C as isAbortError,z0 as generateVectorImage,EZ as extractSvgMarkup,TZ as extractAccountIdFromAccessToken,e as decodeGeneratedImageData,w as createAbortError,kZ as buildVectorPrompt};
|