Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
483 lines (466 loc) · 230 KB
/
Copy pathmain.js
File metadata and controls
483 lines (466 loc) · 230 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/* DIY Desktop Pet - generated by esbuild */
var St=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var ti=Object.prototype.hasOwnProperty;var ei=(a,t)=>{for(var e in t)St(a,e,{get:t[e],enumerable:!0})},ii=(a,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Qe(t))!ti.call(a,n)&&n!==e&&St(a,n,{get:()=>t[n],enumerable:!(i=Ze(t,n))||i.enumerable});return a};var ni=a=>ii(St({},"__esModule",{value:!0}),a);var Nn={};ei(Nn,{default:()=>Pt});module.exports=ni(Nn);var h=require("obsidian");var he=require("obsidian");var ae="obsidogx",re="obsidogx:api-ready",Et="obsidogx:content-updated",se=Date.now(),F=[{id:"idle",name:"Idle",motion:"idle",prompt:"Subtle breathing loop; keep the pet calm and readable."},{id:"wave",name:"Wave",motion:"wave",prompt:"Friendly small paw wave; no extra symbols or text."},{id:"jump",name:"Jump",motion:"jump",prompt:"Short happy hop in place; keep the silhouette centered."},{id:"bob",name:"Bob",motion:"bob",prompt:"Small breathing bob with a soft 3D tilt; keep the silhouette centered."},{id:"spin",name:"Spin",motion:"spin",prompt:"Playful turn in place with readable front-facing identity."},{id:"think",name:"Think",motion:"think",prompt:"Focused thinking pose with a gentle tilt; no speech bubble in the image."},{id:"shake",name:"Shake",motion:"shake",prompt:"Quick side-to-side shake with squash and stretch."},{id:"sleep",name:"Sleep",motion:"sleep",prompt:"Tiny sleepy sway; keep the same pet identity and proportions."}];function W(a,t,e,i){return{id:a,name:t,motion:e,prompt:i,loop:!0,createdAt:Date.now(),updatedAt:Date.now()}}function q(a={}){return{background:"Lives in this Obsidian vault as a tiny workspace companion.",personality:"Warm, concise, curious, and gently playful.",abilities:"Can remind the user about tasks and memos, chat about active notes, and help with study or writing.",preferences:"Prefers practical next steps, short answers, and helpful encouragement.",catchphrases:"",selfIntroduction:"",...a}}function at(a={}){return{id:"starter",name:"Momo",description:"A tiny workspace companion.",profile:q(),emoji:"\u{1F43E}",appearanceTemplates:[],actions:F.map(t=>W(t.id,t.name,t.motion,t.prompt)),createdAt:se,updatedAt:se,...a}}function k(a,t,e,i,n=!0){return{id:a,name:t,description:e,prompt:i,enabled:n,createdAt:Date.now(),updatedAt:Date.now()}}var rt=[k("study-helper","Study Helper","Summarize notes, explain concepts, and make review questions.","When helping with study materials, produce concise summaries, key points, questions for review, and gentle next-step suggestions."),k("task-planner","Task Planner","Organize tasks, memos, and reminders into practical next actions.","When helping with tasks, prefer concrete next actions, priorities, deadlines, and small steps. Use pet content tools when Agent mode is enabled."),k("writing-editor","Writing Editor","Improve drafts, structure, tone, and clarity.","When editing writing, preserve the user's intent, explain major changes briefly, and offer polished alternatives without being verbose.",!1),k("file-summarizer","File Summarizer","Summarize the current note, PDF, or image.","When the user asks about the current file, use active file context first. For PDFs and images, describe visible or available evidence and mention limits clearly.",!1),k("vault-librarian","Vault Librarian","Organize notes, suggest folders, tags, aliases, and cleanup steps.","When helping organize the vault, search/read notes when Agent mode is enabled, identify duplicate themes, suggest stable folders/tags/aliases, and avoid destructive edits unless the user explicitly asks."),k("daily-planner","Daily Planner","Turn notes, tasks, and dashboard items into a focused daily plan.","When planning a day, use pet content tools when available, group work by urgency and energy, propose a short schedule, and keep the plan realistic."),k("review-coach","Review Coach","Create review questions and spaced-review prompts from learned material.","When helping with review, use Study/Learned dashboard context when available, produce active-recall questions, short answers, and a next review suggestion."),k("research-reader","Research Reader","Help read papers, PDFs, images, and source notes.","When helping with research material, summarize claims, evidence, methods, limitations, and useful quotes sparingly. If the active file is a PDF or image, use active file context and mention any API format limits."),k("meeting-notes","Meeting Notes","Convert messy meeting notes into decisions, action items, and follow-ups.","When processing meeting notes, extract agenda, decisions, open questions, owners, due dates, and follow-up messages. Prefer Markdown sections and tasks."),k("apex-dashboard-curator","Apex Dashboard Curator","Maintain Goal, Memo, Todo, Study, and Learned sections.","When working with Apex Dashboard, keep Goal/Memo/Todo/Study/Learned distinct, preserve completed items in the dashboard, move completed Study items to Learned, and include source links for review."),k("dashboard-reviewer","Dashboard Reviewer","Review goals, tasks, study cards, and learned material.","When reviewing the dashboard, separate Goal, Memo, Todo, Study, and Learned. Highlight overdue or upcoming work, suggest the next useful action, and turn Learned items into short review prompts."),k("capture-to-dashboard","Capture To Dashboard","Turn loose ideas into dashboard-ready Goal, Memo, Todo, or Study entries.","When the user captures an idea, classify it as Goal, Memo, Todo, or Study. If Agent write permission is enabled, offer concise Markdown that can be appended to the configured dashboard file."),k("web-research-assistant","Web Research Assistant","Search the web, compare sources, and turn results into notes.","When web_search is enabled and the user asks for current outside information, search first, summarize the useful results, include links, and suggest where the result belongs in the vault.",!1),k("wechat-draft-assistant","WeChat Draft Assistant","Prepare safe WeChat/VX message drafts without sending them.","When the user asks to message someone, draft a concise message, confirm recipient and tone, and use prepare_wechat_message only when external permission is enabled. Never claim the message was sent.",!1),k("link-builder","Link Builder","Suggest useful Obsidian links, backlinks, and MOC structure.","When improving links, suggest [[wikilinks]], aliases, backlinks, and map-of-content structure based on existing vault context. Prefer a small number of high-value links."),k("template-maker","Template Maker","Generate practical Obsidian templates for notes, projects, and reviews.","When creating templates, produce compact Markdown templates with frontmatter, useful sections, and task/reminder fields that work with this pet and Apex Dashboard.",!1),k("reading-knowledge-graph","Reading Knowledge Graph","Create a knowledge graph from a paper reading log.","When the user asks to create, update, refresh, rebuild, or open a knowledge graph for reading records or papers, use Agent mode tool create_knowledge_graph. Prefer the active file if it is a reading log; otherwise let the tool auto-discover a note named \u9605\u8BFB\u8BB0\u5F55.md or Reading Log.md. After the tool runs, tell the user the output path, number of papers, and number of relationships. Do not invent graph results manually."),k("reading-log-analyst","Reading Log Analyst","Analyze reading records into directions, themes, method lines, gaps, and next actions.","When the user asks to analyze reading records, summarize recent paper reading, inspect research directions, find reading gaps, or produce a\u9636\u6BB5\u9605\u8BFB\u5206\u6790, use Agent mode tool analyze_reading_records. Pass recent/from/to when the user specifies a range. After the tool runs, summarize the generated analysis and point to the output note. Do not replace the tool with a generic chat summary when the user asks for a file.")];function M(a,t,e,i,n,s=2800,o=!0){return{id:a,name:t,enabled:o,event:e,pattern:i,actionId:n,timeoutMs:s,createdAt:Date.now(),updatedAt:Date.now()}}var Dt=[M("tail-wag-on-hover","Tail wag on hover","pet-hover","enter,hover","tail-wag",2200),M("wave-on-click","Wave on pet click","pet-click","click,tap","wave",2200),M("running-on-chat-clear","Shake on chat clear","chat-clear","clear,history","shake",2200),M("tail-wag-on-greeting","Bob on greeting","user-message","hello,hi,hey,\u4F60\u597D,\u55E8,\u5728\u5417,\u5341\u4E8C,\u72D7\u72D7,\u53EF\u7231,\u4E56","bob",3200),M("review-on-study-question","Review on study/thinking","user-message","search,web,\u67E5\u627E,\u641C\u7D22,\u68C0\u7D22,\u603B\u7ED3,\u5206\u6790,\u9605\u8BFB,\u8BBA\u6587,\u5B66\u4E60,\u590D\u4E60,\u89E3\u91CA,\u601D\u8003,\u4E3A\u4EC0\u4E48,\u600E\u4E48,study,learn,pdf,\u56FE\u7247,review","review",4600),M("running-on-agent-tool","Running while tools work","agent-tool","","running",3600),M("running-on-note-edit","Run right while notes change","note-edit","","running-right",3200),M("jump-on-happy","Jump on excitement","user-message","\u592A\u597D\u4E86,\u5F00\u5FC3,happy,thanks,thank you,\u8C22\u8C22,\u68D2,\u5389\u5BB3,\u5B8C\u6210\u4E86","jump",2800),M("jump-on-completion","Spin on completion","content-complete","","spin",3e3),M("failed-on-deadline","Waiting on deadline reminders","deadline-reminder","","waiting",4200),M("sleep-on-rest","Sleep on rest","user-message","sleep,rest,\u4F11\u606F,\u7761\u89C9,\u665A\u5B89","sleep",4200),M("failed-on-error","Failed on real errors","assistant-reply","chat request failed,request failed,api error,http error,network error,timeout,timed out,invalid api key,rate limit,unauthorized,forbidden,\u8BF7\u6C42\u5931\u8D25,\u63A5\u53E3\u9519\u8BEF,\u7F51\u7EDC\u9519\u8BEF,\u8D85\u65F6,\u8BA4\u8BC1\u5931\u8D25,\u6743\u9650\u9519\u8BEF,\u53D1\u751F\u9519\u8BEF,\u51FA\u9519\u4E86","failed",3600),M("tail-wag-on-done-reply","Run left on successful reply","assistant-reply","","running-left",2600)];function X(a={}){return{id:"default",name:"Default",messages:[],summary:"",createdAt:Date.now(),updatedAt:Date.now(),...a}}function R(a={}){return{id:"openai-default",name:"OpenAI",providerPreset:"openai",apiFormat:"chat-completions",endpoint:"https://api.openai.com/v1/chat/completions",apiKey:"",model:"gpt-4o-mini",createdAt:Date.now(),updatedAt:Date.now(),...a}}var Mt=[R(),R({id:"openai-responses-default",name:"OpenAI Responses",providerPreset:"openai-responses",apiFormat:"responses",endpoint:"https://api.openai.com/v1/responses",model:"gpt-4o-mini"}),R({id:"deepseek-default",name:"DeepSeek",providerPreset:"deepseek",endpoint:"https://api.deepseek.com/chat/completions",model:"deepseek-chat"}),R({id:"local-default",name:"Local",providerPreset:"ollama",endpoint:"http://localhost:11434/v1/chat/completions",model:"llama3.1"})],f={enabled:!0,activePetId:"starter",pets:[at()],accentColor:"#7c3aed",size:88,panelWidth:280,panelHeight:260,speed:0,stayStill:!0,opacity:96,bounce:!1,mirrorWhenMoving:!0,showSpeech:!0,desktopOverlay:!0,overlayX:null,overlayY:null,x:null,y:null,content:{enabled:!0,showApexDashboard:!0,apexDashboardFile:"dashboard",showMarkdownTasks:!0,showMemos:!0,memoTags:"#memo,#\u5907\u5FD8\u5F55",memoFolders:"Memos,\u5907\u5FD8\u5F55",maxItems:8,refreshMinutes:5,scanLimit:200},generation:{preferredGeneratorId:"default-motion",customEndpoint:"",customApiKey:"",stylePrompt:"Small Obsidian desktop pet, compact chibi proportions, transparent background, readable at 96px."},cutout:{enabled:!0,tolerance:42,feather:24},chat:{enabled:!1,activeModelProfileId:"openai-default",modelProfiles:Mt,providerPreset:"openai",apiFormat:"chat-completions",endpoint:"https://api.openai.com/v1/chat/completions",apiKey:"",model:"gpt-4o-mini",systemPrompt:"You are a small desktop pet inside Obsidian. Be warm, concise, helpful, and playful. Reply in the user's language.",temperature:.7,maxTokens:800,maxHistory:12,historyStrategy:"summarize",summaryPrompt:"Summarize the conversation so far into compact memory for the desktop pet. Keep user preferences, goals, open tasks, and decisions. Do not invent facts.",logHeight:126,activeSessionId:"default",sessions:[X()],includeActiveFile:!0,includeImages:!0,includePdfs:!0,activeFileMaxChars:6e3,maxAttachmentBytes:25e5,logEnabled:!1,logFile:"Pet Chats.md",agentEnabled:!1,agentMaxSteps:4,agentSearchLimit:8,agentReadMaxChars:8e3,agentCanWrite:!1,agentLogTools:!0},webSearch:{enabled:!1,provider:"duckduckgo",endpoint:"",apiKey:"",maxResults:5},externalActions:{allowOpenBrowser:!1,allowPrepareWechat:!1,confirmBeforeExternalAction:!0},reminders:{enabled:!0,leadMinutes:10080,checkMinutes:5,repeatMinutes:60,actionId:"shake"},actionBindings:Dt,skills:rt};var U=require("obsidian");function w(a,t,e){return Math.min(Math.max(a,t),e)}function T(a){return`${a}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function J(a){return a.toLowerCase().replace(/\.[^.]+$/,"").replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/^-+|-+$/g,"")||"pet"}function Tt(a){return a.split(/[,\n]/).map(t=>t.trim()).filter(Boolean)}function $(a){let t=a.toLowerCase();return t.endsWith(".glb")||t.endsWith(".gltf")||t.includes("model/gltf")?"model3d":t.endsWith(".gif")||t.includes("image/gif")?"gif":t.endsWith(".webp")||t.includes("image/webp")?"webp":t.includes("spritesheet")?"spritesheet":"image"}function oe(a){let t=a.match(/\.([a-z0-9]+)$/i);return t?`.${t[1].toLowerCase()}`:".png"}function le(a){return a.includes("gltf-binary")?".glb":a.includes("gltf+json")?".gltf":a.includes("gif")?".gif":a.includes("webp")?".webp":a.includes("jpeg")||a.includes("jpg")?".jpg":".png"}async function _(a,t){let i=(0,U.normalizePath)(t).split("/").filter(Boolean),n="";for(let s of i)n=n?`${n}/${s}`:s,await a.vault.adapter.exists(n)||await a.vault.adapter.mkdir(n)}async function It(a,t,e,i,n){let s=(0,U.normalizePath)(`${t}/pets/${e}`);await _(a,s);let o=J(i.name),r=/\.[a-z0-9]+$/i.test(i.name)?oe(i.name):le(i.type),l=(0,U.normalizePath)(`${s}/${n}-${Date.now()}-${o}${r}`),d=await i.arrayBuffer();return await a.vault.adapter.writeBinary(l,d),{assetPath:l,assetType:$(`${i.name} ${i.type}`)}}async function de(a,t,e,i,n){let s=n.assetDataUrl,o=n.assetBase64;if(!s&&!o)return;let r=s?.match(/^data:([^;]+);base64,(.+)$/),l=n.assetMimeType||r?.[1]||"image/png",d=r?.[2]||o;if(!d)return;let c=window.atob(d),p=new Uint8Array(c.length);for(let y=0;y<c.length;y+=1)p[y]=c.charCodeAt(y);let u=(0,U.normalizePath)(`${t}/pets/${e}`);await _(a,u);let g=n.assetFileName?J(n.assetFileName):J(i),m=n.assetFileName?oe(n.assetFileName):le(l),v=(0,U.normalizePath)(`${u}/generated-${Date.now()}-${g}${m}`);return await a.vault.adapter.writeBinary(v,p.buffer),{assetPath:v,assetType:$(v)}}function ce(a,t){if(t)return a.vault.adapter.getResourcePath((0,U.normalizePath)(t))}var ot=class{id="default-motion";name="Built-in motion actions";async generate(t){let e=new Set(t.requestedActions.length?t.requestedActions:F.map(i=>i.id));return F.filter(i=>e.has(i.id)||e.has(i.name)).map(i=>{let n=W(i.id,i.name,i.motion,[i.prompt,t.coverAssetPath?`Use uploaded cover asset as the visual identity: ${t.coverAssetPath}.`:"Use the pet cover or emoji as the visual identity.",t.stylePrompt?`Style note: ${t.stylePrompt}`:""].filter(Boolean).join(`
`));return t.coverAssetPath&&(n.assetPath=t.coverAssetPath,n.assetType="image"),n})}},lt=class{id="custom-http";name="Custom HTTP action generator";async generate(t,e){let i=e.settings.generation.customEndpoint.trim();if(!i)return[];let s=(await(0,he.requestUrl)({url:i,method:"POST",headers:{"content-type":"application/json",...e.settings.generation.customApiKey?{authorization:`Bearer ${e.settings.generation.customApiKey}`}:{}},body:JSON.stringify({pet:t.pet,coverAssetPath:t.coverAssetPath,requestedActions:t.requestedActions,stylePrompt:t.stylePrompt})})).json?.actions;if(!Array.isArray(s))return[];let o=[];for(let r of s){let l=r.id||`generated-${Date.now()}`,d=await de(e.app,e.pluginDir,t.pet.id,l,r);o.push({id:l,name:r.name||"Generated Action",motion:r.motion||"custom",assetPath:d?.assetPath||r.assetPath,assetType:d?.assetType||r.assetType,frameCount:r.frameCount,frameDurationMs:r.frameDurationMs,loop:r.loop??!0,prompt:r.prompt,createdAt:Date.now(),updatedAt:Date.now()})}return o}};function ue(a,t){return a.vault.getMarkdownFiles().map(e=>({file:e,mtime:e.stat.mtime})).sort((e,i)=>i.mtime-e.mtime).slice(0,t)}function pt(a){return a.replace(/#[\p{L}\p{N}/_-]+/gu,"").replace(/[📅⏳✅➕]\s*\d{4}-\d{2}-\d{2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?/g,"").replace(/\s{2,}/g," ").trim()}function ut(a){let t=a.match(/(?:📅|⏳|due::|due:|deadline::|deadline:|reminder::|reminder:)\s*(\d{4}-\d{2}-\d{2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?)/i);return ve(t?.[1])}function gt(a){return/🔺|⏫|priority::\s*high|priority:\s*high/i.test(a)?"high":/🔽|priority::\s*low|priority:\s*low/i.test(a)?"low":"normal"}var dt=class{id="apex-dashboard";name="Apex Dashboard";async isAvailable(t){return!!(t.settings.content.showApexDashboard&&await pe(t))}async getItems(t){if(!t.settings.content.showApexDashboard)return[];let e=await pe(t);if(!e)return[];let i=await t.app.vault.cachedRead(e),n=ai(i,e.path),s=li(n.content);return(n.changed||s.changed)&&(await t.app.vault.modify(e,s.content),i=s.content),si(i,e)}},ct=class{id="markdown-tasks";name="Markdown tasks";async getItems(t){if(!t.settings.content.showMarkdownTasks)return[];let e=[],i=t.settings.content.maxItems;for(let{file:n}of ue(t.app,t.settings.content.scanLimit)){if(e.length>=i)break;(await t.app.vault.cachedRead(n)).split(/\r?\n/).forEach((r,l)=>{if(e.length>=i)return;let d=r.match(/^\s*[-*+]\s+\[\s\]\s+(.+)$/);if(!d)return;let c=pt(d[1]);c&&e.push({id:`${n.path}:${l+1}`,sourceId:this.id,sourceName:"Tasks",title:c,path:n.path,line:l+1,due:ut(d[1]),priority:gt(d[1]),createdAt:n.stat.mtime})})}return e}};async function pe(a){let t=a.settings.content.apexDashboardFile?.trim()||"dashboard",e=t.endsWith(".md")?[t]:[t,`${t}.md`];for(let i of e){let n=a.app.vault.getFileByPath(i);if(n)return n}return a.app.vault.getMarkdownFiles().find(i=>i.basename===t.replace(/\.md$/,""))}function si(a,t){let e=me(a),i=fe(a,e),n=[];for(let s of i)Y(s,["goal","goals","target","targets","\u76EE\u6807"])&&n.push(...Lt(s,t,"Apex Goal","apex-goal")),Y(s,["study","studies","learning","learn","\u5B66\u4E60","\u7814\u8BFB"])&&n.push(...gi(s,t)),Y(s,["learned","review","reviews","\u5DF2\u5B66","\u5DF2\u5B66\u4E60","\u5DF2\u638C\u63E1","\u590D\u4E60"])&&n.push(...Lt(s,t,"Apex Learned","apex-learned")),Y(s,["memo","memos","note","notes","\u5907\u5FD8","\u5907\u5FD8\u5F55"])&&n.push(...ui(s,t)),Y(s,["todo","todos","task","tasks","\u5F85\u529E","\u4EFB\u52A1"])&&n.push(...mi(s,t));return n}function Y(a,t){let e=`${a.type} ${a.title}`.toLowerCase();return t.some(i=>e.includes(i.toLowerCase()))}function ai(a,t){let e=a.includes(`\r
`)?`\r
`:`
`,i=a.split(/\r?\n/),n=me(a),s=fe(a,n).filter(c=>Y(c,["study","studies","learning","learn","\u5B66\u4E60","\u7814\u8BFB"])),o=[];for(let c of s)for(let p of Q(c))ri(p)&&o.push({start:p.startLine-1,end:p.startLine+p.lines.length,block:oi(p,t)});if(!o.length)return{content:a,changed:!1};o.sort((c,p)=>p.start-c.start).forEach(c=>i.splice(c.start,c.end-c.start));let r=ge(i,"Learned"),l=di(i,r),d=o.sort((c,p)=>c.start-p.start).flatMap(c=>["",...c.block,""]);return i.splice(l,0,...d),{content:i.join(e),changed:!0}}function ri(a){let t=Rt(a.lines,a.startLine);return t.length?t.every(e=>e.checked):Z(a)}function Z(a){if(/^~~.*~~$/.test(a.title.trim()))return!0;let t=mt(a.lines),e=`${t.checked||t.done||t.status||""}`.toLowerCase();return["true","x","done","complete","completed","learned"].includes(e)}function oi(a,t){let e=ci(),i=t.replace(/\.md$/i,""),n=a.lines.filter(s=>!/^\s*(?:learned|source|checked|done|completed|status):/i.test(s)).filter((s,o,r)=>s.trim()||o>0&&o<r.length-1);return[`### ${a.title}`,...n,`learned: ${e}`,`source: [[${i}#${hi(a.title)}]]`]}function li(a){let t=a.includes(`\r
`)?`\r
`:`
`,e=a.split(/\r?\n/),i=e.join(`
`);for(let s of["Goal","Memo","Todo","Study","Learned"])ge(e,s);let n=i!==e.join(`
`);return{content:e.join(t),changed:n}}function ge(a,t){let e=a.findIndex(i=>new RegExp(`^##\\s+${pi(t)}\\s*$`,"i").test(i));return e>=0?e:(a.length&&a[a.length-1].trim()&&a.push(""),a.push(`## ${t}`),a.length-1)}function di(a,t){for(let e=t+1;e<a.length;e+=1)if(/^##\s+/.test(a[e]))return e;return a.length}function ci(){let a=new Date,t=a.getFullYear(),e=String(a.getMonth()+1).padStart(2,"0"),i=String(a.getDate()).padStart(2,"0");return`${t}-${e}-${i}`}function hi(a){return a.replace(/^#+\s*/,"").trim()}function pi(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function me(a){let t=new Map,e=a.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!e)return t;let i=e[1].split(/\r?\n/),n;for(let s of i){let o=s.match(/^\s*-\s+name:\s*"?(.+?)"?\s*$/);if(o){n=$t(o[1].trim());continue}let r=s.match(/^\s*name:\s*"?(.+?)"?\s*$/);if(r){n=$t(r[1].trim());continue}let l=s.match(/^\s*type:\s*"?(.+?)"?\s*$/);l&&n&&t.set(n.toLowerCase(),$t(l[1].trim()))}return t}function fe(a,t){let e=a.split(/\r?\n/),i=[],n;return e.forEach((s,o)=>{let r=s.match(/^##\s+(.+?)\s*$/);if(r){n={title:r[1].trim(),type:t.get(r[1].trim().toLowerCase())||r[1].trim(),startLine:o+1,body:[]},i.push(n);return}n?.body.push(s)}),i}function $t(a){return a.replace(/^["']|["']$/g,"")}function Q(a){let t=[],e;return a.body.forEach((i,n)=>{let s=i.match(/^#{3,6}\s+(.+?)\s*$/);if(s){e={title:s[1].trim(),id:`${a.title}:${s[1].trim()}:${a.startLine+n+1}`,startLine:a.startLine+n+1,lines:[]},t.push(e);return}e?.lines.push(i)}),t.map(i=>{let s=i.lines.find(o=>o.match(/^id:\s*(.+)$/i))?.match(/^id:\s*(.+)$/i)?.[1]?.trim();return s?{...i,id:s}:i})}function ui(a,t){return Q(a).filter(e=>!Z(e)).map(e=>{let i=mt(e.lines),n=Nt(e.lines);return{id:`${t.path}:apex-memo:${e.id}`,sourceId:"apex-dashboard",sourceName:"Apex Memo",title:O(e.title)||"Memo",body:n||void 0,path:t.path,line:e.startLine,due:z(i.reminder)||z(i.due)||z(i.deadline),createdAt:t.stat.mtime}}).filter(e=>e.title||e.body)}function Lt(a,t,e,i){let n=Q(a).filter(o=>!Z(o)).map(o=>ye(t,o,e,i)).filter(o=>o.title||o.body);if(n.length)return n;let s=[];return a.body.forEach((o,r)=>{let l=o.trim();if(!l||/^[-*+]\s+\[[xX]\]/.test(l)||we(l))return;let d=l.match(/^[-*+]\s+\[([ xX-])\]\s+(.+)$/),c=O(d?pt(d[2]):l.replace(/^[-*+]\s+/,""));c&&s.push({id:`${t.path}:${i}:${a.startLine+r+1}`,sourceId:"apex-dashboard",sourceName:e,title:c,path:t.path,line:a.startLine+r+1,due:d?ut(d[2]):void 0,priority:d?gt(d[2]):"normal",createdAt:t.stat.mtime})}),s}function gi(a,t){let e=[];for(let i of Q(a)){if(Z(i))continue;let n=Rt(i.lines,i.startLine);if(!n.length){let s=ye(t,i,"Apex Study","apex-study");(s.title||s.body)&&e.push(s);continue}n.forEach((s,o)=>{if(s.checked)return;let r=pt(s.text||i.title);r&&e.push({id:`${t.path}:apex-study:${i.id}:${o}`,sourceId:"apex-dashboard",sourceName:"Apex Study",title:O(r),body:i.title!==r?O(i.title):void 0,path:t.path,line:s.line,due:z(s.reminder)||ut(s.text),priority:gt(s.text),createdAt:t.stat.mtime})})}return e.length?e:Lt(a,t,"Apex Study","apex-study")}function ye(a,t,e,i){let n=mt(t.lines),s=Nt(t.lines);return{id:`${a.path}:${i}:${t.id}`,sourceId:"apex-dashboard",sourceName:e,title:O(t.title)||e,body:s||void 0,path:a.path,line:t.startLine,due:z(n.reminder)||z(n.due)||z(n.deadline),createdAt:a.stat.mtime}}function mi(a,t){let e=[];for(let i of Q(a)){if(Z(i))continue;let n=mt(i.lines),s=Rt(i.lines,i.startLine);(s.length?s:[{text:i.title,line:i.startLine,checked:!1,reminder:n.reminder||n.due||n.deadline}]).forEach((r,l)=>{if(r.checked)return;let d=pt(r.text||i.title);if(!d)return;let c=Nt(i.lines.filter(p=>!/^\s*(?:task|todo|text):\s*/i.test(p)).filter(p=>!/^\s*(?:checked|done):\s*(?:true|false)\s*$/i.test(p)));e.push({id:`${t.path}:apex-todo:${i.id}:${l}`,sourceId:"apex-dashboard",sourceName:"Apex Todo",title:O(d),body:c||(i.title!==d?O(i.title):void 0),path:t.path,line:r.line,due:z(r.reminder||n.reminder||n.due||n.deadline)||ut(r.text),priority:gt(r.text),createdAt:t.stat.mtime})})}return e}function mt(a){let t={};for(let e of a){let i=e.match(/^([a-zA-Z][\w-]*):\s*(.*)$/);i&&(t[i[1].toLowerCase()]=i[2].trim())}return t}function Nt(a){return a.map(t=>t.trim()).filter(t=>t&&!we(t)).filter(t=>!/^[-*+]\s+\[[xX]\]/.test(t)).map(t=>O(t.replace(/^[-*+]\s+\[[ xX-]\]\s+/,"").replace(/^[-*+]\s+/,""))).filter(Boolean).join(" \xB7 ").slice(0,260)}function we(a){return/^(id|type|color|cover|width|height|reminder|due|deadline|done|checked|completed|status|learned|source|created|updated|priority):/i.test(a.trim())}function O(a){return a.replace(/\uFFFD/g,"").replace(/[\u0000-\u001F\u007F-\u009F]/g," ").replace(/\\u([0-9a-fA-F]{4})/g,(t,e)=>String.fromCharCode(parseInt(e,16))).replace(/&#(\d+);/g,(t,e)=>String.fromCharCode(Number(e))).replace(/&#x([0-9a-fA-F]+);/g,(t,e)=>String.fromCharCode(parseInt(e,16))).replace(/^\s*[|:]\s*/,"").replace(/\s*[|:]\s*$/g,"").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/g,"'").replace(/<[^>]+>/g," ").replace(/!\[[^\]]*]\([^)]+\)/g,"").replace(/\[\[([^|\]]+)\|([^\]]+)]]/g,"$2").replace(/\[\[([^\]]+)]]/g,"$1").replace(/\[([^\]]+)]\([^)]+\)/g,"$1").replace(/^#+\s+/,"").replace(/^[-*+]\s+\[[ xX-]\]\s+/,"").replace(/^[-*+]\s+/,"").replace(/`{1,3}/g,"").replace(/^~~(.+)~~$/,"$1").replace(/\s+/g," ").trim()}function Rt(a,t){let e=[],i;return a.forEach((n,s)=>{let o=n.match(/^\s*[-*+]\s+\[([ xX-])\]\s+(.+)$/);if(o){i={checked:o[1].toLowerCase()==="x",text:o[2].trim(),line:t+s+1},e.push(i);return}let r=n.match(/^\s*(?:task|todo|text):\s*(.+)$/i);if(r){i={checked:!1,text:r[1].trim(),line:t+s+1},e.push(i);return}let l=n.match(/^\s*(?:checked|done):\s*(true|false)$/i);if(l&&i){i.checked=l[1].toLowerCase()==="true";return}let d=n.match(/^\s*(?:reminder|due|deadline):\s*(.+)$/i);d&&i&&(i.reminder=d[1].trim())}),e}function z(a){let t=a?.match(/(\d{4}-\d{2}-\d{2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?)/);return ve(t?.[1])}function ve(a){return a?.trim().replace("T"," ")}var ht=class{id="markdown-memos";name="Markdown memos";async getItems(t){if(!t.settings.content.showMemos)return[];let e=Tt(t.settings.content.memoTags).map(s=>s.startsWith("#")?s:`#${s}`),i=Tt(t.settings.content.memoFolders),n=[];for(let{file:s}of ue(t.app,t.settings.content.scanLimit)){if(n.length>=t.settings.content.maxItems)break;let o=i.some(c=>s.path.startsWith(c.replace(/\/$/,"")+"/")),r=await t.app.vault.cachedRead(s),l=e.some(c=>r.includes(c));if(!o&&!l)continue;let d=fi(s,r,e);d&&n.push({id:`${s.path}:memo`,sourceId:this.id,sourceName:"Memos",title:d.title,body:d.body,path:s.path,createdAt:s.stat.mtime})}return n}};function fi(a,t,e){let i=t.split(/\r?\n/).map(l=>l.trim()).filter(l=>l&&!l.startsWith("---")&&!l.startsWith("# ")),n=i.find(l=>e.some(d=>l.includes(d))),s=i.find(l=>!l.startsWith("#")&&!/^\s*[-*+]\s+\[[ xX-]\]/.test(l)),o=n||s;if(!o)return{title:a.basename};let r=o.replace(/#[\p{L}\p{N}/_-]+/gu,"").replace(/^[-*+]\s+/,"").trim();return r?{title:r.slice(0,90),body:r.length>90?r.slice(90,180):void 0}:{title:a.basename}}function yi(a){return!(!a.type.startsWith("image/")||a.type==="image/gif")}async function _t(a,t){if(!t.enabled||!yi(a))return a;try{let e=await createImageBitmap(a),i=Math.min(1,1024/Math.max(e.width,e.height)),n=Math.max(1,Math.round(e.width*i)),s=Math.max(1,Math.round(e.height*i)),o=document.createElement("canvas");o.width=n,o.height=s;let r=o.getContext("2d");if(!r)return a;r.drawImage(e,0,0,n,s);let l=r.getImageData(0,0,n,s);wi(l,t.tolerance,t.feather),r.putImageData(l,0,0);let d=await new Promise(c=>o.toBlob(c,"image/png"));return d?new File([d],Pi(a.name,"cutout.png"),{type:"image/png"}):a}catch(e){return console.debug("DIY Desktop Pet auto cutout failed; using original upload.",e),a}}function wi(a,t,e){let{data:i,width:n,height:s}=a,o=vi(i,n,s),r=new Uint8Array(n*s),l=[],d=(c,p)=>{if(c<0||p<0||c>=n||p>=s)return;let u=p*n+c;r[u]||(r[u]=1,l.push(u))};for(let c=0;c<n;c+=1)d(c,0),d(c,s-1);for(let c=0;c<s;c+=1)d(0,c),d(n-1,c);for(let c=0;c<l.length;c+=1){let p=l[c],u=p*4;if(Pe(i,u,o)>t)continue;i[u+3]=0;let m=p%n,v=Math.floor(p/n);d(m+1,v),d(m-1,v),d(m,v+1),d(m,v-1)}e>0&&bi(i,n,s,e,t,o)}function vi(a,t,e){let i=[],n=[[0,0],[t-1,0],[0,e-1],[t-1,e-1],[Math.floor(t/2),0],[Math.floor(t/2),e-1],[0,Math.floor(e/2)],[t-1,Math.floor(e/2)]];for(let[r,l]of n){let d=(l*t+r)*4;i.push([a[d],a[d+1],a[d+2]])}i.sort((r,l)=>be(r)-be(l));let s=i.slice(2,i.length-2),o=s.length?s:i;return[Math.round(o.reduce((r,l)=>r+l[0],0)/o.length),Math.round(o.reduce((r,l)=>r+l[1],0)/o.length),Math.round(o.reduce((r,l)=>r+l[2],0)/o.length)]}function be(a){return a[0]+a[1]+a[2]}function Pe(a,t,e){let i=a[t]-e[0],n=a[t+1]-e[1],s=a[t+2]-e[2];return Math.sqrt(i*i+n*n+s*s)}function bi(a,t,e,i,n,s){let o=new Uint8ClampedArray(t*e);for(let r=0;r<t*e;r+=1)o[r]=a[r*4+3];for(let r=1;r<e-1;r+=1)for(let l=1;l<t-1;l+=1){let d=r*t+l;if(o[d]===0||!(o[d-1]===0||o[d+1]===0||o[d-t]===0||o[d+t]===0))continue;let p=d*4,u=Pe(a,p,s);u<n+i&&(a[p+3]=Math.max(80,Math.round(255*(u/(n+i)))))}}function Pi(a,t){return`${a.replace(/\.[^.]+$/,"")}.${t}`}var _e=["idle","bob","wave","jump","spin","think","sleep","shake","custom"],Be=["image","gif","webp","spritesheet"],Fe=["user-message","assistant-reply","agent-tool","content-complete","deadline-reminder","note-edit","pet-hover","pet-click","chat-clear"],Ci="image/png,image/jpeg,image/webp,image/gif",Ai=[".png",".jpg",".jpeg",".webp",".gif"],xi=!0,Ce=["SKILL.md","skill.json","skills.json"],ki=5,Si=80,it={openai:{label:"OpenAI Chat Completions",endpoint:"https://api.openai.com/v1/chat/completions",apiFormat:"chat-completions",model:"gpt-4o-mini"},"openai-responses":{label:"OpenAI Responses",endpoint:"https://api.openai.com/v1/responses",apiFormat:"responses",model:"gpt-4o-mini"},openrouter:{label:"OpenRouter",endpoint:"https://openrouter.ai/api/v1/chat/completions",apiFormat:"chat-completions",model:"openai/gpt-4o-mini"},deepseek:{label:"DeepSeek",endpoint:"https://api.deepseek.com/chat/completions",apiFormat:"chat-completions",model:"deepseek-chat"},siliconflow:{label:"SiliconFlow",endpoint:"https://api.siliconflow.cn/v1/chat/completions",apiFormat:"chat-completions",model:"Qwen/Qwen2.5-7B-Instruct"},moonshot:{label:"Moonshot",endpoint:"https://api.moonshot.cn/v1/chat/completions",apiFormat:"chat-completions",model:"moonshot-v1-8k"},ollama:{label:"Ollama",endpoint:"http://localhost:11434/v1/chat/completions",apiFormat:"chat-completions",model:"llama3.1"},"lm-studio":{label:"LM Studio",endpoint:"http://localhost:1234/v1/chat/completions",apiFormat:"chat-completions",model:"local-model"},custom:{label:"Custom",endpoint:"",apiFormat:"chat-completions",model:""}},Ut=[{id:"focus",name:"Focus",motion:"think",prompt:"Focused reading/listening pose for note review, PDF reading, and analysis.",binding:{event:"user-message",pattern:"\u603B\u7ED3,\u5206\u6790,\u9605\u8BFB,pdf,\u56FE\u7247,\u5B66\u4E60,study,review",timeoutMs:4200}},{id:"search",name:"Search",motion:"think",prompt:"Curious searching pose, eyes scanning side to side.",binding:{event:"agent-tool",pattern:"web_search,search_vault,read_note",timeoutMs:3400}},{id:"notify",name:"Notify",motion:"shake",prompt:"Attention-getting reminder motion without covering the note.",binding:{event:"deadline-reminder",pattern:"",timeoutMs:4200}},{id:"complete",name:"Complete",motion:"jump",prompt:"Small celebratory hop for finishing a task.",binding:{event:"content-complete",pattern:"",timeoutMs:2600}},{id:"rest",name:"Rest",motion:"sleep",prompt:"Soft sleepy pose for breaks, rest, or winding down.",binding:{event:"user-message",pattern:"\u4F11\u606F,\u7761\u89C9,\u665A\u5B89,break,rest,sleep",timeoutMs:4200}}],Bt=8,Ft=9,ft=[{state:"idle",row:0,actionId:"idle",name:"Idle",motion:"idle",frameCount:6,frameDurationMs:160,frameDurationsMs:[280,110,110,140,140,320],prompt:"Codex atlas idle loop."},{state:"running-right",row:1,actionId:"running-right",name:"Run right",motion:"bob",frameCount:8,frameDurationMs:120,frameDurationsMs:[120,120,120,120,120,120,120,220],prompt:"Codex atlas rightward running loop."},{state:"running-left",row:2,actionId:"running-left",name:"Run left",motion:"bob",frameCount:8,frameDurationMs:120,frameDurationsMs:[120,120,120,120,120,120,120,220],prompt:"Codex atlas leftward running loop."},{state:"waving",row:3,actionId:"wave",name:"Wave",motion:"wave",frameCount:4,frameDurationMs:140,frameDurationsMs:[140,140,140,280],prompt:"Codex atlas waving loop."},{state:"jumping",row:4,actionId:"jump",name:"Jump",motion:"jump",frameCount:5,frameDurationMs:140,frameDurationsMs:[140,140,140,140,280],prompt:"Codex atlas jumping loop."},{state:"failed",row:5,actionId:"failed",name:"Failed",motion:"shake",frameCount:8,frameDurationMs:140,frameDurationsMs:[140,140,140,140,140,140,140,240],prompt:"Codex atlas failed reaction loop."},{state:"waiting",row:6,actionId:"waiting",name:"Waiting",motion:"idle",frameCount:6,frameDurationMs:150,frameDurationsMs:[150,150,150,150,150,260],prompt:"Codex atlas waiting loop."},{state:"running",row:7,actionId:"running",name:"Running",motion:"think",frameCount:6,frameDurationMs:120,frameDurationsMs:[120,120,120,120,120,220],prompt:"Codex atlas in-progress running loop."},{state:"review",row:8,actionId:"review",name:"Review",motion:"think",frameCount:6,frameDurationMs:150,frameDurationsMs:[150,150,150,150,150,280],prompt:"Codex atlas review loop."}],yt=[{key:"memo",label:"Memo"},{key:"task",label:"Tasks"},{key:"study",label:"Study"},{key:"learned",label:"Learned"}],Ei=[{kind:"memo",label:"+ Memo"},{kind:"task",label:"+ Task"},{kind:"study",label:"+ Study"}],Pt=class extends h.Plugin{api;pluginDir=`.obsidian/plugins/${ae}`;contentProviders=new Map;actionGenerators=new Map;allContentItems=[];contentItems=[];activeContentItem;contentIndex=-1;currentActionId="idle";petEl;overlayWindow;companionProcess;companionStateText="";companionCommandText="";spriteEl;shadowEl;speechEl;speechSourceEl;speechTitleEl;speechBodyEl;speechActionsEl;speechDoneEl;dashboardEl;menuEl;petSelectEl;chatEl;chatTitleEl;chatLogEl;chatLogResizeEl;chatSessionEl;chatSessionNameEl;chatModeEl;chatModelProfileEl;chatModelProfileNameEl;chatPermissionsEl;chatNewSessionEl;chatDeleteSessionEl;chatInputEl;chatSendEl;chatClearEl;speechOpenEl;panelResizeEl;petResizeEl;chatOpen=!1;chatBusy=!1;chatLogPinnedToBottom=!0;chatHistory=[];chatSummary="";panelMode="dashboard";dashboardTab="task";hiddenContentIds=new Set;expandedMemoIds=new Set;position={x:0,y:0};velocity={x:.25,y:0};animationFrame;actionTimer;spriteFrameTimer;speechTimer;contentTimer;refreshTimer;reminderTimer;companionCommandTimer;lastNoteEditActionAt=0;firedReminderIds=new Map;overlayWanted=!1;overlayPanelVisible=!1;speechState={source:"Desktop Pet",title:"Ready when you are.",body:""};wasDragged=!1;dragState;resizeState;chatLogResizeState;onWindowFocus=()=>{this.syncBackgroundHandoff()};onWindowBlur=()=>{this.syncBackgroundHandoff()};onVisibilityChange=()=>{this.syncBackgroundHandoff()};async onload(){this.pluginDir=this.manifest.dir||this.pluginDir,await this.loadSettings(),this.registerBuiltIns(),this.api=this.createApi(),this.api=this.api,this.addCommands(),this.addSettingTab(new qt(this.app,this)),this.registerEvent(this.app.vault.on("create",()=>this.queueContentRefresh())),this.registerEvent(this.app.vault.on("modify",()=>this.queueContentRefresh())),this.registerEvent(this.app.workspace.on("editor-change",()=>this.handleNoteEdit())),this.registerEvent(this.app.vault.on("delete",()=>this.queueContentRefresh())),this.registerDomEvent(window,"focus",this.onWindowFocus),this.registerDomEvent(window,"blur",this.onWindowBlur),this.registerDomEvent(document,"visibilitychange",this.onVisibilityChange),window.dispatchEvent(new CustomEvent(re,{detail:this.api})),await this.refreshContent(),this.refreshPet(),this.startContentPolling(),this.startReminderPolling()}onunload(){this.writeCompanionState(!1),this.stopCompanionCommandPolling(),this.stopNativeCompanion(),this.destroyPet(),this.destroyOverlayWindow(),this.stopSpriteFrameAnimation(),this.contentTimer&&window.clearInterval(this.contentTimer),this.refreshTimer&&window.clearTimeout(this.refreshTimer),this.reminderTimer&&window.clearInterval(this.reminderTimer)}async loadSettings(){let t=await this.loadData(),e=JSON.parse(JSON.stringify(f));this.settings={...e,...t||{},content:{...e.content,...t?.content||{}},generation:{...e.generation,...t?.generation||{}},cutout:{...e.cutout,...t?.cutout||{}},chat:{...e.chat,...t?.chat||{}},webSearch:{...e.webSearch,...t?.webSearch||{}},externalActions:{...e.externalActions,...t?.externalActions||{}},reminders:{...e.reminders,...t?.reminders||{}},actionBindings:Array.isArray(t?.actionBindings)?t.actionBindings:e.actionBindings,skills:Array.isArray(t?.skills)?t.skills:e.skills,pets:Array.isArray(t?.pets)&&t.pets.length?t.pets:e.pets};let i=new Map(this.settings.actionBindings.map(s=>[s.id,s]));this.settings.actionBindings=Dt.map(s=>({...s,...i.get(s.id)||{}}));for(let s of i.values())this.settings.actionBindings.some(o=>o.id===s.id)||this.settings.actionBindings.push(s);let n=new Map(this.settings.skills.map(s=>[s.id,s]));this.settings.skills=rt.map(s=>({...s,...n.get(s.id)||{}}));for(let s of n.values())this.settings.skills.some(o=>o.id===s.id)||this.settings.skills.push(s);this.settings.pets=this.settings.pets.map(s=>({...at({id:s.id,name:s.name}),...s,profile:{...q(),...s.profile||{}},appearanceTemplates:Array.isArray(s.appearanceTemplates)?s.appearanceTemplates:[],actions:Array.isArray(s.actions)&&s.actions.length?s.actions:F.map(o=>W(o.id,o.name,o.motion,o.prompt))}));for(let s of this.settings.pets){for(let o of s.actions)o.assetType=this.resolveAssetType(o.assetPath,o.assetType);for(let o of s.appearanceTemplates||[])o.assetType=this.resolveAssetType(o.assetPath,o.assetType)}this.getActivePet()||(this.settings.activePetId=this.settings.pets[0]?.id||"starter"),this.normalizeChatModelProfiles(Array.isArray(t?.chat?.modelProfiles)),this.normalizeChatSessions(),this.syncChatStateFromSession()}async saveSettings(){await this.saveData(this.settings)}normalizeChatModelProfiles(t=!0){let e=this.settings.chat,i=new Set,n=Array.isArray(e.modelProfiles)?e.modelProfiles:[],s=new Map(n.filter(r=>r?.id).map(r=>[r.id,r])),o=Mt.map(r=>this.normalizeChatModelProfile({...r,...s.get(r.id)||{}},i));for(let r of n)!r?.id||o.some(l=>l.id===r.id)||o.push(this.normalizeChatModelProfile(r,i));if(e.modelProfiles=o,!t){let r=o.find(c=>c.providerPreset===e.providerPreset)||o[0],l=this.normalizeChatModelProfile({...r,providerPreset:e.providerPreset||r.providerPreset,apiFormat:e.apiFormat||r.apiFormat,endpoint:e.endpoint||r.endpoint,apiKey:e.apiKey||r.apiKey,model:e.model||r.model,updatedAt:Date.now()},new Set(o.filter(c=>c.id!==r.id).map(c=>c.id))),d=o.findIndex(c=>c.id===r.id);d>=0&&(o[d]=l),e.activeModelProfileId=l.id}(!e.activeModelProfileId||!o.some(r=>r.id===e.activeModelProfileId))&&(e.activeModelProfileId=o[0]?.id||R().id),this.syncLegacyChatFieldsFromActiveProfile()}normalizeChatModelProfile(t,e){let i=R({id:T("model"),name:"Custom model",providerPreset:"custom",endpoint:"",model:""}),n=`${t.id||i.id}`.trim()||i.id,s=e.has(n)?T("model"):n;e.add(s);let o=it[t.providerPreset||"custom"]||it.custom;return{...i,...t,id:s,name:`${t.name||o.label||i.name}`.trim()||i.name,providerPreset:t.providerPreset||"custom",apiFormat:t.apiFormat||o.apiFormat,endpoint:`${t.endpoint??o.endpoint??""}`.trim(),apiKey:`${t.apiKey||""}`,model:`${t.model??o.model??""}`.trim(),createdAt:t.createdAt||Date.now(),updatedAt:t.updatedAt||Date.now()}}getActiveChatModelProfile(){return(!Array.isArray(this.settings.chat.modelProfiles)||!this.settings.chat.modelProfiles.length)&&this.normalizeChatModelProfiles(),this.settings.chat.modelProfiles.find(t=>t.id===this.settings.chat.activeModelProfileId)||this.settings.chat.modelProfiles[0]||R()}syncLegacyChatFieldsFromActiveProfile(t=this.getActiveChatModelProfile()){this.settings.chat.providerPreset=t.providerPreset,this.settings.chat.apiFormat=t.apiFormat,this.settings.chat.endpoint=t.endpoint,this.settings.chat.apiKey=t.apiKey,this.settings.chat.model=t.model}async switchChatModelProfile(t){this.normalizeChatModelProfiles(),this.settings.chat.modelProfiles.some(e=>e.id===t)&&(this.settings.chat.activeModelProfileId=t,this.syncLegacyChatFieldsFromActiveProfile(),await this.saveSettings(),this.updateChatControls())}async renameActiveChatModelProfile(t){let e=this.getActiveChatModelProfile();e.name=t.trim()||e.name||"Model",e.updatedAt=Date.now(),this.syncLegacyChatFieldsFromActiveProfile(e),await this.saveSettings(),this.updateChatControls()}async updateActiveChatModelProfile(t){let e=this.getActiveChatModelProfile();t(e),e.updatedAt=Date.now(),this.syncLegacyChatFieldsFromActiveProfile(e),await this.saveSettings(),this.updateChatControls()}async createChatModelProfile(){let t=R({id:T("model"),name:`Model ${this.settings.chat.modelProfiles.length+1}`,providerPreset:"custom",endpoint:"",apiKey:"",model:""});this.settings.chat.modelProfiles.push(t),this.settings.chat.activeModelProfileId=t.id,this.syncLegacyChatFieldsFromActiveProfile(t),await this.saveSettings(),this.updateChatControls()}async deleteActiveChatModelProfile(){if(this.settings.chat.modelProfiles.length<=1){new h.Notice("Keep at least one model profile.");return}let t=this.settings.chat.activeModelProfileId;this.settings.chat.modelProfiles=this.settings.chat.modelProfiles.filter(e=>e.id!==t),this.settings.chat.activeModelProfileId=this.settings.chat.modelProfiles[0].id,this.syncLegacyChatFieldsFromActiveProfile(),await this.saveSettings(),this.updateChatControls()}normalizeChatSessions(){let t=Date.now(),e=new Set,i=(Array.isArray(this.settings.chat.sessions)?this.settings.chat.sessions:[]).map((n,s)=>{let o=X({id:s===0?"default":T("chat"),name:s===0?"Default":`Chat ${s+1}`}),r=(n.id||o.id).trim()||o.id,l=e.has(r)?T("chat"):r;return e.add(l),{...o,...n,id:l,name:(n.name||o.name).trim()||o.name,messages:Array.isArray(n.messages)?n.messages.filter(d=>["user","assistant","system"].includes(d.role)&&typeof d.content=="string"):[],summary:n.summary||"",createdAt:n.createdAt||t,updatedAt:n.updatedAt||t}});i.length||i.push(X()),this.settings.chat.sessions=i,(!this.settings.chat.activeSessionId||!i.some(n=>n.id===this.settings.chat.activeSessionId))&&(this.settings.chat.activeSessionId=i[0].id)}getActiveChatSession(){return this.normalizeChatSessions(),this.settings.chat.sessions.find(t=>t.id===this.settings.chat.activeSessionId)||this.settings.chat.sessions[0]}syncChatStateFromSession(){let t=this.getActiveChatSession();this.chatHistory=[...t.messages],this.chatSummary=t.summary||"",this.chatLogPinnedToBottom=!0,this.updateChatControls(),this.renderChatLog({forceBottom:!0})}async persistActiveChatSession(){let t=this.getActiveChatSession();t.messages=[...this.chatHistory],t.summary=this.chatSummary,t.updatedAt=Date.now(),await this.saveSettings(),this.updateChatControls()}async createChatSession(t){let e=X({id:T("chat"),name:t?.trim()||`Chat ${this.settings.chat.sessions.length+1}`});this.settings.chat.sessions.push(e),this.settings.chat.activeSessionId=e.id,this.syncChatStateFromSession(),await this.saveSettings()}async switchChatSession(t){await this.persistActiveChatSession(),this.settings.chat.sessions.some(e=>e.id===t)&&(this.settings.chat.activeSessionId=t,this.syncChatStateFromSession(),await this.saveSettings())}async renameActiveChatSession(t){let e=this.getActiveChatSession(),i=t.trim()||e.name||"Chat";if(e.name===i){this.updateChatControls();return}e.name=i,e.updatedAt=Date.now(),await this.saveSettings(),this.updateChatControls()}async deleteActiveChatSession(){if(this.settings.chat.sessions.length<=1){this.clearChatHistory();return}let t=this.settings.chat.activeSessionId;this.settings.chat.sessions=this.settings.chat.sessions.filter(e=>e.id!==t),this.settings.chat.activeSessionId=this.settings.chat.sessions[0].id,this.syncChatStateFromSession(),await this.saveSettings()}getActivePet(){return this.settings.pets.find(t=>t.id===this.settings.activePetId)||this.settings.pets[0]}getPetName(){return this.getActivePet()?.name?.trim()||"Pet"}getPetChatSourceName(){return`${this.getPetName()} Chat`}resolveAssetType(t,e){let i=$(t||"");return i==="model3d"?"model3d":e&&e!=="image"?e:i}isDisabledModelAsset(t,e){return xi&&(e==="model3d"||$(t||"")==="model3d")}getCurrentVisualAsset(){let t=this.getActivePet(),e=this.getCurrentAction(),i=t?.actions.find(s=>s.id==="idle")||t?.actions[0],n=[{assetPath:e?.assetPath,assetType:e?.assetType},{assetPath:t?.coverAssetPath,assetType:void 0},{assetPath:i?.assetPath,assetType:i?.assetType}];for(let s of n)if(!(!s.assetPath||this.isDisabledModelAsset(s.assetPath,s.assetType)))return{action:e,assetPath:s.assetPath,assetType:this.resolveAssetType(s.assetPath,s.assetType),motion:e?.motion||"idle"};return{action:e,assetType:"image",motion:e?.motion||"idle"}}getPetSizeLimit(){return 360}getChatLogHeightLimit(){let t=Number(this.settings.panelHeight)||f.panelHeight;return Math.round(w(t-148,72,520))}getActionGenerators(){return Array.from(this.actionGenerators.values())}async openSearchInBrowser(t){let e=t.trim();if(!e)throw new Error("Search query is empty.");await this.agentOpenBrowser(`https://www.google.com/search?q=${encodeURIComponent(e)}`)}async prepareWechatDraft(t,e){await this.agentPrepareWechatMessage(t,e)}async restoreDefaultSkills(){let t=new Map(this.settings.skills.map(e=>[e.id,e]));this.settings.skills=rt.map(e=>({...e,...t.get(e.id)||{}}));for(let e of t.values())this.settings.skills.some(i=>i.id===e.id)||this.settings.skills.push(e);await this.saveSettings()}async importSkillFromUrl(t){let e=await Vi(t);if(!e.length)throw new Error("Enter a GitHub or raw URL for SKILL.md or a skill JSON file.");let i,n=[];for(let o of e)try{let r=await(0,h.requestUrl)({url:o,method:"GET",throw:!1});if(r.status>=400){i=`${r.status} ${r.text.slice(0,120)}`;continue}let l=Zi(r.text||JSON.stringify(r.json||{}),o);if(!l.length){i="No skill definition found.";continue}n.push(...l)}catch(r){i=r instanceof Error?r.message:String(r)}let s=Qi(n);if(s.length)return this.upsertImportedSkills(s),await this.saveSettings(),s;throw new Error(`Skill import failed.${i?` ${i}`:""}`)}upsertImportedSkills(t){let e=Date.now();for(let i of t){let n=H(i.id||i.name||"skill","skill"),s=this.settings.skills.find(r=>r.id===n||r.name.toLowerCase()===i.name.toLowerCase()),o={...i,id:n,name:i.name.trim()||"Imported Skill",description:i.description.trim(),prompt:i.prompt.trim(),enabled:i.enabled!==!1,createdAt:s?.createdAt||i.createdAt||e,updatedAt:e};s?Object.assign(s,{...o,enabled:s.enabled}):this.settings.skills.push(o)}}async importActionPackFromUrl(t){let e=Xt(t,["actions.json","action-pack.json","pet-actions.json"]);if(!e.length)throw new Error("Enter a GitHub or raw URL for actions.json or action-pack.json.");let i;for(let n of e)try{let s=await(0,h.requestUrl)({url:n,method:"GET",throw:!1});if(s.status>=400){i=`${s.status} ${s.text.slice(0,120)}`;continue}let o=sn(s.text||JSON.stringify(s.json||{}),n);if(!o.actions.length){i="No action definitions found.";continue}return this.upsertImportedActions(o),await this.saveSettings(),this.refreshPet(),o}catch(s){i=s instanceof Error?s.message:String(s)}throw new Error(`Action import failed.${i?` ${i}`:""}`)}upsertImportedActions(t){let e=this.getActivePet();if(e){for(let i of t.actions){let n=e.actions.find(s=>s.id===i.id);n?Object.assign(n,{...i,createdAt:n.createdAt,updatedAt:Date.now()}):e.actions.push(i)}for(let i of t.bindings){let n=this.settings.actionBindings.find(s=>s.id===i.id);n?Object.assign(n,{...i,createdAt:n.createdAt,updatedAt:Date.now()}):this.settings.actionBindings.push(i)}e.updatedAt=Date.now()}}async installActionTemplate(t){let e=Ut.find(n=>n.id===t),i=this.getActivePet();if(!(!e||!i)){if(await this.updateActivePet(n=>{let s=n.actions.find(o=>o.id===e.id);s?(s.name=e.name,s.motion=e.motion,s.prompt=e.prompt,s.updatedAt=Date.now()):n.actions.push(W(e.id,e.name,e.motion,e.prompt))}),e.binding){let n=`template-${e.id}-binding`,s=this.settings.actionBindings.find(r=>r.id===n),o={id:n,name:`${e.name} trigger`,enabled:!0,event:e.binding.event,pattern:e.binding.pattern,actionId:e.id,timeoutMs:e.binding.timeoutMs||2600,createdAt:s?.createdAt||Date.now(),updatedAt:Date.now()};s?Object.assign(s,o):this.settings.actionBindings.push(o)}await this.saveSettings(),this.refreshPet(),new h.Notice(`Installed action template: ${e.name}`)}}async createPet(t="New Pet"){let e=at({id:T("pet"),name:t,emoji:"\u2728",createdAt:Date.now(),updatedAt:Date.now()});return this.settings.pets.push(e),this.settings.activePetId=e.id,await this.saveSettings(),this.refreshPet(),e}async deleteActivePet(){if(this.settings.pets.length<=1){new h.Notice("Keep at least one pet.");return}let t=this.settings.activePetId;this.settings.pets=this.settings.pets.filter(e=>e.id!==t),this.settings.activePetId=this.settings.pets[0].id,await this.saveSettings(),this.refreshPet()}async updateActivePet(t){let e=this.getActivePet();e&&(t(e),e.updatedAt=Date.now(),await this.saveSettings(),this.refreshPet())}async updateActivePetData(t){let e=this.getActivePet();e&&(t(e),e.updatedAt=Date.now(),await this.saveSettings())}async uploadCover(t){let e=this.getActivePet();if(!e)return;this.validateUploadFile(t);let i=e.coverAssetPath,n=await _t(t,this.settings.cutout),s=await It(this.app,this.pluginDir,e.id,n,"cover");await this.updateActivePet(o=>{o.coverAssetPath=s.assetPath;for(let r of o.actions)(r.id==="idle"||!r.assetPath||!!(i&&r.assetPath===i))&&(r.assetPath=s.assetPath,r.assetType=s.assetType,r.updatedAt=Date.now())}),this.noticeUploadedAsset(t,s.assetType,"cover")}async saveCurrentAppearanceTemplate(t){this.getActivePet()&&await this.updateActivePetData(i=>{let n=i.actions.find(r=>r.id==="idle")||i.actions[0],s=i.coverAssetPath||n?.assetPath,o=this.resolveAssetType(s,n?.assetType);i.appearanceTemplates=Array.isArray(i.appearanceTemplates)?i.appearanceTemplates:[],i.appearanceTemplates.push({id:T("appearance"),name:t?.trim()||`${i.name||"Pet"} appearance ${i.appearanceTemplates.length+1}`,description:i.description||"",assetPath:s,assetType:o,createdAt:Date.now(),updatedAt:Date.now()})})}async applyAppearanceTemplate(t){let i=this.getActivePet()?.appearanceTemplates?.find(n=>n.id===t);if(i){if(this.isDisabledModelAsset(i.assetPath,i.assetType)){new h.Notice("3D appearance templates are disabled in this low-memory 2D build. Please upload a 2D PNG/JPG/WebP/GIF cover.");return}await this.updateActivePet(n=>{n.coverAssetPath=i.assetPath,i.description&&(n.description=i.description);let s=n.actions.find(o=>o.id==="idle")||n.actions[0];s&&(s.assetPath=i.assetPath,s.assetType=this.resolveAssetType(i.assetPath,i.assetType),s.updatedAt=Date.now())}),this.showMessage(`Applied ${i.name}.`,{sourceName:this.getPetName(),actionId:"wave",timeoutMs:2600})}}async deleteAppearanceTemplate(t){await this.updateActivePetData(e=>{e.appearanceTemplates=(e.appearanceTemplates||[]).filter(i=>i.id!==t)})}async uploadActionAsset(t,e){let i=this.getActivePet();if(!i)return;this.validateUploadFile(e);let n=await _t(e,this.settings.cutout),s=await It(this.app,this.pluginDir,i.id,n,`action-${t}`);await this.updateActivePet(o=>{let r=o.actions.find(l=>l.id===t);r&&(r.assetPath=s.assetPath,r.assetType=s.assetType,r.updatedAt=Date.now())}),this.noticeUploadedAsset(e,s.assetType,"action")}async importCodexSpriteAtlas(t){let e=this.getActivePet();if(!e)return;if(this.validateUploadFile(t),$(`${t.name} ${t.type}`)==="gif")throw new Error("Use a static PNG/WebP Codex atlas, not an animated GIF.");let i=await createImageBitmap(t);try{let o=Bt*192,r=Ft*208;if(i.width!==o||i.height!==r)throw new Error(`Codex atlas must be exactly ${o}x${r} (${Bt}x${Ft} cells, 192x208 each). This image is ${i.width}x${i.height}.`);let l=Date.now(),d=(0,h.normalizePath)(`${this.pluginDir}/pets/${e.id}/codex-atlas-${l}-${J(t.name)}`);await _(this.app,d);let c=new Map,p=await this.normalizeCodexAtlasBitmap(i,192,208),u=await new Promise(g=>p.toBlob(g,"image/png"));if(!u)throw new Error("Unable to export normalized Codex atlas.");await this.app.vault.adapter.writeBinary((0,h.normalizePath)(`${d}/spritesheet-8x9.png`),await u.arrayBuffer());for(let g of ft){let m=192*g.frameCount,v=208,y=document.createElement("canvas");y.width=m,y.height=v;let P=y.getContext("2d");if(!P)throw new Error("Unable to prepare sprite atlas canvas.");P.clearRect(0,0,m,v),P.drawImage(p,0,g.row*208,m,v,0,0,m,v);let S=await new Promise(N=>y.toBlob(N,"image/png"));if(!S)throw new Error(`Unable to export ${g.state} frames from atlas.`);let I=await S.arrayBuffer(),A=(0,h.normalizePath)(`${d}/${String(g.row).padStart(2,"0")}-${g.state}.png`);await this.app.vault.adapter.writeBinary(A,I),c.set(g.actionId,A)}await this.updateActivePet(g=>{for(let m of ft){let v=c.get(m.actionId);if(!v)continue;let y=g.actions.find(P=>P.id===m.actionId);y||(y=W(m.actionId,m.name,m.motion,m.prompt),g.actions.push(y)),y.name=m.name,y.motion=m.motion,y.prompt=m.prompt,y.assetPath=v,y.assetType="spritesheet",y.frameCount=m.frameCount,y.frameDurationMs=m.frameDurationMs,y.frameDurationsMs=m.frameDurationsMs,y.loop=!0,y.updatedAt=Date.now(),m.actionId==="idle"&&(g.coverAssetPath=v)}}),this.currentActionId="idle",this.renderSprite(),new h.Notice(`Imported Codex atlas: ${ft.length} animated actions.`)}finally{i.close()}}async normalizeCodexAtlasBitmap(t,e,i){let n=document.createElement("canvas");n.width=t.width,n.height=t.height;let s=n.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("Unable to inspect Codex atlas.");s.clearRect(0,0,n.width,n.height),s.drawImage(t,0,0);let o=s.getImageData(0,0,n.width,n.height),r=o.data;for(let l=0;l<r.length;l+=4){let d=r[l],c=r[l+1],p=r[l+2],u=r[l+3];if(u>0&&c>105&&c>d*1.18&&c>p*1.18){r[l+3]=0;continue}u>0&&c>d+8&&c>p+8&&(r[l+1]=Math.max(d,p))}return s.putImageData(o,0,0),this.validateCodexAtlasTransparency(s,e,i),n}validateCodexAtlasTransparency(t,e,i){let n=new Map(ft.map(s=>[s.row,s.frameCount]));for(let s=0;s<Ft;s+=1){let o=n.get(s)||0;for(let r=0;r<o;r+=1){let l=t.getImageData(r*e,s*i,e,i),d=0;for(let c=3;c<l.data.length&&(l.data[c]>8&&(d+=1),!(d>24));c+=4);if(d<=24)throw new Error(`Codex atlas used cell row ${s}, column ${r} is empty.`)}for(let r=o;r<Bt;r+=1){let l=t.getImageData(r*e,s*i,e,i),d=0;for(let c=3;c<l.data.length;c+=4)if(l.data[c]>8&&(d+=1),d>24)throw new Error(`Codex atlas unused cell row ${s}, column ${r} must be transparent.`)}}}validateUploadFile(t){let e=t.name.toLowerCase(),i=Ai.some(s=>e.endsWith(s)),n=t.type.startsWith("image/");if(e.endsWith(".glb")||e.endsWith(".gltf")||t.type.includes("gltf"))throw new Error("3D pets are disabled in this build to keep Obsidian memory low. Please upload PNG, JPG, WebP, GIF, or a spritesheet.");if(!i&&!n)throw new Error(`Unsupported pet asset: ${t.name}. Use PNG, JPG, WebP, GIF, or a spritesheet image.`);return $(`${t.name} ${t.type}`)}noticeUploadedAsset(t,e,i){let n=i==="cover"?"cover":"action";new h.Notice(`Uploaded ${t.name} as a 2D ${n} asset.`)}async installGeneratedActions(t){let e=this.getActivePet();if(!e)return[];let i=await this.generateActions({pet:e,coverAssetPath:e.coverAssetPath,requestedActions:t||F.map(n=>n.id),stylePrompt:this.settings.generation.stylePrompt});return i.length?(await this.updateActivePet(n=>{for(let s of i){let o=n.actions.findIndex(r=>r.id===s.id);o>=0?n.actions[o]=s:n.actions.push(s)}}),new h.Notice(`Generated ${i.length} pet actions.`),i):(new h.Notice("No actions were generated."),[])}async generateActions(t={}){let e=t.pet||this.getActivePet();if(!e)return[];let i=this.settings.generation.preferredGeneratorId||"default-motion",n=this.actionGenerators.get(i)||this.actionGenerators.get("default-motion");return n?n.generate({pet:e,coverAssetPath:t.coverAssetPath??e.coverAssetPath,requestedActions:t.requestedActions||F.map(s=>s.id),stylePrompt:t.stylePrompt??this.settings.generation.stylePrompt},this.getProviderContext()):[]}async refreshContent(){let t=this.activeContentItem?.id,e=this.dashboardTab;if(!this.settings.content.enabled)return this.allContentItems=[],this.contentItems=[],this.activeContentItem=void 0,this.renderSpeech(),[];let i=this.getProviderContext(),n=[];for(let r of this.contentProviders.values())try{if(!(r.isAvailable?await r.isAvailable(i):!0))continue;n.push(...await r.getItems(i))}catch(l){console.error(`DIY Desktop Pet content provider failed: ${r.id}`,l)}this.allContentItems=n.map(un).filter(r=>r.title||r.body).filter(r=>!this.hiddenContentIds.has(r.id)).sort((r,l)=>{let d={high:0,normal:1,low:2},c=d[r.priority||"normal"]-d[l.priority||"normal"];return c||(r.due&&l.due&&r.due!==l.due?r.due.localeCompare(l.due):r.due&&!l.due?-1:!r.due&&l.due?1:(l.createdAt||0)-(r.createdAt||0))}),this.contentItems=this.allContentItems.slice(0,this.settings.content.maxItems);let s=new Set(this.allContentItems.map(r=>r.id));for(let r of Array.from(this.expandedMemoIds))s.has(r)||this.expandedMemoIds.delete(r);this.dashboardTab=e;let o=t?this.allContentItems.find(r=>r.id===t):void 0;return o?this.selectDashboardItem(o,!1):this.ensureActiveDashboardItem(),this.renderSpeech(),this.app.workspace.trigger(Et,this.contentItems),window.dispatchEvent(new CustomEvent(Et,{detail:this.contentItems})),this.checkDueReminders(),this.contentItems}refreshPet(){this.destroyPet(),this.destroyOverlayWindow(),this.settings.enabled&&(this.createPetElement(),this.syncBackgroundHandoff())}showMessage(t,e={}){this.speechEl&&(e.actionId&&this.playAction(e.actionId,e.timeoutMs),this.speechDoneEl&&(this.speechDoneEl.checked=!1),this.speechActionsEl?.toggleAttribute("hidden",!0),this.setSpeech(e.sourceName||this.getActivePet()?.name||"Pet",b(t),void 0),this.petEl?.classList.add("diy-desktop-pet--talking"),this.speechTimer&&window.clearTimeout(this.speechTimer),this.speechTimer=window.setTimeout(()=>{this.petEl?.classList.remove("diy-desktop-pet--talking"),this.renderSpeech()},e.timeoutMs||2600))}async chat(t){let e=t.trim();if(!e)return"";if(this.toggleChatPanel(!0),this.triggerBoundAction("user-message",e),this.chatHistory.push({role:"user",content:e}),this.settings.chat.historyStrategy==="rolling"&&this.trimChatHistory(),await this.persistActiveChatSession(),this.renderChatLog({forceBottom:!0}),this.settings.chat.agentEnabled){let s=await this.tryRunDirectAgentCommand(e);if(s){this.chatHistory.push({role:"assistant",content:s}),this.trimChatHistory(),await this.persistActiveChatSession(),await this.appendChatLog(e,s),this.renderChatLog({forceBottom:!0});let o=this.triggerBoundAction("assistant-reply",s);return this.showMessage(s,{sourceName:this.getPetName(),actionId:o?void 0:this.getFirstExistingActionId(["tail-wag","wave"]),timeoutMs:5200}),s}}if(!this.settings.chat.enabled){let s="Chat API is not enabled in plugin settings.";return this.chatHistory.push({role:"assistant",content:s}),await this.persistActiveChatSession(),this.renderChatLog({forceBottom:!0}),this.showMessage(s,{sourceName:this.getPetChatSourceName(),actionId:this.getFirstExistingActionId(["failed","review","think"]),timeoutMs:3600}),s}if(!this.getActiveChatModelProfile().endpoint.trim()){let s="Chat endpoint is empty.";return this.chatHistory.push({role:"assistant",content:s}),await this.persistActiveChatSession(),this.renderChatLog({forceBottom:!0}),this.showMessage(s,{sourceName:this.getPetChatSourceName(),actionId:this.getFirstExistingActionId(["failed","review","think"]),timeoutMs:3600}),s}this.chatBusy=!0,this.updateChatBusy(),this.showMessage("Thinking...",{sourceName:this.getPetChatSourceName(),actionId:this.getFirstExistingActionId(["running","waiting","review","think"]),timeoutMs:9e3});let n=await this.getActiveFileContext();try{let s=await this.requestChatCompletion(n);this.chatHistory.push({role:"assistant",content:s}),await this.applyChatHistoryLimit();let o=this.triggerBoundAction("assistant-reply",s);return await this.persistActiveChatSession(),await this.appendChatLog(e,s,n),this.renderChatLog({forceBottom:!0}),this.showMessage(s,{sourceName:this.getPetName(),actionId:o?void 0:this.getFirstExistingActionId(["tail-wag","wave"]),timeoutMs:6e3}),s}catch(s){console.error("DIY Desktop Pet chat failed.",s);let o=s instanceof Error?s.message:"Chat request failed.";return this.chatHistory.push({role:"assistant",content:o}),await this.persistActiveChatSession(),this.renderChatLog({forceBottom:!0}),this.showMessage(o,{sourceName:this.getPetChatSourceName(),actionId:this.getFirstExistingActionId(["failed","review","think"]),timeoutMs:5e3}),new h.Notice(o),o}finally{this.chatBusy=!1,this.updateChatBusy()}}clearChatHistory(){this.chatHistory=[],this.chatSummary="",this.persistActiveChatSession(),this.chatLogPinnedToBottom=!0,this.renderChatLog({forceBottom:!0});let t=this.triggerBoundAction("chat-clear","clear history");this.showMessage("Chat history cleared.",{sourceName:this.getPetChatSourceName(),actionId:t?void 0:this.getFirstExistingActionId(["shake","running","wave"]),timeoutMs:2600}),new h.Notice(`${this.getPetName()} chat history cleared.`)}async addApexDashboardItem(t,e){let i=Hi(e.title),n=He(e.body||""),s=je(e.date||"");if(!i){new h.Notice("Title is required.");return}let o=await this.getOrCreateApexDashboardFile();await this.app.vault.process(o,r=>Wi(r,t,{title:i,body:n,date:s})),this.dashboardTab=t==="task"?"task":t,await this.refreshContent(),this.showPanelMode("dashboard"),this.showPetPanel(),this.showMessage(`Added ${Oe(t)}: ${i}`,{sourceName:"Apex Dashboard",actionId:"wave",timeoutMs:3e3}),new h.Notice(`Added to ${o.path}.`)}async getOrCreateApexDashboardFile(){let t=(this.settings.content.apexDashboardFile||f.content.apexDashboardFile||"dashboard").trim()||"dashboard",e=(0,h.normalizePath)(t.endsWith(".md")?t:`${t}.md`),i=this.app.vault.getFileByPath(e);if(i)return i;if(!t.includes("/")){let r=e.replace(/\.md$/i,""),l=this.app.vault.getMarkdownFiles().find(d=>d.basename===r);if(l)return l}let n=e.split("/").slice(0,-1).join("/");n&&await _(this.app,n);let s=ze(),o=await this.app.vault.create(e,s);if(!(o instanceof h.TFile))throw new Error(`Could not create dashboard file: ${e}`);return o}registerBuiltIns(){this.registerContentProvider(new dt),this.registerContentProvider(new ct),this.registerContentProvider(new ht),this.registerActionGenerator(new ot),this.registerActionGenerator(new lt)}createApi(){return{version:this.manifest.version,registerContentProvider:t=>this.registerContentProvider(t),registerActionGenerator:t=>this.registerActionGenerator(t),getActivePet:()=>this.getActivePet(),getPets:()=>this.settings.pets,upsertPet:async t=>{let e=this.settings.pets.findIndex(i=>i.id===t.id);e>=0?this.settings.pets[e]=t:this.settings.pets.push(t),this.settings.activePetId||(this.settings.activePetId=t.id),await this.saveSettings(),this.refreshPet()},setActivePet:async t=>{if(!this.settings.pets.some(e=>e.id===t))throw new Error(`Pet not found: ${t}`);this.settings.activePetId=t,await this.saveSettings(),this.refreshPet()},addAction:async(t,e)=>{let i=this.settings.pets.find(s=>s.id===t);if(!i)throw new Error(`Pet not found: ${t}`);let n=i.actions.findIndex(s=>s.id===e.id);n>=0?i.actions[n]=e:i.actions.push(e),i.updatedAt=Date.now(),await this.saveSettings(),this.refreshPet()},removeAction:async(t,e)=>{let i=this.settings.pets.find(n=>n.id===t);if(!i)throw new Error(`Pet not found: ${t}`);i.actions=i.actions.filter(n=>n.id!==e),i.updatedAt=Date.now(),await this.saveSettings(),this.refreshPet()},generateActions:t=>this.generateActions(t),showMessage:(t,e)=>this.showMessage(t,e),chat:t=>this.chat(t),clearChatHistory:()=>this.clearChatHistory(),refreshContent:()=>this.refreshContent()}}registerContentProvider(t){return this.contentProviders.set(t.id,t),this.queueContentRefresh(),()=>{this.contentProviders.delete(t.id),this.queueContentRefresh()}}registerActionGenerator(t){return this.actionGenerators.set(t.id,t),()=>{this.actionGenerators.delete(t.id)}}addCommands(){this.addCommand({id:"toggle-pet",name:"Toggle desktop pet",callback:async()=>{this.settings.enabled=!this.settings.enabled,await this.saveSettings(),this.refreshPet()}}),this.addCommand({id:"reset-pet-position",name:"Reset pet position",callback:async()=>{this.settings.x=null,this.settings.y=null,await this.saveSettings(),this.refreshPet()}}),this.addCommand({id:"show-next-content",name:"Show next pet reminder",callback:()=>this.showNextContent()}),this.addCommand({id:"refresh-pet-content",name:"Refresh pet reminders",callback:async()=>{let t=await this.refreshContent();new h.Notice(`Desktop pet found ${t.length} items.`)}}),this.addCommand({id:"create-reading-knowledge-graph",name:"Create reading knowledge graph",callback:async()=>{this.triggerBoundAction("agent-tool","create_knowledge_graph");let t=await this.agentCreateKnowledgeGraph({open:!0},{requireWritePermission:!1});t.ok||new h.Notice(t.error||"Could not create reading knowledge graph.")}}),this.addCommand({id:"analyze-reading-records",name:"Analyze reading records",callback:async()=>{this.triggerBoundAction("agent-tool","analyze_reading_records");let t=await this.agentAnalyzeReadingRecords({open:!0},{requireWritePermission:!1});t.ok||new h.Notice(t.error||"Could not analyze reading records.")}}),this.addCommand({id:"generate-default-actions",name:"Generate default pet actions",callback:()=>this.installGeneratedActions()}),this.addCommand({id:"clear-pet-chat-history",name:"Clear pet chat history",callback:()=>this.clearChatHistory()})}getProviderContext(){return{app:this.app,activePet:this.getActivePet(),settings:this.settings,pluginDir:this.pluginDir}}createPetElement(){let t=this.getActivePet();this.petEl=document.body.createDiv({cls:"diy-desktop-pet"}),this.petEl.setAttribute("role","button"),this.petEl.setAttribute("tabindex","0"),this.petEl.setAttribute("aria-label",`${t?.name||"Desktop pet"}, desktop pet`),this.spriteEl=this.petEl.createDiv({cls:"diy-desktop-pet__sprite"}),this.shadowEl=this.petEl.createDiv({cls:"diy-desktop-pet__shadow"}),this.speechEl=this.petEl.createDiv({cls:"diy-desktop-pet__speech"}),this.panelResizeEl=this.speechEl.createDiv({cls:"diy-desktop-pet__panel-resize",attr:{"aria-label":"Resize pet panel"}});let e=this.speechEl.createDiv({cls:"diy-desktop-pet__pet-switcher"});this.petSelectEl=e.createEl("select",{attr:{"aria-label":"Active pet"}}),this.menuEl=this.speechEl.createDiv({cls:"diy-desktop-pet__menu"}),this.addMenuButton("Dashboard","dashboard"),this.addMenuButton("Chat","chat"),this.speechSourceEl=this.speechEl.createDiv({cls:"diy-desktop-pet__source"}),this.speechTitleEl=this.speechEl.createDiv({cls:"diy-desktop-pet__title"}),this.speechBodyEl=this.speechEl.createDiv({cls:"diy-desktop-pet__body"}),this.dashboardEl=this.speechEl.createDiv({cls:"diy-desktop-pet__dashboard"}),this.speechActionsEl=this.speechEl.createDiv({cls:"diy-desktop-pet__speech-actions"}),this.speechOpenEl=this.speechActionsEl.createEl("button",{text:"Open",attr:{type:"button","aria-label":"Open current content source"}});let i=this.speechActionsEl.createEl("label",{cls:"diy-desktop-pet__done"});this.speechDoneEl=i.createEl("input",{attr:{type:"checkbox","aria-label":"Mark current pet content complete"}}),i.createSpan({text:"Done"}),this.chatEl=this.speechEl.createDiv({cls:"diy-desktop-pet__chat"});let n=this.chatEl.createDiv({cls:"diy-desktop-pet__chat-header"});this.chatTitleEl=n.createSpan({cls:"diy-desktop-pet__chat-title",text:`${t?.name||"Pet"} chat`}),this.chatModelProfileEl=n.createEl("select",{cls:"diy-desktop-pet__chat-select diy-desktop-pet__chat-model-profile",attr:{"aria-label":"Model profile"}}),this.chatModelProfileNameEl=n.createEl("input",{cls:"diy-desktop-pet__chat-name diy-desktop-pet__chat-model-name",attr:{type:"text","aria-label":"Model profile name",placeholder:"model name"}}),this.chatNewSessionEl=n.createEl("button",{text:"New",attr:{type:"button","aria-label":"Create new chat session"}}),this.chatLogEl=this.chatEl.createDiv({cls:"diy-desktop-pet__chat-log"}),this.chatLogResizeEl=this.chatEl.createDiv({cls:"diy-desktop-pet__chat-log-resize",attr:{"aria-label":"Resize chat messages"}});let s=this.chatEl.createEl("form",{cls:"diy-desktop-pet__chat-form"});this.chatInputEl=s.createEl("textarea",{attr:{placeholder:"Say something...",rows:"1"}}),this.chatSendEl=s.createEl("button",{text:"Send",attr:{type:"submit"}});let o=this.chatEl.createDiv({cls:"diy-desktop-pet__chat-controls"});this.chatSessionEl=o.createEl("select",{cls:"diy-desktop-pet__chat-select",attr:{"aria-label":"Chat session"}}),this.chatSessionNameEl=o.createEl("input",{cls:"diy-desktop-pet__chat-name",attr:{type:"text","aria-label":"Chat session name",placeholder:"session name"}}),this.chatModeEl=o.createEl("select",{cls:"diy-desktop-pet__chat-select",attr:{"aria-label":"Chat mode"}}),tt(this.chatModeEl,"chat","Chat"),tt(this.chatModeEl,"agent","Agent");let r=o.createEl("details",{cls:"diy-desktop-pet__chat-more"});r.createEl("summary",{text:"More"});let l=r.createDiv({cls:"diy-desktop-pet__chat-more-actions"});this.chatPermissionsEl=l.createEl("button",{text:"Permissions",attr:{type:"button","aria-label":"Open pet permissions"}}),this.chatDeleteSessionEl=l.createEl("button",{text:"Delete",attr:{type:"button","aria-label":"Delete current chat session"}}),this.chatClearEl=l.createEl("button",{text:"Clear",attr:{type:"button","aria-label":"Clear current chat history"}}),this.petResizeEl=this.petEl.createDiv({cls:"diy-desktop-pet__pet-resize",attr:{"aria-label":"Resize pet"}}),this.petEl.addEventListener("pointerdown",this.onPointerDown),this.petEl.addEventListener("click",this.onClick),this.petEl.addEventListener("keydown",this.onKeydown),this.spriteEl.addEventListener("pointerenter",this.onPetPointerEnter),this.speechEl.addEventListener("pointerdown",d=>d.stopPropagation()),this.speechEl.addEventListener("click",d=>d.stopPropagation()),this.petSelectEl.addEventListener("change",async()=>{let d=this.petSelectEl?.value||"";!d||d===this.settings.activePetId||(this.settings.activePetId=d,await this.saveSettings(),this.refreshPet(),await this.refreshContent())}),this.speechActionsEl?.addEventListener("pointerdown",d=>d.stopPropagation()),this.speechActionsEl?.addEventListener("click",d=>d.stopPropagation()),this.speechDoneEl?.addEventListener("change",()=>{this.speechDoneEl?.checked&&this.completeActiveContent()}),this.speechOpenEl?.addEventListener("click",d=>{d.stopPropagation(),this.openActiveContentSource()}),this.chatEl.addEventListener("pointerdown",d=>d.stopPropagation()),this.chatEl.addEventListener("click",d=>d.stopPropagation()),this.chatLogEl.addEventListener("scroll",this.onChatLogScroll),this.chatLogResizeEl.addEventListener("pointerdown",this.onChatLogResizeDown),this.chatSessionEl.addEventListener("change",()=>{this.switchChatSession(this.chatSessionEl?.value||"")}),this.chatSessionNameEl.addEventListener("change",()=>{this.renameActiveChatSession(this.chatSessionNameEl?.value||"")}),this.chatSessionNameEl.addEventListener("keydown",d=>{d.key==="Enter"&&(d.preventDefault(),this.renameActiveChatSession(this.chatSessionNameEl?.value||""),this.chatSessionNameEl?.blur())}),this.chatNewSessionEl.addEventListener("click",()=>{this.createChatSession()}),this.chatDeleteSessionEl.addEventListener("click",()=>{this.deleteActiveChatSession()}),this.chatModeEl.addEventListener("change",async()=>{this.settings.chat.agentEnabled=this.chatModeEl?.value==="agent",await this.saveSettings(),this.updateChatControls()}),this.chatModelProfileEl.addEventListener("change",()=>{this.switchChatModelProfile(this.chatModelProfileEl?.value||"")}),this.chatModelProfileNameEl.addEventListener("change",()=>{this.renameActiveChatModelProfile(this.chatModelProfileNameEl?.value||"")}),this.chatModelProfileNameEl.addEventListener("keydown",d=>{d.key==="Enter"&&(d.preventDefault(),this.renameActiveChatModelProfile(this.chatModelProfileNameEl?.value||""),this.chatModelProfileNameEl?.blur())}),this.chatPermissionsEl.addEventListener("click",()=>{new Vt(this.app,this).open()}),this.chatClearEl.addEventListener("click",()=>this.clearChatHistory()),this.chatInputEl.addEventListener("keydown",d=>{d.stopPropagation(),!(d.key!=="Enter"||d.shiftKey||d.ctrlKey||d.metaKey||d.altKey||d.isComposing)&&(d.preventDefault(),this.submitChatInput())}),this.chatInputEl.addEventListener("keyup",d=>d.stopPropagation()),this.chatInputEl.addEventListener("input",()=>this.adjustChatInputHeight()),s.addEventListener("submit",d=>{d.preventDefault(),this.submitChatInput()}),this.petResizeEl.addEventListener("pointerdown",this.onResizeHandleDown),this.panelResizeEl.addEventListener("pointerdown",this.onResizeHandleDown),window.addEventListener("resize",this.onResize),this.applyPetStyles(),this.renderSprite(),this.updateChatControls(),this.updatePetSwitcher(),this.renderSpeech(),this.placePet(),this.startPetLoop()}async syncBackgroundHandoff(t=!1){let e=!!(this.settings.enabled&&this.settings.desktopOverlay&&h.Platform.isDesktopApp&&h.Platform.isMacOS);if(this.destroyOverlayWindow(),!e){this.overlayWanted=!1,this.overlayPanelVisible=!1,this.petEl?.classList.remove("diy-desktop-pet--handoff-hidden"),this.petEl?.classList.remove("diy-desktop-pet--desktop-controller"),await this.writeCompanionState(!1),this.stopCompanionCommandPolling(),this.stopNativeCompanion();return}t&&(this.overlayPanelVisible=!0),await this.writeCompanionState(!0);let i=this.startNativeCompanion();this.overlayWanted=i,this.petEl?.classList.remove("diy-desktop-pet--handoff-hidden"),this.petEl?.classList.toggle("diy-desktop-pet--desktop-controller",i),i?this.startCompanionCommandPolling():(this.stopCompanionCommandPolling(),this.petEl?.classList.remove("diy-desktop-pet--desktop-controller")),i||new h.Notice("DIY Desktop Pet could not start the desktop companion. Falling back to the Obsidian pet.")}startNativeCompanion(){if(!h.Platform.isDesktopApp||!h.Platform.isMacOS)return!1;if(this.companionProcess&&!this.companionProcess.killed)return!0;let t=this.getNodeChildProcess();if(!t?.spawn)return!1;let e=this.getVaultAbsolutePath(`${this.pluginDir}/bin/diy-desktop-pet-companion`),i=this.getCompanionStatePath();if(!e||!i)return!1;try{let n=t.spawn(e,[i],{cwd:this.getVaultBasePath(),detached:!1,stdio:"ignore"});return n.on("exit",()=>{this.companionProcess===n&&(this.companionProcess=void 0)}),n.on("error",s=>{console.error("DIY Desktop Pet companion failed.",s),this.companionProcess===n&&(this.companionProcess=void 0)}),n.unref?.(),this.companionProcess=n,!0}catch(n){return console.error("DIY Desktop Pet could not launch native companion.",n),this.companionProcess=void 0,!1}}stopNativeCompanion(){let t=this.companionProcess;if(this.companionProcess=void 0,!(!t||t.killed))try{t.kill()}catch(e){console.debug("DIY Desktop Pet companion already stopped.",e)}}startCompanionCommandPolling(){this.companionCommandTimer||(this.app.vault.adapter.read(this.getCompanionCommandRelativePath()).then(t=>{this.companionCommandText=t||"";try{let e=t?JSON.parse(t):void 0,i=Number(e?.createdAt||0);e?.command&&Number.isFinite(i)&&Date.now()-i<1e4&&this.handleCompanionCommand(e)}catch(e){console.debug("DIY Desktop Pet ignored an invalid startup companion command.",e)}}).catch(()=>{this.companionCommandText=""}),this.companionCommandTimer=window.setInterval(()=>{this.readCompanionCommand()},80))}stopCompanionCommandPolling(){this.companionCommandTimer&&(window.clearInterval(this.companionCommandTimer),this.companionCommandTimer=void 0,this.companionCommandText="")}async readCompanionCommand(){if(!(!this.settings.enabled||!this.settings.desktopOverlay))try{let t=await this.app.vault.adapter.read(this.getCompanionCommandRelativePath());if(!t||t===this.companionCommandText)return;this.companionCommandText=t;let e=JSON.parse(t);await this.handleCompanionCommand(e)}catch(t){String(t).includes("ENOENT")||console.debug("DIY Desktop Pet companion command read failed.",t)}}async handleCompanionCommand(t){if(this.syncControllerPositionFromCompanion(t),t.command!=="move"){if(t.command==="pet-hover"){this.playHoverAction();return}t.command!=="pet-hover-end"&&t.command==="toggle-main-panel"&&(this.activateObsidian(),this.togglePetPanel(),this.renderSpeech(),this.playClickAction(),await this.writeCompanionState(!0))}}syncControllerPositionFromCompanion(t){if(typeof t.screenX!="number"||typeof t.screenY!="number"||!Number.isFinite(t.screenX)||!Number.isFinite(t.screenY))return;let e=w(Number(this.settings.size)||f.size,48,360),i=t.screenX-window.screenX,n=t.screenY-window.screenY,s=8,o=Math.max(s,window.innerWidth-e-s),r=Math.max(s,window.innerHeight-e-s);this.position={x:w(i,s,o),y:w(n,s,r)},this.renderPosition()}activateObsidian(){window.focus(),this.getNodeChildProcess()?.exec?.(`osascript -e 'tell application "Obsidian" to activate'`)}async writeCompanionState(t){let e=this.getCompanionStateRelativePath(),i=this.getCurrentAction(),n=this.getActivePet(),s=this.getCompanionSpeech(),o={enabled:t,name:n?.name||"Desktop Pet",assetPath:t?this.getVaultAbsolutePath(i?.assetPath||n?.coverAssetPath||""):void 0,frameCount:Math.max(1,i?.frameCount||1),frameDurationsMs:i?this.getActionFrameDurations(i):[180],size:w(Number(this.settings.size)||f.size,48,360),source:s.source,title:s.title,body:s.body,commandPath:this.getCompanionCommandPath()},r=`${JSON.stringify(o,null,2)}
`;if(r!==this.companionStateText){this.companionStateText=r;try{await this.app.vault.adapter.write(e,r)}catch(l){console.error("DIY Desktop Pet could not write companion state.",l)}}}getCompanionSpeech(){if(this.speechState.title)return this.speechState;let t=this.getActivePet();if(this.activeContentItem){let e=this.activeContentItem.due?`Due ${this.activeContentItem.due}`:"";return{source:this.activeContentItem.sourceName,title:this.activeContentItem.title,body:[this.activeContentItem.body,e].filter(Boolean).join(`
`)}}return{source:t?.name||"Desktop Pet",title:t?.description||"Ready when you are.",body:""}}getCompanionStateRelativePath(){return`${this.pluginDir}/companion-state.json`}getCompanionCommandRelativePath(){return`${this.pluginDir}/companion-command.json`}getCompanionStatePath(){return this.getVaultAbsolutePath(this.getCompanionStateRelativePath())}getCompanionCommandPath(){return this.getVaultAbsolutePath(this.getCompanionCommandRelativePath())}getVaultBasePath(){let t=this.app.vault.adapter;return t.getBasePath?.()||t.basePath}getVaultAbsolutePath(t){if(!t)return;if(t.startsWith("/"))return t;let e=this.getVaultBasePath();if(e)return`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`}getOverlayWindowSize(t=this.overlayPanelVisible){let e=w(Number(this.settings.size)||f.size,48,360);return{width:t?Math.max(320,e+300):Math.max(160,e+36),height:t?Math.max(230,e+190):Math.max(150,e+36)}}async refreshOverlayWindow(){if(!this.overlayWindow||this.overlayWindow.isDestroyed())return;let{width:t,height:e}=this.getOverlayWindowSize();this.resizeOverlayWindow(t,e),await this.overlayWindow.loadURL(await this.createOverlayDataUrl(t,e))}async createOverlayWindow(){if(this.overlayWindow&&!this.overlayWindow.isDestroyed())return!0;if(!h.Platform.isDesktopApp)return console.debug("DIY Desktop Pet background handoff is only available in Obsidian desktop."),!1;let t=this.getElectronRemote();if(!t?.BrowserWindow)return console.debug("DIY Desktop Pet background handoff is not available in this Obsidian version."),!1;let{width:e,height:i}=this.getOverlayWindowSize(),n=this.getOverlayPosition(t,e,i);try{return this.overlayWindow=new t.BrowserWindow({width:e,height:i,x:n.x,y:n.y,frame:!1,transparent:!0,hasShadow:!1,resizable:!1,movable:!0,minimizable:!1,maximizable:!1,fullscreenable:!1,alwaysOnTop:!0,skipTaskbar:!0,focusable:!0,acceptFirstMouse:!0,backgroundColor:"#00000000",webPreferences:{backgroundThrottling:!0,contextIsolation:!0}}),this.overlayWindow.setAlwaysOnTop(!0,"floating"),this.overlayWindow.setVisibleOnAllWorkspaces(!0,{visibleOnFullScreen:!0}),this.overlayWindow.setFullScreenable(!1),this.overlayWindow.setIgnoreMouseEvents(!1),this.overlayWindow.on("move",()=>this.saveOverlayPosition()),this.overlayWindow.on("closed",()=>{this.overlayWindow=void 0}),this.overlayWindow.webContents?.on("will-navigate",(s,o)=>{this.handleOverlayCommandUrl(o)&&s.preventDefault()}),this.overlayWindow.webContents?.setWindowOpenHandler?.(s=>this.handleOverlayCommandUrl(s.url)?{action:"deny"}:{action:"allow"}),await this.overlayWindow.loadURL(await this.createOverlayDataUrl(e,i)),!0}catch(s){return console.error("DIY Desktop Pet failed to create background handoff window.",s),this.overlayWindow=void 0,!1}}handleOverlayCommandUrl(t){if(!t.startsWith("diy-desktop-pet://"))return!1;let e=t.replace("diy-desktop-pet://","").replace(/\/$/,"");return e==="toggle-panel"?(this.overlayPanelVisible=!this.overlayPanelVisible,this.refreshOverlayWindow(),!0):e==="show-panel"?(this.overlayPanelVisible=!0,this.refreshOverlayWindow(),!0):(e==="hide-panel"&&(this.overlayPanelVisible=!1,this.refreshOverlayWindow()),!0)}resizeOverlayWindow(t,e){if(!this.overlayWindow||this.overlayWindow.isDestroyed())return;let[i,n]=this.overlayWindow.getPosition(),[s,o]=this.overlayWindow.getSize();this.overlayWindow.setBounds({x:i+s-t,y:n+o-e,width:t,height:e})}destroyOverlayWindow(){if(!this.overlayWindow||this.overlayWindow.isDestroyed()){this.overlayWindow=void 0;return}try{this.overlayWindow.close()}catch(t){console.debug("Desktop pet overlay already closed.",t)}this.overlayWindow=void 0}destroyPet(){window.removeEventListener("resize",this.onResize),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointermove",this.onResizeHandleMove),window.removeEventListener("pointerup",this.onResizeHandleUp),window.removeEventListener("pointermove",this.onChatLogResizeMove),window.removeEventListener("pointerup",this.onChatLogResizeUp),this.animationFrame&&window.cancelAnimationFrame(this.animationFrame),this.actionTimer&&window.clearTimeout(this.actionTimer),this.speechTimer&&window.clearTimeout(this.speechTimer),this.stopSpriteFrameAnimation(),this.animationFrame=void 0,this.petEl?.remove(),this.petEl=void 0,this.spriteEl=void 0,this.speechEl=void 0,this.speechSourceEl=void 0,this.speechTitleEl=void 0,this.speechBodyEl=void 0,this.speechActionsEl=void 0,this.speechDoneEl=void 0,this.speechOpenEl=void 0,this.dashboardEl=void 0,this.menuEl=void 0,this.petSelectEl=void 0,this.chatEl=void 0,this.chatTitleEl=void 0,this.chatLogEl=void 0,this.chatLogResizeEl=void 0,this.chatSessionEl=void 0,this.chatSessionNameEl=void 0,this.chatModeEl=void 0,this.chatModelProfileEl=void 0,this.chatModelProfileNameEl=void 0,this.chatPermissionsEl=void 0,this.chatNewSessionEl=void 0,this.chatDeleteSessionEl=void 0,this.chatInputEl=void 0,this.chatSendEl=void 0,this.chatClearEl=void 0,this.panelResizeEl=void 0,this.petResizeEl=void 0,this.chatLogResizeState=void 0}getElectronRemote(){try{let t=require("electron");if(t.remote)return t.remote}catch(t){console.debug("Electron remote unavailable through require.",t)}try{return window.require?.("electron")?.remote}catch(t){console.debug("Electron remote unavailable through window.require.",t);return}}getElectronShell(){try{let t=require("electron");if(t.shell)return t.shell}catch(t){console.debug("Electron shell unavailable through require.",t)}try{return window.require?.("electron")?.shell}catch(t){console.debug("Electron shell unavailable through window.require.",t);return}}getOverlayPosition(t,e,i){if(typeof this.settings.overlayX=="number"&&typeof this.settings.overlayY=="number")return{x:this.settings.overlayX,y:this.settings.overlayY};let n=t.screen?.getPrimaryDisplay().workArea;return n?{x:n.x+n.width-e-28,y:n.y+n.height-i-80}:{x:80,y:80}}async saveOverlayPosition(){if(!this.overlayWindow||this.overlayWindow.isDestroyed())return;let[t,e]=this.overlayWindow.getPosition();this.settings.overlayX=t,this.settings.overlayY=e,await this.saveSettings()}async createOverlayDataUrl(t,e){let i=this.getActivePet(),{action:n,assetPath:s,assetType:o,motion:r}=this.getCurrentVisualAsset(),l=await this.getAssetDataUrl(s),d=B(i?.emoji||"\u{1F43E}"),c=B(i?.name||"Desktop pet"),p=B(this.settings.accentColor||f.accentColor),u=Math.min(this.settings.size,Math.min(t,e)-36),g=B(b(this.activeContentItem?.sourceName||i?.name||"Desktop pet")),m=B(b(this.activeContentItem?.title||i?.description||"Ready when you are.")),v=B(b([this.activeContentItem?.body,this.activeContentItem?.due?`Due ${this.activeContentItem.due}`:""].filter(Boolean).join(`
`))),y=this.buildOverlayModulesHtml(),P=n?.frameCount&&n.frameCount>1?n.frameCount:1,S=n?.frameDurationMs||140,I=n?this.getActionFrameDurations(n):[S],A=!!(l&&o==="spritesheet"&&P>1),N=l?A?`<div class="pet-spritesheet" role="img" aria-label="${c}" style="--pet-frames: ${P}; --pet-frame-duration: ${S}ms; background-image: url('${l}');"></div>`:`<div class="pet-pseudo3d" aria-hidden="true"><img class="pet-pseudo3d-depth" src="${l}" alt="" draggable="false"><img class="pet-image pet-pseudo3d-main" src="${l}" alt="${c}" draggable="false"></div>`:`<div class="pet-emoji">${d}</div>`,kt=`<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: transparent;
}
body {
display: grid;
place-items: end;
box-sizing: border-box;
padding: 12px;
user-select: none;
}
.pet-root {
position: relative;
display: grid;
place-items: end;
width: 100%;
height: 100%;
}
.pet-shell {
width: ${u}px;
height: ${u}px;
display: grid;
place-items: center;
perspective: ${Math.max(180,Math.round(u*2.8))}px;
filter: drop-shadow(0 14px 22px rgb(0 0 0 / 0.24));
cursor: pointer;
-webkit-app-region: no-drag;
animation: pet-pseudo3d-idle 2.6s ease-in-out infinite;
transform-style: preserve-3d;
}
.pet-shell--spritesheet {
animation: none;
transform-style: flat;
}
.pet-drag-handle {
position: absolute;
right: 18px;
bottom: 0;
width: ${Math.max(48,Math.round(u*.62))}px;
height: 12px;
border-radius: 999px;
background: rgb(255 255 255 / 0.22);
cursor: grab;
-webkit-app-region: drag;
}
.pet-emoji {
width: 86%;
height: 86%;
display: grid;
place-items: center;
border-radius: 30%;
background: ${p};
color: white;
font-size: ${Math.round(u*.46)}px;
line-height: 1;
}
.pet-3d {
position: relative;
background: radial-gradient(circle at 30% 25%, rgb(255 255 255 / 0.44), transparent 30%), ${p};
box-shadow: inset -10px -14px 24px rgb(0 0 0 / 0.18), inset 10px 10px 20px rgb(255 255 255 / 0.16);
}
.pet-3d span {
position: absolute;
right: 8px;
bottom: 8px;
padding: 2px 5px;
border-radius: 999px;
background: rgb(0 0 0 / 0.24);
color: white;
font: 700 10px/1 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.pet-model {
position: relative;
width: 100%;
height: 100%;
display: grid;
place-items: center;
overflow: visible;
}
.pet-model-canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
filter: drop-shadow(0 14px 18px rgb(0 0 0 / 0.24));
}
.pet-model-fallback {
width: 86%;
height: 86%;
display: grid;
place-items: center;
border-radius: 30%;
background: radial-gradient(circle at 30% 25%, rgb(255 255 255 / 0.44), transparent 30%), ${p};
box-shadow: inset -10px -14px 24px rgb(0 0 0 / 0.18), inset 10px 10px 20px rgb(255 255 255 / 0.16);
color: white;
font-size: ${Math.round(u*.46)}px;
line-height: 1;
}
.pet-model.is-loaded .pet-model-fallback {
opacity: 0;
}
.pet-model-fallback span,
.pet-model-error {
position: absolute;
right: 8px;
bottom: 8px;
padding: 2px 5px;
border-radius: 999px;
background: rgb(0 0 0 / 0.24);
color: white;
font: 700 10px/1 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.pet-image {
width: 100%;
height: 100%;
object-fit: contain;
pointer-events: none;
}
.pet-spritesheet {
position: relative;
width: auto;
height: 96%;
aspect-ratio: 192 / 208;
background-position: 0 0;
background-repeat: no-repeat;
background-size: calc(var(--pet-frames) * 100%) 100%;
filter: drop-shadow(-5px -6px 8px rgb(255 255 255 / 0.18)) drop-shadow(8px 12px 13px rgb(0 0 0 / 0.26));
transform: translateZ(18px);
animation: none;
}
.pet-spritesheet::before {
content: "";
position: absolute;
left: 16%;
right: 16%;
bottom: 4%;
height: 13%;
border-radius: 999px;
background: rgb(0 0 0 / 0.24);
filter: blur(7px);
transform: translate3d(0, 10%, -28px) rotateX(72deg);
}
@keyframes pet-spritesheet-frames {
to { background-position: 100% 0; }
}
.pet-pseudo3d {
position: relative;
width: 100%;
height: 100%;
transform-style: preserve-3d;
}
.pet-pseudo3d::before {
content: "";
position: absolute;
left: 16%;
right: 16%;
bottom: 4%;
height: 13%;
border-radius: 999px;
background: rgb(0 0 0 / 0.24);
filter: blur(7px);
transform: translate3d(0, 10%, -28px) rotateX(72deg);
}
.pet-pseudo3d::after {
content: "";
position: absolute;
inset: 7% 8% auto 8%;
height: 38%;
border-radius: 999px;
background: linear-gradient(120deg, rgb(255 255 255 / 0.34), transparent 66%);
mix-blend-mode: screen;
pointer-events: none;
transform: translate3d(-4%, -2%, 22px) rotate(-8deg);
}
.pet-pseudo3d-depth,
.pet-pseudo3d-main {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: contain;
pointer-events: none;
}
.pet-pseudo3d-depth {
opacity: 0.32;
filter: brightness(0.36) saturate(0.7) blur(0.8px);
transform: translate3d(8px, 9px, -22px) scale(0.985) skewY(-2deg);
}
.pet-pseudo3d-main {
filter: drop-shadow(-5px -6px 8px rgb(255 255 255 / 0.18)) drop-shadow(8px 12px 13px rgb(0 0 0 / 0.26));
transform: translateZ(18px);
animation: pet-pseudo3d-breathe 2.8s ease-in-out infinite;
}
.pet-root[data-motion="wave"] .pet-shell {
animation: pet-pseudo3d-wave 820ms ease-in-out infinite;
}
.pet-root[data-motion="jump"] .pet-shell {
animation: pet-pseudo3d-jump 650ms ease-in-out infinite;
}
.pet-root[data-motion="spin"] .pet-shell {
animation: pet-pseudo3d-spin 1s ease-in-out infinite;
}
.pet-root[data-motion="think"] .pet-shell {
animation: pet-pseudo3d-think 1.35s ease-in-out infinite;
}
.pet-root[data-motion="sleep"] .pet-shell {
animation: pet-pseudo3d-sleep 1.9s ease-in-out infinite;
}
.pet-root[data-motion="shake"] .pet-shell {
animation: pet-pseudo3d-shake 430ms ease-in-out infinite;
}
.pet-root[data-motion] .pet-shell--spritesheet {
animation: none;
}
@keyframes pet-pseudo3d-idle {
0%, 100% { transform: rotateY(-5deg) rotateX(2deg) translate3d(0, 0, 0); }
50% { transform: rotateY(7deg) rotateX(5deg) translate3d(0, -4px, 12px); }
}
@keyframes pet-pseudo3d-breathe {
0%, 100% { transform: translateZ(18px) scale3d(1, 1, 1); }
50% { transform: translateZ(24px) scale3d(1.035, 0.985, 1); }
}
@keyframes pet-pseudo3d-wave {
0%, 100% { transform: rotateZ(-5deg) rotateY(-18deg) translate3d(0, 0, 0); }
50% { transform: rotateZ(9deg) rotateY(22deg) translate3d(0, -4px, 18px); }
}
@keyframes pet-pseudo3d-jump {
0%, 100% { transform: translate3d(0, 0, 0) rotateX(0deg) scale3d(1, 1, 1); }
45% { transform: translate3d(0, -22%, 24px) rotateX(12deg) scale3d(1.05, 0.96, 1); }
}
@keyframes pet-pseudo3d-spin {
to { transform: rotateY(360deg); }
}
@keyframes pet-pseudo3d-think {
0%, 100% { transform: rotateZ(-2deg) rotateY(-9deg) rotateX(1deg); }
50% { transform: rotateZ(4deg) rotateY(10deg) rotateX(8deg) translate3d(0, -3px, 15px); }
}
@keyframes pet-pseudo3d-sleep {
0%, 100% { transform: rotateX(-5deg) rotateZ(-3deg) translate3d(0, 2px, -8px); opacity: 0.84; }
50% { transform: rotateX(-10deg) rotateZ(2deg) translate3d(0, 6px, -12px); opacity: 1; }
}
@keyframes pet-pseudo3d-shake {
0%, 100% { transform: translate3d(0, 0, 0) rotateY(0deg); }
25% { transform: translate3d(-6%, 0, 15px) rotateY(-18deg); }
75% { transform: translate3d(6%, 0, 15px) rotateY(18deg); }
}
.pet-bubble {
position: absolute;
right: ${Math.max(16,u-12)}px;
bottom: ${Math.max(24,Math.round(u*.54))}px;
width: min(280px, calc(100% - ${u+28}px));
max-height: min(250px, calc(100% - 24px));
box-sizing: border-box;
padding: 9px 10px;
border: 1px solid rgb(255 255 255 / 0.5);
border-radius: 8px;
background: rgb(30 30 34 / 0.92);
color: white;
box-shadow: 0 12px 26px rgb(0 0 0 / 0.22);
opacity: 0;
overflow: auto;
transform: translateY(6px) scale(0.98);
transition: opacity 160ms ease, transform 160ms ease;
-webkit-app-region: no-drag;
}
.pet-root.pet-panel-visible .pet-bubble {
opacity: 1;
transform: translateY(0) scale(1);
}
.pet-source {
color: ${p};
font: 700 11px/1.2 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.pet-title {
margin-top: 4px;
color: white;
font: 600 12px/1.3 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
overflow-wrap: anywhere;
}
.pet-body {
margin-top: 4px;
color: rgb(255 255 255 / 0.72);
font: 11px/1.35 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
white-space: pre-line;
overflow-wrap: anywhere;
}
.pet-modules {
display: grid;
gap: 7px;
margin-top: 9px;
}
.pet-module-head {
display: flex;
justify-content: space-between;
gap: 8px;
color: rgb(255 255 255 / 0.56);
font: 700 10px/1.2 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
text-transform: uppercase;
}
.pet-row {
margin-top: 3px;
padding: 5px 6px;
border: 1px solid rgb(255 255 255 / 0.14);
border-radius: 6px;
background: rgb(255 255 255 / 0.07);
color: rgb(255 255 255 / 0.88);
font: 11px/1.3 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
overflow-wrap: anywhere;
}
.pet-row-meta {
margin-top: 2px;
color: rgb(255 255 255 / 0.54);
font-size: 10px;
}
.pet-empty {
margin-top: 8px;
color: rgb(255 255 255 / 0.58);
font: 11px/1.35 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
</style>
</head>
<body>
<main class="pet-root${this.overlayPanelVisible?" pet-panel-visible":""}" data-motion="${r}" aria-label="${c}">
<section class="pet-bubble">
<div class="pet-source">${g}</div>
<div class="pet-title">${m}</div>
${v?`<div class="pet-body">${v}</div>`:""}
${y}
</section>
<section class="pet-shell${A?" pet-shell--spritesheet":""}">${N}</section>
<div class="pet-drag-handle" title="Drag pet window"></div>
</main>
<script>
const root = document.querySelector(".pet-root");
const shell = document.querySelector(".pet-shell");
shell?.addEventListener("click", () => {
window.location.href = "diy-desktop-pet://toggle-panel";
});
const spritesheet = document.querySelector(".pet-spritesheet");
const frameCount = ${P};
const frameDurations = ${JSON.stringify(I)};
let frame = 0;
function tickFrame() {
if (!spritesheet || frameCount <= 1) return;
const position = frameCount <= 1 ? 0 : (frame / (frameCount - 1)) * 100;
spritesheet.style.backgroundPosition = position + "% 0";
const duration = frameDurations[frame] || frameDurations[frameDurations.length - 1] || ${S};
frame = (frame + 1) % frameCount;
window.setTimeout(tickFrame, duration);
}
tickFrame();
<\/script>
</body>
</html>`;return`data:text/html;charset=utf-8,${encodeURIComponent(kt)}`}buildOverlayModulesHtml(){let e=[{key:"goal",label:"Goal",items:this.getDashboardModuleItems("goal")},{key:"memo",label:"Memo",items:this.getDashboardModuleItems("memo")},{key:"task",label:"Task",items:this.getDashboardModuleItems("task")},{key:"study",label:"Study",items:this.getDashboardModuleItems("study")},{key:"learned",label:"Learned",items:this.getDashboardModuleItems("learned")}].filter(i=>i.items.length);return e.length?`<div class="pet-modules">${e.map(i=>{let n=i.items.slice(0,3).map(s=>{let o=[s.body,s.due?`Due ${s.due}`:""].filter(Boolean).join(" \xB7 ");return`<div class="pet-row">${B(s.title||"Untitled")}${o?`<div class="pet-row-meta">${B(o)}</div>`:""}</div>`}).join("");return`<section class="pet-module"><div class="pet-module-head"><span>${B(i.label)}</span><span>${i.items.length}</span></div>${n}</section>`}).join("")}</div>`:'<div class="pet-empty">No dashboard items.</div>'}async getAssetDataUrl(t){if(t)try{let e=await this.app.vault.adapter.readBinary(t),i=Buffer.from(e).toString("base64");return`data:${Wt(t)};base64,${i}`}catch(e){console.debug("Unable to load desktop pet overlay asset.",e);return}}applyPetStyles(){this.petEl&&(this.petEl.style.setProperty("--pet-size",`${this.settings.size}px`),this.petEl.style.setProperty("--pet-accent",this.settings.accentColor),this.petEl.style.setProperty("--pet-panel-width",`${this.settings.panelWidth||f.panelWidth}px`),this.petEl.style.setProperty("--pet-panel-height",`${this.settings.panelHeight||f.panelHeight}px`),this.petEl.style.setProperty("--pet-chat-log-height",`${w(Number(this.settings.chat.logHeight)||f.chat.logHeight,72,this.getChatLogHeightLimit())}px`),this.petEl.style.opacity=`${w(this.settings.opacity,20,100)/100}`,this.petEl.classList.toggle("diy-desktop-pet--bounce",this.settings.bounce&&!this.settings.stayStill),this.petEl.classList.toggle("diy-desktop-pet--speech",this.settings.showSpeech))}updatePetSwitcher(){if(!this.petSelectEl)return;let t=this.settings.activePetId;this.petSelectEl.replaceChildren();for(let e of this.settings.pets)tt(this.petSelectEl,e.id,e.name||"Pet");this.petSelectEl.value=t}renderSprite(){if(!this.spriteEl)return;let t=this.getActivePet(),{action:e,assetPath:i,assetType:n,motion:s}=this.getCurrentVisualAsset(),o=ce(this.app,i);if(this.queueCompanionStateWrite(),this.stopSpriteFrameAnimation(),this.spriteEl.replaceChildren(),this.spriteEl.removeAttribute("style"),this.spriteEl.classList.toggle("diy-desktop-pet__sprite--asset",!!o),this.spriteEl.classList.toggle("diy-desktop-pet__sprite--spritesheet",!!(o&&n==="spritesheet")),this.petEl?.setAttribute("data-motion",s),o&&n==="spritesheet"&&e?.frameCount&&e.frameCount>1){this.spriteEl.style.backgroundImage=`url("${o}")`,this.spriteEl.style.setProperty("--pet-frames",`${e.frameCount}`),this.spriteEl.style.setProperty("--pet-frame-duration",`${e.frameDurationMs||140}ms`),this.startSpriteFrameAnimation(this.spriteEl,e);return}if(o){let r=this.spriteEl.createDiv({cls:"diy-desktop-pet__pseudo3d"}),l=document.createElement("img");l.className="diy-desktop-pet__pseudo3d-depth",l.src=o,l.alt="",l.draggable=!1;let d=document.createElement("img");d.className="diy-desktop-pet__pseudo3d-main",d.src=o,d.alt=`${t?.name||"Pet"} ${e?.name||"cover"}`,d.draggable=!1,r.append(l,d);return}this.spriteEl.textContent=t?.emoji||"\u{1F43E}"}stopSpriteFrameAnimation(){this.spriteFrameTimer&&(window.clearTimeout(this.spriteFrameTimer),this.spriteFrameTimer=void 0)}getActionFrameDurations(t){let e=Math.max(1,Math.round(t.frameCount||1)),i=Array.isArray(t.frameDurationsMs)?t.frameDurationsMs.map(n=>Math.round(Number(n))).filter(n=>Number.isFinite(n)&&n>0):[];return i.length?Array.from({length:e},(n,s)=>i[s]||i[i.length-1]||t.frameDurationMs||140):Array.from({length:e},()=>Math.max(40,Math.round(t.frameDurationMs||140)))}startSpriteFrameAnimation(t,e){let i=Math.max(1,Math.round(e.frameCount||1));if(i<=1)return;let n=this.getActionFrameDurations(e),s=0,o=()=>{let r=i<=1?0:s/(i-1)*100;t.style.backgroundPosition=`${r}% 0`;let l=n[s]||n[n.length-1]||140;s=(s+1)%i,this.spriteFrameTimer=window.setTimeout(o,l)};o()}renderSpeech(){let t=this.getActivePet();this.updatePetSwitcher(),this.speechDoneEl&&(this.speechDoneEl.checked=!1);let e=this.panelMode==="chat";if(this.chatOpen=e,this.petEl?.classList.toggle("diy-desktop-pet--chat-open",e),this.petEl?.classList.toggle("diy-desktop-pet--content-open",!e),this.chatEl?.toggleAttribute("hidden",!e),this.speechSourceEl?.toggleAttribute("hidden",e),this.speechTitleEl?.toggleAttribute("hidden",e),this.speechBodyEl?.toggleAttribute("hidden",e),this.dashboardEl?.toggleAttribute("hidden",e),e||this.ensureActiveDashboardItem(),this.speechActionsEl?.toggleAttribute("hidden",!this.activeContentItem),e){this.speechActionsEl?.toggleAttribute("hidden",!0),this.renderChatLog();return}if(this.activeContentItem){let i=this.activeContentItem.due?`Due ${this.activeContentItem.due}`:void 0,n=[this.activeContentItem.body,i].filter(Boolean).join(`
`);this.setSpeech(this.activeContentItem.sourceName,this.activeContentItem.title,n||void 0),this.renderDashboardModules(this.dashboardEl);return}this.setSpeech(t?.name||"Pet",t?.description||"Ready when you are.",void 0),this.renderDashboardModules(this.dashboardEl)}setSpeech(t,e,i){if(!this.speechSourceEl||!this.speechTitleEl||!this.speechBodyEl)return;let n=b(t),s=b(e),o=b(i||"");this.speechState={source:n,title:s,body:o},this.speechSourceEl.textContent=n,this.speechTitleEl.textContent=s,this.speechBodyEl.textContent=o,this.speechBodyEl.toggleAttribute("hidden",!o),this.queueCompanionStateWrite()}queueCompanionStateWrite(){!this.settings.enabled||!this.settings.desktopOverlay||!h.Platform.isDesktopApp||this.writeCompanionState(!0)}renderDashboardModules(t=this.dashboardEl){if(!t)return;t.replaceChildren();let e=t.createDiv({cls:"diy-desktop-pet__dashboard-tabs"});for(let d of yt){let c=this.getDashboardModuleItems(d.key).length,p=e.createEl("button",{cls:`diy-desktop-pet__dashboard-tab${this.dashboardTab===d.key?" diy-desktop-pet__dashboard-tab--active":""}`,attr:{type:"button","aria-pressed":this.dashboardTab===d.key?"true":"false"}});p.createSpan({text:d.label}),p.createSpan({cls:"diy-desktop-pet__dashboard-tab-count",text:String(c)}),p.addEventListener("pointerdown",u=>u.stopPropagation()),p.addEventListener("click",u=>{u.stopPropagation(),this.selectDashboardTab(d.key)})}let i=t.createDiv({cls:"diy-desktop-pet__dashboard-add"});i.createSpan({cls:"diy-desktop-pet__dashboard-add-label",text:"Add"});for(let d of Ei){let c=i.createEl("button",{text:d.label,attr:{type:"button","aria-label":`Add Apex ${d.kind}`}});c.addEventListener("pointerdown",p=>p.stopPropagation()),c.addEventListener("click",p=>{p.stopPropagation(),new Gt(this.app,this,d.kind).open()})}let n=yt.find(d=>d.key===this.dashboardTab)||yt[0],s=this.getDashboardModuleItems(n.key),o=t.createDiv({cls:`diy-desktop-pet__dashboard-module diy-desktop-pet__dashboard-module--${n.key}`}),r=o.createDiv({cls:"diy-desktop-pet__dashboard-module-header"});if(r.createSpan({text:n.label}),r.createSpan({cls:"diy-desktop-pet__dashboard-count",text:String(s.length)}),!s.length){o.createDiv({cls:"diy-desktop-pet__dashboard-empty",text:`No ${n.label} items.`});return}let l=o.createDiv({cls:"diy-desktop-pet__dashboard-list"});for(let d of s){let c=l.createDiv({cls:"diy-desktop-pet__dashboard-row"}),p=n.key==="memo",u=p&&this.expandedMemoIds.has(d.id);p&&c.addClass("diy-desktop-pet__dashboard-row--memo"),u&&c.addClass("diy-desktop-pet__dashboard-row--expanded"),this.activeContentItem?.id===d.id&&c.addClass("diy-desktop-pet__dashboard-row--active"),c.addEventListener("pointerdown",A=>A.stopPropagation()),c.addEventListener("click",A=>{if(A.stopPropagation(),!A.target?.closest("input")){if(p){this.toggleMemoExpanded(d);return}this.selectDashboardItem(d)}});let g=c.createEl("button",{cls:"diy-desktop-pet__dashboard-row-open",attr:{type:"button","aria-label":p?`${u?"Collapse":"Expand"} ${d.title||n.label}`:`Select ${d.title||n.label}`,...p?{"aria-expanded":u?"true":"false"}:{}}});g.addEventListener("click",A=>{if(A.stopPropagation(),p){this.toggleMemoExpanded(d);return}this.selectDashboardItem(d)});let m=g.createDiv({cls:"diy-desktop-pet__dashboard-row-text"}),v=b(d.title||"Untitled");m.createDiv({cls:"diy-desktop-pet__dashboard-row-title",text:v||"Untitled"});let y=b(d.body||""),P=d.due?b(`Due ${d.due}`):"",S=b([y,P].filter(Boolean).join(" \xB7 "));if(p){let A=wn(y||v);A&&m.createDiv({cls:"diy-desktop-pet__dashboard-row-meta diy-desktop-pet__dashboard-row-preview",text:A});let N=b([y,P].filter(Boolean).join(`
`));N&&m.createDiv({cls:"diy-desktop-pet__dashboard-row-full",text:N}),m.createDiv({cls:"diy-desktop-pet__dashboard-row-hint",text:u?"Click to collapse":"Click to read full memo"})}else S&&m.createDiv({cls:"diy-desktop-pet__dashboard-row-meta",text:S});let I=c.createEl("input",{attr:{type:"checkbox","aria-label":`Complete ${d.title||n.label}`}});I.addEventListener("change",()=>{I.checked&&(I.disabled=!0,c.addClass("diy-desktop-pet__dashboard-row--done"),this.completeContentItem(d))})}}async openActiveContentSource(){if(!this.activeContentItem){new h.Notice("No active pet content to open.");return}await this.openContentItemSource(this.activeContentItem)}async openContentItemSource(t){if(!t.path){new h.Notice("This pet content has no source file.");return}let e=this.app.vault.getAbstractFileByPath(t.path);if(!(e instanceof h.TFile)){new h.Notice(`Source file not found: ${t.path}`);return}let i=this.app.workspace.getLeaf(!1);await i.openFile(e,{active:!0}),this.app.workspace.setActiveLeaf(i,{focus:!0}),t.line&&window.setTimeout(()=>{if(!(i.view instanceof h.MarkdownView))return;let n=Math.max(0,t.line-1);i.view.editor.setCursor({line:n,ch:0}),i.view.editor.scrollIntoView({from:{line:n,ch:0},to:{line:n,ch:0}},!0)},80)}getDashboardModuleItems(t){return this.allContentItems.filter(e=>{let i=e.sourceName.toLowerCase(),n=e.id.toLowerCase();return t==="goal"?i.includes("goal")||n.includes("apex-goal"):t==="memo"?i.includes("memo")||n.includes("apex-memo"):t==="study"?i.includes("study")||n.includes("apex-study"):t==="learned"?i.includes("learned")||n.includes("apex-learned"):(e.sourceId==="markdown-tasks"||i.includes("todo")||i.includes("task")||n.includes("apex-todo"))&&!i.includes("study")&&!i.includes("learned")})}getDashboardTabForItem(t){let e=t.sourceName.toLowerCase(),i=t.id.toLowerCase();if(e.includes("study")||i.includes("apex-study"))return"study";if(e.includes("learned")||i.includes("apex-learned"))return"learned";if(e.includes("memo")||i.includes("apex-memo")||t.sourceId==="markdown-memos")return"memo";if(t.sourceId==="markdown-tasks"||e.includes("todo")||e.includes("task")||i.includes("apex-todo"))return"task"}selectDashboardTab(t){this.dashboardTab=t,this.ensureActiveDashboardItem(!0),this.renderSpeech()}toggleMemoExpanded(t){this.selectDashboardItem(t,!1),this.expandedMemoIds.has(t.id)?this.expandedMemoIds.delete(t.id):this.expandedMemoIds.add(t.id),this.renderSpeech()}ensureActiveDashboardItem(t=!1){let e=this.getDashboardModuleItems(this.dashboardTab);if(!e.length){this.activeContentItem=void 0,this.contentIndex=-1;return}!t&&this.activeContentItem&&e.some(i=>i.id===this.activeContentItem?.id)||this.selectDashboardItem(e[0],!1)}selectDashboardItem(t,e=!0){let i=this.getDashboardTabForItem(t);i&&(this.dashboardTab=i),this.activeContentItem=t;let n=this.contentItems.findIndex(s=>s.id===t.id);this.contentIndex=n>=0?n:-1,this.setSpeech(t.sourceName,t.title,[t.body,t.due?`Due ${t.due}`:""].filter(Boolean).join(`
`)||void 0),e&&this.renderSpeech()}addMenuButton(t,e){if(!this.menuEl)return;let i=this.menuEl.createEl("button",{text:t,attr:{type:"button"}});i.dataset.panelMode=e,i.classList.toggle("is-active",this.panelMode===e),i.addEventListener("pointerdown",n=>n.stopPropagation()),i.addEventListener("click",n=>{n.stopPropagation(),this.showPanelMode(e)})}toggleChatPanel(t){this.showPanelMode(typeof t=="boolean"?t?"chat":"dashboard":this.panelMode==="chat"?"dashboard":"chat")}showPanelMode(t){if(this.panelMode=t,this.updateMenuButtons(),t==="chat"){this.renderSpeech(),window.setTimeout(()=>this.chatInputEl?.focus(),0);return}this.ensureActiveDashboardItem(),this.renderSpeech()}updateMenuButtons(){this.menuEl&&this.menuEl.querySelectorAll("button[data-panel-mode]").forEach(t=>{t.classList.toggle("is-active",t.dataset.panelMode===this.panelMode)})}renderChatLog(t={}){if(!this.chatLogEl)return;let e=this.chatLogEl.scrollTop,i=this.isChatLogNearBottom(),n=t.forceBottom||this.chatLogPinnedToBottom||i;this.chatLogEl.replaceChildren();let s=this.chatHistory.filter(o=>o.role!=="system");if(this.chatSummary.trim()){let o=this.chatLogEl.createDiv({cls:"diy-desktop-pet__chat-summary"});o.createDiv({cls:"diy-desktop-pet__chat-summary-title",text:"Earlier context"}),o.createDiv({cls:"diy-desktop-pet__chat-summary-body",text:b(this.chatSummary)})}if(!s.length&&!this.chatSummary.trim()){this.chatLogEl.createDiv({cls:"diy-desktop-pet__chat-empty",text:`Chat with ${this.getPetName()}.`}),this.chatLogPinnedToBottom=!0;return}for(let o of s){let l=this.chatLogEl.createDiv({cls:`diy-desktop-pet__chat-row diy-desktop-pet__chat-row--${o.role}`}).createDiv({cls:`diy-desktop-pet__chat-message diy-desktop-pet__chat-message--${o.role}`});l.createDiv({cls:"diy-desktop-pet__chat-message-role",text:o.role==="user"?"You":this.getPetName()}),l.createDiv({cls:"diy-desktop-pet__chat-message-body",text:b(o.content)})}if(n){this.scrollChatLogToBottom();return}this.chatLogEl.scrollTop=Math.max(0,e),this.chatLogPinnedToBottom=this.isChatLogNearBottom()}isChatLogNearBottom(){return this.chatLogEl?this.chatLogEl.scrollHeight-this.chatLogEl.scrollTop-this.chatLogEl.clientHeight<18:!0}scrollChatLogToBottom(){this.chatLogEl&&(this.chatLogEl.scrollTop=this.chatLogEl.scrollHeight,this.chatLogPinnedToBottom=!0)}onChatLogScroll=()=>{this.chatLogPinnedToBottom=this.isChatLogNearBottom()};triggerBoundAction(t,e){let i=this.getActivePet();if(!i)return!1;let n=e.toLowerCase();for(let s of this.settings.actionBindings){if(!s.enabled||s.event!==t||!s.actionId||!i.actions.some(l=>l.id===s.actionId)||t==="assistant-reply"&&this.isFailureAction(s.actionId)&&!this.isAssistantFailureReply(n))continue;let o=s.pattern.trim();if(!o||Ii(o).some(l=>n.includes(l.toLowerCase())))return this.playAction(s.actionId,s.timeoutMs||2600),!0}return!1}isFailureAction(t){return["failed","shake"].includes(t)}isAssistantFailureReply(t){return["chat request failed","request failed","api error","http error","network error","timeout","timed out","invalid api key","rate limit","unauthorized","forbidden","\u8BF7\u6C42\u5931\u8D25","\u63A5\u53E3\u9519\u8BEF","\u7F51\u7EDC\u9519\u8BEF","\u8D85\u65F6","\u8BA4\u8BC1\u5931\u8D25","\u6743\u9650\u9519\u8BEF","\u53D1\u751F\u9519\u8BEF","\u51FA\u9519\u4E86"].some(i=>t.includes(i))}handleNoteEdit(){let t=Date.now();if(t-this.lastNoteEditActionAt<2800)return;this.lastNoteEditActionAt=t;let e=this.app.workspace.getActiveFile(),i=[e?.basename||"",e?.path||""].filter(Boolean).join(`
`);this.triggerBoundAction("note-edit",i)}updateChatControls(){let t=this.getActiveChatModelProfile();if(this.chatTitleEl&&(this.chatTitleEl.textContent=`${this.getPetName()} chat`),this.chatModelProfileEl){let e=t.id;this.chatModelProfileEl.replaceChildren();for(let i of this.settings.chat.modelProfiles){let n=[i.name||"Model",i.model].filter(Boolean).join(" \xB7 ");tt(this.chatModelProfileEl,i.id,n)}this.chatModelProfileEl.value=e}if(this.chatModelProfileNameEl&&document.activeElement!==this.chatModelProfileNameEl&&(this.chatModelProfileNameEl.value=t.name||"Model"),this.chatSessionEl){let e=this.settings.chat.activeSessionId;this.chatSessionEl.replaceChildren();for(let i of this.settings.chat.sessions)tt(this.chatSessionEl,i.id,i.name||"Chat");this.chatSessionEl.value=e}this.chatSessionNameEl&&document.activeElement!==this.chatSessionNameEl&&(this.chatSessionNameEl.value=this.getActiveChatSession().name||"Chat"),this.chatModeEl&&(this.chatModeEl.value=this.settings.chat.agentEnabled?"agent":"chat"),this.chatDeleteSessionEl&&(this.chatDeleteSessionEl.disabled=this.settings.chat.sessions.length<=1)}async submitChatInput(){let t=this.chatInputEl?.value.trim();!t||this.chatBusy||(this.chatInputEl&&(this.chatInputEl.value="",this.adjustChatInputHeight()),await this.chat(t))}adjustChatInputHeight(){this.chatInputEl&&(this.chatInputEl.style.height="auto",this.chatInputEl.style.height=`${Math.round(w(this.chatInputEl.scrollHeight,30,96))}px`)}updateChatBusy(){this.chatSendEl&&(this.chatSendEl.disabled=this.chatBusy,this.chatSendEl.textContent=this.chatBusy?"...":"Send"),this.chatInputEl&&(this.chatInputEl.disabled=this.chatBusy),this.chatSessionEl&&(this.chatSessionEl.disabled=this.chatBusy),this.chatSessionNameEl&&(this.chatSessionNameEl.disabled=this.chatBusy),this.chatModeEl&&(this.chatModeEl.disabled=this.chatBusy),this.chatModelProfileEl&&(this.chatModelProfileEl.disabled=this.chatBusy),this.chatModelProfileNameEl&&(this.chatModelProfileNameEl.disabled=this.chatBusy),this.chatNewSessionEl&&(this.chatNewSessionEl.disabled=this.chatBusy),this.chatDeleteSessionEl&&(this.chatDeleteSessionEl.disabled=this.chatBusy||this.settings.chat.sessions.length<=1),this.chatClearEl&&(this.chatClearEl.disabled=this.chatBusy),this.chatPermissionsEl&&(this.chatPermissionsEl.disabled=this.chatBusy)}trimChatHistory(){let t=this.getMaxChatHistory();this.chatHistory.length>t&&(this.chatHistory=this.chatHistory.slice(-t))}getMaxChatHistory(){return Math.round(w(Number(this.settings.chat.maxHistory)||f.chat.maxHistory,2,80))}getMaxChatTokens(){return Math.round(w(Number(this.settings.chat.maxTokens)||f.chat.maxTokens,64,64e3))}async applyChatHistoryLimit(){if(this.settings.chat.historyStrategy!=="summarize"){this.trimChatHistory();return}let t=this.getMaxChatHistory();if(this.chatHistory.length<=t)return;let e=this.chatHistory.slice(0,-t);if(e.length){try{let i=await this.requestChatSummary(e);if(i){this.chatSummary=i,this.chatHistory=this.chatHistory.slice(-t);return}}catch(i){console.error("DIY Desktop Pet failed to summarize chat history.",i)}this.trimChatHistory()}}async requestChatCompletion(t){if(this.settings.chat.agentEnabled)return this.requestAgentCompletion(t);let i=this.getActiveChatModelProfile().apiFormat==="responses"?await this.requestResponsesCompletion(t):await this.requestChatCompletionsCompletion(t),n=this.extractChatReply(i);if(!n?.trim())throw new Error("Chat API returned an empty reply.");return n.trim()}async requestAgentCompletion(t){let e=Math.round(w(Number(this.settings.chat.agentMaxSteps)||f.chat.agentMaxSteps,1,10)),i=[];for(let l=0;l<e;l+=1){let c=this.getActiveChatModelProfile().apiFormat==="responses"?await this.requestResponsesCompletion(t,i):await this.requestChatCompletionsCompletion(t,i),p=this.extractChatReply(c).trim();if(!p)throw new Error("Chat API returned an empty agent reply.");let u=Li(p);if(!u)return xe(p);this.triggerBoundAction("agent-tool",u.tool);let g=await this.runAgentTool(u);i.push(g),this.settings.chat.agentLogTools&&console.debug("DIY Desktop Pet agent tool result.",g)}let n="You have reached the maximum tool steps. Answer the user now using the tool results already provided. Do not request another tool.",o=this.getActiveChatModelProfile().apiFormat==="responses"?await this.requestResponsesCompletion(t,i,n):await this.requestChatCompletionsCompletion(t,i,n),r=this.extractChatReply(o).trim();return xe(r||"I reached the tool step limit before finishing.")}async requestChatCompletionsCompletion(t,e=[],i=""){let n=this.buildChatCompletionMessages(t,e,i),s=this.getActiveChatModelProfile();return this.postChatPayload({model:s.model.trim()||f.chat.model,messages:n,temperature:w(Number(this.settings.chat.temperature)||f.chat.temperature,0,2),max_tokens:this.getMaxChatTokens()})}async requestResponsesCompletion(t,e=[],i=""){let n=this.buildResponsesInput(t,e,i),s=this.getActiveChatModelProfile();return this.postChatPayload({model:s.model.trim()||f.chat.model,instructions:this.buildChatInstructions(),input:n,temperature:w(Number(this.settings.chat.temperature)||f.chat.temperature,0,2),max_output_tokens:this.getMaxChatTokens()})}buildChatCompletionMessages(t,e=[],i=""){let n=[{role:"system",content:this.buildChatInstructions(i)}],s=this.chatHistory.filter(r=>r.role!=="system").slice(-this.getMaxChatHistory()),o=Ti(s,r=>r.role==="user");for(let r=0;r<s.length;r+=1){let l=s[r];n.push({role:l.role,content:r===o?this.buildChatCompletionUserContent(l.content,t):l.content})}return e.length&&n.push({role:"user",content:`Agent tool results so far:
${JSON.stringify(e,null,2)}`}),n}buildResponsesInput(t,e=[],i=""){let n=this.chatHistory.filter(d=>d.role!=="system").slice(-this.getMaxChatHistory()),s=[...n].reverse().find(d=>d.role==="user")?.content||"",o=n.slice(0,Math.max(0,n.length-1)),r=this.formatChatTranscript(o),l=[r?`Recent conversation:
${r}`:"",`Current user message:
${s}`,e.length?`Agent tool results so far:
${JSON.stringify(e,null,2)}`:"",i].filter(Boolean).join(`
`);return[{role:"user",content:this.buildResponsesUserContent(l,t)}]}buildChatInstructions(t=""){return[this.settings.chat.systemPrompt||f.chat.systemPrompt,this.buildPetProfileInstructions(),this.buildSkillInstructions(),this.chatSummary?`Conversation memory:
${this.chatSummary}`:"",this.settings.chat.agentEnabled?this.buildAgentInstructions():"",t].filter(Boolean).join(`
`)}buildPetProfileInstructions(){let t=this.getActivePet();if(!t)return"";let e={...q(),...t.profile||{}},i=[`Pet name: ${t.name}`,t.description?`Short description: ${t.description}`:"",e.background?`Background: ${e.background}`:"",e.personality?`Personality: ${e.personality}`:"",e.abilities?`Abilities: ${e.abilities}`:"",e.preferences?`Preferences: ${e.preferences}`:"",e.catchphrases?`Catchphrases: ${e.catchphrases}`:"",e.selfIntroduction?`Preferred self-introduction: ${e.selfIntroduction}`:""].filter(Boolean);return i.length?["Pet profile:",...i,"If the user asks you to introduce yourself, use this profile as the source of truth."].join(`
`):""}buildSkillInstructions(){let t=this.settings.skills.filter(e=>e.enabled&&e.prompt.trim());return t.length?["Enabled pet skills:",...t.map(e=>[`Skill: ${e.name}`,e.description?`Description: ${e.description}`:"",`Instructions: ${e.prompt}`].filter(Boolean).join(`
`))].join(`
`):""}buildAgentInstructions(){return`Agent mode is enabled. You may request one Obsidian tool at a time when you need vault context or need to perform an allowed action.
Available tools:
- read_current_file args {}
- web_search args {"query":"text","limit":5}
- open_web_search args {"query":"text"}
- search_vault args {"query":"text","limit":5}
- read_note args {"path":"Note.md","maxChars":8000}
- create_note args {"path":"Folder/Note.md","content":"markdown"}
- append_note args {"path":"Note.md","content":"markdown"}
- overwrite_note args {"path":"Note.md","content":"markdown"}
- list_pet_content args {}
- refresh_pet_content args {}
- complete_current_pet_content args {}
- show_pet_message args {"message":"short message","sourceName":"Agent","actionId":"think"}
- create_knowledge_graph args {"readingLogPath":"optional Reading Log.md","outputPath":"optional Knowledge Graph.md","open":true}
- analyze_reading_records args {"readingLogPath":"optional Reading Log.md","outputPath":"optional Reading Analysis.md","recent":10,"from":"YYYY-MM-DD","to":"YYYY-MM-DD","open":true}
- open_browser args {"url":"https://example.com"}
- prepare_wechat_message args {"recipient":"optional name","message":"message draft"}
Write tools are only available if agent write permission is enabled. create_knowledge_graph and analyze_reading_records create or overwrite Markdown notes in the vault and therefore also require write permission. External tools are only available if their explicit permission is enabled, and may require user confirmation. Never claim that a WeChat message was sent; prepare the draft, copy it, open WeChat if possible, and ask the user to send it manually.
When you need a tool, reply with exactly one JSON object and no Markdown:
{"tool":"web_search","args":{"query":"example","limit":5}}
When you are done, reply naturally to the user. You may also wrap the final answer as:
{"final":"your answer"}`}buildChatCompletionUserContent(t,e){if(!e)return t;let i=this.formatActiveFileContext(e,this.getActiveChatModelProfile().apiFormat),n=[t,i].filter(Boolean).join(`
`);return e.attachment?.kind==="image"?[{type:"text",text:n},{type:"image_url",image_url:{url:e.attachment.dataUrl}}]:n}buildResponsesUserContent(t,e){let i=[{type:"input_text",text:[t,e?this.formatActiveFileContext(e,"responses"):""].filter(Boolean).join(`
`)}];return e?.attachment?.kind==="image"&&i.push({type:"input_image",image_url:e.attachment.dataUrl}),e?.attachment?.kind==="pdf"&&i.push({type:"input_file",filename:e.attachment.filename,file_data:e.attachment.dataUrl}),i}async requestChatSummary(t){let e=this.settings.chat.summaryPrompt||f.chat.summaryPrompt,i=[this.chatSummary?`Existing memory:
${this.chatSummary}`:"",`New transcript:
${this.formatChatTranscript(t)}`].filter(Boolean).join(`
`),n=this.getActiveChatModelProfile(),s=n.apiFormat==="responses"?await this.postChatPayload({model:n.model.trim()||f.chat.model,instructions:e,input:[{role:"user",content:[{type:"input_text",text:i}]}],temperature:.2,max_output_tokens:Math.min(this.getMaxChatTokens(),900)}):await this.postChatPayload({model:n.model.trim()||f.chat.model,messages:[{role:"system",content:e},{role:"user",content:i}],temperature:.2,max_tokens:Math.min(this.getMaxChatTokens(),900)});return this.extractChatReply(s).trim()||this.chatSummary}async postChatPayload(t){let e=this.getActiveChatModelProfile(),i=e.endpoint.trim(),n={"Content-Type":"application/json"};e.apiKey.trim()&&(n.Authorization=`Bearer ${e.apiKey.trim()}`);let s=await(0,h.requestUrl)({url:i,method:"POST",headers:n,body:JSON.stringify(t),throw:!1});if(s.status>=400)throw new Error(`Chat API failed: ${s.status} ${s.text.slice(0,220)}`);return s.json||s.text}extractChatReply(t){if(typeof t=="string")return t;if(!x(t))return"";let e=t.output_text;if(typeof e=="string")return e;let i=t.choices;if(Array.isArray(i))for(let r of i){if(!x(r))continue;let l=r.message;if(x(l)){let c=this.extractContentText(l.content);if(c)return c}let d=this.extractContentText(r.text);if(d)return d}let n=t.message;if(x(n)){let r=this.extractContentText(n.content);if(r)return r}let s=this.extractContentText(t.content);if(s)return s;let o=t.output;if(Array.isArray(o)){let r=[];for(let l of o){if(!x(l))continue;let d=this.extractContentText(l.content);d&&r.push(d)}return r.join(`
`).trim()}return""}extractContentText(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e=[];for(let i of t){if(typeof i=="string"){e.push(i);continue}x(i)&&(typeof i.text=="string"?e.push(i.text):x(i.text)&&typeof i.text.value=="string"?e.push(i.text.value):typeof i.output_text=="string"&&e.push(i.output_text))}return e.join(`
`).trim()}async getActiveFileContext(){if(!this.settings.chat.includeActiveFile)return;let t=this.app.workspace.getActiveFile();if(!(t instanceof h.TFile))return;let e=t.extension.toLowerCase(),i={path:t.path,name:t.name,extension:e};if(Di(e))return this.settings.chat.includeImages?this.getBinaryActiveFileContext(t,"image"):{...i,note:"Current active file is an image, but image context is disabled."};if(e==="pdf")return this.settings.chat.includePdfs?this.getBinaryActiveFileContext(t,"pdf"):{...i,note:"Current active file is a PDF, but PDF context is disabled."};if(!zt(e))return{...i,note:"Only the active file name and path were included because this file type is not treated as text."};try{let n=Math.round(w(Number(this.settings.chat.activeFileMaxChars)||f.chat.activeFileMaxChars,500,5e4)),s=await this.app.vault.cachedRead(t),o=s.length>n?`${s.slice(0,n)}
[Truncated to ${n} characters.]`:s;return{...i,text:o}}catch(n){return console.debug("DIY Desktop Pet could not read active text file.",n),{...i,note:"The active text file could not be read."}}}async getBinaryActiveFileContext(t,e){let i=Math.round(w(Number(this.settings.chat.maxAttachmentBytes)||f.chat.maxAttachmentBytes,1e4,2e7)),n={path:t.path,name:t.name,extension:t.extension.toLowerCase()};if(t.stat.size>i)return{...n,note:`Current active ${e} is ${t.stat.size} bytes, above the configured attachment limit of ${i} bytes.`};try{let s=await this.app.vault.readBinary(t),o=Mi(s,Wt(t.path));return{...n,attachment:{kind:e,dataUrl:o,mimeType:Wt(t.path),filename:t.name}}}catch(s){return console.debug("DIY Desktop Pet could not read active binary file.",s),{...n,note:`The active ${e} file could not be read.`}}}formatActiveFileContext(t,e){let i=[`Active Obsidian file: ${t.path}`,`File type: ${t.extension||"unknown"}`];return t.text&&i.push(`File excerpt:
${t.text}`),t.attachment?.kind==="image"?i.push("The active image is attached as visual context."):t.attachment?.kind==="pdf"&&i.push(e==="responses"?"The active PDF is attached as file context.":"The active PDF is not attached in Chat Completions mode. Switch chat API format to Responses to send the PDF file."),t.note&&i.push(t.note),i.join(`
`)}formatChatTranscript(t){return t.map(e=>`${e.role==="assistant"?"Assistant":"User"}: ${e.content}`).join(`
`)}async appendChatLog(t,e,i){if(!this.settings.chat.logEnabled)return;let n=this.settings.chat.logFile.trim()||f.chat.logFile,s=(0,h.normalizePath)(/\.[a-z0-9]+$/i.test(n)?n:`${n}.md`),o=s.split("/").slice(0,-1).join("/");o&&await _(this.app,o),await this.app.vault.adapter.exists(s)||await this.app.vault.adapter.write(s,`# Pet Chats
`);let l=i?`
Active file: [[${i.path.replace(/\.md$/i,"")}]]
`:"",d=["",`## ${new Date().toLocaleString()}`,l.trim(),"### User",t,"","### Pet",e,""].filter(c=>c!==void 0).join(`
`);await this.app.vault.adapter.append(s,`${d}
`)}async runAgentTool(t){try{switch(t.tool){case"read_current_file":return{tool:t.tool,ok:!0,result:await this.getActiveFileContext()};case"web_search":return{tool:t.tool,ok:!0,result:await this.agentWebSearch(C(t.args,"query"),et(t.args,"limit",this.settings.webSearch.maxResults))};case"open_web_search":return{tool:t.tool,ok:!0,result:await this.agentOpenBrowser(`https://www.google.com/search?q=${encodeURIComponent(C(t.args,"query"))}`)};case"search_vault":return{tool:t.tool,ok:!0,result:await this.agentSearchVault(C(t.args,"query"),et(t.args,"limit",this.settings.chat.agentSearchLimit))};case"read_note":return{tool:t.tool,ok:!0,result:await this.agentReadNote(C(t.args,"path"),et(t.args,"maxChars",this.settings.chat.agentReadMaxChars))};case"create_note":return await this.agentWriteNote(t.tool,C(t.args,"path"),C(t.args,"content"),!1);case"append_note":return await this.agentAppendNote(C(t.args,"path"),C(t.args,"content"));case"overwrite_note":return await this.agentWriteNote(t.tool,C(t.args,"path"),C(t.args,"content"),!0);case"list_pet_content":return{tool:t.tool,ok:!0,result:this.contentItems};case"refresh_pet_content":return{tool:t.tool,ok:!0,result:await this.refreshContent()};case"complete_current_pet_content":return this.settings.chat.agentCanWrite?(await this.completeActiveContent(),{tool:t.tool,ok:!0,result:{message:"Current pet content was completed or hidden if possible."}}):this.blockedAgentWriteResult(t.tool);case"show_pet_message":return this.showMessage(C(t.args,"message"),{sourceName:C(t.args,"sourceName")||"Pet Agent",actionId:C(t.args,"actionId")||"think",timeoutMs:et(t.args,"timeoutMs",4200)}),{tool:t.tool,ok:!0,result:{message:"Pet message shown."}};case"create_knowledge_graph":return await this.agentCreateKnowledgeGraph(t.args||{});case"analyze_reading_records":return await this.agentAnalyzeReadingRecords(t.args||{});case"open_browser":return{tool:t.tool,ok:!0,result:await this.agentOpenBrowser(C(t.args,"url"))};case"prepare_wechat_message":return{tool:t.tool,ok:!0,result:await this.agentPrepareWechatMessage(C(t.args,"recipient"),C(t.args,"message"))};default:return{tool:String(t.tool),ok:!1,error:"Unknown tool."}}}catch(e){return{tool:String(t.tool),ok:!1,error:e instanceof Error?e.message:String(e)}}}async tryRunDirectAgentCommand(t){let e=t.toLowerCase();try{if(/(刷新|reload|refresh).*(dashboard|提醒|内容|content)|刷新提醒|刷新内容/i.test(t))return this.triggerBoundAction("agent-tool","refresh_pet_content"),`\u5DF2\u5237\u65B0 dashboard/\u63D0\u9192\u5185\u5BB9\uFF0C\u5171\u8BFB\u53D6\u5230 ${(await this.refreshContent()).length} \u6761\u672A\u5B8C\u6210\u5185\u5BB9\u3002`;if(/(完成|勾选|打勾|标记完成|complete|done)/i.test(t)&&/(当前|这条|提醒|任务|todo|study|学习|内容)/i.test(t))return this.triggerBoundAction("agent-tool","complete_current_pet_content"),this.settings.chat.agentCanWrite?(await this.completeActiveContent(),"\u5DF2\u5C1D\u8BD5\u628A\u5F53\u524D\u5BA0\u7269\u5185\u5BB9\u6807\u8BB0\u4E3A\u5B8C\u6210\u3002"):"Agent \u5199\u5165\u6743\u9650\u672A\u5F00\u542F\uFF0C\u4E0D\u80FD\u66FF\u4F60\u52FE\u9009\u5B8C\u6210\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u6253\u5F00 Agent can write vault files\u3002";if(/(知识图谱|关系图|论文图谱|knowledge graph|graph)/i.test(t)&&/(创建|生成|刷新|更新|重建|create|generate|refresh|update|rebuild|分析)?/i.test(t)){this.triggerBoundAction("agent-tool","create_knowledge_graph");let i=await this.agentCreateKnowledgeGraph({readingLogPath:$e(t),open:!/(不打开|不要打开|no open)/i.test(t)});return Le(i)}if(/(阅读记录|论文阅读|reading log|reading records|阶段阅读|阅读分析)/i.test(t)&&/(分析|总结|复盘|方向|趋势|缺口|建议|analyze|analysis|summary)/i.test(t)){this.triggerBoundAction("agent-tool","analyze_reading_records");let i=await this.agentAnalyzeReadingRecords({readingLogPath:$e(t),recent:Dn(t),from:Ie(t,"from"),to:Ie(t,"to"),open:!/(不打开|不要打开|no open)/i.test(t)});return Le(i)}if(/(搜索|查找|检索|search).*(笔记|vault|库|note|notes)|search vault|search notes/i.test(t)){this.triggerBoundAction("agent-tool","search_vault");let i=Me(t,["\u641C\u7D22\u7B14\u8BB0","\u67E5\u627E\u7B14\u8BB0","\u68C0\u7D22\u7B14\u8BB0","\u641C\u7D22 vault","search vault","search notes","\u641C\u7D22","\u67E5\u627E","\u68C0\u7D22"]);if(!i)return"\u8981\u641C\u7D22\u7B14\u8BB0\u7684\u8BDD\uFF0C\u8BF7\u544A\u8BC9\u6211\u8981\u627E\u4EC0\u4E48\u5173\u952E\u8BCD\u3002";let n=await this.agentSearchVault(i,this.settings.chat.agentSearchLimit);return yn(i,n)}if(/(读取|查看|看一下|当前文件|正在看的|active file|read current|current file)/i.test(t)){this.triggerBoundAction("agent-tool","read_current_file");let i=await this.getActiveFileContext();return vn(i)}if(/(dashboard|memo|todo|task|study|learned|goal|备忘|待办|学习|已学|目标|提醒)/i.test(t)&&/(列出|显示|查看|有哪些|有什么|list|show)/i.test(t))return this.triggerBoundAction("agent-tool","list_pet_content"),bn(this.allContentItems.length?this.allContentItems:this.contentItems);if(/(微信|wechat|vx|wx)/i.test(t)){this.triggerBoundAction("agent-tool","prepare_wechat_message");let i=fn(t);if(!i.message)return"\u53EF\u4EE5\uFF0C\u6211\u80FD\u5E2E\u4F60\u51C6\u5907\u5FAE\u4FE1\u8349\u7A3F\u3002\u8BF7\u544A\u8BC9\u6211\u8981\u53D1\u7ED9\u8C01\u4EE5\u53CA\u8349\u7A3F\u5185\u5BB9\uFF1B\u6211\u53EA\u4F1A\u590D\u5236\u8349\u7A3F\u5E76\u6253\u5F00\u5FAE\u4FE1\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u53D1\u9001\u3002";let n=await this.agentPrepareWechatMessage(i.recipient,i.message);return[n.copied?"\u5FAE\u4FE1\u8349\u7A3F\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\u3002":"\u5FAE\u4FE1\u8349\u7A3F\u5DF2\u51C6\u5907\uFF0C\u4F46\u590D\u5236\u5230\u526A\u8D34\u677F\u5931\u8D25\u3002",n.opened?"\u5DF2\u5C1D\u8BD5\u6253\u5F00\u5FAE\u4FE1\u3002":"\u6CA1\u6709\u6210\u529F\u6253\u5F00\u5FAE\u4FE1\uFF0C\u4F60\u53EF\u4EE5\u624B\u52A8\u6253\u5F00\u540E\u7C98\u8D34\u3002","\u4E0D\u4F1A\u81EA\u52A8\u53D1\u9001\uFF0C\u8BF7\u4F60\u786E\u8BA4\u540E\u624B\u52A8\u53D1\u9001\u3002"].join(`
`)}if(/(浏览器|browser|网页|google|百度|搜索网页|web search|open url|打开网址|打开链接)/i.test(t)){this.triggerBoundAction("agent-tool","open_web_search");let i=mn(t);if(i){let r=await this.agentOpenBrowser(i);return r.opened?`\u5DF2\u6253\u5F00\u6D4F\u89C8\u5668\uFF1A${r.url}`:r.message}let n=Me(t,["\u6D4F\u89C8\u5668\u641C\u7D22","\u7F51\u9875\u641C\u7D22","\u641C\u7D22\u7F51\u9875","google","\u767E\u5EA6","\u6253\u5F00\u6D4F\u89C8\u5668\u641C\u7D22","\u7528\u6D4F\u89C8\u5668\u641C\u7D22","web search","browser search","\u641C\u7D22"]);if(!n)return"\u8981\u6253\u5F00\u6D4F\u89C8\u5668\u641C\u7D22\u7684\u8BDD\uFF0C\u8BF7\u544A\u8BC9\u6211\u8981\u641C\u7D22\u4EC0\u4E48\u3002";let s=/百度/i.test(t)?`https://www.baidu.com/s?wd=${encodeURIComponent(n)}`:`https://www.google.com/search?q=${encodeURIComponent(n)}`,o=await this.agentOpenBrowser(s);return o.opened?`\u5DF2\u7528\u6D4F\u89C8\u5668\u641C\u7D22\uFF1A${n}`:o.message}}catch(i){return i instanceof Error?i.message:String(i)}}async agentCreateKnowledgeGraph(t,e={}){let i="create_knowledge_graph";if(e.requireWritePermission!==!1&&!this.settings.chat.agentCanWrite)return this.blockedAgentWriteResult(i);let n=await this.resolveReadingLogFile(C(t,"readingLogPath")),s=await this.app.vault.cachedRead(n),o=Te(s);if(!o.length)throw new Error(`No paper records found in ${n.path}.`);let r=Ke(o),l=this.resolveGeneratedReadingOutputPath(n.path,C(t,"outputPath"),"\u77E5\u8BC6\u56FE\u8C31.md"),d=Cn({readingLogPath:n.path,outputPath:l,papers:o,edges:r.edges,conceptEdges:r.conceptEdges});return await this.writeGeneratedMarkdown(l,d),ke(t,"open",!0)&&await this.openVaultFilePath(l),this.showMessage(`\u77E5\u8BC6\u56FE\u8C31\u5DF2\u751F\u6210\uFF1A${l}`,{sourceName:"Reading Graph",actionId:"wave",timeoutMs:5200}),new h.Notice(`Knowledge graph generated: ${l}`),{tool:i,ok:!0,result:{readingLogPath:n.path,outputPath:l,paperCount:o.length,relationCount:r.edges.length,conceptCount:r.conceptEdges.length,message:`\u5DF2\u751F\u6210 ${l}\uFF0C\u5305\u542B ${o.length} \u7BC7\u8BBA\u6587\u3001${r.edges.length} \u6761\u8BBA\u6587\u5173\u7CFB\u3002`}}}async agentAnalyzeReadingRecords(t,e={}){let i="analyze_reading_records";if(e.requireWritePermission!==!1&&!this.settings.chat.agentCanWrite)return this.blockedAgentWriteResult(i);let n=await this.resolveReadingLogFile(C(t,"readingLogPath")),s=await this.app.vault.cachedRead(n),o=Te(s),r=nt(C(t,"from")),l=nt(C(t,"to")),d=et(t,"recent",0),c=o.filter(m=>!(r&&m.date&&m.date<r||l&&m.date&&m.date>l));if(d>0&&(c=c.slice(-Math.round(w(d,1,200)))),!c.length)throw new Error(`No matching paper records found in ${n.path}.`);let p=this.resolveGeneratedReadingOutputPath(n.path,C(t,"outputPath"),"\u9636\u6BB5\u9605\u8BFB\u5206\u6790.md"),u=d>0?`\u6700\u8FD1 ${Math.round(d)} \u7BC7`:`${r||"\u6700\u65E9"} \u81F3 ${l||"\u6700\u65B0"}`,g=An({readingLogPath:n.path,outputPath:p,rangeLabel:u,papers:c});return await this.writeGeneratedMarkdown(p,g),ke(t,"open",!0)&&await this.openVaultFilePath(p),this.showMessage(`\u9605\u8BFB\u5206\u6790\u5DF2\u751F\u6210\uFF1A${p}`,{sourceName:"Reading Analysis",actionId:"think",timeoutMs:5200}),new h.Notice(`Reading analysis generated: ${p}`),{tool:i,ok:!0,result:{readingLogPath:n.path,outputPath:p,paperCount:c.length,range:u,message:`\u5DF2\u751F\u6210 ${p}\uFF0C\u5206\u6790\u8303\u56F4\uFF1A${u}\uFF0C\u5171 ${c.length} \u7BC7\u8BBA\u6587\u3002`}}}async resolveReadingLogFile(t){let e=t.trim();if(e){let s=(0,h.normalizePath)(/\.[a-z0-9]+$/i.test(e)?e:`${e}.md`),o=this.app.vault.getAbstractFileByPath(s);if(o instanceof h.TFile)return o;throw new Error(`Reading log not found: ${s}`)}let i=this.app.workspace.getActiveFile();if(i&&En(i.path))return i;let n=this.app.vault.getMarkdownFiles().map(s=>({file:s,score:Xe(s.path)})).filter(s=>s.score>0).sort((s,o)=>o.score-s.score||s.file.path.length-o.file.path.length);if(n.length)return n[0].file;for(let s of this.app.vault.getMarkdownFiles())try{let o=(await this.app.vault.cachedRead(s)).slice(0,4e3);if(/type:\s*cs-reading-log|#\s*阅读记录|#\s*Reading Log/i.test(o))return s}catch(o){console.debug("DIY Desktop Pet skipped possible reading log.",s.path,o)}throw new Error("Could not find a reading log. Pass readingLogPath, or create a note named \u9605\u8BFB\u8BB0\u5F55.md / Reading Log.md.")}resolveGeneratedReadingOutputPath(t,e,i){if(e.trim())return this.normalizeAgentNotePath(e);let n=t.split("/").slice(0,-1).join("/");return this.normalizeAgentNotePath(n?`${n}/${i}`:i)}async writeGeneratedMarkdown(t,e){let i=this.normalizeAgentNotePath(t),n=i.split("/").slice(0,-1).join("/");n&&await _(this.app,n);let s=this.app.vault.getAbstractFileByPath(i);if(s instanceof h.TFile){await this.app.vault.modify(s,e);return}await this.app.vault.create(i,e)}async openVaultFilePath(t){let e=this.app.vault.getAbstractFileByPath((0,h.normalizePath)(t));if(!(e instanceof h.TFile))return;let i=this.app.workspace.getLeaf(!1);await i.openFile(e,{active:!0}),this.app.workspace.setActiveLeaf(i,{focus:!0})}async agentSearchVault(t,e){let i=t.trim().toLowerCase();if(!i)throw new Error("search_vault requires a query.");let n=Math.round(w(e||this.settings.chat.agentSearchLimit,1,30)),s=Math.round(w(Number(this.settings.chat.agentReadMaxChars)||f.chat.agentReadMaxChars,500,5e4)),o=[];for(let r of this.app.vault.getFiles()){if(o.length>=n)break;if(zt(r.extension.toLowerCase()))try{let l=await this.app.vault.cachedRead(r),c=l.toLowerCase().indexOf(i);if(c<0)continue;let u=l.slice(0,c).split(/\r?\n/).length,g=Math.max(0,c-160),m=l.slice(g,Math.min(l.length,c+i.length+260));o.push({path:r.path,line:u,excerpt:m.length>s?m.slice(0,s):m})}catch(l){console.debug("DIY Desktop Pet agent skipped unreadable file.",r.path,l)}}return o}async agentWebSearch(t,e){let i=t.trim();if(!i)throw new Error("web_search requires a query.");if(!this.settings.webSearch.enabled)throw new Error("Web search is disabled in plugin settings.");let n=Math.round(w(e||this.settings.webSearch.maxResults||f.webSearch.maxResults,1,10));switch(this.settings.webSearch.provider){case"duckduckgo":return this.searchDuckDuckGo(i,n);case"brave":return this.searchJsonApi({url:this.settings.webSearch.endpoint.trim()||`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(i)}&count=${n}`,headers:this.settings.webSearch.apiKey.trim()?{"X-Subscription-Token":this.settings.webSearch.apiKey.trim()}:{},limit:n,provider:"brave"});case"tavily":return this.searchJsonApi({url:this.settings.webSearch.endpoint.trim()||"https://api.tavily.com/search",method:"POST",body:{api_key:this.settings.webSearch.apiKey.trim(),query:i,max_results:n},limit:n,provider:"tavily"});case"serpapi":return this.searchJsonApi({url:this.settings.webSearch.endpoint.trim()||`https://serpapi.com/search.json?engine=google&q=${encodeURIComponent(i)}&api_key=${encodeURIComponent(this.settings.webSearch.apiKey.trim())}&num=${n}`,limit:n,provider:"serpapi"});case"custom":if(!this.settings.webSearch.endpoint.trim())throw new Error("Custom web search endpoint is empty.");return this.searchJsonApi({url:this.settings.webSearch.endpoint.trim(),method:"POST",body:{query:i,limit:n},headers:this.settings.webSearch.apiKey.trim()?{Authorization:`Bearer ${this.settings.webSearch.apiKey.trim()}`}:{},limit:n,provider:"custom"});default:throw new Error("Unsupported web search provider.")}}async searchDuckDuckGo(t,e){let i=await(0,h.requestUrl)({url:`https://duckduckgo.com/html/?q=${encodeURIComponent(t)}`,method:"GET",headers:{"User-Agent":"Obsidian DIY Desktop Pet"},throw:!1});if(i.status>=400)throw new Error(`DuckDuckGo search failed: ${i.status}`);return $i(i.text,e)}async searchJsonApi(t){let e=await(0,h.requestUrl)({url:t.url,method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers||{}},body:t.body?JSON.stringify(t.body):void 0,throw:!1});if(e.status>=400)throw new Error(`${t.provider} search failed: ${e.status} ${e.text.slice(0,180)}`);return We(e.json||e.text,t.limit)}async agentReadNote(t,e){let i=this.normalizeAgentNotePath(t),n=this.app.vault.getAbstractFileByPath(i);if(!(n instanceof h.TFile))throw new Error(`Note not found: ${i}`);if(!zt(n.extension.toLowerCase()))throw new Error(`File is not readable text: ${i}`);let s=Math.round(w(e||this.settings.chat.agentReadMaxChars,500,5e4)),o=await this.app.vault.cachedRead(n);return{path:n.path,content:o.length>s?`${o.slice(0,s)}
[Truncated to ${s} characters.]`:o}}async agentWriteNote(t,e,i,n){if(!this.settings.chat.agentCanWrite)return this.blockedAgentWriteResult(t);if(!i)throw new Error(`${t} requires content.`);let s=this.normalizeAgentNotePath(e),o=await this.app.vault.adapter.exists(s);if(o&&!n)throw new Error(`File already exists: ${s}`);let r=s.split("/").slice(0,-1).join("/");return r&&await _(this.app,r),o?await this.app.vault.adapter.write(s,i):await this.app.vault.create(s,i),{tool:t,ok:!0,result:{path:s,mode:o?"overwritten":"created"}}}async agentAppendNote(t,e){if(!this.settings.chat.agentCanWrite)return this.blockedAgentWriteResult("append_note");if(!e)throw new Error("append_note requires content.");let i=this.normalizeAgentNotePath(t),n=i.split("/").slice(0,-1).join("/");n&&await _(this.app,n);let s=await this.app.vault.adapter.exists(i);return s?await this.app.vault.adapter.append(i,e):await this.app.vault.create(i,e),{tool:"append_note",ok:!0,result:{path:i,mode:s?"appended":"created"}}}blockedAgentWriteResult(t){return{tool:t,ok:!1,error:"Agent write permission is disabled in plugin settings."}}async agentOpenBrowser(t){if(!this.settings.externalActions.allowOpenBrowser)throw new Error("Open browser permission is disabled in plugin settings.");let e=Ni(t);if(!e)throw new Error("open_browser requires an http or https URL.");return this.confirmExternalAction(`Open this URL in your browser?
${e}`)?(await this.openExternal(e),this.showMessage("Opened browser link.",{sourceName:this.getPetName(),actionId:"wave",timeoutMs:2600}),{url:e,opened:!0,message:"Browser opened."}):{url:e,opened:!1,message:"User cancelled opening the browser."}}async agentPrepareWechatMessage(t,e){if(!this.settings.externalActions.allowPrepareWechat)throw new Error("Prepare WeChat message permission is disabled in plugin settings.");let i=e.trim();if(!i)throw new Error("prepare_wechat_message requires a message.");let n=t.trim(),s=["Prepare this WeChat message?",n?`Recipient hint: ${n}`:"","",i].filter(d=>d!==void 0).join(`
`);if(!this.confirmExternalAction(s))return{recipient:n||void 0,opened:!1,copied:!1,message:"User cancelled the WeChat draft."};let o=!1;try{await navigator.clipboard.writeText(i),o=!0}catch(d){console.debug("DIY Desktop Pet could not copy WeChat draft.",d)}let r=await this.tryOpenWechat(),l=o?"WeChat draft copied. Paste and send it manually.":"WeChat draft prepared, but clipboard copy failed. Please copy it from chat.";return new h.Notice(l),this.showMessage(l,{sourceName:this.getPetName(),actionId:"wave",timeoutMs:4200}),{recipient:n||void 0,opened:r,copied:o,message:"Draft prepared only; it was not sent automatically."}}confirmExternalAction(t){return this.settings.externalActions.confirmBeforeExternalAction?window.confirm(t):!0}async tryOpenWechat(){if(await this.openMacAppByNames(["WeChat","\u5FAE\u4FE1"]))return!0;for(let t of["weixin://dl/chat","weixin://","wechat://"])try{return await this.openExternal(t),!0}catch(e){console.debug(`DIY Desktop Pet could not open WeChat URL scheme ${t}.`,e)}return!1}getNodeChildProcess(){try{return require("child_process")}catch(t){console.debug("child_process unavailable through require.",t)}try{return window.require?.("child_process")}catch(t){console.debug("child_process unavailable through window.require.",t);return}}async openMacAppByNames(t){if(!h.Platform.isMacOS)return!1;let e=this.getNodeChildProcess();if(!e)return!1;for(let i of t)if(await new Promise(s=>{e.exec(`open -a ${Gi(i)}`,o=>s(!o))}))return!0;return!1}async openExternal(t){let e=this.getElectronShell();if(e){await e.openExternal(t);return}window.open(t,"_blank","noopener,noreferrer")}normalizeAgentNotePath(t){let e=t.trim();if(!e)throw new Error("A note path is required.");let i=/\.[a-z0-9]+$/i.test(e)?e:`${e}.md`,n=(0,h.normalizePath)(i);if(n.startsWith(".obsidian/")||n.includes("/.obsidian/"))throw new Error("Agent tools cannot write inside .obsidian.");return n}placePet(){let t=this.settings.size,e=18,i=Math.max(e,window.innerWidth-t-e),n=Math.max(e,window.innerHeight-t-e),s=typeof this.settings.x=="number"?this.settings.x:i,o=typeof this.settings.y=="number"?this.settings.y:n;this.position={x:w(s,e,i),y:w(o,e,n)},this.velocity={x:this.settings.stayStill?0:(Number(this.settings.speed)||0)/12,y:0},this.renderPosition()}renderPosition(){this.petEl&&(this.petEl.style.transform=`translate3d(${Math.round(this.position.x)}px, ${Math.round(this.position.y)}px, 0)`)}startPetLoop(){if(this.animationFrame&&window.cancelAnimationFrame(this.animationFrame),this.settings.stayStill||this.settings.speed<=0){this.animationFrame=void 0;return}let t=()=>{if(this.petEl){if(!this.dragState&&!this.settings.stayStill&&this.settings.speed>0){let e=this.settings.size,i=18,n=Math.max(i,window.innerWidth-e-i);this.position.x+=this.velocity.x,(this.position.x<=i||this.position.x>=n)&&(this.velocity.x*=-1,this.position.x=w(this.position.x,i,n)),this.settings.mirrorWhenMoving&&this.spriteEl&&this.spriteEl.classList.toggle("diy-desktop-pet__sprite--left",this.velocity.x<0),this.renderPosition()}this.animationFrame=window.requestAnimationFrame(t)}};this.animationFrame=window.requestAnimationFrame(t)}getCurrentAction(){let t=this.getActivePet();return t?.actions.find(e=>e.id===this.currentActionId)||t?.actions.find(e=>e.id==="idle")||t?.actions[0]}getFirstExistingActionId(t){let e=this.getActivePet();if(e)return t.find(i=>e.actions.some(n=>n.id===i))}playHoverAction(){if(this.dragState||this.resizeState||this.chatLogResizeState||this.chatBusy||this.currentActionId!=="idle"||this.triggerBoundAction("pet-hover","enter hover"))return;let e=this.getFirstExistingActionId(["tail-wag","wave","jump","bob"]);e&&this.playAction(e,2200)}playClickAction(){if(this.dragState||this.resizeState||this.chatLogResizeState||this.triggerBoundAction("pet-click","click tap"))return;let e=this.getFirstExistingActionId(["wave","jump","tail-wag","bob"]);e&&this.playAction(e,2200)}playAction(t,e=2400){this.getActivePet()?.actions.some(n=>n.id===t)&&(this.currentActionId=t,this.renderSprite(),this.actionTimer&&window.clearTimeout(this.actionTimer),this.actionTimer=window.setTimeout(()=>{this.currentActionId="idle",this.renderSprite()},e))}showNextContent(){if(!this.contentItems.length){this.showMessage("No open tasks or memos found.",{sourceName:"Desktop Pet",actionId:"think"});return}this.contentIndex=(this.contentIndex+1)%this.contentItems.length,this.showContentItem(this.contentItems[this.contentIndex])}showContentItem(t,e=2600){let i=this.getDashboardTabForItem(t);i&&(this.dashboardTab=i),this.activeContentItem=t;let n=this.contentItems.findIndex(s=>s.id===t.id);this.contentIndex=n>=0?n:this.contentIndex,this.renderSpeech(),this.playAction(this.getActivePet()?.actions.some(s=>s.id==="think")?"think":"wave"),this.petEl?.classList.add("diy-desktop-pet--talking"),this.speechTimer&&window.clearTimeout(this.speechTimer),this.speechTimer=window.setTimeout(()=>this.petEl?.classList.remove("diy-desktop-pet--talking"),e)}async completeActiveContent(){let t=this.activeContentItem;if(t){this.speechDoneEl?.setAttribute("disabled","true");try{await this.completeContentItem(t);let e=this.getDashboardModuleItems(this.dashboardTab)[0];if(e)this.showContentItem(e,1800);else{this.activeContentItem=void 0,this.contentIndex=-1;let i=yt.find(n=>n.key===this.dashboardTab);this.showMessage(`Done. No open ${i?.label||"dashboard"} items found.`,{sourceName:"Desktop Pet",actionId:"wave"})}}catch(e){console.error("DIY Desktop Pet failed to complete content item.",e),new h.Notice("Could not mark this item complete."),this.renderSpeech()}finally{this.speechDoneEl?.removeAttribute("disabled")}}}async completeContentItem(t){let i=this.getDashboardTabForItem(t)==="study"?"learned":this.dashboardTab,n=await this.markContentItemComplete(t);this.hiddenContentIds.add(t.id),this.expandedMemoIds.delete(t.id),this.dashboardTab=i,this.allContentItems=this.allContentItems.filter(s=>s.id!==t.id),this.contentItems=this.contentItems.filter(s=>s.id!==t.id),this.activeContentItem?.id===t.id&&(this.activeContentItem=this.getDashboardModuleItems(this.dashboardTab)[0],this.contentIndex=this.activeContentItem?this.contentItems.findIndex(s=>s.id===this.activeContentItem?.id):-1),this.renderSpeech(),n&&await this.refreshContent(),this.triggerBoundAction("content-complete",t.title)}async markContentItemComplete(t){if(!t.path||!t.line||!this.isCompletableSource(t))return!1;let e=this.app.vault.getAbstractFileByPath(t.path);if(!(e instanceof h.TFile))return!1;let i=!1;return await this.app.vault.process(e,n=>{let s=t.sourceId==="apex-dashboard"?Bi(n,t.line||1,t.title,t.sourceName,t.path||e.path):At(n,t.line||1);return i=s.changed,s.content}),i}isCompletableSource(t){let e=t.sourceName.toLowerCase();return!!(t.sourceId==="markdown-tasks"||t.sourceId==="apex-dashboard"&&(e.includes("memo")||e.includes("todo")||e.includes("task")||e.includes("study")||e.includes("learned")))}startContentPolling(){if(this.contentTimer&&window.clearInterval(this.contentTimer),!this.settings.content.enabled)return;let t=w(this.settings.content.refreshMinutes||5,1,120);this.contentTimer=window.setInterval(()=>this.refreshContent(),t*60*1e3)}restartContentPolling(){this.startContentPolling()}startReminderPolling(){if(this.reminderTimer&&window.clearInterval(this.reminderTimer),this.reminderTimer=void 0,!this.settings.reminders.enabled||!this.settings.content.enabled)return;let t=w(Number(this.settings.reminders.checkMinutes)||f.reminders.checkMinutes,1,1440);this.reminderTimer=window.setInterval(()=>{this.checkDueReminders()},t*60*1e3),this.checkDueReminders()}restartReminderPolling(){this.startReminderPolling()}async checkDueReminders(){if(!this.settings.reminders.enabled||!this.settings.content.enabled)return;let t=Date.now(),e=new Set(this.contentItems.map(s=>s.id));for(let s of Array.from(this.firedReminderIds.keys()))e.has(s)||this.firedReminderIds.delete(s);let i=Math.max(0,Number(this.settings.reminders.leadMinutes)||f.reminders.leadMinutes)*60*1e3,n=w(Number(this.settings.reminders.repeatMinutes)||f.reminders.repeatMinutes,1,43200)*60*1e3;for(let s of this.contentItems){let o=Ri(s.due);if(!o)continue;let r=o-t;if(r<0||r>i)continue;let l=this.firedReminderIds.get(s.id)||0;if(!(t-l<n)){this.firedReminderIds.set(s.id,t),await this.showDeadlineReminder(s,r);return}}}async showDeadlineReminder(t,e){this.activeContentItem=t;let i=this.contentItems.findIndex(l=>l.id===t.id);this.contentIndex=i>=0?i:this.contentIndex,this.renderSpeech();let n=_i(e),s=[t.body,t.due?`\u622A\u6B62\uFF1A${t.due}`:"",n?`\u5269\u4F59\uFF1A${n}`:"\u5DF2\u7ECF\u5230\u622A\u6B62\u65F6\u95F4"].filter(Boolean).join(`
`),o=`\u5FEB\u5230\u622A\u6B62\u65F6\u95F4\uFF1A${t.title||"\u63D0\u9192"}`;if(this.setSpeech(t.sourceName||"Deadline",o,s||void 0),!this.triggerBoundAction("deadline-reminder",`${t.title}
${t.body||""}
${t.due||""}`)){let l=this.getActivePet(),d=this.settings.reminders.actionId||f.reminders.actionId,c=l?.actions.some(p=>p.id===d)?d:l?.actions.some(p=>p.id==="think")?"think":"wave";this.playAction(c,4200)}this.petEl?.classList.add("diy-desktop-pet--talking","diy-desktop-pet--panel-visible"),this.speechTimer&&window.clearTimeout(this.speechTimer),this.speechTimer=window.setTimeout(()=>this.petEl?.classList.remove("diy-desktop-pet--talking"),6200),this.speechEl||new h.Notice(`${this.getPetName()} reminder: ${t.title}${t.due?` (${t.due})`:""}`),this.overlayWindow&&!this.overlayWindow.isDestroyed()&&(this.overlayPanelVisible=!0,await this.refreshOverlayWindow())}queueContentRefresh(){this.refreshTimer&&window.clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.refreshContent()},800)}showPetPanel=()=>{this.petEl?.classList.add("diy-desktop-pet--panel-visible")};hidePetPanel=()=>{this.petEl?.classList.remove("diy-desktop-pet--panel-visible")};togglePetPanel=()=>{this.petEl&&this.petEl.classList.toggle("diy-desktop-pet--panel-visible")};onClick=()=>{this.wasDragged||(this.togglePetPanel(),this.renderSpeech(),this.playClickAction())};onKeydown=t=>{if(t.key==="Enter"||t.key===" "){t.preventDefault(),this.togglePetPanel(),this.renderSpeech();return}t.key==="Escape"&&(t.preventDefault(),this.hidePetPanel())};onPetPointerEnter=()=>{this.playHoverAction()};onPointerDown=t=>{this.petEl&&(this.wasDragged=!1,this.dragState={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,offsetX:t.clientX-this.position.x,offsetY:t.clientY-this.position.y},this.petEl.classList.add("diy-desktop-pet--dragging"),this.petEl.setPointerCapture(t.pointerId),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp))};onPointerMove=t=>{if(!this.dragState)return;let e=8,i=Math.max(e,window.innerWidth-this.settings.size-e),n=Math.max(e,window.innerHeight-this.settings.size-e),s=Math.abs(t.clientX-this.dragState.startX),o=Math.abs(t.clientY-this.dragState.startY);this.wasDragged=s+o>4,this.position.x=w(t.clientX-this.dragState.offsetX,e,i),this.position.y=w(t.clientY-this.dragState.offsetY,e,n),this.renderPosition()};onPointerUp=async t=>{if(!(!this.dragState||!this.petEl)){this.petEl.classList.remove("diy-desktop-pet--dragging");try{this.petEl.releasePointerCapture(t.pointerId)}catch(e){console.debug("Pointer capture already released.",e)}window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this.dragState=void 0,this.settings.x=Math.round(this.position.x),this.settings.y=Math.round(this.position.y),await this.saveSettings(),window.setTimeout(()=>{this.wasDragged=!1},0)}};onResizeHandleDown=t=>{if(!this.petEl)return;t.preventDefault(),t.stopPropagation();let e=t.currentTarget,i=e.classList.contains("diy-desktop-pet__panel-resize")?"panel":"pet";this.resizeState={kind:i,pointerId:t.pointerId,handle:e,startX:t.clientX,startY:t.clientY,startSize:this.settings.size,startWidth:this.settings.panelWidth||f.panelWidth,startHeight:this.settings.panelHeight||f.panelHeight,aspectRatio:(this.settings.panelWidth||f.panelWidth)/(this.settings.panelHeight||f.panelHeight)},e.setPointerCapture(t.pointerId),this.petEl.classList.add("diy-desktop-pet--resizing"),window.addEventListener("pointermove",this.onResizeHandleMove),window.addEventListener("pointerup",this.onResizeHandleUp)};onResizeHandleMove=t=>{if(!this.resizeState||!this.petEl)return;t.preventDefault();let e=t.clientX-this.resizeState.startX,i=t.clientY-this.resizeState.startY;if(this.resizeState.kind==="pet"){this.settings.size=Math.round(w(this.resizeState.startSize+Math.max(e,i),48,this.getPetSizeLimit())),this.applyPetStyles(),this.placePet();return}let n=-e,s=-i*this.resizeState.aspectRatio,o=w(this.resizeState.startWidth+Math.max(n,s),220,520);this.settings.panelWidth=Math.round(o),this.settings.panelHeight=Math.round(w(o/this.resizeState.aspectRatio,180,520)),this.applyPetStyles()};onResizeHandleUp=async t=>{if(!(!this.resizeState||!this.petEl)){try{this.resizeState.handle.releasePointerCapture?.(t.pointerId)}catch(e){console.debug("Resize pointer capture already released.",e)}window.removeEventListener("pointermove",this.onResizeHandleMove),window.removeEventListener("pointerup",this.onResizeHandleUp),this.petEl.classList.remove("diy-desktop-pet--resizing"),this.resizeState=void 0,this.settings.size=Math.round(this.settings.size),this.settings.panelWidth=Math.round(this.settings.panelWidth||f.panelWidth),this.settings.panelHeight=Math.round(this.settings.panelHeight||f.panelHeight),await this.saveSettings()}};onChatLogResizeDown=t=>{if(!this.chatLogEl)return;t.preventDefault(),t.stopPropagation();let e=t.currentTarget;this.chatLogResizeState={pointerId:t.pointerId,handle:e,startY:t.clientY,startHeight:this.settings.chat.logHeight||f.chat.logHeight},e.setPointerCapture(t.pointerId),this.petEl?.classList.add("diy-desktop-pet--chat-log-resizing"),window.addEventListener("pointermove",this.onChatLogResizeMove),window.addEventListener("pointerup",this.onChatLogResizeUp)};onChatLogResizeMove=t=>{if(!this.chatLogResizeState)return;t.preventDefault();let e=t.clientY-this.chatLogResizeState.startY;this.settings.chat.logHeight=Math.round(w(this.chatLogResizeState.startHeight+e,72,this.getChatLogHeightLimit())),this.applyPetStyles(),this.chatLogPinnedToBottom&&this.scrollChatLogToBottom()};onChatLogResizeUp=async t=>{if(this.chatLogResizeState){try{this.chatLogResizeState.handle.releasePointerCapture?.(t.pointerId)}catch(e){console.debug("Chat log resize pointer capture already released.",e)}window.removeEventListener("pointermove",this.onChatLogResizeMove),window.removeEventListener("pointerup",this.onChatLogResizeUp),this.petEl?.classList.remove("diy-desktop-pet--chat-log-resizing"),this.chatLogResizeState=void 0,this.settings.chat.logHeight=Math.round(w(this.settings.chat.logHeight||f.chat.logHeight,72,this.getChatLogHeightLimit())),this.chatLogPinnedToBottom&&this.scrollChatLogToBottom(),await this.saveSettings()}};onResize=async()=>{this.petEl&&(this.placePet(),this.settings.x=Math.round(this.position.x),this.settings.y=Math.round(this.position.y),await this.saveSettings())}},Gt=class extends h.Modal{constructor(e,i,n){super(e);this.plugin=i;this.kind=n}titleValue="";bodyValue="";dateValue="";onOpen(){let{contentEl:e}=this,i=Oe(this.kind);e.empty(),e.addClass("diy-pet-add-dashboard-modal"),e.createEl("h2",{text:`Add ${i}`}),e.createEl("p",{cls:"diy-pet-add-dashboard-modal__note",text:"This writes a standard Apex Dashboard card into the configured dashboard.md file."});let n;new h.Setting(e).setName("Title").setDesc(`${i} title shown in the pet Dashboard.`).addText(d=>{n=d.inputEl,d.setPlaceholder(this.kind==="task"?"Finish reading chapter 2":`New ${i}`).onChange(c=>{this.titleValue=c})});let s=e.createDiv({cls:"diy-pet-add-dashboard-modal__field"});s.createEl("label",{text:this.kind==="memo"?"Memo content":"Details"});let o=s.createEl("textarea",{attr:{rows:"5",placeholder:this.kind==="memo"?"Write the memo body here.":"Optional details shown in the dashboard row."}});o.addEventListener("input",()=>{this.bodyValue=o.value}),new h.Setting(e).setName(this.kind==="memo"?"Reminder date":"Due date").setDesc("Optional. Use YYYY-MM-DD or YYYY-MM-DD HH:mm.").addText(d=>d.setPlaceholder("2026-06-15").onChange(c=>{this.dateValue=c}));let r=e.createDiv({cls:"diy-pet-add-dashboard-modal__actions"});r.createEl("button",{text:"Cancel",attr:{type:"button"}}).addEventListener("click",()=>this.close());let l=r.createEl("button",{cls:"mod-cta",text:`Add ${i}`,attr:{type:"button"}});l.addEventListener("click",()=>{this.submit(l)}),window.setTimeout(()=>n?.focus(),0)}async submit(e){let i=this.titleValue.trim();if(!i){new h.Notice("Title is required.");return}e.disabled=!0;try{await this.plugin.addApexDashboardItem(this.kind,{title:i,body:this.bodyValue,date:this.dateValue}),this.close()}catch(n){console.error("DIY Desktop Pet failed to add dashboard item.",n),new h.Notice(n instanceof Error?n.message:"Failed to add dashboard item."),e.disabled=!1}}},Vt=class extends h.Modal{constructor(e,i){super(e);this.plugin=i}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("diy-pet-permissions-modal"),e.createEl("h2",{text:`${this.plugin.getActivePet()?.name||"Pet"} permissions`}),e.createEl("p",{cls:"diy-pet-permissions-modal__note",text:"These permissions control Agent tools. WeChat support prepares a draft only; it never sends automatically."}),new h.Setting(e).setName("Agent can write vault files").setDesc("Allows create_note, append_note, overwrite_note, and completing current pet content.").addToggle(i=>i.setValue(this.plugin.settings.chat.agentCanWrite).onChange(async n=>{this.plugin.settings.chat.agentCanWrite=n,await this.plugin.saveSettings()})),new h.Setting(e).setName("Allow opening browser").setDesc("Allows open_browser and open_web_search for http/https links.").addToggle(i=>i.setValue(this.plugin.settings.externalActions.allowOpenBrowser).onChange(async n=>{this.plugin.settings.externalActions.allowOpenBrowser=n,await this.plugin.saveSettings()})),new h.Setting(e).setName("Allow WeChat draft").setDesc("Allows copying a draft and trying to open WeChat. It does not send messages.").addToggle(i=>i.setValue(this.plugin.settings.externalActions.allowPrepareWechat).onChange(async n=>{this.plugin.settings.externalActions.allowPrepareWechat=n,await this.plugin.saveSettings()})),new h.Setting(e).setName("Confirm external actions").setDesc("Ask before opening a browser link or preparing a WeChat draft.").addToggle(i=>i.setValue(this.plugin.settings.externalActions.confirmBeforeExternalAction).onChange(async n=>{this.plugin.settings.externalActions.confirmBeforeExternalAction=n,await this.plugin.saveSettings()})),new h.Setting(e).addButton(i=>i.setButtonText("Close").onClick(()=>this.close()))}onClose(){this.contentEl.empty()}},qt=class extends h.PluginSettingTab{constructor(e,i){super(e,i);this.plugin=i}openSections=new Set(["General","Pet"]);display(){let{containerEl:e}=this;e.empty(),e.addClass("diy-desktop-pet-settings"),e.createEl("h2",{text:"DIY Desktop Pet"}),this.createSettingsSection(e,"General",i=>this.displayGeneral(i)),this.createSettingsSection(e,"Pet",i=>this.displayPetEditor(i)),this.createSettingsSection(e,"Actions",i=>this.displayActions(i)),this.createSettingsSection(e,"Content & reminders",i=>this.displayContent(i)),this.createSettingsSection(e,"Chat & Agent",i=>this.displayChat(i)),this.createSettingsSection(e,"Skills",i=>this.displaySkills(i)),this.createSettingsSection(e,"Generation",i=>this.displayGeneration(i)),this.createSettingsSection(e,"External actions",i=>this.displayExternalActions(i))}createSettingsSection(e,i,n){let s=e.createEl("details",{cls:"diy-pet-settings-section"});s.open=this.openSections.has(i),s.addEventListener("toggle",()=>{s.open?this.openSections.add(i):this.openSections.delete(i)}),s.createEl("summary",{text:i,cls:"diy-pet-settings-section__summary"});let o=s.createDiv({cls:"diy-pet-settings-section__body"});n(o)}displayGeneral(e){new h.Setting(e).setName("Enable pet").addToggle(i=>i.setValue(this.plugin.settings.enabled).onChange(async n=>{this.plugin.settings.enabled=n,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Active pet").addDropdown(i=>{for(let n of this.plugin.settings.pets)i.addOption(n.id,n.name);i.setValue(this.plugin.settings.activePetId).onChange(async n=>{this.plugin.settings.activePetId=n,await this.plugin.saveSettings(),this.plugin.refreshPet(),this.display()})}).addButton(i=>i.setButtonText("New").onClick(async()=>{await this.plugin.createPet(),this.display()})).addButton(i=>i.setButtonText("Delete").onClick(async()=>{await this.plugin.deleteActivePet(),this.display()})),new h.Setting(e).setName("Pet size").addSlider(i=>i.setLimits(48,360,4).setDynamicTooltip().setValue(this.plugin.settings.size).onChange(async n=>{this.plugin.settings.size=n,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Panel width").setDesc("You can also resize the unified panel by dragging its top-left handle.").addSlider(i=>i.setLimits(220,520,10).setDynamicTooltip().setValue(this.plugin.settings.panelWidth).onChange(async n=>{this.plugin.settings.panelWidth=n,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Panel height").setDesc("You can also resize the unified panel by dragging its top-left handle.").addSlider(i=>i.setLimits(180,520,10).setDynamicTooltip().setValue(this.plugin.settings.panelHeight).onChange(async n=>{this.plugin.settings.panelHeight=n,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Native desktop mirror").setDesc("Experimental: macOS only. Other platforms keep the in-window Obsidian pet.").addToggle(i=>i.setValue(this.plugin.settings.desktopOverlay).onChange(async n=>{this.plugin.settings.desktopOverlay=n,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Stay still").setDesc("Keep the pet fixed in place while still allowing drag and drop.").addToggle(i=>i.setValue(this.plugin.settings.stayStill).onChange(async n=>{this.plugin.settings.stayStill=n,n&&(this.plugin.settings.speed=0),await this.plugin.saveSettings(),this.plugin.refreshPet(),this.display()})),new h.Setting(e).setName("Walking speed").setDesc("Only used when Stay still is off.").addSlider(i=>i.setLimits(0,12,1).setDynamicTooltip().setValue(this.plugin.settings.speed).onChange(async n=>{this.plugin.settings.speed=n,n>0&&(this.plugin.settings.stayStill=!1),await this.plugin.saveSettings(),this.plugin.refreshPet(),this.display()})),new h.Setting(e).setName("Opacity").addSlider(i=>i.setLimits(20,100,1).setDynamicTooltip().setValue(this.plugin.settings.opacity).onChange(async n=>{this.plugin.settings.opacity=n,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Accent color").addText(i=>i.setValue(this.plugin.settings.accentColor).onChange(async n=>{this.plugin.settings.accentColor=n.trim()||f.accentColor,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Speech bubble").addToggle(i=>i.setValue(this.plugin.settings.showSpeech).onChange(async n=>{this.plugin.settings.showSpeech=n,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Bounce").addToggle(i=>i.setValue(this.plugin.settings.bounce).onChange(async n=>{this.plugin.settings.bounce=n,await this.plugin.saveSettings(),this.plugin.refreshPet()})),new h.Setting(e).setName("Reset position").addButton(i=>i.setButtonText("Reset").onClick(async()=>{this.plugin.settings.x=null,this.plugin.settings.y=null,this.plugin.settings.overlayX=null,this.plugin.settings.overlayY=null,await this.plugin.saveSettings(),this.plugin.refreshPet()}))}displayPetEditor(e){let i=this.plugin.getActivePet();if(!i)return;new h.Setting(e).setName("Name").addText(o=>{o.setValue(i.name).onChange(async r=>{await this.plugin.updateActivePetData(l=>{l.name=r.trim()||"Pet"})}),o.inputEl.addEventListener("blur",()=>this.plugin.refreshPet())}),new h.Setting(e).setName("Description").addTextArea(o=>{o.inputEl.rows=2,o.setValue(i.description||"").onChange(async r=>{await this.plugin.updateActivePetData(l=>{l.description=r.trim()})}),o.inputEl.addEventListener("blur",()=>this.plugin.refreshPet())}),e.createEl("h4",{text:"Profile"}),this.addProfileTextArea(e,"Background","background",2),this.addProfileTextArea(e,"Personality","personality",2),this.addProfileTextArea(e,"Abilities","abilities",2),this.addProfileTextArea(e,"Preferences","preferences",2),this.addProfileTextArea(e,"Catchphrases","catchphrases",2),this.addProfileTextArea(e,"Self introduction","selfIntroduction",3),new h.Setting(e).setName("Emoji fallback").addText(o=>{o.setValue(i.emoji).onChange(async r=>{await this.plugin.updateActivePetData(l=>{l.emoji=r.trim()||"\u{1F43E}"})}),o.inputEl.addEventListener("blur",()=>this.plugin.refreshPet())});let n=new h.Setting(e).setName("Cover asset").setDesc(i.coverAssetPath||"Upload a 2D PNG/JPG/WebP/GIF. GLB/GLTF is disabled in this low-memory build.").addButton(o=>o.setButtonText("Upload").onClick(()=>s.click())),s=this.createFileInput(e,async o=>{await this.plugin.uploadCover(o),this.display()});n.settingEl.appendChild(s),this.displayAppearanceTemplates(e,i),new h.Setting(e).setName("Auto cutout uploads").setDesc("Remove plain edge-connected backgrounds from static PNG, JPG, and WebP uploads. GIF uploads stay unchanged.").addToggle(o=>o.setValue(this.plugin.settings.cutout.enabled).onChange(async r=>{this.plugin.settings.cutout.enabled=r,await this.plugin.saveSettings()})),new h.Setting(e).setName("Cutout tolerance").setDesc("Higher values remove more similar background colors.").addSlider(o=>o.setLimits(8,96,1).setDynamicTooltip().setValue(this.plugin.settings.cutout.tolerance).onChange(async r=>{this.plugin.settings.cutout.tolerance=r,await this.plugin.saveSettings()})),new h.Setting(e).setName("Cutout feather").setDesc("Softens edges after background removal.").addSlider(o=>o.setLimits(0,64,1).setDynamicTooltip().setValue(this.plugin.settings.cutout.feather).onChange(async r=>{this.plugin.settings.cutout.feather=r,await this.plugin.saveSettings()}))}addProfileTextArea(e,i,n,s){let o=this.plugin.getActivePet();if(!o)return;let r={...q(),...o.profile||{}};new h.Setting(e).setName(i).addTextArea(l=>{l.inputEl.rows=s,l.setValue(r[n]||"").onChange(async d=>{await this.plugin.updateActivePetData(c=>{c.profile={...q(),...c.profile||{},[n]:d.trim()}})})})}displayAppearanceTemplates(e,i){e.createEl("h4",{text:"Appearance templates"}),new h.Setting(e).setName("Template library").setDesc("Save the current 2D cover as a reusable appearance. Applying a template updates the cover and idle action.").addButton(o=>o.setButtonText("Save current").onClick(async()=>{await this.plugin.saveCurrentAppearanceTemplate(),this.display()}));let n=i.appearanceTemplates||[],s=e.createDiv({cls:"diy-pet-template-list"});if(!n.length){s.createDiv({cls:"diy-pet-template-empty",text:"No appearance templates yet."});return}for(let o of n){let r=s.createEl("details",{cls:"diy-pet-template-item"});r.createEl("summary",{text:o.name||"Appearance template",cls:"diy-pet-template-summary"}),new h.Setting(r).setName("Name").addText(l=>l.setValue(o.name).onChange(async d=>{await this.updateAppearanceTemplate(o.id,c=>{c.name=d.trim()||"Appearance template"})})),new h.Setting(r).setName("Unique info").setDesc("This description is shown here and can be applied to the pet description.").addTextArea(l=>{l.inputEl.rows=2,l.setValue(o.description||"").onChange(async d=>{await this.updateAppearanceTemplate(o.id,c=>{c.description=d.trim()})})}),new h.Setting(r).setName("Asset").setDesc(`${o.assetType||$(o.assetPath||"")}${o.assetPath?` \xB7 ${o.assetPath}`:" \xB7 no uploaded asset"}`).addButton(l=>l.setButtonText("Apply").onClick(async()=>{await this.plugin.applyAppearanceTemplate(o.id),this.display()})).addButton(l=>l.setButtonText("Delete").onClick(async()=>{await this.plugin.deleteAppearanceTemplate(o.id),this.display()}))}}async updateAppearanceTemplate(e,i){await this.plugin.updateActivePetData(n=>{let s=n.appearanceTemplates?.find(o=>o.id===e);s&&(i(s),s.updatedAt=Date.now())})}displayActions(e){let i=this.plugin.getActivePet();if(!i)return;new h.Setting(e).setName("DIY action slots").setDesc("Add a 2D action slot, upload an image/GIF/WebP or horizontal spritesheet, choose motion, then bind it to chat or Agent events.").addButton(r=>r.setButtonText("Generate").onClick(async()=>{await this.plugin.installGeneratedActions(),this.display()})).addButton(r=>r.setButtonText("Add").onClick(async()=>{let l=W(T("action"),"Custom action","custom","");await this.plugin.updateActivePet(d=>d.actions.push(l)),this.display()}));let n=Ut[0]?.id||"";new h.Setting(e).setName("Action templates").setDesc("Install a useful 2D action plus an automatic binding rule, such as search -> think or deadline -> notify.").addDropdown(r=>{for(let l of Ut)r.addOption(l.id,`${l.name} (${l.motion})`);r.setValue(n).onChange(l=>{n=l})}).addButton(r=>r.setButtonText("Install").onClick(async()=>{await this.plugin.installActionTemplate(n),this.display()}));let s=this.createFileInput(e,async r=>{await this.plugin.importCodexSpriteAtlas(r),this.display()});new h.Setting(e).setName("Codex sprite atlas").setDesc("Upload one standard Codex atlas: 1536x1872, 8x9 cells, 192x208 each, transparent unused cells. Green chroma-key is accepted and converted to transparency.").addButton(r=>r.setButtonText("Import atlas").onClick(()=>s.click())),e.appendChild(s),e.createDiv({cls:"diy-pet-spec-note",text:"Manual action interface: use Add to create an action slot, set a stable lowercase id such as think or search, upload a 2D PNG/JPG/WebP/GIF or horizontal spritesheet, then Preview. For Codex-like behavior, import a strict 1536x1872 atlas; the plugin keeps Codex frame timing and registers all standard states automatically."});let o=e.createDiv({cls:"diy-pet-action-list"});for(let r of i.actions){let l=o.createDiv({cls:"diy-pet-action-item"});new h.Setting(l).setName(r.name).setDesc(r.assetPath||r.prompt||r.motion).addText(c=>c.setValue(r.name).onChange(async p=>{await this.plugin.updateActivePet(u=>{let g=u.actions.find(m=>m.id===r.id);g&&(g.name=p.trim()||"Action")})})).addDropdown(c=>{for(let p of _e)c.addOption(p,p);c.setValue(r.motion).onChange(async p=>{await this.plugin.updateActivePet(u=>{let g=u.actions.find(m=>m.id===r.id);g&&(g.motion=p)}),this.display()})}).addButton(c=>c.setButtonText("Preview").onClick(()=>{this.plugin.showMessage(r.name,{sourceName:i.name,actionId:r.id})})).addButton(c=>c.setButtonText("Upload").onClick(()=>d.click())).addButton(c=>c.setButtonText("Remove").onClick(async()=>{await this.plugin.updateActivePet(p=>{p.actions=p.actions.filter(u=>u.id!==r.id)}),this.display()})),new h.Setting(l).setName("Action id").setDesc("Stable lowercase id used by bindings and API calls. Example: idle, wave, search, deadline.").addText(c=>c.setValue(r.id).onChange(async p=>{let u=H(p,"action");!u||u===r.id||(await this.plugin.updateActivePet(g=>{if(g.actions.some(y=>y.id===u&&y.id!==r.id)){new h.Notice(`Action id already exists: ${u}`);return}let m=g.actions.find(y=>y.id===r.id);if(!m)return;let v=m.id;m.id=u,m.updatedAt=Date.now();for(let y of this.plugin.settings.actionBindings)y.actionId===v&&(y.actionId=u,y.updatedAt=Date.now())}),await this.plugin.saveSettings(),this.display())}));let d=this.createFileInput(l,async c=>{await this.plugin.uploadActionAsset(r.id,c),this.display()});l.appendChild(d),new h.Setting(l).setName("Prompt").addTextArea(c=>{c.inputEl.rows=2,c.setValue(r.prompt||"").onChange(async p=>{await this.plugin.updateActivePet(u=>{let g=u.actions.find(m=>m.id===r.id);g&&(g.prompt=p)})})}),new h.Setting(l).setName("Asset playback").setDesc("Use image/gif/webp for normal assets, or spritesheet for horizontal frame images. 3D is disabled.").addDropdown(c=>{for(let p of Be)c.addOption(p,p);c.setValue(r.assetType==="model3d"||$(r.assetPath||"")==="model3d"?"image":r.assetType||"image").onChange(async p=>{await this.plugin.updateActivePet(u=>{let g=u.actions.find(m=>m.id===r.id);g&&(g.assetType=p)}),this.display()})}).addText(c=>{c.inputEl.type="number",c.inputEl.min="1",c.inputEl.max="60",c.setPlaceholder("frames").setValue(String(r.frameCount||"")).onChange(async p=>{await this.plugin.updateActivePet(u=>{let g=u.actions.find(m=>m.id===r.id);g&&(g.frameCount=Number(p)||void 0)})})}).addText(c=>{c.inputEl.type="number",c.inputEl.min="40",c.inputEl.max="2000",c.setPlaceholder("ms").setValue(String(r.frameDurationMs||"")).onChange(async p=>{await this.plugin.updateActivePet(u=>{let g=u.actions.find(m=>m.id===r.id);g&&(g.frameDurationMs=Number(p)||void 0)})})})}this.displayActionBindings(e,i)}displayActionBindings(e,i){e.createEl("h4",{text:"Action bindings"}),new h.Setting(e).setName("Binding rules").setDesc("Automatically play actions when messages, agent tools, or completions match a rule.").addButton(s=>s.setButtonText("Add binding").onClick(async()=>{this.plugin.settings.actionBindings.push({id:T("binding"),name:"Custom binding",enabled:!0,event:"user-message",pattern:"",actionId:i.actions[0]?.id||"idle",timeoutMs:2600,createdAt:Date.now(),updatedAt:Date.now()}),await this.plugin.saveSettings(),this.display()}));let n=e.createDiv({cls:"diy-pet-binding-list"});for(let s of this.plugin.settings.actionBindings){let o=n.createDiv({cls:"diy-pet-binding-item"});new h.Setting(o).setName(s.name).setDesc(`${s.event} -> ${s.actionId}`).addToggle(r=>r.setValue(s.enabled).onChange(async l=>{s.enabled=l,s.updatedAt=Date.now(),await this.plugin.saveSettings()})).addButton(r=>r.setButtonText("Delete").onClick(async()=>{this.plugin.settings.actionBindings=this.plugin.settings.actionBindings.filter(l=>l.id!==s.id),await this.plugin.saveSettings(),this.display()})),new h.Setting(o).setName("Name").addText(r=>r.setValue(s.name).onChange(async l=>{s.name=l.trim()||"Binding",s.updatedAt=Date.now(),await this.plugin.saveSettings()})),new h.Setting(o).setName("Event").addDropdown(r=>{for(let l of Fe)r.addOption(l,l);r.setValue(s.event).onChange(async l=>{s.event=l,s.updatedAt=Date.now(),await this.plugin.saveSettings(),this.display()})}),new h.Setting(o).setName("Pattern").setDesc("Comma-separated keywords. Leave empty to match every event of this type.").addTextArea(r=>{r.inputEl.rows=2,r.setValue(s.pattern).onChange(async l=>{s.pattern=l,s.updatedAt=Date.now(),await this.plugin.saveSettings()})}),new h.Setting(o).setName("Action").addDropdown(r=>{for(let l of i.actions)r.addOption(l.id,l.name||l.id);r.setValue(s.actionId).onChange(async l=>{s.actionId=l,s.updatedAt=Date.now(),await this.plugin.saveSettings()})}).addText(r=>{r.inputEl.type="number",r.inputEl.min="400",r.inputEl.max="20000",r.setValue(String(s.timeoutMs||2600)).onChange(async l=>{s.timeoutMs=Number(l)||2600,s.updatedAt=Date.now(),await this.plugin.saveSettings()})})}}displayContent(e){new h.Setting(e).setName("Enable content").addToggle(n=>n.setValue(this.plugin.settings.content.enabled).onChange(async s=>{this.plugin.settings.content.enabled=s,await this.plugin.saveSettings(),await this.plugin.refreshContent(),this.plugin.restartContentPolling(),this.plugin.restartReminderPolling()})),new h.Setting(e).setName("Apex Dashboard").setDesc("Read memos, todos, task cards, and reminders from the Apex Dashboard markdown file.").addToggle(n=>n.setValue(this.plugin.settings.content.showApexDashboard).onChange(async s=>{this.plugin.settings.content.showApexDashboard=s,await this.plugin.saveSettings(),await this.plugin.refreshContent()})),new h.Setting(e).setName("Apex dashboard file").setDesc("Vault path without or with .md, usually dashboard or notes/dashboard.").addText(n=>n.setValue(this.plugin.settings.content.apexDashboardFile).onChange(async s=>{this.plugin.settings.content.apexDashboardFile=s.trim()||f.content.apexDashboardFile,await this.plugin.saveSettings(),await this.plugin.refreshContent()})),new h.Setting(e).setName("Markdown tasks").addToggle(n=>n.setValue(this.plugin.settings.content.showMarkdownTasks).onChange(async s=>{this.plugin.settings.content.showMarkdownTasks=s,await this.plugin.saveSettings(),await this.plugin.refreshContent()})),new h.Setting(e).setName("Markdown memos").addToggle(n=>n.setValue(this.plugin.settings.content.showMemos).onChange(async s=>{this.plugin.settings.content.showMemos=s,await this.plugin.saveSettings(),await this.plugin.refreshContent()})),new h.Setting(e).setName("Memo tags").addText(n=>n.setValue(this.plugin.settings.content.memoTags).onChange(async s=>{this.plugin.settings.content.memoTags=s,await this.plugin.saveSettings(),await this.plugin.refreshContent()})),new h.Setting(e).setName("Memo folders").addText(n=>n.setValue(this.plugin.settings.content.memoFolders).onChange(async s=>{this.plugin.settings.content.memoFolders=s,await this.plugin.saveSettings(),await this.plugin.refreshContent()})),new h.Setting(e).setName("Max items").addSlider(n=>n.setLimits(1,30,1).setDynamicTooltip().setValue(this.plugin.settings.content.maxItems).onChange(async s=>{this.plugin.settings.content.maxItems=s,await this.plugin.saveSettings(),await this.plugin.refreshContent()})),new h.Setting(e).setName("Refresh minutes").addSlider(n=>n.setLimits(1,60,1).setDynamicTooltip().setValue(this.plugin.settings.content.refreshMinutes).onChange(async s=>{this.plugin.settings.content.refreshMinutes=s,await this.plugin.saveSettings(),this.plugin.restartContentPolling()})),new h.Setting(e).setName("Refresh now").addButton(n=>n.setButtonText("Refresh").onClick(async()=>{let s=await this.plugin.refreshContent();new h.Notice(`Found ${s.length} items.`)})),new h.Setting(e).setName("Deadline reminders").setDesc("Show a pet bubble when dashboard/task deadlines are inside the configured lead time.").addToggle(n=>n.setValue(this.plugin.settings.reminders.enabled).onChange(async s=>{this.plugin.settings.reminders.enabled=s,await this.plugin.saveSettings(),this.plugin.restartReminderPolling()})),new h.Setting(e).setName("Remind before deadline").setDesc("Minutes before due/reminder/deadline. One week is 10080.").addText(n=>{n.inputEl.type="number",n.inputEl.min="0",n.inputEl.max="525600",n.setValue(String(this.plugin.settings.reminders.leadMinutes)).onChange(async s=>{this.plugin.settings.reminders.leadMinutes=Math.max(0,Number(s)||f.reminders.leadMinutes),await this.plugin.saveSettings(),this.plugin.restartReminderPolling()})}),new h.Setting(e).setName("Reminder check minutes").addSlider(n=>n.setLimits(1,120,1).setDynamicTooltip().setValue(this.plugin.settings.reminders.checkMinutes).onChange(async s=>{this.plugin.settings.reminders.checkMinutes=s,await this.plugin.saveSettings(),this.plugin.restartReminderPolling()})),new h.Setting(e).setName("Repeat reminder minutes").setDesc("Avoids repeating the same pet bubble too often.").addSlider(n=>n.setLimits(1,1440,1).setDynamicTooltip().setValue(this.plugin.settings.reminders.repeatMinutes).onChange(async s=>{this.plugin.settings.reminders.repeatMinutes=s,await this.plugin.saveSettings()}));let i=this.plugin.getActivePet();new h.Setting(e).setName("Default reminder action").setDesc("Used when no deadline-reminder action binding matches.").addDropdown(n=>{for(let s of i?.actions||[])n.addOption(s.id,s.name||s.id);n.setValue(this.plugin.settings.reminders.actionId||f.reminders.actionId).onChange(async s=>{this.plugin.settings.reminders.actionId=s||f.reminders.actionId,await this.plugin.saveSettings()})})}displayChat(e){new h.Setting(e).setName("Enable chat").setDesc("Let the pet talk to a model API from the click-open Chat menu.").addToggle(n=>n.setValue(this.plugin.settings.chat.enabled).onChange(async s=>{this.plugin.settings.chat.enabled=s,await this.plugin.saveSettings()}));let i=this.plugin.getActiveChatModelProfile();new h.Setting(e).setName("Model profile").setDesc("Choose the profile used by the pet chat header and API requests.").addDropdown(n=>{for(let s of this.plugin.settings.chat.modelProfiles)n.addOption(s.id,[s.name,s.model].filter(Boolean).join(" \xB7 ")||s.id);n.setValue(i.id).onChange(async s=>{await this.plugin.switchChatModelProfile(s),this.display()})}).addButton(n=>n.setButtonText("New").onClick(async()=>{await this.plugin.createChatModelProfile(),this.display()})).addButton(n=>n.setButtonText("Delete").onClick(async()=>{await this.plugin.deleteActiveChatModelProfile(),this.display()})),new h.Setting(e).setName("Profile name").addText(n=>n.setValue(i.name).onChange(async s=>{await this.plugin.updateActiveChatModelProfile(o=>{o.name=s.trim()||"Model"})})),new h.Setting(e).setName("Provider preset").setDesc("Applies endpoint, format, and default model to the active profile.").addDropdown(n=>{for(let[s,o]of Object.entries(it))n.addOption(s,o.label);n.setValue(i.providerPreset||"custom").onChange(async s=>{let o=it[s]||it.custom;await this.plugin.updateActiveChatModelProfile(r=>{r.providerPreset=s,s!=="custom"&&(r.endpoint=o.endpoint,r.apiFormat=o.apiFormat,r.model=o.model)}),this.display()})}),new h.Setting(e).setName("API format").setDesc("Use Responses when you want to send active PDFs as file context.").addDropdown(n=>{n.addOption("chat-completions","Chat Completions"),n.addOption("responses","Responses"),n.setValue(i.apiFormat).onChange(async s=>{await this.plugin.updateActiveChatModelProfile(o=>{o.apiFormat=s})})}),new h.Setting(e).setName("Endpoint").addText(n=>n.setValue(i.endpoint).onChange(async s=>{await this.plugin.updateActiveChatModelProfile(o=>{o.endpoint=s.trim()})})),new h.Setting(e).setName("Model").addText(n=>n.setValue(i.model).onChange(async s=>{await this.plugin.updateActiveChatModelProfile(o=>{o.model=s.trim()})})),new h.Setting(e).setName("API key").addText(n=>{n.inputEl.type="password",n.setValue(i.apiKey).onChange(async s=>{await this.plugin.updateActiveChatModelProfile(o=>{o.apiKey=s})})}),new h.Setting(e).setName("Temperature").addSlider(n=>n.setLimits(0,2,.05).setDynamicTooltip().setValue(this.plugin.settings.chat.temperature).onChange(async s=>{this.plugin.settings.chat.temperature=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Max output tokens").addText(n=>{n.inputEl.type="number",n.inputEl.min="64",n.inputEl.max="64000",n.setValue(String(this.plugin.settings.chat.maxTokens)).onChange(async s=>{this.plugin.settings.chat.maxTokens=Number(s)||f.chat.maxTokens,await this.plugin.saveSettings()})}),new h.Setting(e).setName("Max history messages").setDesc("When exceeded, history is summarized or rolled over depending on the strategy below.").addSlider(n=>n.setLimits(2,80,1).setDynamicTooltip().setValue(this.plugin.settings.chat.maxHistory).onChange(async s=>{this.plugin.settings.chat.maxHistory=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("History strategy").addDropdown(n=>{n.addOption("summarize","Summarize older context"),n.addOption("rolling","Keep newest messages only"),n.setValue(this.plugin.settings.chat.historyStrategy).onChange(async s=>{this.plugin.settings.chat.historyStrategy=s,await this.plugin.saveSettings()})}),new h.Setting(e).setName("System prompt").addTextArea(n=>{n.inputEl.rows=3,n.setValue(this.plugin.settings.chat.systemPrompt).onChange(async s=>{this.plugin.settings.chat.systemPrompt=s,await this.plugin.saveSettings()})}),new h.Setting(e).setName("Summary prompt").addTextArea(n=>{n.inputEl.rows=3,n.setValue(this.plugin.settings.chat.summaryPrompt).onChange(async s=>{this.plugin.settings.chat.summaryPrompt=s,await this.plugin.saveSettings()})}),new h.Setting(e).setName("Include active file").setDesc("Send the currently active Obsidian file as context when possible.").addToggle(n=>n.setValue(this.plugin.settings.chat.includeActiveFile).onChange(async s=>{this.plugin.settings.chat.includeActiveFile=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Include active images").addToggle(n=>n.setValue(this.plugin.settings.chat.includeImages).onChange(async s=>{this.plugin.settings.chat.includeImages=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Include active PDFs").setDesc("PDF file context is sent in Responses mode. Chat Completions receives only the file note.").addToggle(n=>n.setValue(this.plugin.settings.chat.includePdfs).onChange(async s=>{this.plugin.settings.chat.includePdfs=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Active text max chars").addText(n=>{n.inputEl.type="number",n.inputEl.min="500",n.inputEl.max="50000",n.setValue(String(this.plugin.settings.chat.activeFileMaxChars)).onChange(async s=>{this.plugin.settings.chat.activeFileMaxChars=Number(s)||f.chat.activeFileMaxChars,await this.plugin.saveSettings()})}),new h.Setting(e).setName("Attachment max bytes").setDesc("Limits image and PDF data sent to the API.").addText(n=>{n.inputEl.type="number",n.inputEl.min="10000",n.inputEl.max="20000000",n.setValue(String(this.plugin.settings.chat.maxAttachmentBytes)).onChange(async s=>{this.plugin.settings.chat.maxAttachmentBytes=Number(s)||f.chat.maxAttachmentBytes,await this.plugin.saveSettings()})}),new h.Setting(e).setName("Agent mode").setDesc("Allow the model to request Obsidian tools such as search, read note, and pet actions.").addToggle(n=>n.setValue(this.plugin.settings.chat.agentEnabled).onChange(async s=>{this.plugin.settings.chat.agentEnabled=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Agent can write vault files").setDesc("Allows create, append, overwrite note, and complete current pet content tools.").addToggle(n=>n.setValue(this.plugin.settings.chat.agentCanWrite).onChange(async s=>{this.plugin.settings.chat.agentCanWrite=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Agent max steps").setDesc("Maximum tool calls before the pet must answer.").addSlider(n=>n.setLimits(1,10,1).setDynamicTooltip().setValue(this.plugin.settings.chat.agentMaxSteps).onChange(async s=>{this.plugin.settings.chat.agentMaxSteps=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Agent search limit").addSlider(n=>n.setLimits(1,30,1).setDynamicTooltip().setValue(this.plugin.settings.chat.agentSearchLimit).onChange(async s=>{this.plugin.settings.chat.agentSearchLimit=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Agent read max chars").addText(n=>{n.inputEl.type="number",n.inputEl.min="500",n.inputEl.max="50000",n.setValue(String(this.plugin.settings.chat.agentReadMaxChars)).onChange(async s=>{this.plugin.settings.chat.agentReadMaxChars=Number(s)||f.chat.agentReadMaxChars,await this.plugin.saveSettings()})}),new h.Setting(e).setName("Web search").setDesc("Allow Agent mode to use the web_search tool.").addToggle(n=>n.setValue(this.plugin.settings.webSearch.enabled).onChange(async s=>{this.plugin.settings.webSearch.enabled=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Web search provider").addDropdown(n=>{n.addOption("duckduckgo","DuckDuckGo HTML"),n.addOption("brave","Brave Search API"),n.addOption("tavily","Tavily"),n.addOption("serpapi","SerpAPI"),n.addOption("custom","Custom JSON API"),n.setValue(this.plugin.settings.webSearch.provider).onChange(async s=>{this.plugin.settings.webSearch.provider=s,await this.plugin.saveSettings(),this.display()})}),new h.Setting(e).setName("Web search endpoint").setDesc("Optional for built-in providers; required for Custom.").addText(n=>n.setValue(this.plugin.settings.webSearch.endpoint).onChange(async s=>{this.plugin.settings.webSearch.endpoint=s.trim(),await this.plugin.saveSettings()})),new h.Setting(e).setName("Web search API key").addText(n=>{n.inputEl.type="password",n.setValue(this.plugin.settings.webSearch.apiKey).onChange(async s=>{this.plugin.settings.webSearch.apiKey=s,await this.plugin.saveSettings()})}),new h.Setting(e).setName("Web search results").addSlider(n=>n.setLimits(1,10,1).setDynamicTooltip().setValue(this.plugin.settings.webSearch.maxResults).onChange(async s=>{this.plugin.settings.webSearch.maxResults=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Log agent tools").setDesc("Write tool results to the developer console for debugging.").addToggle(n=>n.setValue(this.plugin.settings.chat.agentLogTools).onChange(async s=>{this.plugin.settings.chat.agentLogTools=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Write chats to file").setDesc("Append each completed exchange to the Markdown file below.").addToggle(n=>n.setValue(this.plugin.settings.chat.logEnabled).onChange(async s=>{this.plugin.settings.chat.logEnabled=s,await this.plugin.saveSettings()})),new h.Setting(e).setName("Chat log file").setDesc("Vault path, for example Pet Chats.md or Logs/Pet Chats.md.").addText(n=>n.setValue(this.plugin.settings.chat.logFile).onChange(async s=>{this.plugin.settings.chat.logFile=s.trim()||f.chat.logFile,await this.plugin.saveSettings()})),new h.Setting(e).setName("Clear chat history").setDesc("Clears the current chat session context and the visible pet chat panel. It does not delete the log file.").addButton(n=>n.setButtonText("Clear").onClick(()=>this.plugin.clearChatHistory()))}displaySkills(e){let i="";new h.Setting(e).setName("Skill set").setDesc("Enabled skills are injected into the pet chat and Agent instructions. Import supports GitHub repos, GitHub tree/blob links, raw SKILL.md, and JSON skill files.").addButton(s=>s.setButtonText("Add skill").onClick(async()=>{this.openSections.add("Skills"),this.plugin.settings.skills.push({id:T("skill"),name:"Custom Skill",description:"",prompt:"Describe how the pet should behave when this skill is relevant.",enabled:!0,createdAt:Date.now(),updatedAt:Date.now()}),await this.plugin.saveSettings(),this.display()})).addButton(s=>s.setButtonText("Restore built-ins").onClick(async()=>{this.openSections.add("Skills"),await this.plugin.restoreDefaultSkills(),new h.Notice("Built-in skills restored without deleting custom skills."),this.display()})),e.createDiv({cls:"diy-pet-spec-note",text:"Skill spec: GitHub repositories or folders can contain multiple SKILL.md, skill.json, or skills.json files. SKILL.md may use Codex-style YAML frontmatter with name and description; the Markdown body becomes the skill instructions. JSON accepts { id, name, description, prompt } or { skills: [...] }."}),new h.Setting(e).setName("Import from GitHub or raw URL").setDesc("Paste a GitHub repository, tree folder, SKILL.md blob/raw URL, skill.json, or skills.json.").addText(s=>{s.setPlaceholder("https://github.com/user/repo or raw SKILL.md").onChange(o=>{i=o.trim()})}).addButton(s=>s.setButtonText("Import").onClick(async()=>{try{let o=await this.plugin.importSkillFromUrl(i);new h.Notice(`Imported ${o.length} skill${o.length===1?"":"s"}.`),this.display()}catch(o){let r=o instanceof Error?o.message:String(o);new h.Notice(r)}}));let n=e.createDiv({cls:"diy-pet-skill-list"});for(let s of this.plugin.settings.skills){let o=n.createDiv({cls:"diy-pet-skill-item"});new h.Setting(o).setName(s.name).setDesc(s.description||s.id).addToggle(r=>r.setValue(s.enabled).onChange(async l=>{s.enabled=l,s.updatedAt=Date.now(),await this.plugin.saveSettings()})).addButton(r=>r.setButtonText("Delete").onClick(async()=>{this.plugin.settings.skills=this.plugin.settings.skills.filter(l=>l.id!==s.id),await this.plugin.saveSettings(),this.display()})),new h.Setting(o).setName("Name").addText(r=>r.setValue(s.name).onChange(async l=>{s.name=l.trim()||"Skill",s.updatedAt=Date.now(),await this.plugin.saveSettings()})),new h.Setting(o).setName("Description").addText(r=>r.setValue(s.description).onChange(async l=>{s.description=l.trim(),s.updatedAt=Date.now(),await this.plugin.saveSettings()})),s.sourceUrl&&new h.Setting(o).setName("Source").setDesc(s.sourceUrl),new h.Setting(o).setName("Prompt").addTextArea(r=>{r.inputEl.rows=3,r.setValue(s.prompt).onChange(async l=>{s.prompt=l,s.updatedAt=Date.now(),await this.plugin.saveSettings()})})}}displayGeneration(e){new h.Setting(e).setName("Generator").addDropdown(i=>{for(let n of this.plugin.getActionGenerators())i.addOption(n.id,n.name);i.setValue(this.plugin.settings.generation.preferredGeneratorId).onChange(async n=>{this.plugin.settings.generation.preferredGeneratorId=n,await this.plugin.saveSettings()})}),new h.Setting(e).setName("Style prompt").addTextArea(i=>{i.inputEl.rows=3,i.setValue(this.plugin.settings.generation.stylePrompt).onChange(async n=>{this.plugin.settings.generation.stylePrompt=n,await this.plugin.saveSettings()})}),new h.Setting(e).setName("HTTP endpoint").addText(i=>i.setValue(this.plugin.settings.generation.customEndpoint).onChange(async n=>{this.plugin.settings.generation.customEndpoint=n.trim(),await this.plugin.saveSettings()})),new h.Setting(e).setName("HTTP API key").addText(i=>{i.inputEl.type="password",i.setValue(this.plugin.settings.generation.customApiKey).onChange(async n=>{this.plugin.settings.generation.customApiKey=n,await this.plugin.saveSettings()})})}displayExternalActions(e){new h.Setting(e).setName("Allow opening browser").setDesc("Lets Agent mode use open_browser for http/https links.").addToggle(i=>i.setValue(this.plugin.settings.externalActions.allowOpenBrowser).onChange(async n=>{this.plugin.settings.externalActions.allowOpenBrowser=n,await this.plugin.saveSettings()})),new h.Setting(e).setName("Allow WeChat draft").setDesc("Lets Agent mode copy a WeChat message draft and try to open WeChat. It never sends automatically.").addToggle(i=>i.setValue(this.plugin.settings.externalActions.allowPrepareWechat).onChange(async n=>{this.plugin.settings.externalActions.allowPrepareWechat=n,await this.plugin.saveSettings()})),new h.Setting(e).setName("Confirm external actions").setDesc("Ask before opening a browser link or preparing a WeChat draft.").addToggle(i=>i.setValue(this.plugin.settings.externalActions.confirmBeforeExternalAction).onChange(async n=>{this.plugin.settings.externalActions.confirmBeforeExternalAction=n,await this.plugin.saveSettings()})),new h.Setting(e).setName("Test external actions").setDesc("Use these buttons after enabling the permission toggles above.").addButton(i=>i.setButtonText("Browser search").onClick(async()=>{if(!this.plugin.settings.externalActions.allowOpenBrowser){new h.Notice("Enable Allow opening browser first.");return}try{await this.plugin.openSearchInBrowser("Obsidian DIY Desktop Pet 2D sprite")}catch(n){let s=n instanceof Error?n.message:String(n);new h.Notice(s)}})).addButton(i=>i.setButtonText("WeChat draft").onClick(async()=>{if(!this.plugin.settings.externalActions.allowPrepareWechat){new h.Notice("Enable Allow WeChat draft first.");return}try{await this.plugin.prepareWechatDraft("","\u8FD9\u662F\u4E00\u6761 DIY Desktop Pet \u6D4B\u8BD5\u8349\u7A3F\u3002")}catch(n){let s=n instanceof Error?n.message:String(n);new h.Notice(s)}}))}createFileInput(e,i){let n=e.createEl("input",{attr:{type:"file",accept:Ci}});return n.addClass("diy-pet-file-input"),n.addEventListener("change",async()=>{let s=n.files?.[0];if(s)try{await i(s)}catch(o){let r=o instanceof Error?o.message:String(o);new h.Notice(r),console.error("DIY Desktop Pet upload failed.",o)}finally{n.value=""}}),n}};function B(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Wt(a){let t=a.toLowerCase();return t.endsWith(".glb")?"model/gltf-binary":t.endsWith(".gltf")?"model/gltf+json":t.endsWith(".pdf")?"application/pdf":t.endsWith(".gif")?"image/gif":t.endsWith(".webp")?"image/webp":t.endsWith(".jpg")||t.endsWith(".jpeg")?"image/jpeg":t.endsWith(".svg")?"image/svg+xml":"image/png"}function Di(a){return["png","jpg","jpeg","webp","gif"].includes(a)}function zt(a){return["md","markdown","txt","canvas","json","csv","tsv","html","css","js","ts","jsx","tsx","xml","yaml","yml"].includes(a)}function Mi(a,t){let e=Buffer.from(a).toString("base64");return`data:${t};base64,${e}`}function Ti(a,t){for(let e=a.length-1;e>=0;e-=1)if(t(a[e]))return e;return-1}function x(a){return typeof a=="object"&&a!==null}function tt(a,t,e){let i=document.createElement("option");i.value=t,i.text=e,a.appendChild(i)}function Ii(a){return a.split(/[,,\n]/).map(t=>t.trim()).filter(Boolean)}function $i(a,t){let e=[],i=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?(?:<a[^>]+class="result__snippet"[^>]*>|<div[^>]+class="result__snippet"[^>]*>)([\s\S]*?)(?:<\/a>|<\/div>)/gi,n;for(;(n=i.exec(a))&&e.length<t;){let o=Ae(Ct(n[1])),r=Ot(n[2]),l=Ot(n[3]);!r||!o||e.push({title:r,url:o,snippet:l,source:"DuckDuckGo"})}if(e.length)return e;let s=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi;for(;(n=s.exec(a))&&e.length<t;){let o=Ae(Ct(n[1])),r=Ot(n[2]);!r||!o||e.push({title:r,url:o,source:"DuckDuckGo"})}return e}function Ae(a){try{let t=new URL(a,"https://duckduckgo.com");return t.searchParams.get("uddg")||t.href}catch{return a}}function We(a,t){if(typeof a=="string")try{return We(JSON.parse(a),t)}catch{return[]}if(!x(a))return[];let e=[];for(let s of["results","organic_results","items"]){let o=a[s];Array.isArray(o)&&e.push(...o)}let i=a.web;x(i)&&Array.isArray(i.results)&&e.push(...i.results);let n=a.data;return Array.isArray(n)&&e.push(...n),e.map(s=>{if(!x(s))return;let o=V(s,["title","name"]),r=V(s,["url","link","href"]),l=V(s,["snippet","description","content","body"]);if(!(!o||!r))return{title:o,url:r,snippet:l}}).filter(s=>!!s).slice(0,t)}function V(a,t){for(let e of t){let i=a[e];if(typeof i=="string"&&i.trim())return i.trim()}return""}function Ot(a){return Ct(a.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim())}function Ct(a){let t=document.createElement("textarea");return t.innerHTML=a,t.value}function Li(a){let t=xt(a);if(!t)return;let e=t.tool;if(typeof e=="string")return{tool:e,args:x(t.args)?t.args:{}}}function xe(a){let t=xt(a);return t&&typeof t.final=="string"?t.final.trim():a.trim()}function xt(a){let t=a.trim(),e=[t,t.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,"")],i=t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);i&&e.push(i[1]);let n=t.match(/\{[\s\S]*\}/);n&&e.push(n[0]);for(let s of e)try{let o=JSON.parse(s);if(x(o))return o}catch{continue}}function C(a,t){let e=a?.[t];return typeof e=="string"?e:""}function et(a,t,e){let i=a?.[t];if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"){let n=Number(i);if(Number.isFinite(n))return n}return e}function ke(a,t,e){let i=a?.[t];if(typeof i=="boolean")return i;if(typeof i=="string"){if(/^(true|yes|1|on)$/i.test(i.trim()))return!0;if(/^(false|no|0|off)$/i.test(i.trim()))return!1}return e}function Ni(a){let t=a.trim();if(t)try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?void 0:e.href}catch{return}}function Ri(a){if(!a)return;let e=a.trim().match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/);if(!e)return;let i=Number(e[1]),n=Number(e[2])-1,s=Number(e[3]),o=e[4]===void 0?23:Number(e[4]),r=e[5]===void 0?59:Number(e[5]),l=e[6]===void 0?59:Number(e[6]),c=new Date(i,n,s,o,r,l).getTime();return Number.isFinite(c)?c:void 0}function _i(a){let t=Math.max(0,Math.ceil(a/6e4)),e=Math.floor(t/1440),i=Math.floor(t%1440/60),n=t%60,s=[];return e&&s.push(`${e}\u5929`),i&&s.push(`${i}\u5C0F\u65F6`),!e&&n&&s.push(`${n}\u5206\u949F`),s.join("")||"\u4E0D\u52301\u5206\u949F"}function At(a,t){let e=a.includes(`\r
`)?`\r
`:`
`,i=a.split(/\r?\n/),n=t-1;if(n<0||n>=i.length)return{content:a,changed:!1};let s=i[n],o=s.match(/^(\s*[-*+]\s+\[)([ xX-])(\]\s+.*)$/);if(o)return o[2].toLowerCase()==="x"?{content:a,changed:!1}:(i[n]=`${o[1]}x${o[3]}`,{content:i.join(e),changed:!0});let r=s.match(/^(\s*(?:checked|done):\s*)(true|false)(\s*)$/i);if(r)return r[2].toLowerCase()==="true"?{content:a,changed:!1}:(i[n]=`${r[1]}true${r[3]}`,{content:i.join(e),changed:!0});let l=s.match(/^(\s*)(?:task|todo|text):\s+.+$/i);if(!l)return{content:a,changed:!1};for(let d=n+1;d<i.length;d+=1){let c=i[d];if(/^\s*#{3,6}\s+/.test(c)||/^\s*[-*+]\s+\[[ xX-]\]/.test(c)||/^\s*(?:task|todo|text):\s+/i.test(c))break;let p=c.match(/^(\s*(?:checked|done):\s*)(true|false)(\s*)$/i);if(p)return p[2].toLowerCase()==="true"?{content:a,changed:!1}:(i[d]=`${p[1]}true${p[3]}`,{content:i.join(e),changed:!0})}return i.splice(n+1,0,`${l[1]}checked: true`),{content:i.join(e),changed:!0}}function Bi(a,t,e,i,n){if(i.toLowerCase().includes("study"))return Fi(a,t,e,n);let s=a.includes(`\r
`)?`\r
`:`
`,o=a.split(/\r?\n/),r=t-1;if(r<0||r>=o.length)return{content:a,changed:!1};let l=At(a,t);if(l.changed)return l;let d=Yt(o,r,/^#{3,6}\s+/);if(d<0)return{content:a,changed:!1};let c=Ue(o,d,/^#{2,6}\s+/),p=!1,u=o[d].match(/^(#{3,6}\s+)(.+?)(\s*)$/);u&&!/^~~.*~~$/.test(u[2].trim())&&(o[d]=`${u[1]}~~${u[2].trim()}~~${u[3]}`,p=!0);let g=ji(o,d+1,c,/^(done|checked|completed):/i);return g>=0?/:\s*true\s*$/i.test(o[g])||(o[g]=o[g].replace(/:\s*.*$/,": true"),p=!0):(o.splice(d+1,0,"done: true"),p=!0),{content:o.join(s),changed:p}}function Fi(a,t,e,i){let n=a.includes(`\r
`)?`\r
`:`
`,s=a.split(/\r?\n/),o=t-1;if(o<0||o>=s.length)return{content:a,changed:!1};let r=Yt(s,o,/^#{3,6}\s+/),l=Yt(s,o,/^##\s+/),d=r>=0&&r>l,c=i.replace(/\.md$/i,""),p=Ve(),u,g=!1;if(d){let P=At(s.join(n),t);P.changed&&s.splice(0,s.length,...P.content.split(/\r?\n/));let S=Ue(s,r,/^#{2,6}\s+/),I=s.slice(r,S).filter(A=>!/^\s*(?:learned|source):/i.test(A));s.splice(r,S-r),u=[...I,`learned: ${p}`,`source: [[${c}#${Ui(e)}]]`],g=!0}else{let P=At(s.join(n),t);P.changed&&s.splice(0,s.length,...P.content.split(/\r?\n/)),g=!0,u=[`### ${e||"Learned item"}`,`learned: ${p}`,`source: [[${c}]]`]}let m=Kt(s,"Learned"),v=Ge(s,m),y=["",...u.filter(P=>P.trim()),""];return s.splice(v,0,...y),{content:s.join(n),changed:g}}function ze(){return["# Dashboard","","## Goal","","## Memo","","## Todo","","## Study","","## Learned",""].join(`
`)}function Wi(a,t,e){let i=a.includes(`\r
`)?`\r
`:`
`,s=(a.trim()?a:ze()).split(/\r?\n/);for(let c of["Goal","Memo","Todo","Study","Learned"])Kt(s,c);let o=Kt(s,Oi(t)),r=Ge(s,o),l=zi(t,e),d=[...s[r-1]?.trim()?[""]:[],...l,""];return s.splice(r,0,...d),`${s.join(i).replace(/\s*$/,"")}${i}`}function zi(a,t){let e=He(t.body||"").split(/\n/).filter(Boolean),i=je(t.date||""),n=`created: ${Ve()}`;return a==="task"?[`### ${t.title}`,...e,`task: ${t.title}`,...i?[`due: ${i}`]:[],n]:[`### ${t.title}`,...e,...i?[`${a==="memo"?"reminder":"due"}: ${i}`]:[],n]}function Oi(a){return a==="task"?"Todo":a==="study"?"Study":"Memo"}function Oe(a){return a==="task"?"Task":a==="study"?"Study":"Memo"}function Hi(a){return b(a).replace(/^#+\s+/,"").replace(/^[-*+]\s+\[[ xX-]\]\s+/,"").replace(/\s+/g," ").trim().slice(0,140)}function He(a){return a.replace(/\uFFFD/g,"").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g," ").replace(/\r/g,"").split(`
`).map(t=>t.trim()).filter(Boolean).map(t=>t.replace(/^#{1,6}\s+/,"").replace(/^(id|type|color|cover|width|height|reminder|due|deadline|done|checked|completed|status|learned|source|created|updated|priority):/i,"note: $&")).join(`
`).slice(0,2e3)}function je(a){let e=b(a).replace(/\s+/g," ").trim().match(/\d{4}-\d{2}-\d{2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?/);return e?e[0].replace("T"," "):""}function ji(a,t,e,i){for(let n=t;n<e;n+=1)if(i.test(a[n].trim()))return n;return-1}function Yt(a,t,e){for(let i=t;i>=0;i-=1)if(e.test(a[i]))return i;return-1}function Ue(a,t,e){for(let i=t+1;i<a.length;i+=1)if(e.test(a[i]))return i;return a.length}function Kt(a,t){let e=a.findIndex(i=>new RegExp(`^##\\s+${st(t)}\\s*$`,"i").test(i));return e>=0?e:(a.length&&a[a.length-1].trim()&&a.push(""),a.push(`## ${t}`),a.length-1)}function Ge(a,t){for(let e=t+1;e<a.length;e+=1)if(/^##\s+/.test(a[e]))return e;return a.length}function Ve(){let a=new Date,t=a.getFullYear(),e=String(a.getMonth()+1).padStart(2,"0"),i=String(a.getDate()).padStart(2,"0");return`${t}-${e}-${i}`}function Ui(a){return a.replace(/^#+\s*/,"").trim()}function st(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gi(a){return`'${a.replace(/'/g,"'\\''")}'`}function H(a,t){return a.trim().toLowerCase().replace(/\.[a-z0-9]+$/i,"").replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||T(t)}async function Vi(a){let t=a.trim();if(!t)return[];let e=[],i=s=>{s&&!e.includes(s)&&e.push(s)},n=qi(t);if(n){if(n.kind==="blob")i(qe(n.owner,n.repo,n.ref||"main",n.path));else{try{for(let s of await Yi(n))i(s)}catch{}for(let s of Xt(t,Ce))i(s)}return e}return Xt(t,Ce)}function qi(a){try{let t=new URL(a.trim());if(t.hostname!=="github.com")return;let e=t.pathname.split("/").filter(Boolean);if(e.length<2)return;let[i,n]=e;return e.length>=5&&e[2]==="blob"?{owner:i,repo:n,ref:e[3],path:e.slice(4).join("/"),kind:"blob"}:e.length>=5&&e[2]==="tree"?{owner:i,repo:n,ref:e[3],path:e.slice(4).join("/"),kind:"tree"}:{owner:i,repo:n,path:"",kind:"repo"}}catch{return}}async function Yi(a){let t=a.ref?[a.ref]:["","main","master"],e=[],i=n=>{n&&!e.includes(n)&&e.push(n)};for(let n of t){let s=await Ki(a,n||void 0);for(let o of s)i(o);if(s.length)break}return e}async function Ki(a,t){let e=[],i=[{path:a.path,depth:0}],n=new Set,s=0,o=r=>{r&&!e.includes(r)&&e.push(r)};for(;i.length&&s<Si;){let r=i.shift();if(!r)break;let l=`${t||"default"}:${r.path}`;if(n.has(l))continue;n.add(l),s+=1;let d=await(0,h.requestUrl)({url:Xi(a.owner,a.repo,r.path,t),method:"GET",headers:{accept:"application/vnd.github+json"},throw:!1});if(d.status>=400)continue;let c=Array.isArray(d.json)?d.json:[d.json],p=[];for(let u of c){if(!x(u))continue;let g=V(u,["type"]),m=V(u,["name"]),v=V(u,["path"]);if(!(!m||!v)){if(g==="file"&&Ji(m)){let y=V(u,["download_url"]);o(y||qe(a.owner,a.repo,t||a.ref||"main",v))}g==="dir"&&r.depth<ki&&p.push({path:v,name:m})}}p.sort((u,g)=>Se(g)-Se(u)).forEach(u=>i.push({path:u.path,depth:r.depth+1}))}return e}function Xi(a,t,e,i){let n=e.split("/").filter(Boolean).map(encodeURIComponent).join("/"),s=`https://api.github.com/repos/${encodeURIComponent(a)}/${encodeURIComponent(t)}/contents${n?`/${n}`:""}`;return i?`${s}?ref=${encodeURIComponent(i)}`:s}function qe(a,t,e,i){let n=i.split("/").filter(Boolean).map(encodeURIComponent).join("/");return`https://raw.githubusercontent.com/${encodeURIComponent(a)}/${encodeURIComponent(t)}/${encodeURIComponent(e)}/${n}`}function Ji(a){let t=a.split("/").filter(Boolean).pop()?.toLowerCase();return t==="skill.md"||t==="skill.json"||t==="skills.json"}function Se(a){let t=`${a.name}/${a.path}`.toLowerCase();return t.includes("skills")?4:t.includes("skill")?3:t.includes(".codex")?2:0}function Xt(a,t){let e=a.trim();if(!e)return[];let i=[],n=o=>{i.includes(o)||i.push(o)},s=(o,r,l,d="")=>{let c=d?`${d.replace(/^\/+|\/+$/g,"")}/`:"";for(let p of t)n(`https://raw.githubusercontent.com/${o}/${r}/${l}/${c}${p}`)};try{let o=new URL(e);if(o.hostname==="github.com"){let r=o.pathname.split("/").filter(Boolean);if(r.length>=5&&r[2]==="blob"?n(`https://raw.githubusercontent.com/${r[0]}/${r[1]}/${r[3]}/${r.slice(4).join("/")}`):r.length>=5&&r[2]==="tree"&&s(r[0],r[1],r[3],r.slice(4).join("/")),r.length>=2)for(let l of["main","master"])s(r[0],r[1],l);return i}n(e)}catch{return[]}return i}function Zi(a,t){let e=String(a||"").trim();if(!e)return[];if(nn(e))return[];try{let n=JSON.parse(Ye(e));if(Array.isArray(n))return Ht(n,t)}catch{}let i=xt(e);if(i){let n=Array.isArray(i.skills)?Ht(i.skills,t):Ht([i],t);if(n.length)return n}return[en(e,t)].filter(n=>n.prompt.trim())}function Ht(a,t){let e=[];for(let i of a){if(!x(i))continue;let n=tn(i,t);n.prompt.trim()&&e.push(n)}return e}function Qi(a){let t=new Map;for(let e of a){let i=H(e.id||e.name||"skill","skill");t.set(i,{...e,id:i})}return Array.from(t.values())}function tn(a,t){let e=Date.now(),i=`${a.name||a.title||a.id||"Imported Skill"}`.trim(),n=`${a.description||""}`.trim(),s=`${a.prompt||a.instructions||a.content||""}`.trim();return{id:H(`${a.id||i}`,"skill"),name:i,description:n,prompt:s,enabled:a.enabled!==!1,sourceUrl:t,version:typeof a.version=="string"?a.version:void 0,createdAt:typeof a.createdAt=="number"?a.createdAt:e,updatedAt:e}}function en(a,t){let e=Date.now(),{data:i,body:n}=pn(a),o=n.split(/\r?\n/).find(c=>/^#\s+/.test(c))?.replace(/^#\s+/,"").trim(),r=n.replace(/^#\s+.+$/m,"").split(/\n\s*\n/).map(c=>b(c).replace(/\s+/g," ").trim()).find(Boolean)||"",l=t.split("/").filter(Boolean).pop()?.replace(/\.[^.]+$/,"")||"Imported Skill",d=i.name||o||l;return{id:H(d,"skill"),name:d,description:(i.description||i["short-description"]||r).slice(0,220),prompt:n.trim(),enabled:!0,sourceUrl:t,version:i.version,createdAt:e,updatedAt:e}}function nn(a){return/^<!doctype\s+html/i.test(a)||/^<html[\s>]/i.test(a)||/<head[\s>][\s\S]*<body[\s>]/i.test(a.slice(0,2e3))}function sn(a,t){let e=Ye(String(a||"").trim());if(!e)return{actions:[],bindings:[]};let i;try{i=JSON.parse(e)}catch{i=xt(e)}let n=[],s=[];Array.isArray(i)?n.push(...i):x(i)&&(Array.isArray(i.actions)?n.push(...i.actions):n.push(i),Array.isArray(i.bindings)&&s.push(...i.bindings),Array.isArray(i.actionBindings)&&s.push(...i.actionBindings));let o=n.filter(x).map(d=>Ee(d)).filter(d=>!!d),r=new Set(o.map(d=>d.id)),l=[];for(let d of n.filter(x)){let c=Ee(d);if(!c)continue;let p=an(d.binding,d.bindings,d);for(let u of p){let g=De(u,c.id,t,r);g&&l.push(g)}}for(let d of s.filter(x)){let c=De(d,"",t,r);c&&l.push(c)}return{actions:cn(o),bindings:hn(l)}}function Ee(a){let t=Date.now(),e=`${a.name||a.title||a.id||""}`.trim(),i=H(`${a.id||e||"action"}`,"action"),n=rn(a.motion),s=on(a.assetType,a.assetPath);if(s==="model3d")return;let o={id:i,name:e||i,motion:n,prompt:`${a.prompt||a.instructions||""}`.trim(),loop:a.loop!==!1,createdAt:typeof a.createdAt=="number"?a.createdAt:t,updatedAt:t};typeof a.assetPath=="string"&&a.assetPath.trim()&&(o.assetPath=(0,h.normalizePath)(a.assetPath.trim())),s&&(o.assetType=s);let r=Number(a.frameCount),l=Number(a.frameDurationMs);if(Number.isFinite(r)&&r>0&&(o.frameCount=Math.round(w(r,1,60))),Number.isFinite(l)&&l>0&&(o.frameDurationMs=Math.round(w(l,40,2e3))),Array.isArray(a.frameDurationsMs)){let d=a.frameDurationsMs.map(c=>Math.round(Number(c))).filter(c=>Number.isFinite(c)&&c>0).map(c=>Math.round(w(c,40,2e3)));d.length&&(o.frameDurationsMs=d)}return o}function an(a,t,e){let i=[];if(x(a)&&i.push(a),Array.isArray(t))for(let n of t)x(n)&&i.push(n);return(e.event||e.pattern||e.keywords||e.trigger)&&i.push(e),i}function De(a,t,e,i){let n=H(`${a.actionId||t||""}`,"action");if(!i.has(n))return;let s=ln(a.event||a.trigger),o=dn(a.pattern??a.keywords),r=`${a.name||a.title||`${s} -> ${n}`}`.trim(),l=Number(a.timeoutMs),d=Date.now();return{id:H(`${a.id||`${e}-${s}-${n}-${o}`}`,"binding"),name:r,enabled:a.enabled!==!1,event:s,pattern:o,actionId:n,timeoutMs:Number.isFinite(l)?Math.round(w(l,400,2e4)):2600,createdAt:typeof a.createdAt=="number"?a.createdAt:d,updatedAt:d}}function rn(a){return _e.includes(a)?a:"custom"}function on(a,t){let e=$(t||""),i=typeof a=="string"?a:e;return i==="model3d"?"model3d":Be.includes(i)?i:void 0}function ln(a){let t=String(a||"").trim();return Fe.includes(t)?t:"user-message"}function dn(a){return Array.isArray(a)?a.map(t=>String(t).trim()).filter(Boolean).join(","):typeof a=="string"?a.trim():""}function cn(a){return Array.from(new Map(a.map(t=>[t.id,t])).values())}function hn(a){return Array.from(new Map(a.map(t=>[t.id,t])).values())}function Ye(a){return a.trim().replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,"")}function pn(a){let t=a.match(/^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/);if(!t)return{data:{},body:a};let e={},i="";for(let n of t[1].split(/\r?\n/)){let s=n.replace(/\s+$/,""),o=s.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);if(o){i=o[1],o[2]&&(e[o[1]]=jt(o[2]));continue}let r=s.match(/^\s+([A-Za-z0-9_.-]+):\s*(.+)$/);r&&(e[r[1]]=jt(r[2]),i&&(e[`${i}.${r[1]}`]=jt(r[2])))}return{data:e,body:a.slice(t[0].length)}}function jt(a){return a.trim().replace(/^['"]|['"]$/g,"")}function un(a){return{...a,sourceName:b(a.sourceName),title:b(a.title),body:a.body?b(a.body):void 0,due:a.due?b(a.due):void 0}}function b(a){return Ct(String(a||"")).replace(/\uFFFD/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g," ").replace(/\\u([0-9a-fA-F]{4})/g,(e,i)=>String.fromCharCode(parseInt(i,16))).replace(/&#(\d+);/g,(e,i)=>String.fromCharCode(Number(i))).replace(/&#x([0-9a-fA-F]+);/g,(e,i)=>String.fromCharCode(parseInt(i,16))).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!gn(e)).join(`
`).replace(/<[^>]+>/g," ").replace(/!\[[^\]]*]\([^)]+\)/g,"").replace(/\[\[([^|\]]+)\|([^\]]+)]]/g,"$2").replace(/\[\[([^\]]+)]]/g,"$1").replace(/\[([^\]]+)]\([^)]+\)/g,"$1").replace(/^#+\s+/gm,"").replace(/^\s*[-*+]\s+\[[ xX-]\]\s+/gm,"").replace(/^\s*[-*+]\s+/gm,"").replace(/~~([^~]+)~~/g,"$1").replace(/[ \t]{2,}/g," ").replace(/\n{3,}/g,`
`).trim()}function gn(a){return/^(id|type|color|cover|width|height|reminder|due|deadline|done|checked|completed|status|learned|source|created|updated|priority|x|y|row|column|collapsed|pinned):\s*/i.test(a)}function mn(a){return a.match(/https?:\/\/[^\s"'<>]+/i)?.[0]}function Me(a,t){let e=a.trim();for(let i of t)e=e.replace(new RegExp(st(i),"ig")," ");return e.replace(/^(帮我|请|麻烦|用|打开|一下|一下子|在|从|里|中|:|:|\s)+/g," ").replace(/[::,,。.!!??]+$/g,"").replace(/\s+/g," ").trim()}function fn(a){let t=a.replace(/(帮我|请|麻烦)?\s*(用)?\s*(微信|wechat|vx|wx)\s*(发消息|发|发送|准备草稿|草稿|message)?/ig," ").trim(),e=t.match(/(?:给|发给|to)\s*([^,,::]+)[,,::]\s*(.+)$/i);if(e)return{recipient:e[1].trim(),message:e[2].trim()};let i=t.match(/["“](.+?)["”]/);return i?{recipient:t.slice(0,i.index).replace(/(?:给|发给|to)/i,"").trim(),message:i[1].trim()}:{recipient:"",message:t.replace(/^(给|发给|to)\s+/i,"").trim()}}function yn(a,t){return t.length?[`\u627E\u5230 ${t.length} \u6761\u548C\u201C${a}\u201D\u76F8\u5173\u7684\u7B14\u8BB0\uFF1A`,...t.slice(0,6).map((e,i)=>`${i+1}. ${e.path}:${e.line} ${ee(e.excerpt,120)}`)].join(`
`):`\u6CA1\u6709\u5728\u7B14\u8BB0\u91CC\u627E\u5230\u201C${a}\u201D\u3002`}function wn(a){let t=b(a).split(/\r?\n/).map(e=>e.trim()).filter(Boolean).join(" ");return ee(t,96)}function vn(a){if(!a)return"\u6CA1\u6709\u8BFB\u53D6\u5230\u5F53\u524D\u6587\u4EF6\u3002\u8BF7\u786E\u8BA4 Obsidian \u5F53\u524D\u6253\u5F00\u7684\u662F\u4E00\u4E2A\u6587\u4EF6\uFF0C\u5E76\u4E14 Chat \u8BBE\u7F6E\u91CC\u5141\u8BB8 Include active file\u3002";let t=`\u5F53\u524D\u6587\u4EF6\uFF1A${a.path}`;return a.text?`${t}
${ee(a.text,900)}`:a.attachment?.kind==="image"?`${t}
\u8FD9\u662F\u5F53\u524D\u56FE\u7247\u6587\u4EF6\u3002\u56FE\u7247\u5185\u5BB9\u9700\u8981\u6A21\u578B API \u5728\u804A\u5929\u8BF7\u6C42\u4E2D\u8BFB\u53D6\uFF1B\u76F4\u63A5\u547D\u4EE4\u4E0D\u4F1A\u628A\u56FE\u7247\u957F\u671F\u4FDD\u7559\u5728\u5386\u53F2\u91CC\u3002`:a.attachment?.kind==="pdf"?`${t}
\u8FD9\u662F\u5F53\u524D PDF \u6587\u4EF6\u3002PDF \u5185\u5BB9\u9700\u8981 Responses \u6A21\u5F0F\u7684\u6A21\u578B API \u8BFB\u53D6\uFF1B\u76F4\u63A5\u547D\u4EE4\u4E0D\u4F1A\u5728\u672C\u5730\u89E3\u6790\u6574\u4EFD PDF\u3002`:`${t}
${a.note||"\u5F53\u524D\u6587\u4EF6\u6CA1\u6709\u53EF\u663E\u793A\u7684\u6587\u672C\u6458\u8981\u3002"}`}function bn(a){return a.length?[`\u5F53\u524D\u6709 ${a.length} \u6761 dashboard/\u63D0\u9192\u5185\u5BB9\uFF1A`,...a.slice(0,10).map((t,e)=>{let i=[t.sourceName,t.due?`due ${t.due}`:""].filter(Boolean).join(" \xB7 ");return`${e+1}. ${t.title}${i?` (${i})`:""}`})].join(`
`):"\u5F53\u524D\u6CA1\u6709\u8BFB\u53D6\u5230 dashboard/\u63D0\u9192\u5185\u5BB9\u3002"}var Pn=[{node:"\u5927\u8BED\u8A00\u6A21\u578B",pattern:/大模型|LLM|GPT|Large Language Model|language model|coding LLM|代码大语言模型/i},{node:"LLM Agent",pattern:/LLM Agent|大模型 Agent|智能体|Agent|agents|Voyager|SkillOS|FutureSim/i},{node:"\u5177\u8EAB\u667A\u80FD",pattern:/具身|embodied|robot|机器人|机械臂|Jaco|ALFRED|Minecraft|Shadow Hand|dexterous|灵巧/i},{node:"\u5F3A\u5316\u5B66\u4E60",pattern:/强化学习|reinforcement learning|RL|offline RL|IQL|PPO|GRPO|reward|奖励/i},{node:"\u6280\u80FD\u5E93",pattern:/技能库|Skill Library|SkillRepo|skill library|skill repertoire|repertoire|程序性记忆/i},{node:"\u6280\u80FD\u8FDB\u5316",pattern:/技能进化|技能自举|skill bootstrapping|Skill Curation|Skill-Aware|技能蒸馏|技能修订|self-evolving|bootstrapping/i},{node:"\u81EA\u8FDB\u5316 Agent",pattern:/自进化|self-evolving|自我进化|持续进化|能力进化|bootstrapping/i},{node:"\u6301\u7EED\u5B66\u4E60",pattern:/持续学习|continual|lifelong|终身学习|长期运行|长期适应|长期能力/i},{node:"\u957F\u671F\u8BB0\u5FC6",pattern:/长期记忆|模块化记忆|long-term memory|memory|记忆|SkillRepo|外部技能/i},{node:"\u53CD\u601D\u673A\u5236",pattern:/反思|reflection|reflective|Reward Reflection|反馈反思|自反思/i},{node:"\u5956\u52B1\u8BBE\u8BA1",pattern:/奖励设计|reward design|reward function|reward code|奖励函数|奖励工程/i},{node:"\u4EE3\u7801\u751F\u6210",pattern:/代码|coding|program|程序|Python|reward code|可执行/i},{node:"\u81EA\u52A8\u8BC4\u4F30\u53CD\u9988",pattern:/反馈|feedback|fitness|evaluation|评估|自验证|Self-Verification|成功率|任务指标/i},{node:"\u52A8\u6001\u73AF\u5883\u8BC4\u4F30",pattern:/动态环境|world events|事件回放|真实世界事件|FutureSim|长期适应能力评估/i},{node:"Prompt \u4F18\u5316",pattern:/prompt|Prompt|提示词/i},{node:"\u8FDB\u5316\u641C\u7D22",pattern:/evolution|进化|Pareto|candidate|mutation|search|候选|搜索|自举/i},{node:"\u957F\u7A0B\u4EFB\u52A1",pattern:/长程|long-horizon|long horizon|多步|技能链|chain/i},{node:"\u673A\u5668\u4EBA\u63A7\u5236",pattern:/机器人控制|robot control|机械臂|Jaco|Shadow Hand|dexterous|灵巧|Isaac|ALFRED/i}];function Te(a){let t=a.split(/\n# 阅读记录\s*\n/)[1]??a,e=[...t.matchAll(/^###\s+(.+?)\s*$/gm)],i=[...t.matchAll(/^##\s+(.+?)\s*$/gm)].map(s=>({index:s.index||0,date:nt(s[1])})).filter(s=>s.date),n=[];for(let s=0;s<e.length;s+=1){let o=e[s],r=o[1].trim(),l=te(r.match(/\[\[[^\]]+\]\]/)?.[0]||r);if(!l||/论文标题|Paper Title/i.test(l))continue;let d=(o.index||0)+o[0].length,c=e[s+1]?.index??t.length,p=t.slice(d,c),u=nt(Ne(p,["\u65E5\u671F","Date"]))||[...i].reverse().find(j=>j.index<(o.index||0))?.date||"",g=wt(p,["\u65B9\u5411","\u7814\u7A76\u65B9\u5411","Direction","Research Direction","Topic","Topics","Keywords"]),m=wt(p,["\u4EFB\u52A1","\u6838\u5FC3\u95EE\u9898","Task","Problem","Goal","Objective","Question"]),v=E(p,"\u603B\u89C8\u6D41\u7A0B")||E(p,"Overview"),y=E(p,"\u7F51\u7EDC\u7ED3\u6784")||E(p,"Structure")||E(p,"Architecture")||E(p,"Methods"),P=E(p,"\u521B\u65B0\u70B9")||E(p,"Innovations")||E(p,"Contributions"),S=E(p,"\u76F8\u5173\u7B97\u6CD5\u6216\u516C\u5F0F")||E(p,"Algorithms")||E(p,"Methods"),I=E(p,"\u603B\u7ED3")||E(p,"Summary"),A=[...Mn(S).filter(j=>/算法|Algorithm/i.test(j)).flatMap(K),...vt(S).filter(j=>/算法|Algorithm/i.test(j)).flatMap(K)],N=vt(S).filter(j=>/公式|机制|Formula|Mechanism/i.test(j)).flatMap(K),kt=Jt(v),ie=D([...Jt(y),...vt(y).flatMap(K),...wt(p,["\u6838\u5FC3\u65B9\u6CD5","Method","Methods"])]),ne=D([...vt(P).flatMap(K),...wt(p,["\u6838\u5FC3\u521B\u65B0","Contribution","Contributions"])]),Je=In([l,p,g.join(" "),m.join(" "),ie.join(" "),ne.join(" "),A.join(" ")].join(`
`));n.push({title:l,date:u,paperFile:Ne(p,["\u8BBA\u6587\u539F\u6587","PDF","Paper"]),direction:g,task:m,topics:Je,flowNodes:kt,structureNodes:ie,innovations:ne,algorithms:D(A),formulas:D(N),summary:b(I).slice(0,900)})}return n}function Ke(a){let t=[],e=(r,l,d)=>{for(let c of d)t.push({paper:r.title,relation:l,concept:c})};for(let r of a)e(r,"\u89E3\u51B3",r.task),e(r,"\u5C5E\u4E8E",r.direction),e(r,"\u6D89\u53CA\u4E3B\u9898",r.topics),e(r,"\u5305\u542B\u7ED3\u6784",r.structureNodes),e(r,"\u63D0\u51FA",r.innovations),e(r,"\u4F7F\u7528",r.algorithms),e(r,"\u4F7F\u7528\u516C\u5F0F",r.formulas);let i=[],n=new Set,s=(r,l,d,c,p,u="\u4E2D")=>{if(!r||!d||r===d)return;let g=[r,l,d,c].sort().join("|");n.has(g)||(n.add(g),i.push({source:r,relation:l,target:d,evidence:c,sourceType:p,strength:u}))},o=[["task","\u5171\u4EAB\u4EFB\u52A1"],["direction","\u5171\u4EAB\u65B9\u5411"],["topics","\u5171\u4EAB\u4E3B\u9898"],["structureNodes","\u5171\u4EAB\u7ED3\u6784\u8282\u70B9"],["innovations","\u5171\u4EAB\u521B\u65B0\u70B9"],["algorithms","\u5171\u4EAB\u7B97\u6CD5"],["formulas","\u5171\u4EAB\u516C\u5F0F/\u673A\u5236"]];for(let[r,l]of o){let d=new Map;for(let c of a){let p=Array.isArray(c[r])?c[r]:[];for(let u of p)d.has(u)||d.set(u,[]),d.get(u)?.push(c.title)}for(let[c,p]of d.entries()){let u=D(p);for(let g=0;g<u.length;g+=1)for(let m=g+1;m<u.length;m+=1)s(u[g],l,u[m],c,r==="topics"?"\u4E3B\u9898\u5F52\u4E00\u5316":"\u89C4\u5219")}}for(let r=0;r<a.length;r+=1)for(let l=r+1;l<a.length;l+=1){let d=a[r],c=a[l],p=D([...bt(d.topics,c.topics),...bt(d.direction,c.direction),...bt(d.algorithms,c.algorithms),...bt(d.structureNodes,c.structureNodes)]);if(p.length<2)continue;let u=`\u5171\u4EAB\u8282\u70B9\uFF1A${p.slice(0,8).join("\u3001")}`;s(d.title,$n(p),c.title,u,"\u672C\u5730\u5F52\u4E00\u5316",p.length>=4?"\u9AD8":"\u4E2D")}return{edges:i,conceptEdges:Ln(t)}}function Cn(a){let t=new Date().toISOString(),e=new Map(a.papers.map((o,r)=>[o.title,`P${r+1}`])),i=["```mermaid","flowchart LR",...a.papers.map(o=>` ${e.get(o.title)}["${Re(`${e.get(o.title)} ${o.title}`,58)}"]`),...a.edges.slice(0,80).map(o=>{let r=e.get(o.source),l=e.get(o.target);return r&&l?` ${r} ---|"${Re(o.relation.replace(/^共享/,"\u5171\u4EAB "),26)}"| ${l}`:""}).filter(Boolean),"```"].join(`
`),n=a.edges.slice().sort((o,r)=>(r.strength||"").localeCompare(o.strength||"")||o.source.localeCompare(r.source)).map(o=>`| ${G(L(o.source))} | ${G(o.relation)} | ${G(L(o.target))} | ${G(o.evidence)} | ${G(o.sourceType)} |`),s=Array.from(Qt(a.conceptEdges.filter(o=>o.relation==="\u6D89\u53CA\u4E3B\u9898"),o=>o.concept).entries()).sort((o,r)=>r[1].length-o[1].length).map(([o,r])=>`| ${G(L(o))} | ${r.length} | ${G(D(r.map(l=>L(l.paper))).join("\u3001"))} |`);return["---","type: diy-pet-reading-graph",`generated: "${t}"`,`source: "[[${a.readingLogPath.replace(/\.md$/i,"")}]]"`,"---","","# \u77E5\u8BC6\u56FE\u8C31","",`> \u7531 DIY Desktop Pet \u5728\u672C\u5730\u751F\u6210\u3002\u6765\u6E90\uFF1A[[${a.readingLogPath.replace(/\.md$/i,"")}]]\u3002`,"","## \u603B\u89C8","",`- \u8BBA\u6587\u6570\u91CF\uFF1A${a.papers.length}`,`- \u8BBA\u6587\u5173\u7CFB\uFF1A${a.edges.length}`,`- \u5185\u5BB9\u8282\u70B9\uFF1A${a.conceptEdges.length}`,"","## \u8BBA\u6587\u5173\u7CFB\u56FE","",i,"","## \u8BBA\u6587\u5173\u7CFB","",n.length?["| \u8BBA\u6587\u4E00 | \u5173\u7CFB | \u8BBA\u6587\u4E8C | \u4F9D\u636E | \u6765\u6E90 |","| --- | --- | --- | --- | --- |",...n].join(`
`):"\u6682\u65E0\u8BBA\u6587\u5173\u7CFB\u3002","","## \u4E3B\u9898\u7D22\u5F15","",s.length?["| \u4E3B\u9898 | \u8BBA\u6587\u6570 | \u76F8\u5173\u8BBA\u6587 |","| --- | ---: | --- |",...s].join(`
`):"\u6682\u65E0\u4E3B\u9898\u8282\u70B9\u3002",""].join(`
`)}function An(a){let t=new Date().toISOString(),e=Ke(a.papers),i=Qt(a.papers.flatMap(c=>c.topics.map(p=>({topic:p,paper:c}))),c=>c.topic),n=Qt(a.papers.flatMap(c=>(c.direction.length?c.direction:c.topics.slice(0,2)).map(u=>({direction:u,paper:c}))),c=>c.direction),s=Array.from(i.entries()).sort((c,p)=>p[1].length-c[1].length).slice(0,8),o=Array.from(n.entries()).sort((c,p)=>p[1].length-c[1].length).slice(0,8),r=a.papers.map(c=>{let p=D([...c.algorithms,...c.structureNodes,...c.innovations,...c.topics]).slice(0,4).join("\u3001")||"\u672A\u89E3\u6790\u5230\u65B9\u6CD5\u8282\u70B9";return`- ${c.date||"\u672A\u6807\u65E5\u671F"} ${L(c.title)}\uFF1A${p}`}),l=kn(a.papers),d=Sn(a.papers,s.map(([c])=>c));return["---","type: diy-pet-reading-analysis",`generated: "${t}"`,`range: "${a.rangeLabel}"`,`source: "[[${a.readingLogPath.replace(/\.md$/i,"")}]]"`,"---","","# \u9636\u6BB5\u9605\u8BFB\u5206\u6790","",`> \u5206\u6790\u8303\u56F4\uFF1A${a.rangeLabel}\u3002\u7531 DIY Desktop Pet \u5728\u672C\u5730\u751F\u6210\u3002`,"","## \u9605\u8BFB\u8BBA\u6587","",...a.papers.map(c=>`- ${c.date||"\u672A\u6807\u65E5\u671F"}\uFF1A${L(c.title)}`),"","## \u603B\u4F53\u603B\u7ED3","",xn(a.papers,s.map(([c])=>c),e.edges),"","## \u65B9\u5411\u5206\u6790","",...o.flatMap(([c,p])=>[`### ${c}`,`- \u76F8\u5173\u8BBA\u6587\uFF1A${D(p.map(u=>L(u.paper.title))).join("\u3001")}`,`- \u5206\u6790\uFF1A\u8FD9\u4E2A\u65B9\u5411\u76EE\u524D\u8986\u76D6 ${p.length} \u7BC7\u8BBA\u6587\uFF0C\u6838\u5FC3\u5173\u6CE8 ${D(p.flatMap(u=>u.paper.topics)).slice(0,5).join("\u3001")||"\u5C1A\u672A\u89E3\u6790\u5230\u4E3B\u9898"}\u3002`,""]),"## \u5185\u5BB9\u4E3B\u9898\u5206\u6790","",...s.flatMap(([c,p])=>[`### ${c}`,`- \u76F8\u5173\u8BBA\u6587\uFF1A${D(p.map(u=>L(u.paper.title))).join("\u3001")}`,`- \u5206\u6790\uFF1A\u8BE5\u4E3B\u9898\u5728\u5F53\u524D\u9605\u8BFB\u8BB0\u5F55\u4E2D\u51FA\u73B0 ${p.length} \u6B21\uFF0C\u53EF\u4F5C\u4E3A\u540E\u7EED\u7EFC\u8FF0\u6216\u77E5\u8BC6\u56FE\u8C31\u7684\u4E3B\u7EBF\u8282\u70B9\u3002`,""]),"## \u65B9\u6CD5\u8109\u7EDC","",...r,"","## \u5173\u952E\u5173\u8054","",...e.edges.slice(0,12).map(c=>`- ${L(c.source)} -> ${c.relation} -> ${L(c.target)}\uFF1A${c.evidence}`),"","## \u9605\u8BFB\u7F3A\u53E3","",...l.map(c=>`- ${c}`),"","## \u4E0B\u4E00\u6B65\u884C\u52A8","",...d.map(c=>`- ${c}`),""].join(`
`)}function xn(a,t,e){let i=t.length?t.slice(0,6).join("\u3001"):"\u5C1A\u672A\u5F62\u6210\u7A33\u5B9A\u4E3B\u9898",n=e.length?`\u672C\u5730\u89C4\u5219\u8BC6\u522B\u51FA ${e.length} \u6761\u8BBA\u6587\u95F4\u5173\u7CFB`:"\u8BBA\u6587\u95F4\u5173\u7CFB\u8FD8\u6BD4\u8F83\u7A00\u758F";return`\u5F53\u524D\u9636\u6BB5\u5171\u8BB0\u5F55 ${a.length} \u7BC7\u8BBA\u6587\uFF0C\u4E3B\u8981\u96C6\u4E2D\u5728 ${i}\u3002${n}\u3002\u5EFA\u8BAE\u540E\u7EED\u56F4\u7ED5\u9AD8\u9891\u4E3B\u9898\u8865\u9F50\u5BF9\u6BD4\u57FA\u7EBF\u3001\u8BC4\u4F30\u65B9\u6CD5\u548C\u843D\u5730\u573A\u666F\uFF0C\u8BA9\u9605\u8BFB\u8BB0\u5F55\u4E0D\u53EA\u662F\u5355\u7BC7\u6458\u8981\uFF0C\u800C\u80FD\u5F62\u6210\u53EF\u590D\u7528\u7684\u65B9\u6CD5\u8109\u7EDC\u3002`}function kn(a){let t=a.map(i=>[i.title,...i.topics,...i.direction,i.summary].join(" ")).join(`
`),e=[];return/评估|benchmark|evaluation|实验|成功率/i.test(t)||e.push("\u8BC4\u4F30\u7EF4\u5EA6\u504F\u5C11\uFF1A\u5EFA\u8BAE\u8865\u5145 benchmark\u3001\u6307\u6807\u3001\u5BF9\u6BD4\u57FA\u7EBF\u548C\u5931\u8D25\u6848\u4F8B\u3002"),/安全|对齐|human feedback|偏好|安全/i.test(t)||e.push("\u4EBA\u7C7B\u504F\u597D\u4E0E\u5B89\u5168\u7EA6\u675F\u8986\u76D6\u4E0D\u8DB3\uFF1A\u5982\u679C\u7814\u7A76 Agent \u843D\u5730\uFF0C\u5EFA\u8BAE\u8865\u8BFB human feedback\u3001alignment \u6216 safety \u76F8\u5173\u5DE5\u4F5C\u3002"),/真实|real robot|sim2real|部署|硬件/i.test(t)||e.push("\u771F\u5B9E\u73AF\u5883\u843D\u5730\u7EBF\u7D22\u4E0D\u8DB3\uFF1A\u5EFA\u8BAE\u5173\u6CE8 Sim2Real\u3001\u771F\u5B9E\u673A\u5668\u4EBA\u6216\u5B9E\u9645\u5E94\u7528\u90E8\u7F72\u8BBA\u6587\u3002"),/消融|ablation|局限|limitation/i.test(t)||e.push("\u6279\u5224\u6027\u9605\u8BFB\u8FD8\u53EF\u4EE5\u52A0\u5F3A\uFF1A\u6BCF\u7BC7\u8BB0\u5F55\u6700\u597D\u8865\u4E0A\u6D88\u878D\u5B9E\u9A8C\u3001\u5C40\u9650\u548C\u9002\u7528\u8FB9\u754C\u3002"),e.length?e:["\u5F53\u524D\u8BB0\u5F55\u5DF2\u7ECF\u8986\u76D6\u65B9\u6CD5\u3001\u8BC4\u4F30\u548C\u5E94\u7528\u7EBF\u7D22\uFF1B\u4E0B\u4E00\u6B65\u53EF\u4EE5\u505A\u6A2A\u5411\u8868\u683C\uFF0C\u5BF9\u6BD4\u5404\u65B9\u6CD5\u7684\u8F93\u5165\u3001\u8F93\u51FA\u3001\u53CD\u9988\u4FE1\u53F7\u548C\u9650\u5236\u3002"]}function Sn(a,t){let e=["\u628A\u6BCF\u7BC7\u8BBA\u6587\u7684 `\u65B9\u5411` \u63A7\u5236\u5728 2-5 \u4E2A\u7A33\u5B9A\u53CC\u94FE\uFF0C\u4F8B\u5982 [[\u6280\u80FD\u8FDB\u5316]]\u3001[[\u5F3A\u5316\u5B66\u4E60]]\u3001[[\u5177\u8EAB\u667A\u80FD]]\uFF0C\u907F\u514D\u540C\u4E49\u8BCD\u5206\u6563\u3002","\u7ED9\u6BCF\u7BC7\u8BBA\u6587\u8865\u4E00\u6761 `\u4EFB\u52A1` \u53CC\u94FE\u548C 2-4 \u4E2A\u7B97\u6CD5/\u673A\u5236\u53CC\u94FE\uFF0C\u77E5\u8BC6\u56FE\u8C31\u4F1A\u66F4\u5BB9\u6613\u8FDE\u8FB9\u3002","\u5728\u65B0\u589E\u8BBA\u6587\u540E\u8BA9\u5BA0\u7269\u6267\u884C `\u521B\u5EFA\u77E5\u8BC6\u56FE\u8C31`\uFF0C\u518D\u6267\u884C `\u5206\u6790\u9605\u8BFB\u8BB0\u5F55`\uFF0C\u5F62\u6210\u201C\u5355\u7BC7\u8BB0\u5F55 -> \u56FE\u8C31 -> \u9636\u6BB5\u590D\u76D8\u201D\u7684\u95ED\u73AF\u3002"];return t.includes("\u6280\u80FD\u8FDB\u5316")&&e.push("\u56F4\u7ED5\u6280\u80FD\u8FDB\u5316\u7EBF\uFF0C\u505A\u4E00\u5F20\u5BF9\u6BD4\u8868\uFF1A\u6280\u80FD\u8868\u793A\u3001\u66F4\u65B0\u89E6\u53D1\u3001\u53CD\u9988\u4FE1\u53F7\u3001\u662F\u5426\u8BAD\u7EC3\u6A21\u578B\u3001\u8BC4\u4F30\u73AF\u5883\u3002"),t.includes("\u5956\u52B1\u8BBE\u8BA1")&&e.push("\u56F4\u7ED5\u5956\u52B1\u8BBE\u8BA1\u7EBF\uFF0C\u6BD4\u8F83\u624B\u5199\u5956\u52B1\u3001LLM \u751F\u6210\u5956\u52B1\u3001human feedback \u548C\u771F\u5B9E\u4EFB\u52A1 fitness \u7684\u5173\u7CFB\u3002"),a.length>=8&&e.push("\u8BBA\u6587\u6570\u91CF\u5DF2\u7ECF\u8DB3\u591F\uFF0C\u53EF\u4EE5\u6BCF\u5468\u751F\u6210\u4E00\u6B21\u9636\u6BB5\u5206\u6790\uFF0C\u628A\u9AD8\u9891\u4E3B\u9898\u8F6C\u6210\u4E0B\u4E00\u9636\u6BB5\u9605\u8BFB\u8BA1\u5212\u3002"),e}function Xe(a){let t=a.toLowerCase(),e=0;return(/阅读记录/.test(a)||/reading[-_\s]?log|research[-_\s]?log|paper[-_\s]?log/.test(t))&&(e+=80),(/阅读总结|论文/.test(a)||/reading|papers?|literature|review|research/.test(t))&&(e+=20),t.endsWith(".md")&&(e+=5),e}function En(a){return Xe(a)>=80}function nt(a){let t=String(a||"").match(/(\d{4})[-/](\d{1,2})[-/](\d{1,2})/);return t?`${t[1]}-${t[2].padStart(2,"0")}-${t[3].padStart(2,"0")}`:""}function Ie(a,t){let e=t==="from"?"(?:from|\u8D77\u59CB|\u5F00\u59CB|\u4ECE)":"(?:to|\u622A\u6B62|\u7ED3\u675F|\u5230|\u81F3)",i=new RegExp(`${e}\\s*[:\uFF1A]?\\s*(\\d{4}[-/]\\d{1,2}[-/]\\d{1,2})`,"i");return nt(a.match(i)?.[1]||"")}function Dn(a){let t=a.match(/(?:最近|recent)\s*(\d{1,3})\s*(?:篇|papers?)?/i);return t?Number(t[1]):0}function $e(a){let t=a.match(/(?:path|文件|路径)\s*[::]\s*([^\n,。;;]+\.md)/i)?.[1];return t?t.trim():a.match(/([^\s"',。;;]+\.md)/i)?.[1]?.trim()||""}function Le(a){if(!a.ok)return a.error||"\u5DE5\u5177\u6267\u884C\u5931\u8D25\u3002";let t=a.result;return t?.message?t.message:"\u5DE5\u5177\u6267\u884C\u5B8C\u6210\u3002"}function Ne(a,t){for(let e of t){let i=a.match(new RegExp(`^\\s*(?:[-*]\\s*)?${st(e)}\\s*[:\uFF1A]\\s*(.+)$`,"mi"));if(i?.[1])return i[1].trim()}return""}function wt(a,t){return D(t.flatMap(e=>{let i=a.match(new RegExp(`^\\s*(?:[-*]\\s*)?${st(e)}\\s*[:\uFF1A]\\s*(.+)$`,"mi"));return i?.[0]?K(i[0]):[]}))}function E(a,t){let e=new RegExp(`^####\\s+${st(t)}\\s*\\n([\\s\\S]*?)(?=^####\\s+|^###\\s+|^##\\s+|$)`,"m");return a.match(e)?.[1]?.trim()||""}function vt(a){return a.split(/\r?\n/).filter(t=>/^\s*[-*]\s+/.test(t))}function Mn(a){return a.split(/\r?\n/).filter(t=>/^#####\s+/.test(t))}function Jt(a){return D([...a.matchAll(/\[\[[^\]]+\]\]/g)].map(t=>te(t[0])).filter(t=>!Zt(t)))}function K(a){let t=Jt(a);if(t.length)return t;let e=b(a).replace(/^(日期|Date|论文原文|PDF|Paper|方向|研究方向|Direction|Research Direction|Topic|Topics|Keywords|任务|核心问题|Task|Problem|Goal|Objective|Question|核心方法|Method|Methods|核心创新|Contribution|Contributions|算法|Algorithm|Algorithms|公式\s*\/?\s*机制|Formula|Mechanism)\s*[::]\s*/i,"").replace(/^#{1,6}\s*/,"").replace(/^\s*[-*]\s*/,"").trim();return!e||e.length>100||Zt(e)?[]:Tn(e).filter(i=>!Zt(i))}function Tn(a){let e=a.split(/[、,,;;/]+/).map(i=>i.trim()).filter(Boolean).flatMap(i=>{let n=i.split(/\s+/).filter(Boolean);return n.length>1&&n.length<=5&&n.every(o=>/^[\u4e00-\u9fffA-Za-z0-9_-]+$/.test(o)&&/[\u4e00-\u9fff]/.test(o))?n.filter(o=>o.length>=2):[i]});return D(e)}function te(a){let t=String(a||"").trim();return t.startsWith("[[")?t.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|").pop()?.replace(/\s+/g," ").trim()||"":t.replace(/\s+/g," ").trim()}function L(a){return`[[${te(a)}]]`}function In(a){return Pn.filter(t=>t.pattern.test(a)).map(t=>t.node)}function Zt(a){return!a||/论文标题|研究方向|任务或问题|输入或数据|输出或结果|步骤\d*|算法名称|公式或机制|文件名\.pdf/i.test(a)||/^Pasted image/i.test(a)||/\.(png|jpe?g|gif|webp|svg|pdf)$/i.test(a)}function $n(a){let t=a.join(" ");return/技能|Skill/i.test(t)&&/具身|机器人|ALFRED|控制|灵巧/i.test(t)?"\u5177\u8EAB\u6280\u80FD\u5B66\u4E60\u76F8\u5173":/技能|Skill/i.test(t)&&/记忆|Memory|SkillRepo|技能库/i.test(t)?"\u6280\u80FD\u8BB0\u5FC6\u7814\u7A76\u7EBF":/反思|反馈|Reflection|Prompt/i.test(t)?"\u53CD\u9988\u53CD\u601D\u673A\u5236\u76F8\u5173":/强化学习|奖励|Reward|RL/i.test(t)?"\u5F3A\u5316\u5B66\u4E60\u95ED\u73AF\u76F8\u5173":"\u4E3B\u9898\u76F8\u5173"}function D(a){return Array.from(new Set(a.map(t=>t.trim()).filter(Boolean)))}function bt(a,t){let e=new Set(t);return a.filter(i=>e.has(i))}function Ln(a){let t=new Set;return a.filter(e=>{let i=`${e.paper}|${e.relation}|${e.concept}`;return t.has(i)?!1:(t.add(i),!0)})}function Qt(a,t){let e=new Map;for(let i of a){let n=t(i);e.has(n)||e.set(n,[]),e.get(n)?.push(i)}return e}function G(a){return String(a??"").replace(/\r?\n/g,"<br>").replace(/\|/g,"\\|").trim()||" "}function Re(a,t){let e=b(a).replace(/"/g,"'").replace(/\|/g,"/").replace(/[\[\]<>`]/g,"").replace(/\s+/g," ").trim();return e.length>t?`${e.slice(0,t-3)}...`:e}function ee(a,t){let e=b(a).replace(/\s+/g," ").trim();return e.length>t?`${e.slice(0,t)}...`:e}