@duckmind/dm-darwin-x64 0.50.0 → 0.51.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dm CHANGED
Binary file
@@ -17,21 +17,11 @@
17
17
  "target_dir": "extensions/dm-fff",
18
18
  "bundle_mode": "source-package-with-runtime-deps"
19
19
  },
20
- {
21
- "id": "dm-tasks",
22
- "target_dir": "extensions/dm-tasks",
23
- "bundle_mode": "source-package-with-runtime-deps"
24
- },
25
20
  {
26
21
  "id": "greedysearch-dm",
27
22
  "target_dir": "extensions/greedysearch-dm",
28
23
  "bundle_mode": "source-package-with-runtime-deps"
29
24
  },
30
- {
31
- "id": "dm-ask-user",
32
- "target_dir": "extensions/dm-ask-user",
33
- "bundle_mode": "source-package"
34
- },
35
25
  {
36
26
  "id": "dm-usage",
37
27
  "target_dir": "extensions/dm-usage",
@@ -47,11 +37,6 @@
47
37
  "target_dir": "extensions/dm-cliproxy",
48
38
  "bundle_mode": "source-package-with-runtime-deps"
49
39
  },
50
- {
51
- "id": "dm-grill-me",
52
- "target_dir": "extensions/dm-grill-me",
53
- "bundle_mode": "source-package-with-runtime-deps"
54
- },
55
40
  {
56
41
  "id": "dm-caveman",
57
42
  "target_dir": "extensions/dm-caveman",
@@ -68,11 +53,6 @@
68
53
  "id": "dm-image2",
69
54
  "target_dir": "extensions/dm-image2",
70
55
  "bundle_mode": "local-source-package"
71
- },
72
- {
73
- "id": "dm-cli-anything",
74
- "target_dir": "extensions/dm-cli-anything",
75
- "bundle_mode": "local-source-package"
76
56
  }
77
57
  ],
78
58
  "prepared_entries": [
@@ -293,54 +273,6 @@
293
273
  ]
294
274
  }
295
275
  },
296
- {
297
- "id": "dm-tasks",
298
- "staged_dir": "extensions/dm-tasks",
299
- "bundle_mode": "source-package-with-runtime-deps",
300
- "dependencies_installed": false,
301
- "dependency_mode": "platform-package-dependency",
302
- "dependencies_declared": [
303
- "typebox"
304
- ],
305
- "dependency_patches": [
306
- "dm.extensions ts->js",
307
- "drop-dependencies",
308
- "drop-devDependencies",
309
- "drop-scripts",
310
- "drop-files"
311
- ],
312
- "stripped_documentation": [
313
- "LICENSE",
314
- "README.md"
315
- ],
316
- "javascript_bundle_minify": {
317
- "tool": "bun build --minify",
318
- "files": [
319
- "src/auto-clear.js",
320
- "src/index.js",
321
- "src/process-tracker.js",
322
- "src/task-store.js",
323
- "src/tasks-config.js",
324
- "src/types.js",
325
- "src/ui/settings-menu.js",
326
- "src/ui/task-widget.js"
327
- ],
328
- "file_count": 8,
329
- "before_bytes": 79022,
330
- "after_bytes": 49861,
331
- "externals": [
332
- "@biomejs/biome",
333
- "@duckmind/dm-agent-core",
334
- "@duckmind/dm-ai",
335
- "@duckmind/dm-coding-agent",
336
- "@duckmind/dm-tui",
337
- "@types/node",
338
- "typebox",
339
- "typescript",
340
- "vitest"
341
- ]
342
- }
343
- },
344
276
  {
345
277
  "id": "greedysearch-dm",
346
278
  "staged_dir": "extensions/greedysearch-dm",
@@ -440,44 +372,6 @@
440
372
  ]
441
373
  }
442
374
  },
443
- {
444
- "id": "dm-ask-user",
445
- "staged_dir": "extensions/dm-ask-user",
446
- "bundle_mode": "source-package",
447
- "dependencies_installed": false,
448
- "dependency_mode": "platform-package-dependency",
449
- "dependencies_declared": [
450
- "@duckmind/dm-ai",
451
- "@duckmind/dm-coding-agent",
452
- "@duckmind/dm-tui",
453
- "@sinclair/typebox"
454
- ],
455
- "dependency_patches": [
456
- "dm.extensions ts->js",
457
- "drop-devDependencies",
458
- "drop-peerDependencies",
459
- "drop-files"
460
- ],
461
- "stripped_documentation": [
462
- "README.md"
463
- ],
464
- "javascript_bundle_minify": {
465
- "tool": "bun build --minify",
466
- "files": [
467
- "index.js"
468
- ],
469
- "file_count": 1,
470
- "before_bytes": 30280,
471
- "after_bytes": 12912,
472
- "externals": [
473
- "@duckmind/dm-agent-core",
474
- "@duckmind/dm-ai",
475
- "@duckmind/dm-coding-agent",
476
- "@duckmind/dm-tui",
477
- "@sinclair/typebox"
478
- ]
479
- }
480
- },
481
375
  {
482
376
  "id": "dm-usage",
483
377
  "staged_dir": "extensions/dm-usage",
@@ -631,49 +525,6 @@
631
525
  ]
632
526
  }
633
527
  },
634
- {
635
- "id": "dm-grill-me",
636
- "staged_dir": "extensions/dm-grill-me",
637
- "bundle_mode": "source-package-with-runtime-deps",
638
- "dependencies_installed": false,
639
- "dependency_mode": "platform-package-dependency",
640
- "dependencies_declared": [
641
- "@duckmind/dm-coding-agent",
642
- "@duckmind/dm-tui",
643
- "typebox"
644
- ],
645
- "dependency_patches": [
646
- "dm.extensions ts->js",
647
- "drop-dependencies",
648
- "drop-devDependencies",
649
- "drop-peerDependencies",
650
- "drop-scripts",
651
- "drop-files"
652
- ],
653
- "stripped_documentation": [
654
- "DESIGN.md",
655
- "LICENSE",
656
- "README.md"
657
- ],
658
- "javascript_bundle_minify": {
659
- "tool": "bun build --minify",
660
- "files": [
661
- "index.js"
662
- ],
663
- "file_count": 1,
664
- "before_bytes": 53067,
665
- "after_bytes": 37967,
666
- "externals": [
667
- "@duckmind/dm-agent-core",
668
- "@duckmind/dm-ai",
669
- "@duckmind/dm-coding-agent",
670
- "@duckmind/dm-tui",
671
- "@types/node",
672
- "typebox",
673
- "typescript"
674
- ]
675
- }
676
- },
677
528
  {
678
529
  "id": "dm-caveman",
679
530
  "staged_dir": "extensions/dm-caveman",
@@ -764,8 +615,8 @@
764
615
  "src/image-lib.mjs"
765
616
  ],
766
617
  "file_count": 2,
767
- "before_bytes": 47834,
768
- "after_bytes": 50025,
618
+ "before_bytes": 47805,
619
+ "after_bytes": 49995,
769
620
  "externals": [
770
621
  "@duckmind/dm-agent-core",
771
622
  "@duckmind/dm-ai",
@@ -774,38 +625,6 @@
774
625
  "@sinclair/typebox"
775
626
  ]
776
627
  }
777
- },
778
- {
779
- "id": "dm-cli-anything",
780
- "staged_dir": "extensions/dm-cli-anything",
781
- "bundle_mode": "local-source-package",
782
- "dependencies_installed": false,
783
- "dependency_mode": "none",
784
- "dependency_patches": [
785
- "drop-devDependencies",
786
- "drop-peerDependencies",
787
- "drop-files"
788
- ],
789
- "stripped_documentation": [
790
- "LICENSE",
791
- "README.md",
792
- "vendor/UPSTREAM.md"
793
- ],
794
- "javascript_bundle_minify": {
795
- "tool": "bun build --minify",
796
- "files": [
797
- "index.js"
798
- ],
799
- "file_count": 1,
800
- "before_bytes": 11318,
801
- "after_bytes": 7451,
802
- "externals": [
803
- "@duckmind/dm-agent-core",
804
- "@duckmind/dm-ai",
805
- "@duckmind/dm-coding-agent",
806
- "@duckmind/dm-tui"
807
- ]
808
- }
809
628
  }
810
629
  ],
811
630
  "bundled_dependencies": {
@@ -1,9 +1,9 @@
1
- import{existsSync as X$}from"node:fs";import{join as f$}from"node:path";import{Type as D}from"@sinclair/typebox";import{getAgentDir as H1}from"@duckmind/dm-coding-agent";import{randomUUID as i}from"node:crypto";import{existsSync as w,mkdirSync as x,readFileSync as k,unlinkSync as J$,writeFileSync as o}from"node:fs";import{dirname as A,join as N,resolve as S}from"node:path";import{spawn as Q$,spawnSync as z$}from"node:child_process";import{homedir as u}from"node:os";import{getAgentDir as r}from"@duckmind/dm-coding-agent";var O$="https://chatgpt.com/backend-api/codex/responses",V$="https://openrouter.ai/api/v1/chat/completions",P="1:1",U$="png",v=900000,B$="DM_IMAGE_TEST_DELAY_MS",s="DM_IMAGE_ALLOW_LEGACY_FALLBACK",I="@preset/image2",_$=I,R="gpt-5.5",q$=new Set(["image2",I,"duckmind/image2","duckmind/@preset/image2","openrouter/image2","openrouter/@preset/image2"]),N$=new Set([R,`openai-codex/${R}`,`codex/${R}`]),F={"1:1":{width:1024,height:1024},"4:5":{width:1024,height:1280},"16:9":{width:1600,height:900}},a=S(A(new URL(import.meta.url).pathname),"..","vendor","imagen"),y=N(a,"imagen.py");function D$($){return String($??"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"image"}function g($){return typeof $==="string"&&$ in F?$:P}function h($){return $==="svg"?"svg":U$}function t($){let j=String($??"").trim();if(N$.has(j))return R;return q$.has(j)?I:_$}function M$($){return t($)===I}function L$($=process.env[s]){return typeof $==="string"&&/^(1|true|yes|on)$/i.test($.trim())}function C($="Request was aborted"){let j=Error($);return j.name="AbortError",j}function b($){if(!$)return!1;if($ instanceof Error&&$.name==="AbortError")return!0;let j=$ instanceof Error?$.message:String($);return j==="Request was aborted"||j==="This operation was aborted"}function E($){if(!$?.aborted)return;if($.reason instanceof Error)throw $.reason;throw C()}function S$($,j=v){let Y=new AbortController,Z=setTimeout(()=>Y.abort(C(`Image request timed out after ${Math.round(j/1000)}s`)),j),G=()=>{Y.abort($?.reason instanceof Error?$.reason:C())};if($?.aborted)G();else if($)$.addEventListener("abort",G,{once:!0});return{signal:Y.signal,cleanup(){clearTimeout(Z),$?.removeEventListener("abort",G)}}}function T$($,j){if(!Number.isFinite($)||$<=0)return Promise.resolve();return E(j),new Promise((Y,Z)=>{let G=setTimeout(()=>{j?.removeEventListener("abort",H),Y()},$),H=()=>{clearTimeout(G),j?.removeEventListener("abort",H),Z(C())};j?.addEventListener("abort",H,{once:!0})})}function b$(){let $=String(process.env[B$]??"").trim();if(!$)return 0;let j=Number.parseInt($,10);if(!Number.isFinite(j)||j<=0)return 0;return Math.min(j,300000)}function e($){return N(r(),$)}function p($){try{return JSON.parse(k($,"utf-8"))}catch{return}}function w$($){if(!$||typeof $!=="object")return;let j=Object.keys($).filter((H)=>H==="openai-codex"||/^openai-codex-account-\d+$/.test(H)).sort((H,W)=>{if(H==="openai-codex")return-1;if(W==="openai-codex")return 1;return H.localeCompare(W,void 0,{numeric:!0})}).find((H)=>{let W=$[H];return W&&typeof W==="object"&&!Array.isArray(W)}),Y=j?$[j]:void 0;if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let Z=typeof Y.access==="string"?Y.access:void 0,G=typeof Y.accountId==="string"?Y.accountId:typeof Y.account_id==="string"?Y.account_id:void 0;if(!Z||!G)return;return{accessToken:Z,accountId:G,email:typeof Y.email==="string"?Y.email:void 0}}function k$($){try{let j=String($??"").split(".");if(j.length!==3)return;let Z=JSON.parse(Buffer.from(j[1],"base64url").toString("utf8"))?.["https://api.openai.com/auth"]?.chatgpt_account_id;return typeof Z==="string"&&Z.trim()?Z.trim():void 0}catch{return}}function d($,j){if(!$||typeof $!=="object")return;let Y=j.toLowerCase();for(let[Z,G]of Object.entries($)){if(String(Z).toLowerCase()!==Y)continue;if(typeof G==="string"&&G.trim())return G.trim()}return}function F$($){let j=$?.modelRegistry,Y=[],Z=new Set,G=(H)=>{if(!H||typeof H!=="object")return;if(H.provider!=="openai-codex")return;let W=`${H.provider}/${H.id}`;if(Z.has(W))return;Z.add(W),Y.push(H)};if(G($?.model),j&&typeof j.find==="function")G(j.find("openai-codex",R));if(j&&typeof j.getAvailable==="function")for(let H of j.getAvailable())G(H);return Y}async function C$($){let j=$?.modelRegistry;if(!j||typeof j.getApiKeyAndHeaders!=="function")return;for(let Y of F$($)){let Z=await j.getApiKeyAndHeaders(Y);if(!Z?.ok||!Z.apiKey)continue;let G=k$(Z.apiKey)||d(Z.headers,"ChatGPT-Account-Id")||d(Z.headers,"chatgpt-account-id");if(!G)continue;return{accessToken:Z.apiKey,accountId:G,email:void 0,source:`model-registry:${Y.provider}/${Y.id}`}}return}function $$(){let $=p(e("auth.json")),j=w$($);if(j)return{...j,source:"auth.json"};throw Error("Missing active Codex credentials. Ensure ~/.dm/agent/auth.json contains an openai-codex or openai-codex-account-N account.")}function E$(){return["You are a focused image-generation assistant.","Finish by calling image_generation for the final answer.","Do not stop at plain text when the user asked for an image.","Follow the requested visual direction, aspect ratio, and subject details closely."].join(" ")}function R$(){return["You are a vector illustrator.","Return exactly one standalone SVG image and no prose.","Do not wrap the SVG in markdown fences.","Do not return a data URI unless absolutely necessary.","Do not mention limitations, policies, or explanations in the answer."].join(" ")}function I$($,j){let Y=F[j]??F[P];return[`Create one polished self-contained SVG illustration for this brief: ${$}`,`Use a ${j} aspect ratio with a ${Y.width}x${Y.height} canvas and a matching viewBox.`,"Return only raw <svg>...</svg> markup.","Use simple shapes, gradients, paths, and fills; avoid external fonts, scripts, or remote URLs.","If the request is a portrait, make it respectful, stylized, and presentation-ready."].join(`
1
+ import{existsSync as X$}from"node:fs";import{join as f$}from"node:path";import{Type as D}from"@sinclair/typebox";import{getAgentDir as H1}from"@duckmind/dm-coding-agent";import{randomUUID as i}from"node:crypto";import{existsSync as w,mkdirSync as x,readFileSync as k,unlinkSync as J$,writeFileSync as o}from"node:fs";import{dirname as A,join as N,resolve as S}from"node:path";import{spawn as Q$,spawnSync as z$}from"node:child_process";import{homedir as u}from"node:os";import{getAgentDir as r}from"@duckmind/dm-coding-agent";var V$="https://chatgpt.com/backend-api/codex/responses",O$="https://openrouter.ai/api/v1/chat/completions",P="1:1",U$="png",v=900000,B$="DM_IMAGE_TEST_DELAY_MS",s="DM_IMAGE_ALLOW_LEGACY_FALLBACK",I="@preset/image2",_$=I,R="gpt-5.5",q$=new Set(["image2",I,"duckmind/image2","duckmind/@preset/image2","openrouter/image2","openrouter/@preset/image2"]),N$=new Set([R,`openai-codex/${R}`,`codex/${R}`]),F={"1:1":{width:1024,height:1024},"4:5":{width:1024,height:1280},"16:9":{width:1600,height:900}},a=S(A(new URL(import.meta.url).pathname),"..","vendor","imagen"),y=N(a,"imagen.py");function D$($){return String($??"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"image"}function g($){return typeof $==="string"&&$ in F?$:P}function h($){return $==="svg"?"svg":U$}function t($){let j=String($??"").trim();if(N$.has(j))return R;return q$.has(j)?I:_$}function M$($){return t($)===I}function L$($=process.env[s]){return typeof $==="string"&&/^(1|true|yes|on)$/i.test($.trim())}function C($="Request was aborted"){let j=Error($);return j.name="AbortError",j}function b($){if(!$)return!1;if($ instanceof Error&&$.name==="AbortError")return!0;let j=$ instanceof Error?$.message:String($);return j==="Request was aborted"||j==="This operation was aborted"}function E($){if(!$?.aborted)return;if($.reason instanceof Error)throw $.reason;throw C()}function S$($,j=v){let Y=new AbortController,Z=setTimeout(()=>Y.abort(C(`Image request timed out after ${Math.round(j/1000)}s`)),j),G=()=>{Y.abort($?.reason instanceof Error?$.reason:C())};if($?.aborted)G();else if($)$.addEventListener("abort",G,{once:!0});return{signal:Y.signal,cleanup(){clearTimeout(Z),$?.removeEventListener("abort",G)}}}function T$($,j){if(!Number.isFinite($)||$<=0)return Promise.resolve();return E(j),new Promise((Y,Z)=>{let G=setTimeout(()=>{j?.removeEventListener("abort",H),Y()},$),H=()=>{clearTimeout(G),j?.removeEventListener("abort",H),Z(C())};j?.addEventListener("abort",H,{once:!0})})}function b$(){let $=String(process.env[B$]??"").trim();if(!$)return 0;let j=Number.parseInt($,10);if(!Number.isFinite(j)||j<=0)return 0;return Math.min(j,300000)}function e($){return N(r(),$)}function p($){try{return JSON.parse(k($,"utf-8"))}catch{return}}function w$($){if(!$||typeof $!=="object")return;let j=Object.keys($).filter((H)=>H==="openai-codex"||/^openai-codex-account-\d+$/.test(H)).sort((H,W)=>{if(H==="openai-codex")return-1;if(W==="openai-codex")return 1;return H.localeCompare(W,void 0,{numeric:!0})}).find((H)=>{let W=$[H];return W&&typeof W==="object"&&!Array.isArray(W)}),Y=j?$[j]:void 0;if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let Z=typeof Y.access==="string"?Y.access:void 0,G=typeof Y.accountId==="string"?Y.accountId:typeof Y.account_id==="string"?Y.account_id:void 0;if(!Z||!G)return;return{accessToken:Z,accountId:G,email:typeof Y.email==="string"?Y.email:void 0}}function k$($){try{let j=String($??"").split(".");if(j.length!==3)return;let Z=JSON.parse(Buffer.from(j[1],"base64url").toString("utf8"))?.["https://api.openai.com/auth"]?.chatgpt_account_id;return typeof Z==="string"&&Z.trim()?Z.trim():void 0}catch{return}}function d($,j){if(!$||typeof $!=="object")return;let Y=j.toLowerCase();for(let[Z,G]of Object.entries($)){if(String(Z).toLowerCase()!==Y)continue;if(typeof G==="string"&&G.trim())return G.trim()}return}function F$($){let j=$?.modelRegistry,Y=[],Z=new Set,G=(H)=>{if(!H||typeof H!=="object")return;if(H.provider!=="openai-codex")return;let W=`${H.provider}/${H.id}`;if(Z.has(W))return;Z.add(W),Y.push(H)};if(G($?.model),j&&typeof j.find==="function")G(j.find("openai-codex",R));if(j&&typeof j.getAvailable==="function")for(let H of j.getAvailable())G(H);return Y}async function C$($){let j=$?.modelRegistry;if(!j||typeof j.getApiKeyAndHeaders!=="function")return;for(let Y of F$($)){let Z=await j.getApiKeyAndHeaders(Y);if(!Z?.ok||!Z.apiKey)continue;let G=k$(Z.apiKey)||d(Z.headers,"ChatGPT-Account-Id")||d(Z.headers,"chatgpt-account-id");if(!G)continue;return{accessToken:Z.apiKey,accountId:G,email:void 0,source:`model-registry:${Y.provider}/${Y.id}`}}return}function $$(){let $=p(e("auth.json")),j=w$($);if(j)return{...j,source:"auth.json"};throw Error("Missing active Codex credentials. Ensure ~/.dm/agent/auth.json contains an openai-codex or openai-codex-account-N account.")}function E$(){return["You are a focused image-generation assistant.","Finish by calling image_generation for the final answer.","Do not stop at plain text when the user asked for an image.","Follow the requested visual direction, aspect ratio, and subject details closely."].join(" ")}function R$(){return["You are a vector illustrator.","Return exactly one standalone SVG image and no prose.","Do not wrap the SVG in markdown fences.","Do not return a data URI unless absolutely necessary.","Do not mention limitations, policies, or explanations in the answer."].join(" ")}function I$($,j){let Y=F[j]??F[P];return[`Create one polished self-contained SVG illustration for this brief: ${$}`,`Use a ${j} aspect ratio with a ${Y.width}x${Y.height} canvas and a matching viewBox.`,"Return only raw <svg>...</svg> markup.","Use simple shapes, gradients, paths, and fills; avoid external fonts, scripts, or remote URLs.","If the request is a portrait, make it respectful, stylized, and presentation-ready."].join(`
2
2
  `)}function x$($,j){let Y=F[j]??F[P];return[$,`Output in exactly ${Y.width}px x ${Y.height}px (${j}).`,"Prefer production-ready composition, grounded local detail when relevant, and the strongest final image_generation call."].join(`
3
3
  `)}function j$($,j){let Y=F[j]??F[P];return[$,`Target aspect ratio: ${j}.`,`Compose for roughly ${Y.width}x${Y.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
- `)}function A$($){let j=String($??"").trim();if(!j)throw Error("Codex returned an empty image response.");let Y=j.match(/!\[[^\]]*]\((data:image\/svg\+xml[^)]+)\)/i);if(Y?.[1]){let X=Y[1],f=X.indexOf(",");if(f!==-1)return decodeURIComponent(X.slice(f+1)).trim()}let Z=j.match(/data:image\/svg\+xml[^,]*,(.+)$/is);if(Z?.[1])return decodeURIComponent(Z[1]).trim();let H=j.match(/```(?:svg)?\s*([\s\S]*?)```/i)?.[1]?.trim();if(H?.startsWith("<svg"))return H;let W=j.match(/<svg[\s\S]*<\/svg>/i);if(W?.[0])return W[0].trim();throw Error(`Expected SVG markup from Codex, received: ${j.slice(0,240)}`)}async function l($,j,Y){let Z=S$(Y,v),G;try{G=await fetch(O$,{method:"POST",signal:Z.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.accessToken}`,Accept:"text/event-stream","Cache-Control":"no-cache",originator:"Codex Desktop","User-Agent":"Codex Desktop/26.212.1823 (darwin; arm64)","ChatGPT-Account-Id":j.accountId},body:JSON.stringify($)})}catch(K){if(Z.cleanup(),b(K)||Z.signal.aborted)throw C();throw K}if(!G.ok){Z.cleanup();let K=await G.text().catch(()=>"");throw Error(`Codex image request failed: HTTP ${G.status} ${K.slice(0,240)}`)}if(!G.body)throw Z.cleanup(),Error("Codex image request returned no response body.");let H=new TextDecoder,W=G.body.getReader(),X="",f=null,O=[],V="",z,B=[],U=()=>{if(!f||O.length===0)return f=null,O=[],!1;let K=JSON.parse(O.join(`
5
- `));if(f==="response.output_text.delta"&&typeof K.delta==="string")V+=K.delta;if(f==="response.output_item.done"&&K.item&&typeof K.item==="object")B.push(K.item);if(f==="response.completed"||f==="response.done")return z=K.response?.id??z,f=null,O=[],!0;if(f==="response.failed"||f==="response.incomplete"){let Q=K.response?.error?.message||K.response?.incomplete_details?.reason||"Codex image request did not complete.";throw Error(String(Q))}return f=null,O=[],!1};try{while(!0){E(Z.signal);let{value:K,done:Q}=await W.read();X+=H.decode(K??new Uint8Array,{stream:!Q});while(!0){let _=X.indexOf(`
6
- `);if(_===-1)break;let J=X.slice(0,_);if(X=X.slice(_+1),J.endsWith("\r"))J=J.slice(0,-1);if(!J){if(U())return{assistantText:V.trim(),outputItems:B,responseId:z};continue}if(J.startsWith("event: "))f=J.slice(7).trim();else if(J.startsWith("data: "))O.push(J.slice(6))}if(Q)break}if(O.length>0)U();return{assistantText:V.trim(),outputItems:B,responseId:z}}catch(K){if(await W.cancel().catch(()=>{}),b(K)||Z.signal.aborted)throw C();throw K}finally{Z.cleanup(),W.releaseLock()}}function P$($,j,Y){switch(j){case"global":return S(N(r(),"generated-images"));case"custom":if(!Y||!String(Y).trim())throw Error("save=custom requires saveDir.");return S(String(Y).trim());case"project":default:return S($,".dm","generated-images")}}function y$($,j,Y,Z){let G=Z||`run-${i().slice(0,8)}`;return S("/tmp","dm-imagen-runs",G)}function m($,j){x(A($),{recursive:!0}),o($,j,"utf-8")}function c($,j){x(A($),{recursive:!0}),o($,j)}function v$($,j){let Y=z$("sips",["-s","format","png",$,"--out",j],{encoding:"utf-8"});if(Y.status===0&&w(j))return;let Z=(Y.stderr||Y.stdout||`exit ${Y.status??"unknown"}`).trim();throw Error(`Failed to convert SVG to PNG via sips: ${Z}`)}function Y$($,j="png"){let Y=String($??"").trim();if(!Y)throw Error("image_generation.result is empty");let Z=Y,G="";if(Y.startsWith("data:")){let X=Y.indexOf(",");if(X===-1)throw Error("image_generation.result data URL is malformed");let f=Y.slice(5,X);G=String(f.split(";",1)[0]??"").trim(),Z=Y.slice(X+1)}let H=Buffer.from(Z,"base64");if(!H.length)throw Error("image_generation.result decoded to empty bytes");let W=String(j||"png").trim().toLowerCase().replace(/^\./,"")||"png";if(G==="image/jpeg")W="jpg";else if(G==="image/webp")W="webp";else if(G==="image/gif")W="gif";else if(G==="image/png")W="png";return{bytes:H,mimeType:G||(W==="jpg"?"image/jpeg":`image/${W}`),extension:W}}function g$($){return String($??"").trim().replace(/^['"]|['"]$/g,"")}function h$($){if(!$||!w($))return;try{for(let j of k($,"utf-8").split(/\r?\n/)){let Y=j.trim();if(!Y||Y.startsWith("#")||!Y.includes("="))continue;if(Y.startsWith("export "))Y=Y.slice(7).trim();let[Z,...G]=Y.split("="),H=Z.trim(),W=g$(G.join("="));if((H==="OPENROUTER_API_KEY"||H==="OPENROUTER_KEY")&&W)return{apiKey:W,source:`config:${$}`}}}catch{return}return}function n($){let j=[],Y=S($||process.cwd());while(!0){j.push(N(Y,"config","openrouter.cnf"));let Z=A(Y);if(Z===Y)break;Y=Z}return j}function p$($){let j=process.env.OPENROUTER_API_KEY||process.env.OPENROUTER_KEY;if(j)return{apiKey:j,source:"env:OPENROUTER_API_KEY"};let Y=[...n($),...n(process.cwd()),N(u(),".dm","openrouter.cnf"),N(u(),".config","dm","openrouter.cnf")],Z=new Set;for(let G of Y){if(Z.has(G))continue;Z.add(G);let H=h$(G);if(H)return H}return}async function m$($){let j=$?.modelRegistry;if(!j||typeof j!=="object")return;if(typeof j.getApiKeyForProvider==="function")for(let H of["openrouter","duckmind"]){let W=await j.getApiKeyForProvider(H);if(typeof W==="string"&&W.trim())return{apiKey:W.trim(),source:`model-registry:${H}`}}if(typeof j.getApiKeyAndHeaders!=="function")return;let Y=[],Z=new Set,G=(H)=>{if(!H||typeof H!=="object")return;let W=String(H.provider??"").toLowerCase();if(W!=="openrouter"&&W!=="duckmind")return;let X=String(H.id??H.modelId??""),f=`${W}/${X}`;if(Z.has(f))return;Z.add(f),Y.push(H)};if(G($?.model),typeof j.find==="function")G(j.find("openrouter",I)),G(j.find("openrouter","@preset/free"));if(typeof j.getAvailable==="function")for(let H of j.getAvailable())G(H);for(let H of Y){let W=await j.getApiKeyAndHeaders(H);if(W?.ok&&typeof W.apiKey==="string"&&W.apiKey.trim())return{apiKey:W.apiKey.trim(),source:`model-registry:${H.provider}/${H.id??H.modelId??""}`}}return}async function c$($,j){return await m$(j)??p$($)}function u$($){let j=$?.content;if(typeof j==="string")return j.trim();if(!Array.isArray(j))return"";return j.map((Y)=>{if(!Y||typeof Y!=="object")return"";return typeof Y.text==="string"?Y.text:""}).join("").trim()}function d$($){for(let j of Array.isArray($?.choices)?$.choices:[]){let Y=j?.message;for(let Z of Array.isArray(Y?.images)?Y.images:[]){let G=Z?.image_url,H=typeof G==="string"?G:G?.url??Z?.url;if(typeof H==="string"&&H.trim())return H.trim()}for(let Z of Array.isArray(Y?.content)?Y.content:[]){let G=Z?.image_url,H=typeof G==="string"?G:G?.url??Z?.url;if(typeof H==="string"&&H.trim())return H.trim()}}return""}async function l$({prompt:$,aspectRatio:j,outputFormat:Y,model:Z,outputRoot:G,baseName:H,cwd:W,signal:X,runtimeAuthContext:f}){if(Y!=="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 O=await c$(W,f);if(!O?.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/OpenRouter config.");let V={model:Z,modalities:["image","text"],messages:[{role:"user",content:[{type:"text",text:j$($,j)}]}]},z=await fetch(V$,{method:"POST",headers:{Authorization:`Bearer ${O.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(V),signal:X}),B=await z.text(),U;try{U=B?JSON.parse(B):{}}catch{U={}}if(!z.ok){let q=U?.error?.message||U?.message||B.slice(0,400)||z.statusText;throw Error(`OpenRouter image_generation failed (${z.status}): ${q}`)}let K=d$(U);if(!K)throw Error("OpenRouter image_generation returned no image data.");let Q=Y$(K,Y),_=N(G,`${H}.${Q.extension}`);c(_,Q.bytes);let J=U?.choices?.[0]?.message;return{status:"ok",imagePath:_,svgPath:"",imageBase64:Q.bytes.toString("base64"),mimeType:Q.mimeType,prompt:$,aspectRatio:j,model:Z,source:O.source,responseId:typeof U?.id==="string"?U.id:"",revisedPrompt:"",backendMode:"openrouter-image-generation",requestedBackend:"openrouter:image2",authSource:O.source,assistantText:u$(J),openRouterModel:typeof U?.model==="string"?U.model:""}}function n$($){return Array.isArray($)?$.filter((j)=>j&&typeof j==="object"&&j.type==="image_generation_call"):[]}function i$(){let $=$$();return{tokens:{access_token:$.accessToken,account_id:$.accountId}}}function o$($){let j=N($,"auth.json");return m(j,JSON.stringify(i$(),null,2)+`
7
- `),j}function Z$(){let $=[],j=new Set;for(let[Y,Z]of[["env:auth_file",process.env.auth_file],["env:M_AUTH_FILE",process.env.M_AUTH_FILE]]){if(typeof Z!=="string"||!Z.trim())continue;let G=S(Z);if(!w(G)||j.has(G))continue;j.add(G),$.push({kind:"file",authSource:Y,authFile:G})}return $}function G$(){let $=p(e("auth.json"));if(!$||typeof $!=="object")return[];return Object.keys($).filter((j)=>j==="openai-codex"||/^openai-codex-account-\d+$/.test(j)).sort((j,Y)=>{if(j==="openai-codex")return-1;if(Y==="openai-codex")return 1;return j.localeCompare(Y,void 0,{numeric:!0})}).map((j)=>{let Y=$[j],Z=typeof Y?.access==="string"?Y.access:"",G=typeof Y?.accountId==="string"?Y.accountId:typeof Y?.account_id==="string"?Y.account_id:"";if(!Z||!G)return;return{kind:"managed",authSource:`auth.json:${j}`,email:typeof Y?.email==="string"?Y.email:j,authData:{tokens:{access_token:Z,account_id:G}}}}).filter(Boolean)}function r$($,j){let Y=[],Z=new Set,G=(X,f)=>{let O=f?.tokens?.access_token,V=f?.tokens?.account_id;if(typeof O!=="string"||!O.trim())return;if(typeof V!=="string"||!V.trim())return;let z=`inline:${X}:${V}`;if(Z.has(z))return;Z.add(z),Y.push({kind:"managed",authSource:X,email:X,authData:f})},H=(X,f)=>{if(!f)return;let O=S(f);if(!w(O))return;let V=`file:${O}`;if(Z.has(V))return;Z.add(V),Y.push({kind:"file",authSource:X,authFile:O})},W=j?.liveCodexCredentials;if(W?.accessToken&&W?.accountId)G(W.source||"model-registry",{tokens:{access_token:W.accessToken,account_id:W.accountId}});for(let X of Z$())H(X.authSource,X.authFile);for(let X of G$()){let f=`managed:${X.email}`;if(Z.has(f))continue;Z.add(f),Y.push(X)}if(Y.length===0)Y.push({kind:"file",authSource:"dm-auth-shim",authFile:o$($)});return Y}function s$($){let Y=p($)?.tokens,Z=typeof Y?.access_token==="string"?Y.access_token.trim():"",G=typeof Y?.account_id==="string"?Y.account_id.trim():"";if(!Z||!G)return;return{accessToken:Z,accountId:G,email:void 0,source:$}}function a$($){let j=$?.tokens,Y=typeof j?.access_token==="string"?j.access_token.trim():"",Z=typeof j?.account_id==="string"?j.account_id.trim():"";if(!Y||!Z)return;return{accessToken:Y,accountId:Z,email:void 0,source:"managed-inline"}}function t$(){for(let $ of Z$()){let j=s$($.authFile);if(j)return{...j,source:$.authSource}}for(let $ of G$()){let j=a$($.authData);if(j)return{...j,source:$.authSource}}return $$()}function H$($){return String($??"").split(/\r?\n/).map((j)=>j.trim()).filter(Boolean).map((j)=>S(j))}function e$($){if(!w($))return[];return k($,"utf-8").split(/\r?\n/).map((j)=>j.trim()).filter(Boolean).map((j)=>{try{return JSON.parse(j)}catch{return null}}).filter(Boolean)}function $1($){let j=e$($),Y="",Z="";for(let G of j)if(G?.type==="image_generation_call"&&typeof G.saved_path==="string"&&G.saved_path){if(Y=G.saved_path,typeof G.revised_prompt==="string"&&G.revised_prompt)Z=G.revised_prompt}return{savedPath:Y,revisedPrompt:Z}}async function j1({prompt:$,aspectRatio:j,model:Y,outputFormat:Z,cwd:G,signal:H,sessionRoot:W,candidate:X,index:f}){let O=N(W,`session-${f}.jsonl`),V=X.authFile;if(X.kind==="managed")V=N(W,`auth-${f}.json`),m(V,JSON.stringify(X.authData,null,2)+`
8
- `);let z={...process.env,PYTHONPATH:a+(process.env.PYTHONPATH?`:${process.env.PYTHONPATH}`:""),auth_file:V,model:Y,quiet:"1",no_session_lock:"1",session:`new:${O}`},B=v;return await new Promise((U,K)=>{let Q=!1,_="",J="",q=Q$("python3",[y,x$($,j)],{cwd:G,env:z,stdio:["ignore","pipe","pipe"]}),T=setTimeout(()=>{q.kill("SIGTERM")},B),M=()=>{q.kill("SIGTERM")};H?.addEventListener("abort",M,{once:!0}),q.stdout.on("data",(L)=>{_+=L.toString("utf-8")}),q.stderr.on("data",(L)=>{J+=L.toString("utf-8")}),q.on("error",(L)=>{if(Q)return;Q=!0,clearTimeout(T),H?.removeEventListener("abort",M),K(L)}),q.on("close",(L,K$)=>{if(Q)return;if(Q=!0,clearTimeout(T),H?.removeEventListener("abort",M),H?.aborted){K(C());return}if(K$==="SIGTERM"){K(Error(`imagen.py timed out after ${Math.round(B/1000)}s`));return}if(L!==0){K(Error(J.trim()||_.trim()||`imagen.py exited ${L}`));return}U({stdout:_,stderr:J,sessionFile:O,sessionRoot:W,authSource:X.authSource})})})}async function Y1({prompt:$,aspectRatio:j,model:Y,outputFormat:Z,cwd:G,save:H,saveDir:W,signal:X,runId:f,runtimeAuthContext:O}){if(Z!=="png")throw Error("The bundled imagen.py lane only supports PNG output.");if(!w(y))throw Error(`Bundled imagen.py is missing: ${y}`);let V=y$(G,H,W,f);x(V,{recursive:!0});let z=r$(V,O),B=[];for(let[U,K]of z.entries())try{let Q=await j1({prompt:$,aspectRatio:j,model:Y,outputFormat:Z,cwd:G,signal:X,sessionRoot:V,candidate:K,index:U});if(H$(Q.stdout).length>0)return Q;B.push(`${K.authSource}: no saved image path`)}catch(Q){if(b(Q))throw Q;B.push(`${K.authSource}: ${Q instanceof Error?Q.message:String(Q)}`)}throw Error(`imagen.py candidates exhausted: ${B.slice(-5).join(" | ")}`)}function Z1($,j,Y){let Z=S($);if(!w(Z))throw Error(`imagen.py reported a missing artifact: ${Z}`);let G=Z.split(".").pop()||"png",H=N(j,`${Y}.${G}`);return c(H,k(Z)),H}async function G1({prompt:$,aspectRatio:j,outputFormat:Y,model:Z,outputRoot:G,baseName:H,credentials:W,signal:X,imagenError:f,requestedBackend:O}){let V="",z="",B="",U="image/png";try{if(Y==="png"){let J=await l({model:Z,instructions:E$(),input:[{type:"message",role:"user",content:[{type:"input_text",text:j$($,j)}]}],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"]},W,X),q=n$(J.outputItems);if(q.length>0){let T=q[0],M=Y$(T.result,"png");return z=N(G,`${H}.${M.extension}`),c(z,M.bytes),B=k(z).toString("base64"),{status:"ok",imagePath:z,svgPath:"",imageBase64:B,mimeType:M.mimeType,prompt:$,aspectRatio:j,model:Z,source:W.source,responseId:J.responseId,revisedPrompt:typeof T.revised_prompt==="string"?T.revised_prompt:"",backendMode:"native-image-generation",requestedBackend:O,imagenError:f,assistantText:J.assistantText}}}let{assistantText:K,responseId:Q}=await l({model:Z,instructions:R$(),input:[{type:"message",role:"user",content:[{type:"input_text",text:I$($,j)}]}],reasoning:{effort:"medium",summary:"detailed"},tool_choice:"auto",parallel_tool_calls:!1,store:!1,stream:!0,include:["reasoning.encrypted_content"]},W,X);E(X);let _=A$(K);if(V=N(G,`${H}.svg`),m(V,_),z=V,U="image/svg+xml",Y==="png"){let J=N(G,`${H}.png`);E(X),v$(V,J),E(X),z=J,B=k(J).toString("base64"),U="image/png"}return{status:"ok",imagePath:z,svgPath:V,imageBase64:B,mimeType:U,prompt:$,aspectRatio:j,model:Z,source:W.source,responseId:Q,backendMode:"svg-fallback",requestedBackend:O,imagenError:f,assistantText:K}}catch(K){if(b(K))for(let Q of[z,V]){if(!Q||!w(Q))continue;try{J$(Q)}catch{}}throw K}}async function W$($,j,Y,Z=void 0){let G=String($.prompt??"").trim();if(!G)throw Error("image_generation.prompt is required.");E(Y);let H=g($.aspectRatio),W=h($.outputFormat),X=t($.model),f=P$(j,$.save??"project",$.saveDir);x(f,{recursive:!0});let O=new Date().toISOString().replace(/[:.]/g,"-"),V=D$(G),z=`image-${O}-${V}-${i().slice(0,8)}`;if(M$(X))return await l$({prompt:G,aspectRatio:H,outputFormat:W,model:X,outputRoot:f,baseName:z,cwd:j,signal:Y,runtimeAuthContext:Z});let B=await C$(Z),U=B??t$();try{let K=b$();if(K>0)await T$(K,Y);let Q="",_=L$();if(W==="png"){try{let J=await Y1({prompt:G,aspectRatio:H,model:X,outputFormat:W,cwd:j,save:$.save??"project",saveDir:$.saveDir,signal:Y,runId:z,runtimeAuthContext:B?{liveCodexCredentials:B}:Z}),q=H$(J.stdout);if(q.length>0){let T=$1(J.sessionFile),M=Z1(T.savedPath||q[0],f,z),L=k(M).toString("base64");return{status:"ok",imagePath:M,svgPath:"",imageBase64:L,mimeType:"image/png",prompt:G,aspectRatio:H,model:X,source:U.source,responseId:"",revisedPrompt:T.revisedPrompt||"",backendMode:"imagen-py",requestedBackend:"imagen-py",authSource:J.authSource,assistantText:String(J.stderr??"").trim(),sessionFile:J.sessionFile,imagenSavedPaths:q}}Q=`imagen.py produced no saved image path. stderr=${J.stderr.trim().slice(0,400)}`}catch(J){if(b(J))throw J;Q=J instanceof Error?J.message:String(J)}if(!_)throw Error(`Bundled imagen.py is required for PNG image_generation, but it failed: ${Q}. Provide a healthy DM Codex credential source or set ${s}=1 only for emergency legacy fallback debugging.`)}return await G1({prompt:G,aspectRatio:H,outputFormat:W,model:X,outputRoot:f,baseName:z,credentials:U,signal:Y,imagenError:Q,requestedBackend:"legacy-fallback"})}catch(K){if(b(K))throw K;throw K}}var W1=["project","global","custom"],X1=D.Object({prompt:D.String({description:"Detailed art direction for the image. Include subject, pose, mood, style, background, and any research findings you want preserved."}),aspectRatio:D.Optional(D.String({description:"Target aspect ratio. Supported: 1:1, 4:5, 16:9. Default: 1:1."})),model:D.Optional(D.String({description:"Optional model override. Defaults to DuckMind image2/@preset/image2 on OpenRouter. Use gpt-5.5/openai-codex/gpt-5.5 only for the legacy Codex lane."})),outputFormat:D.Optional(D.String({description:"Artifact format. Supported: png, svg. Default: png."})),save:D.Optional(D.String({description:"Artifact destination: project, global, or custom. Default: project."})),saveDir:D.Optional(D.String({description:"Custom artifact directory when save=custom."}))},{additionalProperties:!1});function f1($){let j=[`Saved image: ${$.imagePath}`];if($.svgPath&&$.svgPath!==$.imagePath)j.push(`SVG source: ${$.svgPath}`);if(j.push(`Model: ${$.model}`),j.push(`Aspect: ${$.aspectRatio}`),$.backendMode)j.push(`Backend: ${$.backendMode}`);if($.source)j.push(`Auth source: ${$.source}`);return j.join(`
9
- `)}function K1($){$.on("session_start",async(j,Y)=>{let Z=H1(),G=typeof Y.modelRegistry?.getProviderAuthStatus==="function"?Y.modelRegistry.getProviderAuthStatus("openrouter"):void 0;if(!(process.env.OPENROUTER_API_KEY||process.env.OPENROUTER_KEY||X$(f$(process.cwd(),"config","openrouter.cnf"))||G?.configured)&&!X$(f$(Z,"auth.json")))Y.ui.notify("dm-image2: no DuckMind API key or Codex auth.json account found. image2 can use OPENROUTER_API_KEY, /login, or local config; the legacy Codex lane needs ~/.dm/agent/auth.json.","warning")}),$.registerTool({name:"image_generation",label:"Image Generation",description:"Generate a polished PNG image artifact using DuckMind image2 on OpenRouter by default, or the bundled imagen.py lane from M only when model=gpt-5.5/openai-codex/gpt-5.5. Use this after research for logos, diagrams, posters, portraits, and other image tasks instead of asking the model to dump raw image data inline.",promptSnippet:"Dedicated image-generation lane. Use it for logos, portraits, diagrams, product shots, posters, UI mockups, character sheets, and artifacts you want saved to disk.",promptGuidelines:["Prefer image_generation over raw SVG or markdown image data in the final answer.","Use the bundled image-generation skill's pattern families: product hero, ad storyboard, editorial portrait, poster, character sheet, UI mockup, and comparison exploration.","Do research first when the image must reflect real people, products, or public facts.","Do not call third-party image APIs; route generation through this tool.","Answer with the saved artifact path after the tool succeeds."],parameters:X1,async execute(j,Y,Z,G,H){try{let W=await W$({prompt:Y.prompt,aspectRatio:g(Y.aspectRatio),model:Y.model,outputFormat:h(Y.outputFormat),save:typeof Y.save==="string"&&W1.includes(Y.save)?Y.save:"project",saveDir:typeof Y.saveDir==="string"?Y.saveDir:void 0},H.cwd,Z,{modelRegistry:H.modelRegistry,model:H.model}),X=[{type:"text",text:f1(W)}];if(W.imageBase64&&W.mimeType==="image/png")X.push({type:"image",data:W.imageBase64,mimeType:W.mimeType});return{content:X,details:W}}catch(W){if(Z?.aborted||b(W))throw W;let X=W instanceof Error?W.message:String(W);return{content:[{type:"text",text:`image_generation failed: ${X}`}],details:{status:"error",message:X},isError:!0}}}})}export{K1 as default};
4
+ `)}function A$($){let j=String($??"").trim();if(!j)throw Error("Codex returned an empty image response.");let Y=j.match(/!\[[^\]]*]\((data:image\/svg\+xml[^)]+)\)/i);if(Y?.[1]){let X=Y[1],f=X.indexOf(",");if(f!==-1)return decodeURIComponent(X.slice(f+1)).trim()}let Z=j.match(/data:image\/svg\+xml[^,]*,(.+)$/is);if(Z?.[1])return decodeURIComponent(Z[1]).trim();let H=j.match(/```(?:svg)?\s*([\s\S]*?)```/i)?.[1]?.trim();if(H?.startsWith("<svg"))return H;let W=j.match(/<svg[\s\S]*<\/svg>/i);if(W?.[0])return W[0].trim();throw Error(`Expected SVG markup from Codex, received: ${j.slice(0,240)}`)}async function l($,j,Y){let Z=S$(Y,v),G;try{G=await fetch(V$,{method:"POST",signal:Z.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.accessToken}`,Accept:"text/event-stream","Cache-Control":"no-cache",originator:"Codex Desktop","User-Agent":"Codex Desktop/26.212.1823 (darwin; arm64)","ChatGPT-Account-Id":j.accountId},body:JSON.stringify($)})}catch(K){if(Z.cleanup(),b(K)||Z.signal.aborted)throw C();throw K}if(!G.ok){Z.cleanup();let K=await G.text().catch(()=>"");throw Error(`Codex image request failed: HTTP ${G.status} ${K.slice(0,240)}`)}if(!G.body)throw Z.cleanup(),Error("Codex image request returned no response body.");let H=new TextDecoder,W=G.body.getReader(),X="",f=null,V=[],O="",z,B=[],U=()=>{if(!f||V.length===0)return f=null,V=[],!1;let K=JSON.parse(V.join(`
5
+ `));if(f==="response.output_text.delta"&&typeof K.delta==="string")O+=K.delta;if(f==="response.output_item.done"&&K.item&&typeof K.item==="object")B.push(K.item);if(f==="response.completed"||f==="response.done")return z=K.response?.id??z,f=null,V=[],!0;if(f==="response.failed"||f==="response.incomplete"){let Q=K.response?.error?.message||K.response?.incomplete_details?.reason||"Codex image request did not complete.";throw Error(String(Q))}return f=null,V=[],!1};try{while(!0){E(Z.signal);let{value:K,done:Q}=await W.read();X+=H.decode(K??new Uint8Array,{stream:!Q});while(!0){let _=X.indexOf(`
6
+ `);if(_===-1)break;let J=X.slice(0,_);if(X=X.slice(_+1),J.endsWith("\r"))J=J.slice(0,-1);if(!J){if(U())return{assistantText:O.trim(),outputItems:B,responseId:z};continue}if(J.startsWith("event: "))f=J.slice(7).trim();else if(J.startsWith("data: "))V.push(J.slice(6))}if(Q)break}if(V.length>0)U();return{assistantText:O.trim(),outputItems:B,responseId:z}}catch(K){if(await W.cancel().catch(()=>{}),b(K)||Z.signal.aborted)throw C();throw K}finally{Z.cleanup(),W.releaseLock()}}function P$($,j,Y){switch(j){case"global":return S(N(r(),"generated-images"));case"custom":if(!Y||!String(Y).trim())throw Error("save=custom requires saveDir.");return S(String(Y).trim());case"project":default:return S($,".dm","generated-images")}}function y$($,j,Y,Z){let G=Z||`run-${i().slice(0,8)}`;return S("/tmp","dm-imagen-runs",G)}function m($,j){x(A($),{recursive:!0}),o($,j,"utf-8")}function c($,j){x(A($),{recursive:!0}),o($,j)}function v$($,j){let Y=z$("sips",["-s","format","png",$,"--out",j],{encoding:"utf-8"});if(Y.status===0&&w(j))return;let Z=(Y.stderr||Y.stdout||`exit ${Y.status??"unknown"}`).trim();throw Error(`Failed to convert SVG to PNG via sips: ${Z}`)}function Y$($,j="png"){let Y=String($??"").trim();if(!Y)throw Error("image_generation.result is empty");let Z=Y,G="";if(Y.startsWith("data:")){let X=Y.indexOf(",");if(X===-1)throw Error("image_generation.result data URL is malformed");let f=Y.slice(5,X);G=String(f.split(";",1)[0]??"").trim(),Z=Y.slice(X+1)}let H=Buffer.from(Z,"base64");if(!H.length)throw Error("image_generation.result decoded to empty bytes");let W=String(j||"png").trim().toLowerCase().replace(/^\./,"")||"png";if(G==="image/jpeg")W="jpg";else if(G==="image/webp")W="webp";else if(G==="image/gif")W="gif";else if(G==="image/png")W="png";return{bytes:H,mimeType:G||(W==="jpg"?"image/jpeg":`image/${W}`),extension:W}}function g$($){return String($??"").trim().replace(/^['"]|['"]$/g,"")}function h$($){if(!$||!w($))return;try{for(let j of k($,"utf-8").split(/\r?\n/)){let Y=j.trim();if(!Y||Y.startsWith("#")||!Y.includes("="))continue;if(Y.startsWith("export "))Y=Y.slice(7).trim();let[Z,...G]=Y.split("="),H=Z.trim(),W=g$(G.join("="));if((H==="OPENROUTER_API_KEY"||H==="OPENROUTER_KEY")&&W)return{apiKey:W,source:`config:${$}`}}}catch{return}return}function n($){let j=[],Y=S($||process.cwd());while(!0){j.push(N(Y,"config","openrouter.cnf"));let Z=A(Y);if(Z===Y)break;Y=Z}return j}function p$($){let j=process.env.OPENROUTER_API_KEY||process.env.OPENROUTER_KEY;if(j)return{apiKey:j,source:"env:OPENROUTER_API_KEY"};let Y=[...n($),...n(process.cwd()),N(u(),".dm","openrouter.cnf"),N(u(),".config","dm","openrouter.cnf")],Z=new Set;for(let G of Y){if(Z.has(G))continue;Z.add(G);let H=h$(G);if(H)return H}return}async function m$($){let j=$?.modelRegistry;if(!j||typeof j!=="object")return;if(typeof j.getApiKeyForProvider==="function")for(let H of["openrouter","duckmind"]){let W=await j.getApiKeyForProvider(H);if(typeof W==="string"&&W.trim())return{apiKey:W.trim(),source:`model-registry:${H}`}}if(typeof j.getApiKeyAndHeaders!=="function")return;let Y=[],Z=new Set,G=(H)=>{if(!H||typeof H!=="object")return;let W=String(H.provider??"").toLowerCase();if(W!=="openrouter"&&W!=="duckmind")return;let X=String(H.id??H.modelId??""),f=`${W}/${X}`;if(Z.has(f))return;Z.add(f),Y.push(H)};if(G($?.model),typeof j.find==="function")G(j.find("openrouter",I)),G(j.find("openrouter","@preset/free"));if(typeof j.getAvailable==="function")for(let H of j.getAvailable())G(H);for(let H of Y){let W=await j.getApiKeyAndHeaders(H);if(W?.ok&&typeof W.apiKey==="string"&&W.apiKey.trim())return{apiKey:W.apiKey.trim(),source:`model-registry:${H.provider}/${H.id??H.modelId??""}`}}return}async function c$($,j){return await m$(j)??p$($)}function u$($){let j=$?.content;if(typeof j==="string")return j.trim();if(!Array.isArray(j))return"";return j.map((Y)=>{if(!Y||typeof Y!=="object")return"";return typeof Y.text==="string"?Y.text:""}).join("").trim()}function d$($){for(let j of Array.isArray($?.choices)?$.choices:[]){let Y=j?.message;for(let Z of Array.isArray(Y?.images)?Y.images:[]){let G=Z?.image_url,H=typeof G==="string"?G:G?.url??Z?.url;if(typeof H==="string"&&H.trim())return H.trim()}for(let Z of Array.isArray(Y?.content)?Y.content:[]){let G=Z?.image_url,H=typeof G==="string"?G:G?.url??Z?.url;if(typeof H==="string"&&H.trim())return H.trim()}}return""}async function l$({prompt:$,aspectRatio:j,outputFormat:Y,model:Z,outputRoot:G,baseName:H,cwd:W,signal:X,runtimeAuthContext:f}){if(Y!=="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 V=await c$(W,f);if(!V?.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 O={model:Z,modalities:["image","text"],messages:[{role:"user",content:[{type:"text",text:j$($,j)}]}]},z=await fetch(O$,{method:"POST",headers:{Authorization:`Bearer ${V.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(O),signal:X}),B=await z.text(),U;try{U=B?JSON.parse(B):{}}catch{U={}}if(!z.ok){let q=U?.error?.message||U?.message||B.slice(0,400)||z.statusText;throw Error(`DuckMind image_generation failed (${z.status}): ${q}`)}let K=d$(U);if(!K)throw Error("DuckMind image_generation returned no image data.");let Q=Y$(K,Y),_=N(G,`${H}.${Q.extension}`);c(_,Q.bytes);let J=U?.choices?.[0]?.message;return{status:"ok",imagePath:_,svgPath:"",imageBase64:Q.bytes.toString("base64"),mimeType:Q.mimeType,prompt:$,aspectRatio:j,model:Z,source:V.source,responseId:typeof U?.id==="string"?U.id:"",revisedPrompt:"",backendMode:"openrouter-image-generation",requestedBackend:"openrouter:image2",authSource:V.source,assistantText:u$(J),openRouterModel:typeof U?.model==="string"?U.model:""}}function n$($){return Array.isArray($)?$.filter((j)=>j&&typeof j==="object"&&j.type==="image_generation_call"):[]}function i$(){let $=$$();return{tokens:{access_token:$.accessToken,account_id:$.accountId}}}function o$($){let j=N($,"auth.json");return m(j,JSON.stringify(i$(),null,2)+`
7
+ `),j}function Z$(){let $=[],j=new Set;for(let[Y,Z]of[["env:auth_file",process.env.auth_file],["env:M_AUTH_FILE",process.env.M_AUTH_FILE]]){if(typeof Z!=="string"||!Z.trim())continue;let G=S(Z);if(!w(G)||j.has(G))continue;j.add(G),$.push({kind:"file",authSource:Y,authFile:G})}return $}function G$(){let $=p(e("auth.json"));if(!$||typeof $!=="object")return[];return Object.keys($).filter((j)=>j==="openai-codex"||/^openai-codex-account-\d+$/.test(j)).sort((j,Y)=>{if(j==="openai-codex")return-1;if(Y==="openai-codex")return 1;return j.localeCompare(Y,void 0,{numeric:!0})}).map((j)=>{let Y=$[j],Z=typeof Y?.access==="string"?Y.access:"",G=typeof Y?.accountId==="string"?Y.accountId:typeof Y?.account_id==="string"?Y.account_id:"";if(!Z||!G)return;return{kind:"managed",authSource:`auth.json:${j}`,email:typeof Y?.email==="string"?Y.email:j,authData:{tokens:{access_token:Z,account_id:G}}}}).filter(Boolean)}function r$($,j){let Y=[],Z=new Set,G=(X,f)=>{let V=f?.tokens?.access_token,O=f?.tokens?.account_id;if(typeof V!=="string"||!V.trim())return;if(typeof O!=="string"||!O.trim())return;let z=`inline:${X}:${O}`;if(Z.has(z))return;Z.add(z),Y.push({kind:"managed",authSource:X,email:X,authData:f})},H=(X,f)=>{if(!f)return;let V=S(f);if(!w(V))return;let O=`file:${V}`;if(Z.has(O))return;Z.add(O),Y.push({kind:"file",authSource:X,authFile:V})},W=j?.liveCodexCredentials;if(W?.accessToken&&W?.accountId)G(W.source||"model-registry",{tokens:{access_token:W.accessToken,account_id:W.accountId}});for(let X of Z$())H(X.authSource,X.authFile);for(let X of G$()){let f=`managed:${X.email}`;if(Z.has(f))continue;Z.add(f),Y.push(X)}if(Y.length===0)Y.push({kind:"file",authSource:"dm-auth-shim",authFile:o$($)});return Y}function s$($){let Y=p($)?.tokens,Z=typeof Y?.access_token==="string"?Y.access_token.trim():"",G=typeof Y?.account_id==="string"?Y.account_id.trim():"";if(!Z||!G)return;return{accessToken:Z,accountId:G,email:void 0,source:$}}function a$($){let j=$?.tokens,Y=typeof j?.access_token==="string"?j.access_token.trim():"",Z=typeof j?.account_id==="string"?j.account_id.trim():"";if(!Y||!Z)return;return{accessToken:Y,accountId:Z,email:void 0,source:"managed-inline"}}function t$(){for(let $ of Z$()){let j=s$($.authFile);if(j)return{...j,source:$.authSource}}for(let $ of G$()){let j=a$($.authData);if(j)return{...j,source:$.authSource}}return $$()}function H$($){return String($??"").split(/\r?\n/).map((j)=>j.trim()).filter(Boolean).map((j)=>S(j))}function e$($){if(!w($))return[];return k($,"utf-8").split(/\r?\n/).map((j)=>j.trim()).filter(Boolean).map((j)=>{try{return JSON.parse(j)}catch{return null}}).filter(Boolean)}function $1($){let j=e$($),Y="",Z="";for(let G of j)if(G?.type==="image_generation_call"&&typeof G.saved_path==="string"&&G.saved_path){if(Y=G.saved_path,typeof G.revised_prompt==="string"&&G.revised_prompt)Z=G.revised_prompt}return{savedPath:Y,revisedPrompt:Z}}async function j1({prompt:$,aspectRatio:j,model:Y,outputFormat:Z,cwd:G,signal:H,sessionRoot:W,candidate:X,index:f}){let V=N(W,`session-${f}.jsonl`),O=X.authFile;if(X.kind==="managed")O=N(W,`auth-${f}.json`),m(O,JSON.stringify(X.authData,null,2)+`
8
+ `);let z={...process.env,PYTHONPATH:a+(process.env.PYTHONPATH?`:${process.env.PYTHONPATH}`:""),auth_file:O,model:Y,quiet:"1",no_session_lock:"1",session:`new:${V}`},B=v;return await new Promise((U,K)=>{let Q=!1,_="",J="",q=Q$("python3",[y,x$($,j)],{cwd:G,env:z,stdio:["ignore","pipe","pipe"]}),T=setTimeout(()=>{q.kill("SIGTERM")},B),M=()=>{q.kill("SIGTERM")};H?.addEventListener("abort",M,{once:!0}),q.stdout.on("data",(L)=>{_+=L.toString("utf-8")}),q.stderr.on("data",(L)=>{J+=L.toString("utf-8")}),q.on("error",(L)=>{if(Q)return;Q=!0,clearTimeout(T),H?.removeEventListener("abort",M),K(L)}),q.on("close",(L,K$)=>{if(Q)return;if(Q=!0,clearTimeout(T),H?.removeEventListener("abort",M),H?.aborted){K(C());return}if(K$==="SIGTERM"){K(Error(`imagen.py timed out after ${Math.round(B/1000)}s`));return}if(L!==0){K(Error(J.trim()||_.trim()||`imagen.py exited ${L}`));return}U({stdout:_,stderr:J,sessionFile:V,sessionRoot:W,authSource:X.authSource})})})}async function Y1({prompt:$,aspectRatio:j,model:Y,outputFormat:Z,cwd:G,save:H,saveDir:W,signal:X,runId:f,runtimeAuthContext:V}){if(Z!=="png")throw Error("The bundled imagen.py lane only supports PNG output.");if(!w(y))throw Error(`Bundled imagen.py is missing: ${y}`);let O=y$(G,H,W,f);x(O,{recursive:!0});let z=r$(O,V),B=[];for(let[U,K]of z.entries())try{let Q=await j1({prompt:$,aspectRatio:j,model:Y,outputFormat:Z,cwd:G,signal:X,sessionRoot:O,candidate:K,index:U});if(H$(Q.stdout).length>0)return Q;B.push(`${K.authSource}: no saved image path`)}catch(Q){if(b(Q))throw Q;B.push(`${K.authSource}: ${Q instanceof Error?Q.message:String(Q)}`)}throw Error(`imagen.py candidates exhausted: ${B.slice(-5).join(" | ")}`)}function Z1($,j,Y){let Z=S($);if(!w(Z))throw Error(`imagen.py reported a missing artifact: ${Z}`);let G=Z.split(".").pop()||"png",H=N(j,`${Y}.${G}`);return c(H,k(Z)),H}async function G1({prompt:$,aspectRatio:j,outputFormat:Y,model:Z,outputRoot:G,baseName:H,credentials:W,signal:X,imagenError:f,requestedBackend:V}){let O="",z="",B="",U="image/png";try{if(Y==="png"){let J=await l({model:Z,instructions:E$(),input:[{type:"message",role:"user",content:[{type:"input_text",text:j$($,j)}]}],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"]},W,X),q=n$(J.outputItems);if(q.length>0){let T=q[0],M=Y$(T.result,"png");return z=N(G,`${H}.${M.extension}`),c(z,M.bytes),B=k(z).toString("base64"),{status:"ok",imagePath:z,svgPath:"",imageBase64:B,mimeType:M.mimeType,prompt:$,aspectRatio:j,model:Z,source:W.source,responseId:J.responseId,revisedPrompt:typeof T.revised_prompt==="string"?T.revised_prompt:"",backendMode:"native-image-generation",requestedBackend:V,imagenError:f,assistantText:J.assistantText}}}let{assistantText:K,responseId:Q}=await l({model:Z,instructions:R$(),input:[{type:"message",role:"user",content:[{type:"input_text",text:I$($,j)}]}],reasoning:{effort:"medium",summary:"detailed"},tool_choice:"auto",parallel_tool_calls:!1,store:!1,stream:!0,include:["reasoning.encrypted_content"]},W,X);E(X);let _=A$(K);if(O=N(G,`${H}.svg`),m(O,_),z=O,U="image/svg+xml",Y==="png"){let J=N(G,`${H}.png`);E(X),v$(O,J),E(X),z=J,B=k(J).toString("base64"),U="image/png"}return{status:"ok",imagePath:z,svgPath:O,imageBase64:B,mimeType:U,prompt:$,aspectRatio:j,model:Z,source:W.source,responseId:Q,backendMode:"svg-fallback",requestedBackend:V,imagenError:f,assistantText:K}}catch(K){if(b(K))for(let Q of[z,O]){if(!Q||!w(Q))continue;try{J$(Q)}catch{}}throw K}}async function W$($,j,Y,Z=void 0){let G=String($.prompt??"").trim();if(!G)throw Error("image_generation.prompt is required.");E(Y);let H=g($.aspectRatio),W=h($.outputFormat),X=t($.model),f=P$(j,$.save??"project",$.saveDir);x(f,{recursive:!0});let V=new Date().toISOString().replace(/[:.]/g,"-"),O=D$(G),z=`image-${V}-${O}-${i().slice(0,8)}`;if(M$(X))return await l$({prompt:G,aspectRatio:H,outputFormat:W,model:X,outputRoot:f,baseName:z,cwd:j,signal:Y,runtimeAuthContext:Z});let B=await C$(Z),U=B??t$();try{let K=b$();if(K>0)await T$(K,Y);let Q="",_=L$();if(W==="png"){try{let J=await Y1({prompt:G,aspectRatio:H,model:X,outputFormat:W,cwd:j,save:$.save??"project",saveDir:$.saveDir,signal:Y,runId:z,runtimeAuthContext:B?{liveCodexCredentials:B}:Z}),q=H$(J.stdout);if(q.length>0){let T=$1(J.sessionFile),M=Z1(T.savedPath||q[0],f,z),L=k(M).toString("base64");return{status:"ok",imagePath:M,svgPath:"",imageBase64:L,mimeType:"image/png",prompt:G,aspectRatio:H,model:X,source:U.source,responseId:"",revisedPrompt:T.revisedPrompt||"",backendMode:"imagen-py",requestedBackend:"imagen-py",authSource:J.authSource,assistantText:String(J.stderr??"").trim(),sessionFile:J.sessionFile,imagenSavedPaths:q}}Q=`imagen.py produced no saved image path. stderr=${J.stderr.trim().slice(0,400)}`}catch(J){if(b(J))throw J;Q=J instanceof Error?J.message:String(J)}if(!_)throw Error(`Bundled imagen.py is required for PNG image_generation, but it failed: ${Q}. Provide a healthy DM Codex credential source or set ${s}=1 only for emergency legacy fallback debugging.`)}return await G1({prompt:G,aspectRatio:H,outputFormat:W,model:X,outputRoot:f,baseName:z,credentials:U,signal:Y,imagenError:Q,requestedBackend:"legacy-fallback"})}catch(K){if(b(K))throw K;throw K}}var W1=["project","global","custom"],X1=D.Object({prompt:D.String({description:"Detailed art direction for the image. Include subject, pose, mood, style, background, and any research findings you want preserved."}),aspectRatio:D.Optional(D.String({description:"Target aspect ratio. Supported: 1:1, 4:5, 16:9. Default: 1:1."})),model:D.Optional(D.String({description:"Optional model override. Defaults to DuckMind image2/@preset/image2. Use gpt-5.5/openai-codex/gpt-5.5 only for the legacy Codex lane."})),outputFormat:D.Optional(D.String({description:"Artifact format. Supported: png, svg. Default: png."})),save:D.Optional(D.String({description:"Artifact destination: project, global, or custom. Default: project."})),saveDir:D.Optional(D.String({description:"Custom artifact directory when save=custom."}))},{additionalProperties:!1});function f1($){let j=[`Saved image: ${$.imagePath}`];if($.svgPath&&$.svgPath!==$.imagePath)j.push(`SVG source: ${$.svgPath}`);if(j.push(`Model: ${$.model}`),j.push(`Aspect: ${$.aspectRatio}`),$.backendMode)j.push(`Backend: ${$.backendMode}`);if($.source)j.push(`Auth source: ${$.source}`);return j.join(`
9
+ `)}function K1($){$.on("session_start",async(j,Y)=>{let Z=H1(),G=typeof Y.modelRegistry?.getProviderAuthStatus==="function"?Y.modelRegistry.getProviderAuthStatus("openrouter"):void 0;if(!(process.env.OPENROUTER_API_KEY||process.env.OPENROUTER_KEY||X$(f$(process.cwd(),"config","openrouter.cnf"))||G?.configured)&&!X$(f$(Z,"auth.json")))Y.ui.notify("dm-image2: no DuckMind API key or Codex auth.json account found. image2 can use OPENROUTER_API_KEY, /login, or local config; the legacy Codex lane needs ~/.dm/agent/auth.json.","warning")}),$.registerTool({name:"image_generation",label:"Image Generation",description:"Generate a polished PNG image artifact using DuckMind image2 by default, or the bundled imagen.py lane from M only when model=gpt-5.5/openai-codex/gpt-5.5. Use this after research for logos, diagrams, posters, portraits, and other image tasks instead of asking the model to dump raw image data inline.",promptSnippet:"Dedicated image-generation lane. Use it for logos, portraits, diagrams, product shots, posters, UI mockups, character sheets, and artifacts you want saved to disk.",promptGuidelines:["Prefer image_generation over raw SVG or markdown image data in the final answer.","Use the bundled image-generation skill's pattern families: product hero, ad storyboard, editorial portrait, poster, character sheet, UI mockup, and comparison exploration.","Do research first when the image must reflect real people, products, or public facts.","Do not call third-party image APIs; route generation through this tool.","Answer with the saved artifact path after the tool succeeds."],parameters:X1,async execute(j,Y,Z,G,H){try{let W=await W$({prompt:Y.prompt,aspectRatio:g(Y.aspectRatio),model:Y.model,outputFormat:h(Y.outputFormat),save:typeof Y.save==="string"&&W1.includes(Y.save)?Y.save:"project",saveDir:typeof Y.saveDir==="string"?Y.saveDir:void 0},H.cwd,Z,{modelRegistry:H.modelRegistry,model:H.model}),X=[{type:"text",text:f1(W)}];if(W.imageBase64&&W.mimeType==="image/png")X.push({type:"image",data:W.imageBase64,mimeType:W.mimeType});return{content:X,details:W}}catch(W){if(Z?.aborted||b(W))throw W;let X=W instanceof Error?W.message:String(W);return{content:[{type:"text",text:`image_generation failed: ${X}`}],details:{status:"error",message:X},isError:!0}}}})}export{K1 as default};
@@ -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/OpenRouter 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(`OpenRouter image_generation failed (${G.status}): ${_}`)}let K=pZ(U);if(!K)throw Error("OpenRouter 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)+`
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duckmind/dm-darwin-x64",
3
- "version": "0.50.0",
3
+ "version": "0.51.1",
4
4
  "description": "DuckMind (dm) binary payload for darwin x64",
5
5
  "license": "MIT",
6
6
  "os": [