@nagellabs/libi 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/build-manifest.json +5 -5
- package/.next/diagnostics/route-bundle-stats.json +16 -16
- package/.next/externals-manifest.json +1 -1
- package/.next/fallback-build-manifest.json +3 -3
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/(app)/editor/page/build-manifest.json +2 -2
- package/.next/server/app/(app)/instructions/page/build-manifest.json +2 -2
- package/.next/server/app/(app)/mcps-skills/page/build-manifest.json +2 -2
- package/.next/server/app/(app)/mcps-skills/skills/[name]/page/build-manifest.json +2 -2
- package/.next/server/app/(app)/mcps-skills/skills/new/page/build-manifest.json +2 -2
- package/.next/server/app/(app)/settings/page/build-manifest.json +2 -2
- package/.next/server/app/_global-error/page/build-manifest.json +2 -2
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page/build-manifest.json +2 -2
- package/.next/server/app/api/agent/cancel/route.js +8 -8
- package/.next/server/app/api/agent/cancel/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/detect/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/dispatch/route.js +5 -5
- package/.next/server/app/api/agent/dispatch/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/events/route.js +11 -11
- package/.next/server/app/api/agent/events/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/messages/route.js +7 -7
- package/.next/server/app/api/agent/messages/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/providers/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/send/route.js +7 -7
- package/.next/server/app/api/agent/send/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/start/route.js +7 -7
- package/.next/server/app/api/agent/start/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/stop/route.js +8 -8
- package/.next/server/app/api/agent/stop/route.js.nft.json +1 -1
- package/.next/server/app/api/agents/[agentId]/install/route.js +4 -4
- package/.next/server/app/api/agents/[agentId]/install/route.js.nft.json +1 -1
- package/.next/server/app/api/codex/connect/route.js.nft.json +1 -1
- package/.next/server/app/api/db/resolve/route.js +9 -9
- package/.next/server/app/api/db/resolve/route.js.nft.json +1 -1
- package/.next/server/app/api/export/chromium/route.js +5 -5
- package/.next/server/app/api/export/chromium/route.js.nft.json +1 -1
- package/.next/server/app/api/export/route.js +4 -4
- package/.next/server/app/api/export/route.js.nft.json +1 -1
- package/.next/server/app/api/files/by-id/[fileId]/filmstrip-status/route.js +4 -4
- package/.next/server/app/api/files/by-id/[fileId]/filmstrip-status/route.js.nft.json +1 -1
- package/.next/server/app/api/files/by-id/[fileId]/rename/route.js +7 -7
- package/.next/server/app/api/files/by-id/[fileId]/rename/route.js.nft.json +1 -1
- package/.next/server/app/api/folders/[folderId]/duplicate/route.js +6 -6
- package/.next/server/app/api/folders/[folderId]/duplicate/route.js.nft.json +1 -1
- package/.next/server/app/api/install-from-url/route.js +10 -10
- package/.next/server/app/api/install-from-url/route.js.nft.json +1 -1
- package/.next/server/app/api/instructions/override/route.js.nft.json +1 -1
- package/.next/server/app/api/jobs/[id]/events/route.js +8 -8
- package/.next/server/app/api/jobs/[id]/events/route.js.nft.json +1 -1
- package/.next/server/app/api/jobs/[id]/retry/route.js +4 -4
- package/.next/server/app/api/jobs/[id]/retry/route.js.nft.json +1 -1
- package/.next/server/app/api/jobs/[id]/route.js +4 -4
- package/.next/server/app/api/jobs/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/jobs/[id]/status/route.js +3 -3
- package/.next/server/app/api/jobs/[id]/status/route.js.nft.json +1 -1
- package/.next/server/app/api/jobs/route.js +9 -9
- package/.next/server/app/api/jobs/route.js.nft.json +1 -1
- package/.next/server/app/api/notify/route.js.nft.json +1 -1
- package/.next/server/app/api/pieces/[pieceId]/duplicate/route.js +4 -4
- package/.next/server/app/api/pieces/[pieceId]/duplicate/route.js.nft.json +1 -1
- package/.next/server/app/api/pieces/[pieceId]/tracks/[trackId]/manual-anchors/apply-deletes/route.js +9 -9
- package/.next/server/app/api/pieces/[pieceId]/tracks/[trackId]/manual-anchors/apply-deletes/route.js.nft.json +1 -1
- package/.next/server/app/api/pieces/[pieceId]/tracks/[trackId]/manual-anchors/route.js +9 -9
- package/.next/server/app/api/pieces/[pieceId]/tracks/[trackId]/manual-anchors/route.js.nft.json +1 -1
- package/.next/server/app/api/render/frames/route.js +7 -7
- package/.next/server/app/api/render/frames/route.js.nft.json +1 -1
- package/.next/server/app/api/runtime/update/route.js +5 -5
- package/.next/server/app/api/runtime/update/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[sessionId]/activate/route.js +8 -8
- package/.next/server/app/api/sessions/[sessionId]/activate/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[sessionId]/context/route.js +8 -8
- package/.next/server/app/api/sessions/[sessionId]/context/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[sessionId]/deactivate/route.js +8 -8
- package/.next/server/app/api/sessions/[sessionId]/deactivate/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[sessionId]/model/route.js +7 -7
- package/.next/server/app/api/sessions/[sessionId]/model/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[sessionId]/permission/route.js +7 -7
- package/.next/server/app/api/sessions/[sessionId]/permission/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/permission-modes/route.js +7 -7
- package/.next/server/app/api/sessions/permission-modes/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/route.js +7 -7
- package/.next/server/app/api/sessions/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/mcp-servers/[id]/dependencies/route.js +7 -7
- package/.next/server/app/api/settings/mcp-servers/[id]/dependencies/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/mcp-servers/[id]/install-plan/route.js +5 -5
- package/.next/server/app/api/settings/mcp-servers/[id]/install-plan/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/mcp-servers/[id]/retry/route.js +7 -7
- package/.next/server/app/api/settings/mcp-servers/[id]/retry/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/mcp-servers/[id]/retry-dep/route.js +7 -7
- package/.next/server/app/api/settings/mcp-servers/[id]/retry-dep/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/mcp-servers/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/mcp-servers/resync/route.js +7 -7
- package/.next/server/app/api/settings/mcp-servers/resync/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/memories/route.js.nft.json +1 -1
- package/.next/server/app/api/skill-eval/configure/route.js +8 -8
- package/.next/server/app/api/skill-eval/configure/route.js.nft.json +1 -1
- package/.next/server/app/api/terminal/sessions/route.js +2 -2
- package/.next/server/app/api/terminal/ws-info/route.js.nft.json +1 -1
- package/.next/server/app/api/tracking/run/route.js +4 -4
- package/.next/server/app/api/tracking/run/route.js.nft.json +1 -1
- package/.next/server/app/page/build-manifest.json +2 -2
- package/.next/server/chunks/[root-of-the-server]__04thdbt._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__04thdbt._.js.map +2 -2
- package/.next/server/chunks/[root-of-the-server]__05bfu4m._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__05bfu4m._.js.map +2 -2
- package/.next/server/chunks/[root-of-the-server]__09qyvq1._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__09qyvq1._.js.map +2 -2
- package/.next/server/chunks/[root-of-the-server]__0gnut6f._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__0gnut6f._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__0l_-iy7._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__0l_-iy7._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__0s0b6ty._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__0s0b6ty._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__0sj68ta._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__0sj68ta._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__10oxitf._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__10oxitf._.js.map +2 -2
- package/.next/server/chunks/[root-of-the-server]__11.cp_g._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__11.cp_g._.js.map +2 -2
- package/.next/server/chunks/_04i643i._.js +3 -3
- package/.next/server/chunks/_0_t4b-f._.js +4 -4
- package/.next/server/chunks/_0gc3hkv._.js +3 -3
- package/.next/server/chunks/_0hainf0._.js +4 -4
- package/.next/server/chunks/_0jrwb4i._.js +3 -3
- package/.next/server/chunks/_0ms~zo_._.js +3 -3
- package/.next/server/chunks/_0ou5g0c._.js +4 -4
- package/.next/server/chunks/_0ovzm6d._.js +4 -4
- package/.next/server/chunks/_0pwx1vo._.js +3 -3
- package/.next/server/chunks/_0snzqta._.js +4 -4
- package/.next/server/chunks/lib_08x49mw._.js +3 -3
- package/.next/server/chunks/lib_runtime_runtime-prune_ts_0eaw~-q._.js +3 -3
- package/.next/server/chunks/node_modules_003ody_._.js +3 -3
- package/.next/server/chunks/ssr/_0675jux._.js +3 -3
- package/.next/server/instrumentation.js.nft.json +1 -1
- package/.next/server/middleware-build-manifest.js +5 -5
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.js +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/{0tfripjpjgh0x.js → 0rgnvt2t.fexk.js} +3 -3
- package/.next/static/chunks/{turbopack-0nj3aucu1vtlz.js → turbopack-06tait4frhc5a.js} +3 -3
- package/.next/trace-build +1 -1
- package/THIRD-PARTY-NOTICES.md +1 -1
- package/dist-cli/BUILD_INFO.json +6 -6
- package/dist-cli/lib/analytics/config.js +1 -1
- package/dist-cli/lib/install/next-externals.js +6 -1
- package/dist-cli/lib/onboarding/piece/v1/index.js +5 -1
- package/dist-cli/lib/server/next-server.js +12 -2
- package/lib/analytics/config.ts +15 -2
- package/lib/install/next-externals.ts +36 -1
- package/lib/onboarding/piece/v1/index.ts +5 -1
- package/lib/server/next-server.ts +29 -4
- package/package.json +1 -1
- /package/.next/static/{AKrgjfjGvLuWkXofXFBpx → 05vWgPQtQKJ6EuLHg8nZ3}/_buildManifest.js +0 -0
- /package/.next/static/{AKrgjfjGvLuWkXofXFBpx → 05vWgPQtQKJ6EuLHg8nZ3}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{AKrgjfjGvLuWkXofXFBpx → 05vWgPQtQKJ6EuLHg8nZ3}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="
|
|
1
|
+
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="a113923a-565c-0148-8e48-67981226f105")}catch(e){}}();
|
|
2
2
|
module.exports=[246682,e=>{"use strict";var t=e.i(233405),A=e.i(640911),r=e.i(190793),i=e.i(478181),n=e.i(875225),s=e.i(49614),o=e.i(665455),a=e.i(107500);async function l(e){let t=(0,r.getDb)();t.update(i.mcpServers).set({serverStatus:"starting",serverLastChecked:new Date,updatedAt:new Date}).where((0,n.eq)(i.mcpServers.id,e.id)).run();let[l]=t.select().from(i.mcpServers).where((0,n.eq)(i.mcpServers.id,e.id)).limit(1).all(),c=l?.envVars?JSON.parse(l.envVars):{},h=(0,s.buildSpawnEnv)(c),d=(0,o.resolveBundledSpawn)(e);A.serverLogger.info({tag:"mcp-probe",op:"probe_start",mcpId:e.id,command:d.command,args:d.args,spawnSource:d.source,envKeys:Object.keys(h).sort(),hasHome:"string"==typeof h.HOME&&h.HOME.length>0,timeoutMs:18e4},`Probing MCP server "${e.id}" (${d.source})`);let u=await g({command:d.command,args:d.args,env:h,timeoutMs:18e4}),E=function(e){if(!e)return[];let t=[],A=e=>{if(e)try{let A=JSON.parse(e);if(A&&"object"==typeof A)for(let e of Object.values(A))"string"==typeof e&&e&&t.push(e)}catch{}};return A(e.envVars),A(e.headers),t}(l),Q=u.error?(0,a.scrubSecrets)(u.error,E):u.error;return t.update(i.mcpServers).set({serverStatus:u.status,serverError:Q,serverLastChecked:new Date,updatedAt:new Date}).where((0,n.eq)(i.mcpServers.id,e.id)).run(),"up"===u.status?A.serverLogger.info({tag:"mcp-probe",op:"probe_persisted",mcpId:e.id,status:u.status,durationMs:u.durationMs},`MCP server "${e.id}" is up`):A.serverLogger.warn({tag:"mcp-probe",op:"probe_persisted",mcpId:e.id,status:u.status,durationMs:u.durationMs,error:Q},`MCP server "${e.id}" is down`),u}async function g(e){let{command:r,args:i,env:n,timeoutMs:s=1e4}=e,o=Date.now();return A.serverLogger.debug({tag:"mcp-probe",op:"spawn",command:r,args:i,timeoutMs:s},"Spawning MCP child for probe"),new Promise(e=>{let a,l,g=!1,c="",h=0,d=null,u=null,E=t=>{if(!g){g=!0;try{l.kill("SIGTERM")}catch{}e(t)}};try{a=(l=(0,t.spawn)(r,i,{env:n,windowsHide:!0,stdio:["pipe","pipe","pipe"]})).pid,A.serverLogger.debug({tag:"mcp-probe",op:"spawned",command:r,pid:a},`MCP child spawned (pid=${a??"?"})`)}catch(t){let e=t instanceof Error?t.message:String(t);A.serverLogger.warn({tag:"mcp-probe",op:"spawn_failed",command:r,args:i,err:e},"Failed to spawn MCP child"),E({status:"down",error:e,durationMs:Date.now()-o});return}let Q=setTimeout(()=>{A.serverLogger.warn({tag:"mcp-probe",op:"timeout",command:r,pid:a,timeoutMs:s,stderrBytes:h,stderrLength:c.length,initSentAt:d,firstStdoutAt:u},`MCP probe timed out after ${s}ms`),E({status:"down",error:`MCP probe timed out after ${s}ms${c?`
|
|
3
3
|
stderr: ${c.slice(0,4096)}`:""}`,durationMs:Date.now()-o})},s);l.stderr?.on("data",e=>{let t=e.toString("utf-8");h+=e.length,(c+=t).length>8192&&(c=c.slice(-4096)),A.serverLogger.trace({tag:"mcp-probe",op:"stderr",command:r,pid:a,bytes:e.length,stderrLength:c.length},"MCP child stderr")}),l.on("error",e=>{clearTimeout(Q),A.serverLogger.warn({tag:"mcp-probe",op:"child_error",command:r,pid:a,err:e.message,stderrLength:c.length},"MCP child errored"),E({status:"down",error:`${e.message}${c?`
|
|
4
4
|
stderr: ${c.slice(0,4096)}`:""}`,durationMs:Date.now()-o})}),l.on("exit",(e,t)=>{g||(clearTimeout(Q),A.serverLogger.warn({tag:"mcp-probe",op:"exit_before_init",command:r,pid:a,code:e,signal:t,stderrLength:c.length},`MCP child exited before initialize (code=${e} signal=${t})`),E({status:"down",error:`MCP exited before initialize (code=${e} signal=${t})${c?`
|
|
@@ -164,7 +164,7 @@ For EACH distinct caption output a terse, NUMERIC, directly-usable spec:
|
|
|
164
164
|
|
|
165
165
|
Finally: one short paragraph on the SHARED motion language — do ALL captions live in the 3D world and move with the camera, or are they screen-space? This decides the whole rebuild.
|
|
166
166
|
|
|
167
|
-
Be terse and numeric. NO generic advice. One block per caption.`;await e.checkpoint({stage:"submitted"}),e.reportProgress(1,4,"step");let r=new AbortController,i=setInterval(()=>{e.shouldCancel()&&!r.signal.aborted&&r.abort()},1e3);try{t=(await h.generate({localPath:c,durationSeconds:g.mediaDuration??0,promptInstructions:A,onProgress:t=>e.reportProgress(2,4,"step"),signal:r.signal})).text}finally{clearInterval(i)}if(e.shouldCancel())throw Error("cancelled");return await e.checkpoint({stage:"received"}),e.reportProgress(3,4,"step"),await (0,z.saveCaptionSpec)({fileId:s,providerId:o,modelId:a,text:t}),e.reportProgress(4,4,"step"),er.info({op:"done",fileId:s,providerId:o,modelId:a,focus:l},"caption spec saved"),{captionSpec:t}}let d='You are watching a video and producing a production script that another text-to-video model could use to recreate it.\n\nOutput STRICTLY ONE JSON object with this shape. NO markdown fences. NO prose before or after. ONLY the JSON object.\n\nSchema (script_v1):\n{\n "schema_version": "script_v1",\n "duration": <number>, // seconds\n "overall_style": "<one or two sentence look-and-feel summary>",\n "pacing": "<optional short phrase>",\n "shots": [ // chronological, non-overlapping, covers full duration\n {\n "index": <0-based>,\n "start": <seconds>,\n "end": <seconds>,\n "description": "<detailed enough for a text-to-video model to recreate: subject, action, environment, lighting, framing, mood>",\n "action": "<optional verb-phrase>",\n "camera": { "shot": "close-up|medium|wide|extreme-wide", "angle": "eye-level|high|low|dutch", "motion": "static|pan|zoom|dolly|tracking|handheld|shake", "lens": "<optional>" },\n "lighting": "<optional, e.g. golden hour, low key>",\n "mood": "<optional>",\n "dialogue": "<spoken in this shot, verbatim if heard>",\n "text_on_screen": ["<optional>"],\n "transition_out": "cut|fade|dissolve|wipe|match"\n }\n ],\n "music": { // required\n "present": <true|false>,\n "genre": "<optional>",\n "mood": "<optional>",\n "tempo": "<optional, e.g. fast ~130bpm>",\n "instruments": ["<optional>"],\n "cues": [ { "timestamp": <seconds>, "description": "<music change point>" } ]\n },\n "sound_design": [ { "timestamp": <seconds>, "description": "<notable non-music audio event>" } ],\n "dialogue_summary": "<paraphrased; do NOT verbatim-transcribe long speeches>"\n}\n\nRules:\n- Walk the video chronologically. Cut a new shot when there is a visible cut, hard music change, or location change.\n- start / end are seconds from the start of the clip. They must not overlap and must cover the full duration.\n- description must be detailed enough for a text-to-video model to recreate the shot WITHOUT seeing it.\n- music.present is false if no music plays; otherwise fill genre/mood/tempo/instruments as best you can hear.\n- sound_design lists notable non-music audio events with timestamps (knocks, footsteps, dings, ambient).\n- dialogue_summary is paraphrased; full speech goes in shot.dialogue when relevant.\n- overall_style summarizes look-and-feel in one or two sentences (cinematic / UGC / animated / cartoon / etc.).\n- pacing is one short phrase (e.g. fast cuts, 8s avg shot, slow contemplative single take).\n- Do NOT include a `provider` field. The caller fills that in.\n\nOutput budget (so the JSON is never truncated):\n- Keep each shot.description ≤ 240 characters — dense, not flowery.\n- Merge adjacent near-identical shots. Aim for ≤ 16 shots total even for long videos.\n- Keep every other free-text field to one short phrase. The whole JSON must fit well under 5000 characters.\n\nReturn only the JSON object — no markdown, no commentary.',u=new Date().toISOString();await e.checkpoint({stage:"submitted"}),e.reportProgress(1,4,"step");let E=new AbortController,Q=setInterval(()=>{e.shouldCancel()&&!E.signal.aborted&&E.abort()},1e3),I=()=>h.estimateCostUsd?h.estimateCostUsd({durationSeconds:g.mediaDuration??0}):null;try{let t=await h.generate({localPath:c,durationSeconds:g.mediaDuration??0,promptInstructions:d,onProgress:t=>e.reportProgress(2,4,"step"),signal:E.signal});await e.checkpoint({stage:"received_first"}),e.reportProgress(2,4,"step");let n=K(t.text,{providerName:t.providerName,modelId:t.modelId??a,generatedAt:u,costUsd:I(),costEstimated:!0,requestId:t.requestId});if(n.ok)i=n.script;else{let t,s,l;er.warn({op:"validation_failed_first",error:n.error},"first attempt failed validation; retrying once");let Q=(A=n.error,r=h.maxPromptChars,t="\n\nYour previous output failed validation with the following errors:\n",s="\n\nReturn ONLY valid JSON conforming to script_v1 this time. NO markdown, NO commentary.",l=A,"number"==typeof r&&r>0&&(l=function(e,t){if(t<=0)return"";if(e.length<=t)return e;let A="\n…[error truncated]…\n";if(t<=A.length)return e.slice(0,t);let r=t-A.length,i=Math.ceil(.6*r),n=r-i;return e.slice(0,i)+A+e.slice(e.length-n)}(A,r-d.length-t.length-s.length-64)),d+t+l+s),B=await h.generate({localPath:c,durationSeconds:g.mediaDuration??0,promptInstructions:Q,onProgress:t=>e.reportProgress(2,4,"step"),signal:E.signal}),C=K(B.text,{providerName:B.providerName,modelId:B.modelId??a,generatedAt:u,costUsd:null===I()?null:2*I(),costEstimated:!0,requestId:B.requestId});if(!C.ok)throw Error(`Script provider ${o} returned invalid output on both attempts. Last error: ${C.error}`);i=C.script}}finally{clearInterval(Q)}if(e.shouldCancel())throw Error("cancelled");return await e.checkpoint({stage:"validated"}),e.reportProgress(3,4,"step"),await (0,z.saveScript)({fileId:s,providerId:o,modelId:a,script:i}),e.reportProgress(4,4,"step"),er.info({op:"done",fileId:s,providerId:o,modelId:a},"script saved"),{script:i}}};e.s(["extraAnalysisModelRunner",0,ei],291083);var en=e.i(912714),es=e.i(775719),eo=e.i(867773),ea=e.i(153708),el=e.i(511956);async function eg(e,t){let A=e.body;if(!A){let A=Buffer.from(await e.arrayBuffer());if(A.byteLength>t)throw Error(`file too large: ${A.byteLength} bytes (max ${t})`);return A}let r=A.getReader(),i=[],n=0,s=!1;try{for(;;){let{done:e,value:A}=await r.read();if(e)break;if(A){if((n+=A.byteLength)>t)throw s=!0,Error(`file too large: exceeds ${t} bytes`);i.push(Buffer.from(A))}}}finally{r.releaseLock(),s&&A.cancel().catch(()=>{})}return Buffer.concat(i,n)}async function ec(e){let{url:t,guard:A}=e,r=e.maxBytes??524288e3,i=await (0,eo.fetchFollowingVettedRedirects)(t,A,{signal:e.signal??AbortSignal.timeout(12e4)});if(!i.ok)throw Error(`http ${i.status}`);let n=Number(i.headers.get("content-length"));if(Number.isFinite(n)&&n>r)throw Error(`file too large: ${n} bytes (max ${r})`);let s=await eg(i,r),o=e.filename||q.default.basename(new URL(t).pathname)||"download.bin",a=function(e){if(!e)return null;let t=e.split(";")[0].trim().toLowerCase();return t&&"application/octet-stream"!==t?e:null}(i.headers.get("content-type"))??(0,el.mimeFromExtension)(o);return{buffer:s,filename:o,contentType:a}}let eh=/^[0-9a-f]{64}$/;async function ed(e){let{buffer:t,filename:A,contentType:r}=await ec(e);if(void 0!==e.expectSha256){let r=e.expectSha256.trim().toLowerCase();if(!eh.test(r))throw Error(`invalid expectSha256 for ${A}: expected 64 hex characters, got ${JSON.stringify(e.expectSha256)} — refusing to store an unverified download.`);let i=(0,ea.sha256OfBuffer)(t);if(i!==r)throw Error(`sha256 mismatch for ${A}: expected ${r.slice(0,16)}…, got ${i.slice(0,16)}… — refusing to store a tampered/corrupt download.`)}let i=await (0,el.storeFile)({pieceId:e.pieceId,filename:A,buffer:t,contentType:e.contentType??r,skipProxyGeneration:e.skipProxyGeneration});return{fileId:i.id,bytes:t.byteLength,filename:i.filename}}e.s(["fetchAndStoreRemoteFile",0,ed,"fetchRemoteBuffer",0,ec],592720);let eu={kind:"remote_fetch",maxConcurrent:3,paramsSchema:t.z.object({urls:t.z.array(t.z.string()).min(1).max(20),pieceId:t.z.string().nullable(),autoUpload:t.z.boolean().default(!0)}),resumable:!0,noProgressTimeoutMs:12e4,mcpToolId:(0,S.makeMcpToolId)("libi","libi.import_remote_files"),async run(e){let{urls:t,pieceId:A,autoUpload:r}=e.params,i=[...e.resumeState?.items??[]];e.reportProgress(i.length,t.length,"files");for(let n=i.length;n<t.length;n++){if(e.shouldCancel())throw Error("cancelled");let s=t[n],o=function(e){try{return q.default.basename(new URL(e).pathname)}catch{return""}}(s)||`download-${n}.bin`;try{if(r){let e=await ed({url:s,guard:es.assertPublicHttpUrl,pieceId:A,filename:o});i.push({url:s,status:"ok",fileId:e.fileId,bytes:e.bytes})}else{let{buffer:t}=await ec({url:s,guard:es.assertPublicHttpUrl,filename:o}),A=q.default.join((0,j.getLibiHome)(),"tmp","remote-fetch",e.jobId);await en.default.mkdir(A,{recursive:!0});let r=q.default.join(A,o);await en.default.writeFile(r,t),i.push({url:s,status:"ok",localPath:r,bytes:t.byteLength})}}catch(t){J.serverLogger.warn({tag:"remote-fetch",op:"url_error",url:s,jobId:e.jobId,err:t},"remote_fetch: url failed"),i.push({url:s,status:"error",error:t instanceof Error?t.message:String(t)})}await e.checkpoint({items:i}),e.reportProgress(i.length,t.length,"files")}if(i.length>0&&i.every(e=>"error"===e.status)){let e=i.find(e=>"error"===e.status);throw Error(`all ${i.length} downloads failed: ${e&&"error"in e?e.error:"unknown"}`)}return{items:i}}};e.s(["remoteFetchRunner",0,eu],449080);var eE=e.i(660526),eQ=e.i(567209),eI=e.i(366087),eB=e.i(874533),eC=e.i(695687);async function ef(e){let t=(0,eC.sidecarProjectDir)(),A=(0,eB.spawn)((0,eC.uvPath)(),["run","--frozen","python","track_runner.py"],{cwd:t,env:(0,a.buildUvEnv)({UV_PROJECT_ENVIRONMENT:(0,a.trackingVenvDir)(),LIBI_TRACK_MODELS:process.env.LIBI_TRACK_MODELS??(0,eC.trackingModelsDir)()}),windowsHide:!0,stdio:["pipe","pipe","pipe"]});A.stdin.write(JSON.stringify({method:"matte",videoPath:(0,q.resolve)(e.videoPath),range:e.range,outputDir:(0,q.resolve)(e.outputDir),seedBox:e.seedBox??null,seedMaskPath:e.seedMaskPath??null,maxDim:e.maxDim??1080,warmup:10})),A.stdin.end();let r="",i=null,n=setInterval(()=>{if(e.shouldCancel?.())try{A.kill("SIGKILL")}catch{}},1e3);A.stdout.on("data",t=>{let A;for(r+=t.toString("utf8");(A=r.indexOf("\n"))>=0;){let t,n=r.slice(0,A).trim();if(r=r.slice(A+1),n){try{t=JSON.parse(n)}catch{continue}"progress"===t.type?e.onProgress?.(Number(t.done),Number(t.total)):"result"===t.type&&(i={outputDir:String(t.outputDir??""),frameCount:Number(t.frameCount??0),framerate:Number(t.framerate??0),device:String(t.device??"cpu"),msPerFrame:Number(t.msPerFrame??0),coverage:Number(t.coverage??0),flags:Array.isArray(t.flags)?t.flags.map(String):[],..."string"==typeof t.error?{error:t.error}:{}})}}});let s="";if(A.stderr.on("data",e=>{s+=e.toString("utf8")}),await new Promise((e,t)=>{A.on("error",t),A.on("close",A=>{if(clearInterval(n),0!==A&&!i)return J.serverLogger.error({tag:"matte",op:"sidecar.fail",code:A,stderr:s.slice(-1e3)},"matte sidecar failed"),t(Error(`matte sidecar exited ${A}: ${s.slice(-500)}`));e()})}),!i)throw Error("matte sidecar produced no result");return i}var ep=e.i(632484),ey=e.i(110139);let em=t.z.object({fileId:t.z.string().min(1),engine:t.z.literal("local"),subject:t.z.object({kind:t.z.enum(["auto","box"]),box:t.z.tuple([t.z.number(),t.z.number(),t.z.number(),t.z.number()]).optional()}),range:t.z.object({start:t.z.number().nonnegative(),end:t.z.number().positive()}).optional()}),ew={kind:"matte_gen",mcpToolId:[(0,S.makeMcpToolId)("libi","libi.remove_background"),(0,S.makeMcpToolId)("libi-tracking","libi.remove_background")],maxConcurrent:1,paramsSchema:em,resumable:!1,noProgressTimeoutMs:null,async run(e){if(!(0,ep.trackingEngineInstalled)())throw Error(JSON.stringify((0,ep.trackingNotInstalledError)()));let[t]=(0,v.getDb)().select().from(x.files).where((0,L.eq)(x.files.id,e.params.fileId)).limit(1).all();if(!t)throw Error(`file not found: ${e.params.fileId}`);if("video"!==t.type)throw Error(`file is not a video: ${t.id} (photos go through the fal birefnet path)`);let A=t.pieceId?q.default.join((0,j.getLibiStorageDir)(),t.pieceId):q.default.join((0,j.getLibiStorageDir)(),"_global"),r=q.default.join(A,t.filename);if(!T.default.existsSync(r))throw Error(`source missing: ${r}`);let i=t.mediaDuration??null;if(null==i&&(i=(await (0,eI.probeMedia)(r)).duration??null),null==i)throw Error(`cannot determine duration of ${r}`);let n=e.params.range??{start:0,end:i},s=T.default.mkdtempSync(q.default.join(eE.default.tmpdir(),"libi-matte-")),o=q.default.join(s,"alpha");T.default.mkdirSync(o,{recursive:!0});try{var a,l;let A,i;J.serverLogger.info({tag:"matte",op:"matte_start",jobId:e.jobId,fileId:t.id,range:n,subject:e.params.subject.kind},"matte generation start");let g=await ef({videoPath:r,range:n,outputDir:o,seedBox:"box"===e.params.subject.kind?e.params.subject.box??null:null,onProgress:(t,A)=>e.reportProgress(t,A,"frames"),shouldCancel:()=>e.shouldCancel()});if(e.shouldCancel())throw new ey.CancelledError(e.jobId);if(g.error||0===g.frameCount)throw Error("no_seed_instance"===g.error?"no_seed_instance: the seed step found no subject at the range start — pass a subject box from libi.ground_target, or use the fal engine":"matte produced no frames");if(g.flags.length>0){let A=(100*g.coverage).toFixed(2),r=g.flags.includes("empty_matte")?`empty_matte: the matte kept only ${A}% of the frame — the subject was lost, so the cutout would render as nothing. Re-seed with a subject box from libi.ground_target, start the range where the subject is clearly visible, or use the paid fal engine.`:`full_frame_matte: the matte kept ${A}% of the frame — nothing was removed, so compositing this over a new background would silently show the original scene. Re-seed with a tighter subject box, or use the paid fal engine.`;throw J.serverLogger.warn({tag:"matte",op:"matte_coverage_rejected",jobId:e.jobId,fileId:t.id,coverage:g.coverage,flags:g.flags,frameCount:g.frameCount},"matte rejected by coverage gate"),Error(r)}let c=(a=t.filename,A=q.default.extname(a),i=q.default.basename(a,A),`${i}-cutout.webm`),h=q.default.join(s,c),d=new AbortController,u=setInterval(()=>{e.shouldCancel()&&!d.signal.aborted&&d.abort()},1e3);try{await (0,eQ.runFfmpeg)((l={range:n,framerate:g.framerate,frameCount:g.frameCount},["-y","-ss",String(l.range.start),"-to",String(l.range.end),"-i",r,"-framerate",String(l.framerate),"-start_number","0","-i",q.default.join(o,"f%06d.png"),"-filter_complex",`[0:v]fps=${l.framerate},format=rgba[rgb];[1:v]format=gray[a];[rgb][a]alphamerge[out]`,"-map","[out]","-frames:v",String(l.frameCount),"-c:v","libvpx-vp9","-pix_fmt","yuva420p","-auto-alt-ref","0","-b:v","0","-crf","30","-row-mt","1","-an",h]),{op:"matte_compose",context:{fileId:t.id,pieceId:t.pieceId,jobId:e.jobId},signal:d.signal})}finally{clearInterval(u)}if(e.shouldCancel())throw new ey.CancelledError(e.jobId);let E=await (0,el.storeFile)({pieceId:t.pieceId,filename:c,buffer:T.default.readFileSync(h),contentType:"video/webm",hasAlpha:!0,name:c,description:`Alpha cutout of "${t.name}" (${n.start.toFixed(2)}-${n.end.toFixed(2)}s, MatAnyone local matte, VP9-alpha WebM)`});try{t.pieceId?M.navigationEmitter.emit("refresh_query",{queryKey:"piece",pieceId:t.pieceId}):M.navigationEmitter.emit("refresh_query",{queryKey:"files"})}catch(e){J.serverLogger.warn({tag:"matte",op:"refresh_query_emit_failed",err:e,fileId:t.id},"matte refresh_query emit failed")}return J.serverLogger.info({tag:"matte",op:"matte_done",jobId:e.jobId,fileId:t.id,cutoutFileId:E.id,frameCount:g.frameCount,device:g.device,msPerFrame:g.msPerFrame},"matte generation complete"),{cutoutFileId:E.id,frameCount:g.frameCount,framerate:g.framerate,engine:"local",msPerFrame:g.msPerFrame}}finally{T.default.rmSync(s,{recursive:!0,force:!0})}}};e.s(["matteGenRunner",0,ew],241744);var eD=e.i(991858),eb=e.i(812057),eS=e.i(986343),eN=e.i(49614),eR=e.i(652851);let eF="https://registry.npmjs.org/",ek=new Set(["localhost","127.0.0.1","[::1]","::1"]);function eM(e){let t=e.env??process.env,A=t.LIBI_REGISTRY_URL?.trim();if(!A)return{url:eF,source:"public"};if(!e.isPackaged)return{url:eF,source:"public",rejected:"not-packaged"};if(t.LIBI_WORKTREE_NAME?.trim())return{url:eF,source:"public",rejected:"worktree"};let r=function(e){let t,A=e?.trim();if(!A)return{rejected:"invalid-url"};try{t=new URL(A)}catch{return{rejected:"invalid-url"}}return"http:"!==t.protocol&&"https:"!==t.protocol?{rejected:"unsupported-protocol"}:t.username||t.password?{rejected:"embedded-credentials"}:"http:"!==t.protocol||ek.has(t.hostname)?(t.search="",t.hash="",t.pathname.endsWith("/")||(t.pathname+="/"),{url:t.toString()}):{rejected:"insecure-remote"}}(A);return"rejected"in r?{url:eF,source:"public",rejected:r.rejected}:{url:r.url,source:"override"}}function eU(){return!!process.versions.electron&&!process.defaultApp}var eT=e.i(772991),eL=e.i(511724);class ev extends Error{code;constructor(e,t){super(t),this.name="NextExternalsError",this.code=e}}let ex="externals-manifest.json";function eY(e){return`Rebuild with \`npm run build\` (or \`node scripts/next-build-release.js\`), which writes ${q.default.join(".next",ex)} as part of the build; if you installed this from npm, reinstall the package (the published tarball always carries the manifest). Checked: ${e}`}let eH=(0,eb.promisify)(eB.execFile),eG="@nagellabs/libi",eO=".libi-runtime.json",eV="github.com",eJ="runtime-install";class e_ extends Error{kind;host;constructor(e,t,A=null){super(t),this.name="RuntimeInstallError",this.kind=e,this.host=A}}function eP(){return q.default.join((0,j.getLibiHome)(),"runtime")}function eW(e){return q.default.join(e,"node_modules",...eG.split("/"))}function eq(e){try{return new URL(e).host}catch{return e}}async function ej(e,t,A){let r=(0,eN.buildSpawnEnv)();return"electron-utility-process"===(0,eS.selectNpmRunner)()?await (0,eS.runNpmViaUtilityProcess)(e,t,{cwd:A,env:r,timeoutMs:9e5}):await eH(process.execPath,[e,...t],{cwd:A,env:{...r,ELECTRON_RUN_AS_NODE:"1"},timeout:9e5,windowsHide:!0,maxBuffer:0x1000000})}async function ez(e){let t=e.registryUrl??eF,A=e.runtimeRootDir??eP(),r=q.default.join(A,e.version),i=q.default.join(A,`.tmp-${e.version}-${process.pid}-${Date.now()}`),n=e.onProgress??(()=>{});T.default.mkdirSync(A,{recursive:!0}),T.default.rmSync(i,{recursive:!0,force:!0}),T.default.mkdirSync(i,{recursive:!0});try{T.default.writeFileSync(q.default.join(i,"package.json"),JSON.stringify({name:"libi-runtime",version:"0.0.0",private:!0,description:"Generated by lib/runtime/runtime-install.ts — a fetched @nagellabs/libi runtime snapshot. Do not edit."},null,2)+"\n");let A=(0,eS.resolveVendoredNpmCli)(),s=["install",`${eG}@${e.version}`,"--omit=dev","--ignore-scripts","--no-audit","--no-fund",`--registry=${t}`];n(`Downloading libi ${e.version}…`),J.serverLogger.info({tag:eJ,op:"npm_install_start",version:e.version,registryUrl:t},"installing runtime snapshot");try{await ej(A,s,i)}catch(A){let e=A instanceof Error?A.message:String(A);if((0,eT.looksUnreachable)(e))throw new e_("registry-unreachable",`Could not reach the npm registry (${eq(t)}): ${e}`,eq(t));throw new e_("unknown",`npm install failed: ${e}`)}let o=eW(i);if(!T.default.existsSync(o))throw new e_("verification-failed",`npm install produced no runtime root at ${o}`);n("Preparing the database engine…"),await eZ({prefix:i}),await eK({prefix:i,electronVersion:e.electronVersion});let a=JSON.parse(T.default.readFileSync(q.default.join(o,"package.json"),"utf-8")),l=a.libi?.shellApiVersion;if(a.name!==eG||!Number.isInteger(l))throw new e_("verification-failed",`installed package is ${String(a.name)}@${String(a.version)} with shellApiVersion ${String(l)}`);for(let e of["dist-cli/lib/runtime/shell-api.js",".next/BUILD_ID"])if(!T.default.existsSync(q.default.join(o,e)))throw new e_("verification-failed",`the downloaded runtime is missing ${e}`);try{!function(e){let t=q.default.join(e,"node_modules"),A=function(e){let t=q.default.join(e,ex);try{let e=T.default.readFileSync(t,"utf-8"),A=JSON.parse(e);if(!A||"object"!=typeof A||Array.isArray(A))return null;let{buildId:r,links:i}=A;if("string"!=typeof r||0===r.length||!Array.isArray(i))return null;return{buildId:r,links:i.filter(e=>!!e&&"string"==typeof e.link&&"string"==typeof e.package)}}catch{return null}}(e);if(!A){let A,r;if(A=!1,r=!0,!function e(t){let i;try{i=T.default.readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of i){let i=q.default.join(t,n.name);if(n.isSymbolicLink()){A=!0;try{T.default.realpathSync(i)}catch{r=!1}}else n.isDirectory()&&e(i)}}(t),A&&r)return;throw new ev("MANIFEST_MISSING",`Next.js externals manifest is missing or unreadable and .next/node_modules holds no usable symlinks. Turbopack externalises packages under hashed names that resolve only through that symlink farm, so the server would start and then fail EVERY request with a 500. ${eY(e)}`)}let r=function(e){try{let t=T.default.readFileSync(q.default.join(e,"BUILD_ID"),"utf-8").trim();return t.length>0?t:null}catch{return null}}(e);if(null===r)throw new ev("MANIFEST_STALE",`Next.js externals manifest found, but .next/BUILD_ID is missing — this is not a complete production build, so the manifest cannot be verified against it. ${eY(e)}`);if(r!==A.buildId)throw new ev("MANIFEST_STALE",`Next.js externals manifest is STALE: it was written for build "${A.buildId}" but .next/BUILD_ID is "${r}". Turbopack's hashed external names change between builds, so restoring from it would create symlinks under the previous build's names and every request would 500. ${eY(e)}`);if(0===A.links.length)return;let i=[],n=[],s=[];for(let r of A.links){let A=function(e,t){let A=q.default.resolve(e);for(let e=0;e<64;e++){let e=q.default.join(A,"node_modules",t);if(T.default.existsSync(e))return e;let r=q.default.dirname(A);if(r===A)break;A=r}return null}(e,r.package);if(!A){s.push(r);continue}let o=q.default.join(t,r.link);try{if(T.default.lstatSync(o).isSymbolicLink()&&T.default.realpathSync(o)===T.default.realpathSync(A)){n.push(r);continue}T.default.rmSync(o,{force:!0,recursive:!0})}catch{}let a=q.default.dirname(o);T.default.mkdirSync(a,{recursive:!0}),T.default.symlinkSync(q.default.relative(a,A),o,"dir"),i.push(r)}if(s.length>0)throw new ev("PACKAGES_MISSING",`Could not locate ${s.length} externalised package(s) in any ancestor node_modules: ${s.map(e=>e.package).join(", ")}. The server would start and then fail requests that touch them. Reinstall dependencies (\`npm install\`) and try again. Searched upward from: ${e}`)}(q.default.join(o,".next"))}catch(e){throw new e_("verification-failed",`the downloaded runtime's Next.js externals could not be restored: ${e instanceof Error?e.message:String(e)}`)}T.default.writeFileSync(q.default.join(i,eO),JSON.stringify({package:eG,version:a.version,shellApiVersion:l,abi:e.abi,electronVersion:e.electronVersion,source:"fetched",installedAt:new Date().toISOString()},null,2)+"\n");let g=T.default.existsSync(r)?`${r}.old-${Date.now()}`:null;return g&&T.default.renameSync(r,g),T.default.renameSync(i,r),g&&T.default.rmSync(g,{recursive:!0,force:!0}),J.serverLogger.info({tag:eJ,op:"install_done",version:a.version,shellApiVersion:l,abi:e.abi,prefix:r},"runtime snapshot installed"),{prefix:r,root:eW(r),version:a.version,shellApiVersion:l,abi:e.abi}}catch(t){T.default.rmSync(i,{recursive:!0,force:!0});let e=t instanceof e_?t:new e_("unknown",t instanceof Error?t.message:String(t));throw J.serverLogger.warn({tag:eJ,op:"install_failed",kind:e.kind,host:e.host},e.message),e}}function eX(e){let t=(0,eL.betterSqliteModuleDir)(e);if(!T.default.existsSync(t))throw new e_("verification-failed",`better-sqlite3 is not present in the downloaded runtime (${t})`);let A=[q.default.join(e,"node_modules","prebuild-install","bin.js"),q.default.join(t,"node_modules","prebuild-install","bin.js")].find(e=>T.default.existsSync(e));if(!A)throw new e_("verification-failed","prebuild-install is missing from the downloaded runtime, so the native database binding cannot be resolved without compiling — which libi will not do.");return{moduleDir:t,bin:A}}async function eZ(e){let{moduleDir:t,bin:A}=eX(e.prefix),r=q.default.join(t,"build"),i=q.default.join(r,"Release","better_sqlite3.node"),n=[];for(let e of eL.NODE_ABI_SIDECAR_MAJORS){try{await eH((0,eR.resolveNodeCommand)(),[A,"--runtime=node",`--target=${e}.0.0`],{cwd:t,windowsHide:!0,env:(0,eN.buildSpawnEnv)(),timeout:3e5,maxBuffer:0x1000000})}catch{}if(!T.default.existsSync(i)){J.serverLogger.warn({tag:eJ,op:"sidecar_skipped",major:e},"no better-sqlite3 prebuild for this node major");continue}let s=q.default.join(r,(0,eL.sidecarDirName)(e));T.default.mkdirSync(s,{recursive:!0}),T.default.copyFileSync(i,q.default.join(s,"better_sqlite3.node")),n.push(e)}if(T.default.rmSync(i,{force:!0}),0===n.length)throw new e_("prebuild-unreachable",`Could not download a Node database binding from ${eV} for any supported Node version (${eL.NODE_ABI_SIDECAR_MAJORS.join(", ")}). libi's agent tools run in a separate Node process, so this runtime would boot a working window in which none of them can reach the database.`,eV);return J.serverLogger.info({tag:eJ,op:"sidecars_fetched",majors:n},"parked plain-node better-sqlite3 bindings"),n}async function eK(e){let{moduleDir:t,bin:A}=eX(e.prefix),r=[A,"--runtime=electron",`--target=${e.electronVersion}`,"--dist-url=https://electronjs.org/headers"],i=q.default.join(t,"build","Release","better_sqlite3.node");try{await eH((0,eR.resolveNodeCommand)(),r,{cwd:t,windowsHide:!0,env:(0,eN.buildSpawnEnv)(),timeout:3e5,maxBuffer:0x1000000})}catch(e){if(T.default.existsSync(i))J.serverLogger.warn({tag:eJ,op:"prebuild_command_failed_artifact_ok",err:e instanceof Error?e.message:String(e)},"prebuild-install did not exit cleanly but the binding is present");else{let t=e instanceof Error?e.message:String(e);throw new e_("prebuild-unreachable",`Could not download the native database binding from ${eV}: ${t}`,eV)}}if(!T.default.existsSync(i))throw new e_("prebuild-unreachable",`prebuild-install reported success but ${i} is missing`,eV)}e.s(["RUNTIME_PACKAGE",0,eG,"RUNTIME_STAMP_FILE",0,eO,"RuntimeInstallError",0,e_,"installRuntime",0,ez,"userRuntimeDir",0,eP],997734);let e$="LIBI_SHELL_API_MIN",e0="LIBI_SHELL_API_MAX";function e1(e,t){let A=e[t]?.trim();if(!A)return null;let r=Number(A);return Number.isInteger(r)?r:null}function e2(e={}){let t=e.env??process.env,A=e.cwd??process.cwd(),r=e.isPackaged??eU(),i=function(e){try{let t=T.default.readFileSync(q.default.join(e,"package.json"),"utf-8"),A=JSON.parse(t),r="string"==typeof A.version?A.version:null,i=A.libi?.shellApiVersion;return{version:r,shellApiVersion:Number.isInteger(i)?i:null}}catch{return{version:null,shellApiVersion:null}}}(A),n=t.LIBI_RUNTIME_VERSION?.trim()||i.version,s=t.LIBI_RUNTIME_SOURCE?.trim(),o="bundled"===s||"user"===s?s:r?"bundled":q.default.resolve(A).split(q.default.sep).includes("node_modules")?"npm":"dev",a=i.shellApiVersion,l=e1(t,e$),g=e1(t,e0),c=null;return null!==l&&null!==g&&l<=g?c={min:l,max:g}:null!==a&&(c={min:a,max:a},r&&(null!==l||null!==g)&&J.serverLogger.warn({tag:"runtime-update",op:"shell_api_range_partial",min:l,max:g},"shell published only half a shellApiVersion range — falling back to the runtime's own version")),{version:n,shellApiVersion:a,source:o,shellApi:c,bundledVersion:t.LIBI_BUNDLED_VERSION?.trim()||null,updatesSupported:r}}e.s(["SHELL_API_MAX_ENV",0,e0,"SHELL_API_MIN_ENV",0,e$,"describeCurrentRuntime",0,e2],263874);let e4="runtime-update";function e8(e,t){let A=e=>{let[t,...A]=e.trim().split("-"),r=t.split(".").map(e=>{let t=Number.parseInt(e,10);return Number.isFinite(t)?t:0});for(;r.length<3;)r.push(0);return{nums:r,pre:A.length>0?A.join("-"):null}},r=A(e),i=A(t);for(let e=0;e<Math.max(r.nums.length,i.nums.length);e+=1){let t=(r.nums[e]??0)-(i.nums[e]??0);if(0!==t)return t}return r.pre===i.pre?0:null===r.pre?1:null===i.pre||r.pre<i.pre?-1:1}function e3(e){let t=e.now??Date.now(),A={currentVersion:e.currentVersion,latestVersion:e.latest?.version??null,latestShellApiVersion:e.latest?.shellApiVersion??null,checkedAt:t};if(!e.updatesSupported)return{...A,state:"unsupported"};if(!e.currentVersion||!e.latest)return{...A,state:"unknown"};if(!(e8(e.latest.version,e.currentVersion)>0)||e.bundledVersion&&!(e8(e.latest.version,e.bundledVersion)>0))return{...A,state:"up-to-date"};if(null===e.latest.shellApiVersion||null===e.shellApi)return J.serverLogger.warn({tag:e4,op:"classify_indeterminate",latest:e.latest.version,latestShellApiVersion:e.latest.shellApiVersion,shellApi:e.shellApi},"newer version found but its shell-API compatibility could not be determined"),{...A,state:"unknown"};let r=e.latest.shellApiVersion;return r<e.shellApi.min||r>e.shellApi.max?{...A,state:"shell-update-required"}:{...A,state:"update-available"}}function e5(e){if(!e||"object"!=typeof e||"string"!=typeof e.version||0===e.version.length)return null;let t=e.libi?.shellApiVersion;return{version:e.version,shellApiVersion:Number.isInteger(t)?t:null}}async function e9(e){let t=e.fetchImpl??fetch,A=e.timeoutMs??8e3,r=async e=>{let r=new AbortController,i=setTimeout(()=>r.abort(),A);try{let A=await t(e,{signal:r.signal,headers:{accept:"application/json"}});if(!A.ok)return null;return await A.json()}catch{return null}finally{clearTimeout(i)}},i=e5(await r(function(e,t=eG){let A=e.endsWith("/")?e:`${e}/`;return`${A}${t.replace("/","%2F")}/latest`}(e.registryUrl)));if(i)return i;let n=await r(function(e,t=eG){let A=e.endsWith("/")?e:`${e}/`;return`${A}${t.replace("/","%2F")}`}(e.registryUrl));if(!n||"object"!=typeof n)return null;let s=n["dist-tags"]?.latest;return"string"!=typeof s?null:e5(n.versions?.[s])??{version:s,shellApiVersion:null}}let e6=null;async function e7(e={}){let t=e.now??Date.now();if(!e.force&&e6&&e6.expiresAt>t)return e6.status;let A=e.current??e2();if(!A.updatesSupported)return e3({currentVersion:A.version,latest:null,shellApi:A.shellApi,updatesSupported:!1,now:t});let r=e.registry??eM({isPackaged:eU()});r.rejected&&J.serverLogger.warn({tag:e4,op:"registry_override_ignored",reason:r.rejected},"LIBI_REGISTRY_URL was set but not applied");let i=await e9({registryUrl:r.url,fetchImpl:e.fetchImpl}),n=e3({currentVersion:A.version,latest:i,shellApi:A.shellApi,updatesSupported:!0,bundledVersion:A.bundledVersion,now:t});return null===i?J.serverLogger.info({tag:e4,op:"check_failed",registry:r.url},"update check could not reach the registry — staying silent"):J.serverLogger.info({tag:e4,op:"check_done",state:n.state,current:n.currentVersion,latest:n.latestVersion},"update check complete"),e6={status:n,expiresAt:t+("unknown"===n.state?9e5:216e5)},n}e.s(["checkForRuntimeUpdate",0,e7,"compareVersions",0,e8],419704);let te="runtime-update",tt="runtime-update",tA=t.z.object({version:t.z.string().min(1)});e.s(["runtimeUpdateRunner",0,{kind:"runtime_update",maxConcurrent:1,paramsSchema:tA,resumable:!1,noProgressTimeoutMs:null,async run(e){let t,A=process.versions.electron,r=eU();if(!A||!r)throw Error("in-app runtime updates are only available in the packaged desktop app");let i=e2(),n=eM({isPackaged:r}).url,s=0;e.reportProgress(s,3,"steps"),J.serverLogger.info({tag:tt,op:"install_start",version:e.params.version,from:i.version,registryUrl:n},"installing runtime update");try{t=await ez({version:e.params.version,registryUrl:n,electronVersion:A,abi:process.versions.modules,onProgress:t=>{s=Math.min(s+1,2),e.reportProgress(s,3,"steps"),J.serverLogger.info({tag:tt,op:"install_progress",message:t},"runtime update progress")}})}catch(e){throw e instanceof e_&&J.serverLogger.warn({tag:tt,op:"install_failed",kind:e.kind,host:e.host},e.message),e}let o=[];try{o=function(e={}){let t,A=Math.max(1,e.keep??2),r=e.rootDir??eP(),i=e.protectPrefix?q.default.resolve(e.protectPrefix):null;try{t=T.default.readdirSync(r,{withFileTypes:!0})}catch{return{removed:[],kept:[]}}let n=[],s=(e,t)=>{let A=q.default.join(r,e);if(!i||q.default.resolve(A)!==i)try{T.default.rmSync(A,{recursive:!0,force:!0}),n.push(A),J.serverLogger.info({tag:te,op:"prune_removed",dir:A,why:t},"pruned runtime")}catch(e){J.serverLogger.warn({tag:te,op:"prune_failed",dir:A,err:e.message},"could not prune runtime directory")}};for(let e of t)e.isDirectory()&&(e.name.startsWith(".tmp-")||e.name.includes(".old-"))&&s(e.name,"debris");let o=t.filter(e=>e.isDirectory()&&!e.name.startsWith(".")).map(e=>e.name).filter(e=>!e.includes(".old-")).sort((e,t)=>e8(t,e)),a=[],l=0;for(let e of o){let t=q.default.join(r,e),n=null!==i&&q.default.resolve(t)===i;if(l<A||n){a.push(t),l+=1;continue}s(e,"surplus")}return{removed:n,kept:a}}({protectPrefix:function(e=process.cwd()){let t=q.default.resolve(e).split(q.default.sep);if(t.length<4)return null;let[A,r]=[t[t.length-2],t[t.length-1]];return"node_modules"!==t[t.length-3]||"@nagellabs/libi"!=`${A}/${r}`?null:t.slice(0,t.length-3).join(q.default.sep)}(),rootDir:eP()}).removed}catch(e){J.serverLogger.warn({tag:tt,op:"prune_error",err:e.message},"post-install prune failed (harmless)")}return e.reportProgress(3,3,"steps"),J.serverLogger.info({tag:tt,op:"install_done",version:t.version,prefix:t.prefix,prunedCount:o.length},"runtime update installed — applies at next launch"),(0,eD.trackServerEvent)("runtime_update_installed",{previous_source:i.source}),{version:t.version,prefix:t.prefix,shellApiVersion:t.shellApiVersion,pruned:o}}}],958933)},241983,788170,e=>{"use strict";var t=e.i(522734),A=e.i(814747),r=e.i(577833),i=e.i(246387);let n="yt-dlp-uv@2026-07-06",s="__NODE__";function o(e){return A.default.join(e,"yt-dlp.install-token")}let a={"tracking-pyenv":r.trackingPyenvInstaller,"playwright-chromium":{verify:async()=>{try{let{chromium:A}=await e.A(164351),r=A.executablePath();return t.default.existsSync(r)?r:null}catch{return null}},install:{command:s,args:["__PLAYWRIGHT_CORE_CLI__","install","chromium"],timeoutMs:6e5}},"yt-dlp-uv":{verify:async()=>{let{getLibiBinDir:r}=await e.A(336270),s=r(),a=A.default.join(s,(0,i.isWindows)()?"yt-dlp.cmd":"yt-dlp");try{t.default.lstatSync(a)}catch{return null}try{t.default.realpathSync(a)}catch{return null}let l="";try{l=t.default.readFileSync(o(s),"utf-8").trim()}catch{l=""}return l!==n?null:a},install:{command:"__YT_DLP_UV_INSTALL__",args:[],timeoutMs:3e5}}};function l(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}e.s(["NODE_COMMAND_SENTINEL",0,s,"YT_DLP_UV_TOKEN",0,n,"getCustomInstaller",0,function(e){return a[e]},"resolvePlaywrightCoreCli",0,function(){let e=process.cwd();for(let r=0;r<8;r++){let r=A.default.join(e,"node_modules","playwright-core","cli.js");if(t.default.existsSync(r))return r;let i=A.default.dirname(e);if(i===e)break;e=i}throw Error("Could not locate node_modules/playwright-core/cli.js relative to cwd. Ensure playwright-core is installed.")},"ytDlpTokenPath",0,o],241983),e.s(["resolveGlob",0,function(e,r){let i=r.split("/"),n=[e];for(let e of i){if(!e.includes("*")){n=n.map(t=>A.default.join(t,e));continue}let r=[],i=RegExp("^"+e.split("*").map(l).join(".*")+"$");for(let e of n)if(t.default.existsSync(e))for(let n of t.default.readdirSync(e))i.test(n)&&r.push(A.default.join(e,n));n=r}for(let e of n)if(t.default.existsSync(e))return e;return null}],788170)},719373,921179,100164,e=>{"use strict";e.s(["DependencyManager",()=>K],719373);var t=e.i(233405),A=e.i(224361),r=e.i(522734),i=e.i(814747),n=e.i(446786),s=e.i(190793),o=e.i(478181),a=e.i(875225),l=e.i(88690),g=e.i(246682),c=e.i(241983),h=e.i(652851),d=e.i(246387),u=e.i(270958),E=e.i(470072),Q=e.i(640911),I=e.i(153708),B=e.i(788170),C=e.i(452183);e.s(["ensureBootstrapped",()=>X,"getVirtualDepsForMcp",()=>j],100164);var f=e.i(619955),p=e.i(48989);let y=new Set;function m(e){return y.has(e)}e.s(["clearInstalling",0,function(e){y.delete(e)},"isInstalling",0,m,"markInstalling",0,function(e){y.add(e)}],921179);let w={id:"ace-step-model",label:`ace-step weights (${f.ACESTEP_DOWNLOAD_SIZE_HUMAN})`,async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,f.isAceStepModelInstalled)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,p.getJobManager)(),t=await e.enqueue("music_model_download",{force:!1});"matching_completed"!==t.status&&await e.runToCompletion(t.jobId)}};var D=e.i(407415);e.i(254799);var b=e.i(346385),S=e.i(775497);e.i(961288);let N="3.12",R=["librosa==0.11.0","soundfile"];function F(){return(0,S.hashSpec)(N,R)}[...R.flatMap(e=>["--with",e])];class k extends Error{constructor(e){super(e),this.name="MusicAnalyzeError"}}var M=e.i(799261);let U=".libi-music-analysis.install-token";async function T(e=3e5){let A=(0,b.requireUvBinary)(k,"Music analysis"),r=["run","--python",N,...R.flatMap(e=>["--with",e]),"python","-c","import librosa, soundfile; print('ok')"];await new Promise((i,n)=>{let s=(0,t.spawn)(A,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"],env:(0,E.buildUvEnv)()}),o="",a=setTimeout(()=>{s.kill("SIGKILL"),n(new k(`install timed out after ${e}ms`))},e);s.stdout.on("data",()=>{}),s.stderr.on("data",e=>o+=e.toString()),s.on("close",e=>{clearTimeout(a),0===e?i():n(new k(`install exited ${e}: ${(0,D.formatStderrTail)(o)}`))})}),(0,M.writeInstallToken)(U,F())}let L=[w,{id:"ace-step-env",label:"ace-step env",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,D.isAceStepEnvCurrent)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){await (0,D.generateMusic)({prompt:"warmup",durationSeconds:1,instrumental:!0,seed:0})}},{id:"music-analysis-env",label:"librosa env (~50 MB)",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,M.isTokenCurrent)(U,F());return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){await T()}}];var v=e.i(332879);let x=v.DEFAULT_WHISPER_MODEL,Y={id:"whisper-model",label:`whisper ${x} weights`,async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,v.isWhisperModelInstalled)(x);return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,p.getJobManager)(),t=await e.enqueue("whisper_model_download",{model:x});"matching_completed"!==t.status&&await e.runToCompletion(t.jobId)}};var H=e.i(720659);class G extends Error{constructor(e){super(e),this.name="WhisperEnvInstallError"}}let O=[Y,{id:"whisper-env",label:"whisper env (faster-whisper)",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,H.isWhisperEnvCurrent)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,b.requireUvBinary)(G,"Whisper"),A=["run","--python",H.WHISPER_PYTHON_VERSION,...H.WHISPER_WITH_SPECS.flatMap(e=>["--with",e]),"python","-c","import faster_whisper; print('ok')"];await new Promise((r,i)=>{let n=(0,t.spawn)(e,A,{windowsHide:!0,stdio:["ignore","pipe","pipe"],env:(0,E.buildUvEnv)()}),s="",o=setTimeout(()=>{n.kill("SIGKILL"),i(new G("install timed out after 5 minutes"))},3e5);n.stdout.on("data",()=>{}),n.stderr.on("data",e=>s+=e.toString()),n.on("close",e=>{clearTimeout(o),0===e?r():i(new G(`install exited ${e}: ${s.trim().slice(-2e3)}`))})}),(0,H.writeWhisperEnvToken)()}}];var V=e.i(513887),J=e.i(457888);class _ extends Error{constructor(e){super(e),this.name="TtsEnvInstallError"}}let P=[{id:"tts-model",label:"kokoro TTS weights",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,V.isKokoroModelInstalled)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,p.getJobManager)(),t=await e.enqueue("tts_model_download",{});"matching_completed"!==t.status&&await e.runToCompletion(t.jobId)}},{id:"tts-env",label:"kokoro env (kokoro-onnx)",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,J.isTtsEnvCurrent)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,b.requireUvBinary)(_,"Kokoro TTS"),A=["run","--python",J.TTS_PYTHON_VERSION,...J.TTS_WITH_SPECS.flatMap(e=>["--with",e]),"python","-c","import kokoro_onnx, soundfile; print('ok')"];await new Promise((r,i)=>{let n=(0,t.spawn)(e,A,{windowsHide:!0,stdio:["ignore","pipe","pipe"],env:(0,E.buildUvEnv)()}),s="",o=setTimeout(()=>{n.kill("SIGKILL"),i(new _("install timed out after 5 minutes"))},3e5);n.stdout.on("data",()=>{}),n.stderr.on("data",e=>s+=e.toString()),n.on("close",e=>{clearTimeout(o),0===e?r():i(new _(`install exited ${e}: ${s.trim().slice(-2e3)}`))})}),(0,J.writeTtsEnvToken)()}}],W=new Map;function q(e,t){let A=new Set;for(let r of t){if(A.has(r.id))throw Error(`duplicate virtual-dep id "${r.id}" for mcp "${e}"`);A.add(r.id)}W.set(e,t)}function j(e){return W.get(e)??[]}let z=!1;function X(){z||(z=!0,q("local-music",L),q("whisper",O),q("local-tts",P))}let Z=(0,A.promisify)(t.execFile);class K{skipDbWrites=!1;static unverifiedBinariesWarned=new Set;async verifyBinaryIntegrity(e,t){if(e.sha256){try{await (0,I.verifySha256)(t,e.sha256)}catch(e){try{r.default.unlinkSync(t)}catch{}throw e}Q.serverLogger.info({tag:"security",op:"binary_verified",binary:e.binary,sha256Prefix:e.sha256.slice(0,16)},`Verified sha256 of downloaded binary "${e.binary}"`);return}K.unverifiedBinariesWarned.has(e.binary)||(K.unverifiedBinariesWarned.add(e.binary),Q.serverLogger.warn({tag:"security",op:"binary_unverified",binary:e.binary},`Downloaded binary "${e.binary}" WITHOUT sha256 verification — its download URL is a "latest" alias with no pinned hash (transport was HTTPS-only). Re-host as a pinned release asset + set the dep's sha256 to enable content verification.`))}setSkipDbWrites(e){this.skipDbWrites=e}async ensureAll(e){await this.installBundledDeps(e),await this.prewarmBundledMcps(e)}static syncLog(t){try{let A=e.r(902157),r=e.r(750227),i=e.r(660526),n=r.join(process.env.LIBI_HOME??r.join(i.homedir(),".libi"),"logs");A.mkdirSync(n,{recursive:!0}),A.appendFileSync(r.join(n,"category-a-sync.log"),`[${new Date().toISOString()}] dm: ${t}
|
|
167
|
+
Be terse and numeric. NO generic advice. One block per caption.`;await e.checkpoint({stage:"submitted"}),e.reportProgress(1,4,"step");let r=new AbortController,i=setInterval(()=>{e.shouldCancel()&&!r.signal.aborted&&r.abort()},1e3);try{t=(await h.generate({localPath:c,durationSeconds:g.mediaDuration??0,promptInstructions:A,onProgress:t=>e.reportProgress(2,4,"step"),signal:r.signal})).text}finally{clearInterval(i)}if(e.shouldCancel())throw Error("cancelled");return await e.checkpoint({stage:"received"}),e.reportProgress(3,4,"step"),await (0,z.saveCaptionSpec)({fileId:s,providerId:o,modelId:a,text:t}),e.reportProgress(4,4,"step"),er.info({op:"done",fileId:s,providerId:o,modelId:a,focus:l},"caption spec saved"),{captionSpec:t}}let d='You are watching a video and producing a production script that another text-to-video model could use to recreate it.\n\nOutput STRICTLY ONE JSON object with this shape. NO markdown fences. NO prose before or after. ONLY the JSON object.\n\nSchema (script_v1):\n{\n "schema_version": "script_v1",\n "duration": <number>, // seconds\n "overall_style": "<one or two sentence look-and-feel summary>",\n "pacing": "<optional short phrase>",\n "shots": [ // chronological, non-overlapping, covers full duration\n {\n "index": <0-based>,\n "start": <seconds>,\n "end": <seconds>,\n "description": "<detailed enough for a text-to-video model to recreate: subject, action, environment, lighting, framing, mood>",\n "action": "<optional verb-phrase>",\n "camera": { "shot": "close-up|medium|wide|extreme-wide", "angle": "eye-level|high|low|dutch", "motion": "static|pan|zoom|dolly|tracking|handheld|shake", "lens": "<optional>" },\n "lighting": "<optional, e.g. golden hour, low key>",\n "mood": "<optional>",\n "dialogue": "<spoken in this shot, verbatim if heard>",\n "text_on_screen": ["<optional>"],\n "transition_out": "cut|fade|dissolve|wipe|match"\n }\n ],\n "music": { // required\n "present": <true|false>,\n "genre": "<optional>",\n "mood": "<optional>",\n "tempo": "<optional, e.g. fast ~130bpm>",\n "instruments": ["<optional>"],\n "cues": [ { "timestamp": <seconds>, "description": "<music change point>" } ]\n },\n "sound_design": [ { "timestamp": <seconds>, "description": "<notable non-music audio event>" } ],\n "dialogue_summary": "<paraphrased; do NOT verbatim-transcribe long speeches>"\n}\n\nRules:\n- Walk the video chronologically. Cut a new shot when there is a visible cut, hard music change, or location change.\n- start / end are seconds from the start of the clip. They must not overlap and must cover the full duration.\n- description must be detailed enough for a text-to-video model to recreate the shot WITHOUT seeing it.\n- music.present is false if no music plays; otherwise fill genre/mood/tempo/instruments as best you can hear.\n- sound_design lists notable non-music audio events with timestamps (knocks, footsteps, dings, ambient).\n- dialogue_summary is paraphrased; full speech goes in shot.dialogue when relevant.\n- overall_style summarizes look-and-feel in one or two sentences (cinematic / UGC / animated / cartoon / etc.).\n- pacing is one short phrase (e.g. fast cuts, 8s avg shot, slow contemplative single take).\n- Do NOT include a `provider` field. The caller fills that in.\n\nOutput budget (so the JSON is never truncated):\n- Keep each shot.description ≤ 240 characters — dense, not flowery.\n- Merge adjacent near-identical shots. Aim for ≤ 16 shots total even for long videos.\n- Keep every other free-text field to one short phrase. The whole JSON must fit well under 5000 characters.\n\nReturn only the JSON object — no markdown, no commentary.',u=new Date().toISOString();await e.checkpoint({stage:"submitted"}),e.reportProgress(1,4,"step");let E=new AbortController,Q=setInterval(()=>{e.shouldCancel()&&!E.signal.aborted&&E.abort()},1e3),I=()=>h.estimateCostUsd?h.estimateCostUsd({durationSeconds:g.mediaDuration??0}):null;try{let t=await h.generate({localPath:c,durationSeconds:g.mediaDuration??0,promptInstructions:d,onProgress:t=>e.reportProgress(2,4,"step"),signal:E.signal});await e.checkpoint({stage:"received_first"}),e.reportProgress(2,4,"step");let n=K(t.text,{providerName:t.providerName,modelId:t.modelId??a,generatedAt:u,costUsd:I(),costEstimated:!0,requestId:t.requestId});if(n.ok)i=n.script;else{let t,s,l;er.warn({op:"validation_failed_first",error:n.error},"first attempt failed validation; retrying once");let Q=(A=n.error,r=h.maxPromptChars,t="\n\nYour previous output failed validation with the following errors:\n",s="\n\nReturn ONLY valid JSON conforming to script_v1 this time. NO markdown, NO commentary.",l=A,"number"==typeof r&&r>0&&(l=function(e,t){if(t<=0)return"";if(e.length<=t)return e;let A="\n…[error truncated]…\n";if(t<=A.length)return e.slice(0,t);let r=t-A.length,i=Math.ceil(.6*r),n=r-i;return e.slice(0,i)+A+e.slice(e.length-n)}(A,r-d.length-t.length-s.length-64)),d+t+l+s),B=await h.generate({localPath:c,durationSeconds:g.mediaDuration??0,promptInstructions:Q,onProgress:t=>e.reportProgress(2,4,"step"),signal:E.signal}),C=K(B.text,{providerName:B.providerName,modelId:B.modelId??a,generatedAt:u,costUsd:null===I()?null:2*I(),costEstimated:!0,requestId:B.requestId});if(!C.ok)throw Error(`Script provider ${o} returned invalid output on both attempts. Last error: ${C.error}`);i=C.script}}finally{clearInterval(Q)}if(e.shouldCancel())throw Error("cancelled");return await e.checkpoint({stage:"validated"}),e.reportProgress(3,4,"step"),await (0,z.saveScript)({fileId:s,providerId:o,modelId:a,script:i}),e.reportProgress(4,4,"step"),er.info({op:"done",fileId:s,providerId:o,modelId:a},"script saved"),{script:i}}};e.s(["extraAnalysisModelRunner",0,ei],291083);var en=e.i(912714),es=e.i(775719),eo=e.i(867773),ea=e.i(153708),el=e.i(511956);async function eg(e,t){let A=e.body;if(!A){let A=Buffer.from(await e.arrayBuffer());if(A.byteLength>t)throw Error(`file too large: ${A.byteLength} bytes (max ${t})`);return A}let r=A.getReader(),i=[],n=0,s=!1;try{for(;;){let{done:e,value:A}=await r.read();if(e)break;if(A){if((n+=A.byteLength)>t)throw s=!0,Error(`file too large: exceeds ${t} bytes`);i.push(Buffer.from(A))}}}finally{r.releaseLock(),s&&A.cancel().catch(()=>{})}return Buffer.concat(i,n)}async function ec(e){let{url:t,guard:A}=e,r=e.maxBytes??524288e3,i=await (0,eo.fetchFollowingVettedRedirects)(t,A,{signal:e.signal??AbortSignal.timeout(12e4)});if(!i.ok)throw Error(`http ${i.status}`);let n=Number(i.headers.get("content-length"));if(Number.isFinite(n)&&n>r)throw Error(`file too large: ${n} bytes (max ${r})`);let s=await eg(i,r),o=e.filename||q.default.basename(new URL(t).pathname)||"download.bin",a=function(e){if(!e)return null;let t=e.split(";")[0].trim().toLowerCase();return t&&"application/octet-stream"!==t?e:null}(i.headers.get("content-type"))??(0,el.mimeFromExtension)(o);return{buffer:s,filename:o,contentType:a}}let eh=/^[0-9a-f]{64}$/;async function ed(e){let{buffer:t,filename:A,contentType:r}=await ec(e);if(void 0!==e.expectSha256){let r=e.expectSha256.trim().toLowerCase();if(!eh.test(r))throw Error(`invalid expectSha256 for ${A}: expected 64 hex characters, got ${JSON.stringify(e.expectSha256)} — refusing to store an unverified download.`);let i=(0,ea.sha256OfBuffer)(t);if(i!==r)throw Error(`sha256 mismatch for ${A}: expected ${r.slice(0,16)}…, got ${i.slice(0,16)}… — refusing to store a tampered/corrupt download.`)}let i=await (0,el.storeFile)({pieceId:e.pieceId,filename:A,buffer:t,contentType:e.contentType??r,skipProxyGeneration:e.skipProxyGeneration});return{fileId:i.id,bytes:t.byteLength,filename:i.filename}}e.s(["fetchAndStoreRemoteFile",0,ed,"fetchRemoteBuffer",0,ec],592720);let eu={kind:"remote_fetch",maxConcurrent:3,paramsSchema:t.z.object({urls:t.z.array(t.z.string()).min(1).max(20),pieceId:t.z.string().nullable(),autoUpload:t.z.boolean().default(!0)}),resumable:!0,noProgressTimeoutMs:12e4,mcpToolId:(0,S.makeMcpToolId)("libi","libi.import_remote_files"),async run(e){let{urls:t,pieceId:A,autoUpload:r}=e.params,i=[...e.resumeState?.items??[]];e.reportProgress(i.length,t.length,"files");for(let n=i.length;n<t.length;n++){if(e.shouldCancel())throw Error("cancelled");let s=t[n],o=function(e){try{return q.default.basename(new URL(e).pathname)}catch{return""}}(s)||`download-${n}.bin`;try{if(r){let e=await ed({url:s,guard:es.assertPublicHttpUrl,pieceId:A,filename:o});i.push({url:s,status:"ok",fileId:e.fileId,bytes:e.bytes})}else{let{buffer:t}=await ec({url:s,guard:es.assertPublicHttpUrl,filename:o}),A=q.default.join((0,j.getLibiHome)(),"tmp","remote-fetch",e.jobId);await en.default.mkdir(A,{recursive:!0});let r=q.default.join(A,o);await en.default.writeFile(r,t),i.push({url:s,status:"ok",localPath:r,bytes:t.byteLength})}}catch(t){J.serverLogger.warn({tag:"remote-fetch",op:"url_error",url:s,jobId:e.jobId,err:t},"remote_fetch: url failed"),i.push({url:s,status:"error",error:t instanceof Error?t.message:String(t)})}await e.checkpoint({items:i}),e.reportProgress(i.length,t.length,"files")}if(i.length>0&&i.every(e=>"error"===e.status)){let e=i.find(e=>"error"===e.status);throw Error(`all ${i.length} downloads failed: ${e&&"error"in e?e.error:"unknown"}`)}return{items:i}}};e.s(["remoteFetchRunner",0,eu],449080);var eE=e.i(660526),eQ=e.i(567209),eI=e.i(366087),eB=e.i(874533),eC=e.i(695687);async function ef(e){let t=(0,eC.sidecarProjectDir)(),A=(0,eB.spawn)((0,eC.uvPath)(),["run","--frozen","python","track_runner.py"],{cwd:t,env:(0,a.buildUvEnv)({UV_PROJECT_ENVIRONMENT:(0,a.trackingVenvDir)(),LIBI_TRACK_MODELS:process.env.LIBI_TRACK_MODELS??(0,eC.trackingModelsDir)()}),windowsHide:!0,stdio:["pipe","pipe","pipe"]});A.stdin.write(JSON.stringify({method:"matte",videoPath:(0,q.resolve)(e.videoPath),range:e.range,outputDir:(0,q.resolve)(e.outputDir),seedBox:e.seedBox??null,seedMaskPath:e.seedMaskPath??null,maxDim:e.maxDim??1080,warmup:10})),A.stdin.end();let r="",i=null,n=setInterval(()=>{if(e.shouldCancel?.())try{A.kill("SIGKILL")}catch{}},1e3);A.stdout.on("data",t=>{let A;for(r+=t.toString("utf8");(A=r.indexOf("\n"))>=0;){let t,n=r.slice(0,A).trim();if(r=r.slice(A+1),n){try{t=JSON.parse(n)}catch{continue}"progress"===t.type?e.onProgress?.(Number(t.done),Number(t.total)):"result"===t.type&&(i={outputDir:String(t.outputDir??""),frameCount:Number(t.frameCount??0),framerate:Number(t.framerate??0),device:String(t.device??"cpu"),msPerFrame:Number(t.msPerFrame??0),coverage:Number(t.coverage??0),flags:Array.isArray(t.flags)?t.flags.map(String):[],..."string"==typeof t.error?{error:t.error}:{}})}}});let s="";if(A.stderr.on("data",e=>{s+=e.toString("utf8")}),await new Promise((e,t)=>{A.on("error",t),A.on("close",A=>{if(clearInterval(n),0!==A&&!i)return J.serverLogger.error({tag:"matte",op:"sidecar.fail",code:A,stderr:s.slice(-1e3)},"matte sidecar failed"),t(Error(`matte sidecar exited ${A}: ${s.slice(-500)}`));e()})}),!i)throw Error("matte sidecar produced no result");return i}var ep=e.i(632484),ey=e.i(110139);let em=t.z.object({fileId:t.z.string().min(1),engine:t.z.literal("local"),subject:t.z.object({kind:t.z.enum(["auto","box"]),box:t.z.tuple([t.z.number(),t.z.number(),t.z.number(),t.z.number()]).optional()}),range:t.z.object({start:t.z.number().nonnegative(),end:t.z.number().positive()}).optional()}),ew={kind:"matte_gen",mcpToolId:[(0,S.makeMcpToolId)("libi","libi.remove_background"),(0,S.makeMcpToolId)("libi-tracking","libi.remove_background")],maxConcurrent:1,paramsSchema:em,resumable:!1,noProgressTimeoutMs:null,async run(e){if(!(0,ep.trackingEngineInstalled)())throw Error(JSON.stringify((0,ep.trackingNotInstalledError)()));let[t]=(0,v.getDb)().select().from(x.files).where((0,L.eq)(x.files.id,e.params.fileId)).limit(1).all();if(!t)throw Error(`file not found: ${e.params.fileId}`);if("video"!==t.type)throw Error(`file is not a video: ${t.id} (photos go through the fal birefnet path)`);let A=t.pieceId?q.default.join((0,j.getLibiStorageDir)(),t.pieceId):q.default.join((0,j.getLibiStorageDir)(),"_global"),r=q.default.join(A,t.filename);if(!T.default.existsSync(r))throw Error(`source missing: ${r}`);let i=t.mediaDuration??null;if(null==i&&(i=(await (0,eI.probeMedia)(r)).duration??null),null==i)throw Error(`cannot determine duration of ${r}`);let n=e.params.range??{start:0,end:i},s=T.default.mkdtempSync(q.default.join(eE.default.tmpdir(),"libi-matte-")),o=q.default.join(s,"alpha");T.default.mkdirSync(o,{recursive:!0});try{var a,l;let A,i;J.serverLogger.info({tag:"matte",op:"matte_start",jobId:e.jobId,fileId:t.id,range:n,subject:e.params.subject.kind},"matte generation start");let g=await ef({videoPath:r,range:n,outputDir:o,seedBox:"box"===e.params.subject.kind?e.params.subject.box??null:null,onProgress:(t,A)=>e.reportProgress(t,A,"frames"),shouldCancel:()=>e.shouldCancel()});if(e.shouldCancel())throw new ey.CancelledError(e.jobId);if(g.error||0===g.frameCount)throw Error("no_seed_instance"===g.error?"no_seed_instance: the seed step found no subject at the range start — pass a subject box from libi.ground_target, or use the fal engine":"matte produced no frames");if(g.flags.length>0){let A=(100*g.coverage).toFixed(2),r=g.flags.includes("empty_matte")?`empty_matte: the matte kept only ${A}% of the frame — the subject was lost, so the cutout would render as nothing. Re-seed with a subject box from libi.ground_target, start the range where the subject is clearly visible, or use the paid fal engine.`:`full_frame_matte: the matte kept ${A}% of the frame — nothing was removed, so compositing this over a new background would silently show the original scene. Re-seed with a tighter subject box, or use the paid fal engine.`;throw J.serverLogger.warn({tag:"matte",op:"matte_coverage_rejected",jobId:e.jobId,fileId:t.id,coverage:g.coverage,flags:g.flags,frameCount:g.frameCount},"matte rejected by coverage gate"),Error(r)}let c=(a=t.filename,A=q.default.extname(a),i=q.default.basename(a,A),`${i}-cutout.webm`),h=q.default.join(s,c),d=new AbortController,u=setInterval(()=>{e.shouldCancel()&&!d.signal.aborted&&d.abort()},1e3);try{await (0,eQ.runFfmpeg)((l={range:n,framerate:g.framerate,frameCount:g.frameCount},["-y","-ss",String(l.range.start),"-to",String(l.range.end),"-i",r,"-framerate",String(l.framerate),"-start_number","0","-i",q.default.join(o,"f%06d.png"),"-filter_complex",`[0:v]fps=${l.framerate},format=rgba[rgb];[1:v]format=gray[a];[rgb][a]alphamerge[out]`,"-map","[out]","-frames:v",String(l.frameCount),"-c:v","libvpx-vp9","-pix_fmt","yuva420p","-auto-alt-ref","0","-b:v","0","-crf","30","-row-mt","1","-an",h]),{op:"matte_compose",context:{fileId:t.id,pieceId:t.pieceId,jobId:e.jobId},signal:d.signal})}finally{clearInterval(u)}if(e.shouldCancel())throw new ey.CancelledError(e.jobId);let E=await (0,el.storeFile)({pieceId:t.pieceId,filename:c,buffer:T.default.readFileSync(h),contentType:"video/webm",hasAlpha:!0,name:c,description:`Alpha cutout of "${t.name}" (${n.start.toFixed(2)}-${n.end.toFixed(2)}s, MatAnyone local matte, VP9-alpha WebM)`});try{t.pieceId?M.navigationEmitter.emit("refresh_query",{queryKey:"piece",pieceId:t.pieceId}):M.navigationEmitter.emit("refresh_query",{queryKey:"files"})}catch(e){J.serverLogger.warn({tag:"matte",op:"refresh_query_emit_failed",err:e,fileId:t.id},"matte refresh_query emit failed")}return J.serverLogger.info({tag:"matte",op:"matte_done",jobId:e.jobId,fileId:t.id,cutoutFileId:E.id,frameCount:g.frameCount,device:g.device,msPerFrame:g.msPerFrame},"matte generation complete"),{cutoutFileId:E.id,frameCount:g.frameCount,framerate:g.framerate,engine:"local",msPerFrame:g.msPerFrame}}finally{T.default.rmSync(s,{recursive:!0,force:!0})}}};e.s(["matteGenRunner",0,ew],241744);var eD=e.i(991858),eb=e.i(812057),eS=e.i(986343),eN=e.i(49614),eR=e.i(652851);let eF="https://registry.npmjs.org/",ek=new Set(["localhost","127.0.0.1","[::1]","::1"]);function eM(e){let t=e.env??process.env,A=t.LIBI_REGISTRY_URL?.trim();if(!A)return{url:eF,source:"public"};if(!e.isPackaged)return{url:eF,source:"public",rejected:"not-packaged"};if(t.LIBI_WORKTREE_NAME?.trim())return{url:eF,source:"public",rejected:"worktree"};let r=function(e){let t,A=e?.trim();if(!A)return{rejected:"invalid-url"};try{t=new URL(A)}catch{return{rejected:"invalid-url"}}return"http:"!==t.protocol&&"https:"!==t.protocol?{rejected:"unsupported-protocol"}:t.username||t.password?{rejected:"embedded-credentials"}:"http:"!==t.protocol||ek.has(t.hostname)?(t.search="",t.hash="",t.pathname.endsWith("/")||(t.pathname+="/"),{url:t.toString()}):{rejected:"insecure-remote"}}(A);return"rejected"in r?{url:eF,source:"public",rejected:r.rejected}:{url:r.url,source:"override"}}function eU(){return!!process.versions.electron&&!process.defaultApp}var eT=e.i(772991),eL=e.i(511724),ev=e.i(246387);class ex extends Error{code;constructor(e,t){super(t),this.name="NextExternalsError",this.code=e}}let eY="externals-manifest.json";function eH(e){return`Rebuild with \`npm run build\` (or \`node scripts/next-build-release.js\`), which writes ${q.default.join(".next",eY)} as part of the build; if you installed this from npm, reinstall the package (the published tarball always carries the manifest). Checked: ${e}`}let eG=(0,eb.promisify)(eB.execFile),eO="@nagellabs/libi",eV=".libi-runtime.json",eJ="github.com",e_="runtime-install";class eP extends Error{kind;host;constructor(e,t,A=null){super(t),this.name="RuntimeInstallError",this.kind=e,this.host=A}}function eW(){return q.default.join((0,j.getLibiHome)(),"runtime")}function eq(e){return q.default.join(e,"node_modules",...eO.split("/"))}function ej(e){try{return new URL(e).host}catch{return e}}async function ez(e,t,A){let r=(0,eN.buildSpawnEnv)();return"electron-utility-process"===(0,eS.selectNpmRunner)()?await (0,eS.runNpmViaUtilityProcess)(e,t,{cwd:A,env:r,timeoutMs:9e5}):await eG(process.execPath,[e,...t],{cwd:A,env:{...r,ELECTRON_RUN_AS_NODE:"1"},timeout:9e5,windowsHide:!0,maxBuffer:0x1000000})}async function eX(e){let t=e.registryUrl??eF,A=e.runtimeRootDir??eW(),r=q.default.join(A,e.version),i=q.default.join(A,`.tmp-${e.version}-${process.pid}-${Date.now()}`),n=e.onProgress??(()=>{});T.default.mkdirSync(A,{recursive:!0}),T.default.rmSync(i,{recursive:!0,force:!0}),T.default.mkdirSync(i,{recursive:!0});try{T.default.writeFileSync(q.default.join(i,"package.json"),JSON.stringify({name:"libi-runtime",version:"0.0.0",private:!0,description:"Generated by lib/runtime/runtime-install.ts — a fetched @nagellabs/libi runtime snapshot. Do not edit."},null,2)+"\n");let A=(0,eS.resolveVendoredNpmCli)(),s=["install",`${eO}@${e.version}`,"--omit=dev","--ignore-scripts","--no-audit","--no-fund",`--registry=${t}`];n(`Downloading libi ${e.version}…`),J.serverLogger.info({tag:e_,op:"npm_install_start",version:e.version,registryUrl:t},"installing runtime snapshot");try{await ez(A,s,i)}catch(A){let e=A instanceof Error?A.message:String(A);if((0,eT.looksUnreachable)(e))throw new eP("registry-unreachable",`Could not reach the npm registry (${ej(t)}): ${e}`,ej(t));throw new eP("unknown",`npm install failed: ${e}`)}let o=eq(i);if(!T.default.existsSync(o))throw new eP("verification-failed",`npm install produced no runtime root at ${o}`);n("Preparing the database engine…"),await eK({prefix:i}),await e$({prefix:i,electronVersion:e.electronVersion});let a=JSON.parse(T.default.readFileSync(q.default.join(o,"package.json"),"utf-8")),l=a.libi?.shellApiVersion;if(a.name!==eO||!Number.isInteger(l))throw new eP("verification-failed",`installed package is ${String(a.name)}@${String(a.version)} with shellApiVersion ${String(l)}`);for(let e of["dist-cli/lib/runtime/shell-api.js",".next/BUILD_ID"])if(!T.default.existsSync(q.default.join(o,e)))throw new eP("verification-failed",`the downloaded runtime is missing ${e}`);try{!function(e){let t=q.default.join(e,"node_modules"),A=function(e){let t=q.default.join(e,eY);try{let e=T.default.readFileSync(t,"utf-8"),A=JSON.parse(e);if(!A||"object"!=typeof A||Array.isArray(A))return null;let{buildId:r,links:i}=A;if("string"!=typeof r||0===r.length||!Array.isArray(i))return null;return{buildId:r,links:i.filter(e=>!!e&&"string"==typeof e.link&&"string"==typeof e.package)}}catch{return null}}(e);if(!A){let A,r;if(A=!1,r=!0,!function e(t){let i;try{i=T.default.readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of i){let i=q.default.join(t,n.name);if(n.isSymbolicLink()){A=!0;try{T.default.realpathSync(i)}catch{r=!1}}else n.isDirectory()&&e(i)}}(t),A&&r)return;throw new ex("MANIFEST_MISSING",`Next.js externals manifest is missing or unreadable and .next/node_modules holds no usable symlinks. Turbopack externalises packages under hashed names that resolve only through that symlink farm, so the server would start and then fail EVERY request with a 500. ${eH(e)}`)}let r=function(e){try{let t=T.default.readFileSync(q.default.join(e,"BUILD_ID"),"utf-8").trim();return t.length>0?t:null}catch{return null}}(e);if(null===r)throw new ex("MANIFEST_STALE",`Next.js externals manifest found, but .next/BUILD_ID is missing — this is not a complete production build, so the manifest cannot be verified against it. ${eH(e)}`);if(r!==A.buildId)throw new ex("MANIFEST_STALE",`Next.js externals manifest is STALE: it was written for build "${A.buildId}" but .next/BUILD_ID is "${r}". Turbopack's hashed external names change between builds, so restoring from it would create symlinks under the previous build's names and every request would 500. ${eH(e)}`);if(0===A.links.length)return;let i=[],n=[],s=[];for(let r of A.links){let A=function(e,t){let A=q.default.resolve(e);for(let e=0;e<64;e++){let e=q.default.join(A,"node_modules",t);if(T.default.existsSync(e))return e;let r=q.default.dirname(A);if(r===A)break;A=r}return null}(e,r.package);if(!A){s.push(r);continue}let o=q.default.join(t,r.link);try{if(T.default.lstatSync(o).isSymbolicLink()&&T.default.realpathSync(o)===T.default.realpathSync(A)){n.push(r);continue}T.default.rmSync(o,{force:!0,recursive:!0})}catch{}let a=q.default.dirname(o);T.default.mkdirSync(a,{recursive:!0}),(0,ev.isWindows)()?T.default.symlinkSync(A,o,"junction"):T.default.symlinkSync(q.default.relative(a,A),o,"dir"),i.push(r)}if(s.length>0)throw new ex("PACKAGES_MISSING",`Could not locate ${s.length} externalised package(s) in any ancestor node_modules: ${s.map(e=>e.package).join(", ")}. The server would start and then fail requests that touch them. Reinstall dependencies (\`npm install\`) and try again. Searched upward from: ${e}`)}(q.default.join(o,".next"))}catch(e){throw new eP("verification-failed",`the downloaded runtime's Next.js externals could not be restored: ${e instanceof Error?e.message:String(e)}`)}T.default.writeFileSync(q.default.join(i,eV),JSON.stringify({package:eO,version:a.version,shellApiVersion:l,abi:e.abi,electronVersion:e.electronVersion,source:"fetched",installedAt:new Date().toISOString()},null,2)+"\n");let g=T.default.existsSync(r)?`${r}.old-${Date.now()}`:null;return g&&T.default.renameSync(r,g),T.default.renameSync(i,r),g&&T.default.rmSync(g,{recursive:!0,force:!0}),J.serverLogger.info({tag:e_,op:"install_done",version:a.version,shellApiVersion:l,abi:e.abi,prefix:r},"runtime snapshot installed"),{prefix:r,root:eq(r),version:a.version,shellApiVersion:l,abi:e.abi}}catch(t){T.default.rmSync(i,{recursive:!0,force:!0});let e=t instanceof eP?t:new eP("unknown",t instanceof Error?t.message:String(t));throw J.serverLogger.warn({tag:e_,op:"install_failed",kind:e.kind,host:e.host},e.message),e}}function eZ(e){let t=(0,eL.betterSqliteModuleDir)(e);if(!T.default.existsSync(t))throw new eP("verification-failed",`better-sqlite3 is not present in the downloaded runtime (${t})`);let A=[q.default.join(e,"node_modules","prebuild-install","bin.js"),q.default.join(t,"node_modules","prebuild-install","bin.js")].find(e=>T.default.existsSync(e));if(!A)throw new eP("verification-failed","prebuild-install is missing from the downloaded runtime, so the native database binding cannot be resolved without compiling — which libi will not do.");return{moduleDir:t,bin:A}}async function eK(e){let{moduleDir:t,bin:A}=eZ(e.prefix),r=q.default.join(t,"build"),i=q.default.join(r,"Release","better_sqlite3.node"),n=[];for(let e of eL.NODE_ABI_SIDECAR_MAJORS){try{await eG((0,eR.resolveNodeCommand)(),[A,"--runtime=node",`--target=${e}.0.0`],{cwd:t,windowsHide:!0,env:(0,eN.buildSpawnEnv)(),timeout:3e5,maxBuffer:0x1000000})}catch{}if(!T.default.existsSync(i)){J.serverLogger.warn({tag:e_,op:"sidecar_skipped",major:e},"no better-sqlite3 prebuild for this node major");continue}let s=q.default.join(r,(0,eL.sidecarDirName)(e));T.default.mkdirSync(s,{recursive:!0}),T.default.copyFileSync(i,q.default.join(s,"better_sqlite3.node")),n.push(e)}if(T.default.rmSync(i,{force:!0}),0===n.length)throw new eP("prebuild-unreachable",`Could not download a Node database binding from ${eJ} for any supported Node version (${eL.NODE_ABI_SIDECAR_MAJORS.join(", ")}). libi's agent tools run in a separate Node process, so this runtime would boot a working window in which none of them can reach the database.`,eJ);return J.serverLogger.info({tag:e_,op:"sidecars_fetched",majors:n},"parked plain-node better-sqlite3 bindings"),n}async function e$(e){let{moduleDir:t,bin:A}=eZ(e.prefix),r=[A,"--runtime=electron",`--target=${e.electronVersion}`,"--dist-url=https://electronjs.org/headers"],i=q.default.join(t,"build","Release","better_sqlite3.node");try{await eG((0,eR.resolveNodeCommand)(),r,{cwd:t,windowsHide:!0,env:(0,eN.buildSpawnEnv)(),timeout:3e5,maxBuffer:0x1000000})}catch(e){if(T.default.existsSync(i))J.serverLogger.warn({tag:e_,op:"prebuild_command_failed_artifact_ok",err:e instanceof Error?e.message:String(e)},"prebuild-install did not exit cleanly but the binding is present");else{let t=e instanceof Error?e.message:String(e);throw new eP("prebuild-unreachable",`Could not download the native database binding from ${eJ}: ${t}`,eJ)}}if(!T.default.existsSync(i))throw new eP("prebuild-unreachable",`prebuild-install reported success but ${i} is missing`,eJ)}e.s(["RUNTIME_PACKAGE",0,eO,"RUNTIME_STAMP_FILE",0,eV,"RuntimeInstallError",0,eP,"installRuntime",0,eX,"userRuntimeDir",0,eW],997734);let e0="LIBI_SHELL_API_MIN",e1="LIBI_SHELL_API_MAX";function e2(e,t){let A=e[t]?.trim();if(!A)return null;let r=Number(A);return Number.isInteger(r)?r:null}function e4(e={}){let t=e.env??process.env,A=e.cwd??process.cwd(),r=e.isPackaged??eU(),i=function(e){try{let t=T.default.readFileSync(q.default.join(e,"package.json"),"utf-8"),A=JSON.parse(t),r="string"==typeof A.version?A.version:null,i=A.libi?.shellApiVersion;return{version:r,shellApiVersion:Number.isInteger(i)?i:null}}catch{return{version:null,shellApiVersion:null}}}(A),n=t.LIBI_RUNTIME_VERSION?.trim()||i.version,s=t.LIBI_RUNTIME_SOURCE?.trim(),o="bundled"===s||"user"===s?s:r?"bundled":q.default.resolve(A).split(q.default.sep).includes("node_modules")?"npm":"dev",a=i.shellApiVersion,l=e2(t,e0),g=e2(t,e1),c=null;return null!==l&&null!==g&&l<=g?c={min:l,max:g}:null!==a&&(c={min:a,max:a},r&&(null!==l||null!==g)&&J.serverLogger.warn({tag:"runtime-update",op:"shell_api_range_partial",min:l,max:g},"shell published only half a shellApiVersion range — falling back to the runtime's own version")),{version:n,shellApiVersion:a,source:o,shellApi:c,bundledVersion:t.LIBI_BUNDLED_VERSION?.trim()||null,updatesSupported:r}}e.s(["SHELL_API_MAX_ENV",0,e1,"SHELL_API_MIN_ENV",0,e0,"describeCurrentRuntime",0,e4],263874);let e8="runtime-update";function e3(e,t){let A=e=>{let[t,...A]=e.trim().split("-"),r=t.split(".").map(e=>{let t=Number.parseInt(e,10);return Number.isFinite(t)?t:0});for(;r.length<3;)r.push(0);return{nums:r,pre:A.length>0?A.join("-"):null}},r=A(e),i=A(t);for(let e=0;e<Math.max(r.nums.length,i.nums.length);e+=1){let t=(r.nums[e]??0)-(i.nums[e]??0);if(0!==t)return t}return r.pre===i.pre?0:null===r.pre?1:null===i.pre||r.pre<i.pre?-1:1}function e5(e){let t=e.now??Date.now(),A={currentVersion:e.currentVersion,latestVersion:e.latest?.version??null,latestShellApiVersion:e.latest?.shellApiVersion??null,checkedAt:t};if(!e.updatesSupported)return{...A,state:"unsupported"};if(!e.currentVersion||!e.latest)return{...A,state:"unknown"};if(!(e3(e.latest.version,e.currentVersion)>0)||e.bundledVersion&&!(e3(e.latest.version,e.bundledVersion)>0))return{...A,state:"up-to-date"};if(null===e.latest.shellApiVersion||null===e.shellApi)return J.serverLogger.warn({tag:e8,op:"classify_indeterminate",latest:e.latest.version,latestShellApiVersion:e.latest.shellApiVersion,shellApi:e.shellApi},"newer version found but its shell-API compatibility could not be determined"),{...A,state:"unknown"};let r=e.latest.shellApiVersion;return r<e.shellApi.min||r>e.shellApi.max?{...A,state:"shell-update-required"}:{...A,state:"update-available"}}function e9(e){if(!e||"object"!=typeof e||"string"!=typeof e.version||0===e.version.length)return null;let t=e.libi?.shellApiVersion;return{version:e.version,shellApiVersion:Number.isInteger(t)?t:null}}async function e6(e){let t=e.fetchImpl??fetch,A=e.timeoutMs??8e3,r=async e=>{let r=new AbortController,i=setTimeout(()=>r.abort(),A);try{let A=await t(e,{signal:r.signal,headers:{accept:"application/json"}});if(!A.ok)return null;return await A.json()}catch{return null}finally{clearTimeout(i)}},i=e9(await r(function(e,t=eO){let A=e.endsWith("/")?e:`${e}/`;return`${A}${t.replace("/","%2F")}/latest`}(e.registryUrl)));if(i)return i;let n=await r(function(e,t=eO){let A=e.endsWith("/")?e:`${e}/`;return`${A}${t.replace("/","%2F")}`}(e.registryUrl));if(!n||"object"!=typeof n)return null;let s=n["dist-tags"]?.latest;return"string"!=typeof s?null:e9(n.versions?.[s])??{version:s,shellApiVersion:null}}let e7=null;async function te(e={}){let t=e.now??Date.now();if(!e.force&&e7&&e7.expiresAt>t)return e7.status;let A=e.current??e4();if(!A.updatesSupported)return e5({currentVersion:A.version,latest:null,shellApi:A.shellApi,updatesSupported:!1,now:t});let r=e.registry??eM({isPackaged:eU()});r.rejected&&J.serverLogger.warn({tag:e8,op:"registry_override_ignored",reason:r.rejected},"LIBI_REGISTRY_URL was set but not applied");let i=await e6({registryUrl:r.url,fetchImpl:e.fetchImpl}),n=e5({currentVersion:A.version,latest:i,shellApi:A.shellApi,updatesSupported:!0,bundledVersion:A.bundledVersion,now:t});return null===i?J.serverLogger.info({tag:e8,op:"check_failed",registry:r.url},"update check could not reach the registry — staying silent"):J.serverLogger.info({tag:e8,op:"check_done",state:n.state,current:n.currentVersion,latest:n.latestVersion},"update check complete"),e7={status:n,expiresAt:t+("unknown"===n.state?9e5:216e5)},n}e.s(["checkForRuntimeUpdate",0,te,"compareVersions",0,e3],419704);let tt="runtime-update",tA="runtime-update",tr=t.z.object({version:t.z.string().min(1)});e.s(["runtimeUpdateRunner",0,{kind:"runtime_update",maxConcurrent:1,paramsSchema:tr,resumable:!1,noProgressTimeoutMs:null,async run(e){let t,A=process.versions.electron,r=eU();if(!A||!r)throw Error("in-app runtime updates are only available in the packaged desktop app");let i=e4(),n=eM({isPackaged:r}).url,s=0;e.reportProgress(s,3,"steps"),J.serverLogger.info({tag:tA,op:"install_start",version:e.params.version,from:i.version,registryUrl:n},"installing runtime update");try{t=await eX({version:e.params.version,registryUrl:n,electronVersion:A,abi:process.versions.modules,onProgress:t=>{s=Math.min(s+1,2),e.reportProgress(s,3,"steps"),J.serverLogger.info({tag:tA,op:"install_progress",message:t},"runtime update progress")}})}catch(e){throw e instanceof eP&&J.serverLogger.warn({tag:tA,op:"install_failed",kind:e.kind,host:e.host},e.message),e}let o=[];try{o=function(e={}){let t,A=Math.max(1,e.keep??2),r=e.rootDir??eW(),i=e.protectPrefix?q.default.resolve(e.protectPrefix):null;try{t=T.default.readdirSync(r,{withFileTypes:!0})}catch{return{removed:[],kept:[]}}let n=[],s=(e,t)=>{let A=q.default.join(r,e);if(!i||q.default.resolve(A)!==i)try{T.default.rmSync(A,{recursive:!0,force:!0}),n.push(A),J.serverLogger.info({tag:tt,op:"prune_removed",dir:A,why:t},"pruned runtime")}catch(e){J.serverLogger.warn({tag:tt,op:"prune_failed",dir:A,err:e.message},"could not prune runtime directory")}};for(let e of t)e.isDirectory()&&(e.name.startsWith(".tmp-")||e.name.includes(".old-"))&&s(e.name,"debris");let o=t.filter(e=>e.isDirectory()&&!e.name.startsWith(".")).map(e=>e.name).filter(e=>!e.includes(".old-")).sort((e,t)=>e3(t,e)),a=[],l=0;for(let e of o){let t=q.default.join(r,e),n=null!==i&&q.default.resolve(t)===i;if(l<A||n){a.push(t),l+=1;continue}s(e,"surplus")}return{removed:n,kept:a}}({protectPrefix:function(e=process.cwd()){let t=q.default.resolve(e).split(q.default.sep);if(t.length<4)return null;let[A,r]=[t[t.length-2],t[t.length-1]];return"node_modules"!==t[t.length-3]||"@nagellabs/libi"!=`${A}/${r}`?null:t.slice(0,t.length-3).join(q.default.sep)}(),rootDir:eW()}).removed}catch(e){J.serverLogger.warn({tag:tA,op:"prune_error",err:e.message},"post-install prune failed (harmless)")}return e.reportProgress(3,3,"steps"),J.serverLogger.info({tag:tA,op:"install_done",version:t.version,prefix:t.prefix,prunedCount:o.length},"runtime update installed — applies at next launch"),(0,eD.trackServerEvent)("runtime_update_installed",{previous_source:i.source}),{version:t.version,prefix:t.prefix,shellApiVersion:t.shellApiVersion,pruned:o}}}],958933)},241983,788170,e=>{"use strict";var t=e.i(522734),A=e.i(814747),r=e.i(577833),i=e.i(246387);let n="yt-dlp-uv@2026-07-06",s="__NODE__";function o(e){return A.default.join(e,"yt-dlp.install-token")}let a={"tracking-pyenv":r.trackingPyenvInstaller,"playwright-chromium":{verify:async()=>{try{let{chromium:A}=await e.A(164351),r=A.executablePath();return t.default.existsSync(r)?r:null}catch{return null}},install:{command:s,args:["__PLAYWRIGHT_CORE_CLI__","install","chromium"],timeoutMs:6e5}},"yt-dlp-uv":{verify:async()=>{let{getLibiBinDir:r}=await e.A(336270),s=r(),a=A.default.join(s,(0,i.isWindows)()?"yt-dlp.cmd":"yt-dlp");try{t.default.lstatSync(a)}catch{return null}try{t.default.realpathSync(a)}catch{return null}let l="";try{l=t.default.readFileSync(o(s),"utf-8").trim()}catch{l=""}return l!==n?null:a},install:{command:"__YT_DLP_UV_INSTALL__",args:[],timeoutMs:3e5}}};function l(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}e.s(["NODE_COMMAND_SENTINEL",0,s,"YT_DLP_UV_TOKEN",0,n,"getCustomInstaller",0,function(e){return a[e]},"resolvePlaywrightCoreCli",0,function(){let e=process.cwd();for(let r=0;r<8;r++){let r=A.default.join(e,"node_modules","playwright-core","cli.js");if(t.default.existsSync(r))return r;let i=A.default.dirname(e);if(i===e)break;e=i}throw Error("Could not locate node_modules/playwright-core/cli.js relative to cwd. Ensure playwright-core is installed.")},"ytDlpTokenPath",0,o],241983),e.s(["resolveGlob",0,function(e,r){let i=r.split("/"),n=[e];for(let e of i){if(!e.includes("*")){n=n.map(t=>A.default.join(t,e));continue}let r=[],i=RegExp("^"+e.split("*").map(l).join(".*")+"$");for(let e of n)if(t.default.existsSync(e))for(let n of t.default.readdirSync(e))i.test(n)&&r.push(A.default.join(e,n));n=r}for(let e of n)if(t.default.existsSync(e))return e;return null}],788170)},719373,921179,100164,e=>{"use strict";e.s(["DependencyManager",()=>K],719373);var t=e.i(233405),A=e.i(224361),r=e.i(522734),i=e.i(814747),n=e.i(446786),s=e.i(190793),o=e.i(478181),a=e.i(875225),l=e.i(88690),g=e.i(246682),c=e.i(241983),h=e.i(652851),d=e.i(246387),u=e.i(270958),E=e.i(470072),Q=e.i(640911),I=e.i(153708),B=e.i(788170),C=e.i(452183);e.s(["ensureBootstrapped",()=>X,"getVirtualDepsForMcp",()=>j],100164);var f=e.i(619955),p=e.i(48989);let y=new Set;function m(e){return y.has(e)}e.s(["clearInstalling",0,function(e){y.delete(e)},"isInstalling",0,m,"markInstalling",0,function(e){y.add(e)}],921179);let w={id:"ace-step-model",label:`ace-step weights (${f.ACESTEP_DOWNLOAD_SIZE_HUMAN})`,async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,f.isAceStepModelInstalled)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,p.getJobManager)(),t=await e.enqueue("music_model_download",{force:!1});"matching_completed"!==t.status&&await e.runToCompletion(t.jobId)}};var D=e.i(407415);e.i(254799);var b=e.i(346385),S=e.i(775497);e.i(961288);let N="3.12",R=["librosa==0.11.0","soundfile"];function F(){return(0,S.hashSpec)(N,R)}[...R.flatMap(e=>["--with",e])];class k extends Error{constructor(e){super(e),this.name="MusicAnalyzeError"}}var M=e.i(799261);let U=".libi-music-analysis.install-token";async function T(e=3e5){let A=(0,b.requireUvBinary)(k,"Music analysis"),r=["run","--python",N,...R.flatMap(e=>["--with",e]),"python","-c","import librosa, soundfile; print('ok')"];await new Promise((i,n)=>{let s=(0,t.spawn)(A,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"],env:(0,E.buildUvEnv)()}),o="",a=setTimeout(()=>{s.kill("SIGKILL"),n(new k(`install timed out after ${e}ms`))},e);s.stdout.on("data",()=>{}),s.stderr.on("data",e=>o+=e.toString()),s.on("close",e=>{clearTimeout(a),0===e?i():n(new k(`install exited ${e}: ${(0,D.formatStderrTail)(o)}`))})}),(0,M.writeInstallToken)(U,F())}let L=[w,{id:"ace-step-env",label:"ace-step env",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,D.isAceStepEnvCurrent)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){await (0,D.generateMusic)({prompt:"warmup",durationSeconds:1,instrumental:!0,seed:0})}},{id:"music-analysis-env",label:"librosa env (~50 MB)",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,M.isTokenCurrent)(U,F());return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){await T()}}];var v=e.i(332879);let x=v.DEFAULT_WHISPER_MODEL,Y={id:"whisper-model",label:`whisper ${x} weights`,async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,v.isWhisperModelInstalled)(x);return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,p.getJobManager)(),t=await e.enqueue("whisper_model_download",{model:x});"matching_completed"!==t.status&&await e.runToCompletion(t.jobId)}};var H=e.i(720659);class G extends Error{constructor(e){super(e),this.name="WhisperEnvInstallError"}}let O=[Y,{id:"whisper-env",label:"whisper env (faster-whisper)",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,H.isWhisperEnvCurrent)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,b.requireUvBinary)(G,"Whisper"),A=["run","--python",H.WHISPER_PYTHON_VERSION,...H.WHISPER_WITH_SPECS.flatMap(e=>["--with",e]),"python","-c","import faster_whisper; print('ok')"];await new Promise((r,i)=>{let n=(0,t.spawn)(e,A,{windowsHide:!0,stdio:["ignore","pipe","pipe"],env:(0,E.buildUvEnv)()}),s="",o=setTimeout(()=>{n.kill("SIGKILL"),i(new G("install timed out after 5 minutes"))},3e5);n.stdout.on("data",()=>{}),n.stderr.on("data",e=>s+=e.toString()),n.on("close",e=>{clearTimeout(o),0===e?r():i(new G(`install exited ${e}: ${s.trim().slice(-2e3)}`))})}),(0,H.writeWhisperEnvToken)()}}];var V=e.i(513887),J=e.i(457888);class _ extends Error{constructor(e){super(e),this.name="TtsEnvInstallError"}}let P=[{id:"tts-model",label:"kokoro TTS weights",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,V.isKokoroModelInstalled)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,p.getJobManager)(),t=await e.enqueue("tts_model_download",{});"matching_completed"!==t.status&&await e.runToCompletion(t.jobId)}},{id:"tts-env",label:"kokoro env (kokoro-onnx)",async inspect(){if(m(this.id))return{binary:this.label,installed:!1,path:null,source:null,runtimeStatus:"installing",error:null};let e=(0,J.isTtsEnvCurrent)();return{binary:this.label,installed:e,path:null,source:e?"bundled":null,runtimeStatus:e?"installed":"pending",error:null}},async install(){let e=(0,b.requireUvBinary)(_,"Kokoro TTS"),A=["run","--python",J.TTS_PYTHON_VERSION,...J.TTS_WITH_SPECS.flatMap(e=>["--with",e]),"python","-c","import kokoro_onnx, soundfile; print('ok')"];await new Promise((r,i)=>{let n=(0,t.spawn)(e,A,{windowsHide:!0,stdio:["ignore","pipe","pipe"],env:(0,E.buildUvEnv)()}),s="",o=setTimeout(()=>{n.kill("SIGKILL"),i(new _("install timed out after 5 minutes"))},3e5);n.stdout.on("data",()=>{}),n.stderr.on("data",e=>s+=e.toString()),n.on("close",e=>{clearTimeout(o),0===e?r():i(new _(`install exited ${e}: ${s.trim().slice(-2e3)}`))})}),(0,J.writeTtsEnvToken)()}}],W=new Map;function q(e,t){let A=new Set;for(let r of t){if(A.has(r.id))throw Error(`duplicate virtual-dep id "${r.id}" for mcp "${e}"`);A.add(r.id)}W.set(e,t)}function j(e){return W.get(e)??[]}let z=!1;function X(){z||(z=!0,q("local-music",L),q("whisper",O),q("local-tts",P))}let Z=(0,A.promisify)(t.execFile);class K{skipDbWrites=!1;static unverifiedBinariesWarned=new Set;async verifyBinaryIntegrity(e,t){if(e.sha256){try{await (0,I.verifySha256)(t,e.sha256)}catch(e){try{r.default.unlinkSync(t)}catch{}throw e}Q.serverLogger.info({tag:"security",op:"binary_verified",binary:e.binary,sha256Prefix:e.sha256.slice(0,16)},`Verified sha256 of downloaded binary "${e.binary}"`);return}K.unverifiedBinariesWarned.has(e.binary)||(K.unverifiedBinariesWarned.add(e.binary),Q.serverLogger.warn({tag:"security",op:"binary_unverified",binary:e.binary},`Downloaded binary "${e.binary}" WITHOUT sha256 verification — its download URL is a "latest" alias with no pinned hash (transport was HTTPS-only). Re-host as a pinned release asset + set the dep's sha256 to enable content verification.`))}setSkipDbWrites(e){this.skipDbWrites=e}async ensureAll(e){await this.installBundledDeps(e),await this.prewarmBundledMcps(e)}static syncLog(t){try{let A=e.r(902157),r=e.r(750227),i=e.r(660526),n=r.join(process.env.LIBI_HOME??r.join(i.homedir(),".libi"),"logs");A.mkdirSync(n,{recursive:!0}),A.appendFileSync(r.join(n,"category-a-sync.log"),`[${new Date().toISOString()}] dm: ${t}
|
|
168
168
|
`)}catch{}}async installBundledDeps(e){this.ensureBinDir();let t=e?.tier??"all",A="tier-1"===t?l.BUNDLED_MCP_SERVERS.filter(e=>(e.installFlow??"tier-1")==="tier-1"||e.dependencies.some(e=>"tier-1"===e.installFlow)):l.BUNDLED_MCP_SERVERS;for(let r of(K.syncLog(`installBundledDeps: ${A.length} defs, tier=${t}`),A)){if(K.syncLog(`def loop: ${r.id} (deps=${r.dependencies.length})`),e?.failedOnly){let[e]=(0,s.getDb)().select().from(o.mcpServers).where((0,a.eq)(o.mcpServers.id,r.id)).limit(1).all();if(e&&"failed"!==e.installStatus)continue}if("tier-1"===t&&(r.installFlow??"tier-1")==="tier-2"){for(let t of r.dependencies.filter(e=>"tier-1"===e.installFlow))await this.installSingleDep(r.id,t,e?.onProgress);continue}await this.ensureMcp(r,e?.onProgress)}}async prewarmBundledMcps(e){let t=e?.tier??"all",A=l.BUNDLED_MCP_SERVERS.filter(e=>!e.core&&!e.noServer&&"http"!==e.type&&("tier-1"!==t||(e.installFlow??"tier-1")==="tier-1")),r=Date.now();Q.serverLogger.info({tag:"mcp-prewarm",op:"batch_start",count:A.length,ids:A.map(e=>e.id),failedOnly:e?.failedOnly===!0},`Pre-warming ${A.length} bundled MCP server(s)`);let i=[];for(let t of A)i.push(await this.prewarmMcp(t,e));Q.serverLogger.info({tag:"mcp-prewarm",op:"batch_done",durationMs:Date.now()-r,results:i},`Pre-warm batch done in ${Date.now()-r}ms`)}async prewarmMcp(e,t){if(e.core)return{id:e.id,status:"skipped",durationMs:0,skipped:"core"};if(e.noServer)return{id:e.id,status:"skipped",durationMs:0,skipped:"no-server"};if("http"===e.type)return{id:e.id,status:"skipped",durationMs:0,skipped:"http"};let[A]=(0,s.getDb)().select().from(o.mcpServers).where((0,a.eq)(o.mcpServers.id,e.id)).limit(1).all();if(A?.installStatus!=="installed"&&A?.installStatus!=="not_required")return Q.serverLogger.info({tag:"mcp-prewarm",op:"skip",mcpId:e.id,reason:"install_not_ready",installStatus:A?.installStatus??null},`Skipping pre-warm for "${e.id}" — install not ready`),{id:e.id,status:"skipped",durationMs:0,skipped:"install_not_ready"};if(t?.failedOnly&&"down"!==A.serverStatus)return{id:e.id,status:"skipped",durationMs:0,skipped:"not_failed"};let r=Date.now();Q.serverLogger.info({tag:"mcp-prewarm",op:"start",mcpId:e.id,command:e.command,args:e.args},`Pre-warming MCP "${e.id}" (${e.command} ${(e.args??[]).join(" ")})`);try{let t=await (0,g.probeAndPersist)(e),A=Date.now()-r;return Q.serverLogger.info({tag:"mcp-prewarm",op:"done",mcpId:e.id,status:t.status,durationMs:A},`Pre-warm done for "${e.id}" (${t.status}, ${A}ms)`),{id:e.id,status:t.status,durationMs:A}}catch(i){let t=Date.now()-r,A=i instanceof Error?i.message:String(i);return Q.serverLogger.error({tag:"mcp-prewarm",op:"error",mcpId:e.id,durationMs:t,err:A},`Pre-warm threw for "${e.id}"`),{id:e.id,status:"error",durationMs:t}}}static getBinDir(){return(0,u.getLibiBinDir)()}static pickPlatformValue(e){let t=process.platform,A=e[t];if(void 0===A)throw Error(`No download URL for platform=${t}`);if("string"==typeof A)return A;let r=process.arch,i=A[r];if(void 0!==i)return i;let n=Object.values(A).find(e=>void 0!==e);if(void 0===n)throw Error(`No download URL for platform=${t}, arch=${r}`);return n}static resolveDownloadUrl(e){if(!e.downloadUrl)throw Error(`Dependency ${e.binary} has no downloadUrl — likely a customInstaller dep called via the wrong path.`);return K.pickPlatformValue(e.downloadUrl)}static resolveBinaryPathInArchive(e){if(!e.archive)throw Error(`Dependency ${e.binary} has no archive metadata`);return K.pickPlatformValue(e.archive.binaryPathInArchive)}static evaluateConfigStatus(e){let t=e.requiredEnvVars??[];if(0===t.length)return{status:"installed",missing:[]};let A={};if(e.envVarsJson)try{A=JSON.parse(e.envVarsJson)}catch{}let r=t.filter(e=>!A[e]||""===A[e]);return 0===r.length?{status:"installed",missing:[]}:{status:"needs_config",missing:r}}async getStatuses(e){X();let t=l.BUNDLED_MCP_SERVERS.find(t=>t.id===e);return[...t?await Promise.all(t.dependencies.map(e=>this.resolveStatusAsync(e))):[],...await Promise.all(j(e).map(e=>e.inspect().catch(t=>({binary:e.label,installed:!1,path:null,source:null,runtimeStatus:"failed",error:t instanceof Error?t.message:String(t)}))))]}async settleInstallStatus(e){let t,A=l.BUNDLED_MCP_SERVERS.find(t=>t.id===e);if(!A||A.core)return null;let r=(0,s.getDb)(),[i]=r.select().from(o.mcpServers).where((0,a.eq)(o.mcpServers.id,e)).limit(1).all();if(!i)return null;if("failed"===i.installStatus||"installing"===i.installStatus)return i.installStatus;let n=await this.getStatuses(e),g=n.every(e=>e.installed),c=null;if(g)if(A.requiredEnvVars&&A.requiredEnvVars.length>0){let e=K.evaluateConfigStatus({requiredEnvVars:A.requiredEnvVars,envVarsJson:i.envVars??null});t=e.status,c="needs_config"===e.status?`Missing required env vars: ${e.missing.join(", ")}`:null}else t=0===A.dependencies.length&&0===j(e).length?"not_required":"installed";else t="pending";return r.update(o.mcpServers).set({installStatus:t,installError:c,dependencyStatus:JSON.stringify(n),updatedAt:new Date}).where((0,a.eq)(o.mcpServers.id,e)).run(),"installed"!==t&&"not_required"!==t&&"unknown"!==i.serverStatus&&r.update(o.mcpServers).set({serverStatus:"unknown",serverError:null,updatedAt:new Date}).where((0,a.eq)(o.mcpServers.id,e)).run(),t}async settleAllBundledStatuses(){for(let e of l.BUNDLED_MCP_SERVERS)if(!e.core)try{await this.settleInstallStatus(e.id)}catch(t){Q.serverLogger.warn({tag:"mcp-settle",op:"settle_failed",mcpId:e.id,err:t instanceof Error?t.message:String(t)},`settleInstallStatus failed for "${e.id}"`)}}async retryDep(e,t){let A=l.BUNDLED_MCP_SERVERS.find(t=>t.id===e);if(!A)throw Error(`No bundled MCP with id ${e}`);let r=A.dependencies.find(e=>e.binary===t);if(!r)throw Error(`No dep ${t} on MCP ${e}`);this.ensureBinDir(),this.writeDepTransition(e,t,{runtimeStatus:"installing",error:null});try{if(r.files)await this.installMultiFile(r);else if(r.customInstallerId)await this.runCustomInstaller(r);else{let e=K.resolveDownloadUrl(r);await this.downloadGroup(e,[r])}let A=await this.resolveStatusAsync(r);if(!A.installed)return void this.writeDepTransition(e,t,{runtimeStatus:"failed",error:"Install completed without throwing, but binary still not detected."});this.writeDepTransition(e,t,A)}catch(r){let A=r instanceof Error?r.message:String(r);throw Q.serverLogger.error({mcpId:e,binary:t,err:A},"retryDep failed"),this.writeDepTransition(e,t,{runtimeStatus:"failed",error:A}),r}}async installSingleDep(e,t,A){if(this.ensureBinDir(),(await this.resolveStatusAsync(t)).installed)return void A?.({binary:t.binary,mcpId:e,status:"skipped",reason:"already_installed"});this.writeDepTransition(e,t.binary,{runtimeStatus:"installing",error:null}),A?.({binary:t.binary,mcpId:e,status:"downloading"});try{if(t.files)await this.installMultiFile(t);else if(t.customInstallerId)await this.runCustomInstaller(t);else{let r=K.resolveDownloadUrl(t);await this.downloadGroup(r,[t],A?r=>A({...r,binary:t.binary,mcpId:e}):void 0)}let r=await this.resolveStatusAsync(t);this.writeDepTransition(e,t.binary,r),A?.({binary:t.binary,mcpId:e,status:"done"})}catch(r){let A=r instanceof Error?r.message:String(r);throw Q.serverLogger.error({mcpId:e,binary:t.binary,err:A},"installSingleDep failed"),this.writeDepTransition(e,t.binary,{runtimeStatus:"failed",error:A}),r}}ensureBinDir(){r.default.existsSync((0,u.getLibiBinDir)())||r.default.mkdirSync((0,u.getLibiBinDir)(),{recursive:!0})}async ensureMcp(e,t){let A,r;K.syncLog(`ensureMcp(${e.id}): before getDb()`);let i=(0,s.getDb)();K.syncLog(`ensureMcp(${e.id}): after getDb()`);let n=e.id;if(K.syncLog(`ensureMcp(${e.id}): deps=${e.dependencies.length}`),0===e.dependencies.length){if(this.skipDbWrites)return;let t="not_required",A=null;if(e.requiredEnvVars&&e.requiredEnvVars.length>0){let[r]=i.select().from(o.mcpServers).where((0,a.eq)(o.mcpServers.id,e.id)).limit(1).all(),n=K.evaluateConfigStatus({requiredEnvVars:e.requiredEnvVars,envVarsJson:r?.envVars??null});t=n.status,A="needs_config"===n.status?`Missing required env vars: ${n.missing.join(", ")}`:null}i.update(o.mcpServers).set({installStatus:t,installError:A,dependencyStatus:JSON.stringify([]),updatedAt:new Date}).where((0,a.eq)(o.mcpServers.id,n)).run();return}this.skipDbWrites||(K.syncLog(`ensureMcp(${n}): UPDATE mcpServers SET installStatus=checking`),i.update(o.mcpServers).set({installStatus:"checking",updatedAt:new Date}).where((0,a.eq)(o.mcpServers.id,n)).run(),K.syncLog(`ensureMcp(${n}): UPDATE done`));let l=[],g=new Map,c=e.dependencies.filter(e=>e.files),h=e.dependencies.filter(e=>e.customInstallerId&&!e.files),d=e.dependencies.filter(e=>!e.customInstallerId&&!e.files),u=new Map;for(let e of d){let t=K.resolveDownloadUrl(e),A=u.get(t)??[];A.push(e),u.set(t,A)}for(let e of c){if(this.isMultiFileInstalled(e)){t?.({binary:e.binary,mcpId:n,status:"skipped",reason:"already_installed"});continue}this.writeDepTransition(n,e.binary,{runtimeStatus:"installing",error:null}),t?.({binary:e.binary,mcpId:n,status:"downloading"});try{await this.installMultiFile(e);let A=await this.resolveStatusAsync(e);this.writeDepTransition(n,e.binary,A),t?.({binary:e.binary,mcpId:n,status:"done"})}catch(A){let t=A instanceof Error?A.message:String(A);l.push(`${e.binary}: ${t}`),Q.serverLogger.error({binary:e.binary,err:t},"Multi-file installer failed"),g.set(e.binary,t),this.writeDepTransition(n,e.binary,{runtimeStatus:"failed",error:t})}}for(let e of h){if((await this.resolveStatusAsync(e)).installed){t?.({binary:e.binary,mcpId:n,status:"skipped",reason:"already_installed"});continue}this.writeDepTransition(n,e.binary,{runtimeStatus:"installing",error:null}),t?.({binary:e.binary,mcpId:n,status:"downloading"});try{await this.runCustomInstaller(e),t?.({binary:e.binary,mcpId:n,status:"done"})}catch(A){let t=A instanceof Error?A.message:String(A);l.push(`${e.binary}: ${t}`),Q.serverLogger.error({binary:e.binary,err:t},"Custom installer failed"),g.set(e.binary,t),this.writeDepTransition(n,e.binary,{runtimeStatus:"failed",error:t})}}for(let[e,A]of u){if(A.every(e=>this.resolveStatus(e).installed)){for(let e of A)t?.({binary:e.binary,mcpId:n,status:"skipped",reason:"already_installed"});continue}let r=new Set;for(let e of A)this.resolveStatus(e).installed?t?.({binary:e.binary,mcpId:n,status:"skipped",reason:"already installed"}):(r.add(e.binary),this.writeDepTransition(n,e.binary,{runtimeStatus:"installing",error:null}),t?.({binary:e.binary,mcpId:n,status:"downloading"}));try{for(let i of(await this.downloadGroup(e,A,t?e=>{for(let i of A)r.has(i.binary)&&t({...e,binary:i.binary,mcpId:n})}:void 0),A))r.has(i.binary)&&t?.({binary:i.binary,mcpId:n,status:"done"})}catch(t){let e=t instanceof Error?t.message:String(t);for(let t of(l.push(`${A.map(e=>e.binary).join(", ")}: ${e}`),Q.serverLogger.error({binaries:A.map(e=>e.binary),err:e},"Failed to download dependency group"),A))g.set(t.binary,e),this.writeDepTransition(n,t.binary,{runtimeStatus:"failed",error:e})}}if(this.skipDbWrites)return;let E=(await Promise.all(e.dependencies.map(e=>this.resolveStatusAsync(e)))).map(e=>{let t=g.get(e.binary);return t&&!e.installed?{...e,runtimeStatus:"failed",error:t}:e});if(E.every(e=>e.installed))if(e.requiredEnvVars&&e.requiredEnvVars.length>0){let[t]=i.select().from(o.mcpServers).where((0,a.eq)(o.mcpServers.id,e.id)).limit(1).all(),n=K.evaluateConfigStatus({requiredEnvVars:e.requiredEnvVars,envVarsJson:t?.envVars??null});A=n.status,r="needs_config"===n.status?`Missing required env vars: ${n.missing.join(", ")}`:null}else A="installed",r=null;else A="failed",r=l.join(" | ")||"unknown";i.update(o.mcpServers).set({installStatus:A,installError:r,dependencyStatus:JSON.stringify(E),updatedAt:new Date}).where((0,a.eq)(o.mcpServers.id,n)).run(),e.core||"installed"!==A&&i.update(o.mcpServers).set({serverStatus:"down",serverError:`Dependencies not installed: ${r??"unknown"}`,serverLastChecked:new Date,updatedAt:new Date}).where((0,a.eq)(o.mcpServers.id,n)).run()}writeDepTransition(e,t,A){if(this.skipDbWrites)return;let r=(0,s.getDb)(),[i]=r.select().from(o.mcpServers).where((0,a.eq)(o.mcpServers.id,e)).limit(1).all();if(!i)return;let n=[];try{n=JSON.parse(i.dependencyStatus??"[]")}catch{}let l=n.findIndex(e=>e.binary===t);-1===l?n.push({binary:t,installed:!1,path:null,source:null,runtimeStatus:"pending",...A}):n[l]={...n[l],...A},r.update(o.mcpServers).set({dependencyStatus:JSON.stringify(n),updatedAt:new Date}).where((0,a.eq)(o.mcpServers.id,e)).run();try{C.navigationEmitter.emit("refresh_query",{queryKey:"mcp-servers"})}catch{}}resolveStatus(e){if(e.files){let t="models"===e.destination?(0,u.getLibiModelsDir)():(0,u.getLibiBinDir)(),A=i.default.join(t,e.binary),n=e.files.every(e=>r.default.existsSync(i.default.join(A,e.relPath)))&&this.installTokenMatches(e);return{binary:e.binary,installed:n,path:n?A:null,source:n?"bundled":null,runtimeStatus:n?"installed":"pending"}}if(e.customInstallerId)return{binary:e.binary,installed:!1,path:null,source:null,runtimeStatus:"pending"};let t=this.getBinaryPath(e.binary);if(r.default.existsSync(t)){let A=this.installTokenMatches(e);return{binary:e.binary,installed:A,path:A?t:null,source:A?"bundled":null,runtimeStatus:A?"installed":"pending"}}return!e.requireBundled&&this.binaryExistsOnPath(e.binary)?{binary:e.binary,installed:!0,path:null,source:"system",runtimeStatus:"installed"}:{binary:e.binary,installed:!1,path:null,source:null,runtimeStatus:"pending"}}async resolveStatusAsync(e){if(e.files){let t="models"===e.destination?(0,u.getLibiModelsDir)():(0,u.getLibiBinDir)(),A=i.default.join(t,e.binary),n=e.files.every(e=>r.default.existsSync(i.default.join(A,e.relPath)))&&this.installTokenMatches(e);return{binary:e.binary,installed:n,path:n?A:null,source:n?"bundled":null,runtimeStatus:n?"installed":"pending"}}if(e.customInstallerId){let t=(0,c.getCustomInstaller)(e.customInstallerId);if(!t)return Q.serverLogger.warn({binary:e.binary,customInstallerId:e.customInstallerId},"Unknown customInstallerId — no implementation registered"),{binary:e.binary,installed:!1,path:null,source:null,runtimeStatus:"pending"};try{let A=await t.verify();if(A)return{binary:e.binary,installed:!0,path:A,source:"bundled",runtimeStatus:"installed"}}catch(t){Q.serverLogger.warn({binary:e.binary,err:t instanceof Error?t.message:String(t)},"customInstaller.verify threw")}return{binary:e.binary,installed:!1,path:null,source:null,runtimeStatus:"pending"}}let t=this.resolveStatus(e);if(e.runCheck&&t.installed&&t.path&&!await K.isBinaryRunnable(t.path,e.runCheck))return Q.serverLogger.warn({binary:e.binary,path:t.path,tag:"dep-runcheck"},"installed binary failed its runCheck (likely wrong CPU arch) — marking for re-install"),{binary:e.binary,installed:!1,path:null,source:null,runtimeStatus:"pending"};if(e.capabilityCheck&&t.installed&&t.path){let A=await K.missingCapabilities(t.path,e.capabilityCheck);if(A.length>0)return Q.serverLogger.warn({binary:e.binary,path:t.path,missing:A,tag:"dep-capability"},`installed ${e.binary} is missing required capabilities (${A.join(", ")}) — marking for re-install`),{binary:e.binary,installed:!1,path:null,source:null,runtimeStatus:"pending"}}return t}static async isBinaryRunnable(e,t){try{return await Z(e,t,{timeout:1e4,windowsHide:!0,killSignal:"SIGKILL"}),!0}catch{return!1}}static async missingCapabilities(e,t){let A;try{let{stdout:r,stderr:i}=await Z(e,t.args,{timeout:15e3,windowsHide:!0,killSignal:"SIGKILL",maxBuffer:8388608});A=`${r}
|
|
169
169
|
${i}`}catch{return[...t.mustContain]}return t.mustContain.filter(e=>!A.includes(e))}async installMultiFile(e){if(!e.files||0===e.files.length)throw Error(`installMultiFile called on dep ${e.binary} without files[]`);let t="models"===e.destination?(0,u.getLibiModelsDir)():(0,u.getLibiBinDir)(),A=i.default.join(t,e.binary);r.default.mkdirSync(A,{recursive:!0});let n=[];try{for(let t of e.files){let s=i.default.join(A,t.relPath);r.default.mkdirSync(i.default.dirname(s),{recursive:!0});let o=await (0,I.downloadBufferWithStallGuard)(t.url,{label:`${e.binary}/${t.relPath}`,onRetry:({attempt:A,maxAttempts:r,delayMs:i,error:n,bytesDownloaded:s})=>{Q.serverLogger.warn({url:t.url,binary:e.binary,relPath:t.relPath,attempt:A,maxAttempts:r,delayMs:i,bytesDownloaded:s,err:n.message},"Model-file download failed — retrying")}});r.default.writeFileSync(s,o),n.push(s),t.sha256&&await (0,I.verifySha256)(s,t.sha256)}}catch(e){for(let e of n)try{r.default.unlinkSync(e)}catch{}throw e}this.writeInstallToken(e)}isMultiFileInstalled(e){if(!e.files)return!1;let t="models"===e.destination?(0,u.getLibiModelsDir)():(0,u.getLibiBinDir)(),A=i.default.join(t,e.binary);return e.files.every(e=>r.default.existsSync(i.default.join(A,e.relPath)))&&this.installTokenMatches(e)}async runCustomInstaller(t){if(!t.customInstallerId)return;let A=(0,c.getCustomInstaller)(t.customInstallerId);if(!A)throw Error(`Unknown customInstallerId: ${t.customInstallerId}`);let{command:r,args:i,timeoutMs:n}=A.install;if("__TRACKING_PYENV_INSTALL__"===r){let{runTrackingPyenvInstall:r}=await e.A(391894);await r();let i=await A.verify();if(!i)throw Error(`${t.binary} install command completed but verify() still returns null`);Q.serverLogger.info({binary:t.binary,path:i,via:"tracking-pyenv"},"Custom installer succeeded");return}if("__YT_DLP_UV_INSTALL__"===r){await this.installYtDlpViaUv(t,n);let e=await A.verify();if(!e)throw Error(`${t.binary} install command completed but verify() still returns null`);Q.serverLogger.info({binary:t.binary,path:e,via:"uv"},"Custom installer succeeded");return}let s=i.map(e=>"__PLAYWRIGHT_CORE_CLI__"===e?(0,c.resolvePlaywrightCoreCli)():e),o=r===c.NODE_COMMAND_SENTINEL?(0,h.resolveNodeCommand)():r;Q.serverLogger.info({binary:t.binary,command:o,args:s},"Running custom installer"),await Z(o,s,{timeout:n??6e4,windowsHide:!0,maxBuffer:0x2000000});let a=await A.verify();if(!a)throw Error(`${t.binary} install command completed but verify() still returns null`);Q.serverLogger.info({binary:t.binary,path:a},"Custom installer succeeded")}async installYtDlpViaUv(e,t){let A=this.getBinaryPath("uv");if(!r.default.existsSync(A))try{let{stdout:e}=await Z((0,d.isWindows)()?"where":"which",["uv"],{timeout:5e3,windowsHide:!0});if(!(A=e.split("\n")[0]?.trim())||!r.default.existsSync(A))throw Error("uv not on PATH")}catch{throw Error(`Cannot install yt-dlp via uv: uv not found in ${this.getBinaryPath("uv")} or on PATH. Expected uv to be installed earlier (tier-1 dep on the youtube-downloader def).`)}Q.serverLogger.info({binary:e.binary,uvBinary:A},"Installing yt-dlp via uv tool install"),await Z(A,["tool","install","yt-dlp","--reinstall","--python","3.12","--with","certifi"],{timeout:t??3e5,windowsHide:!0,maxBuffer:0x2000000,env:(0,E.buildUvEnv)()});let{stdout:n}=await Z(A,["tool","dir"],{timeout:1e4,windowsHide:!0,env:(0,E.buildUvEnv)({NO_COLOR:"1"})}),s=n.replace(/\[[0-9;]*m/g,"").trim(),o=(0,d.isWindows)()?"Scripts":"bin",a=i.default.join(s,"yt-dlp",o,`yt-dlp${(0,d.exeSuffix)()}`);if(!r.default.existsSync(a))throw Error(`uv tool install completed but expected entry point not found: ${a}`);let l=i.default.join(s,"yt-dlp",o,(0,d.isWindows)()?"python.exe":"python3"),g="";try{let{stdout:e}=await Z(l,["-m","certifi"],{timeout:1e4,windowsHide:!0,env:{...process.env,NO_COLOR:"1"}});g=e.replace(/\[[0-9;]*m/g,"").trim(),r.default.existsSync(g)||(g="")}catch{}let h=i.default.join((0,u.getLibiBinDir)(),"yt-dlp");try{r.default.unlinkSync(h)}catch(e){if("ENOENT"!==e.code)throw e}if((0,d.isWindows)()){let t=h+".cmd";try{r.default.unlinkSync(t)}catch(e){if("ENOENT"!==e.code)throw e}let A=g?`set SSL_CERT_FILE=${g}\r
|
|
170
170
|
set REQUESTS_CA_BUNDLE=${g}\r
|
|
@@ -853,7 +853,7 @@ const g = ctx.createRadialGradient(W / 2, H / 2, H * 0.12, W / 2, H / 2, H * 0.9
|
|
|
853
853
|
g.addColorStop(0, \`rgba(0,0,0,\${0.45 * a})\`);
|
|
854
854
|
g.addColorStop(1, \`rgba(0,0,0,\${0.85 * a})\`);
|
|
855
855
|
ctx.fillStyle = g;
|
|
856
|
-
ctx.fillRect(0, 0, W, H);`,displayName:"Ad end vignette"},{id:"img-zyv32z0t",kind:"image",startTime:37.4,duration:2.1,rect:{x:820,y:140,width:280,height:280},z:10,opacity:1,assetSlug:"logo-mark.png",group:"shoe-brand",keyframes:{rect:{keyframes:[{t:0,value:{x:869.25,y:309.25,width:181.50000000000003,height:181.50000000000003},easing:"ease-out"},{t:.2222222222222222,value:{x:795,y:235,width:330,height:330},easing:"linear"},{t:.3492063492063492,value:{x:785.4497891718671,y:98.38367346938782,width:333.2326530612245,height:333.2326530612245}},{t:1,value:{x:820,y:140,width:280,height:280}}]},opacity:{keyframes:[{t:0,value:0,easing:"ease-out"},{t:.2222222222222222,value:1,easing:"linear"},{t:1,value:1}]}}},{id:"text-hlcq7y7c",kind:"text",startTime:38.1,duration:1.4,rect:{x:460,y:775,width:1e3,height:55},z:10,opacity:1,content:"ENGINEERED TO FLOAT",font:"48px Inter",color:"#9aa3b2",align:"center",fontFamily:"Inter",fontSize:32,fontWeight:500,reveal:{mode:"fade-words",durationMs:500},group:"shoe-brand"},{id:"text-16gcy19w",kind:"text",startTime:40.8,duration:11.2,rect:{x:1010,y:745,width:460,height:80},z:21,opacity:1,content:"Or download for Mac",font:"48px Inter",color:"#cdd3de",align:"center",fontFamily:"Inter",fontSize:42,fontWeight:500,background:{color:"rgba(255,255,255,0.08)",padding:18,radius:12},reveal:{mode:"fade-words",durationMs:300},group:"end-card"},{id:"img-vxnkonqd",kind:"image",startTime:39.8,duration:12.2,rect:{x:670,y:228,width:320,height:320},z:21,opacity:1,assetSlug:"libi-ring-glyph.png",group:"end-card",keyframes:{rect:{keyframes:[{t:0,value:{x:670,y:228,width:320,height:320},easing:"ease-out"},{t:.062842,value:{x:670,y:228,width:320,height:320},easing:"linear"},{t:.180328,value:{x:663.6,y:221.6,width:332.8,height:332.8},easing:"linear"},{t:1,value:{x:663.6,y:221.6,width:332.8,height:332.8}}]},opacity:{keyframes:[{t:0,value:0,easing:"ease-out"},{t:.062842,value:1,easing:"linear"},{t:.180328,value:1,easing:"linear"},{t:1,value:1}]}},shadow:{color:"rgba(139,180,139,0.55)",blur:70,dx:0,dy:0}},{id:"text-3048dja6",kind:"text",startTime:41.2,duration:10.8,rect:{x:610,y:872,width:700,height:64},z:21,opacity:1,content:"libi.nagellabs.com",font:"48px Inter",color:"#8b93a7",align:"center",fontFamily:"Inter",fontSize:40,fontWeight:400,reveal:{mode:"fade-words",durationMs:300},group:"end-card"}],audioClips:[{id:"clip_i13f0m0n",kind:"inline",assetSlug:"clip-water-impact.mp4",startTime:34.4,duration:6,trimStart:0,volume:.6,enabled:!0,linkedOverlayId:"vid-so51lufn",label:"film audio — splash"},{id:"clip_4t921f5s",kind:"standalone",assetSlug:"music-build-28s.mp3",startTime:0,duration:28,trimStart:0,volume:.85,enabled:!0,label:"music — build (hard cut at 0:28)",duck:{sidechainClipIds:["clip_vo1","clip_vo2","clip_vo3","clip_vo4","clip_vo5","clip_vo6"],thresholdDb:-30,ratio:4,attackMs:50,releaseMs:250,reductionDb:-12}},{id:"clip_g0uxbvkf",kind:"standalone",assetSlug:"sfx-typing.mp3",startTime:.2,duration:3.6,trimStart:0,volume:.5,enabled:!0,label:"SFX typing"},{id:"clip_pj7r0it5",kind:"standalone",assetSlug:"sfx-basshit.mp3",startTime:3.95,duration:1,trimStart:0,volume:.9,enabled:!0,label:"SFX bass hit (Enter)"},{id:"clip_316hr7uq",kind:"standalone",assetSlug:"sfx-clicks.mp3",startTime:4.6,duration:4,trimStart:0,volume:.35,enabled:!0,label:"SFX UI clicks"},{id:"clip_wuk6rzqz",kind:"standalone",assetSlug:"sfx-riser.mp3",startTime:24,duration:4,trimStart:0,volume:.7,enabled:!0,label:"SFX riser → cut"},{id:"clip_v4tmovmb",kind:"inline",assetSlug:"clip-hero-orbit-v2.mp4",startTime:30,duration:4.4,trimStart:0,volume:.6,enabled:!0,linkedOverlayId:"vid-gdgll882",label:"film audio — orbit"},{id:"clip_c44rnjt8",kind:"standalone",assetSlug:"music-anthem-12s.mp3",startTime:30,duration:12,trimStart:0,volume:.9,enabled:!0,label:"music — anthem (0:30–0:42)",duck:{sidechainClipIds:["clip_vo1","clip_vo2","clip_vo3","clip_vo4","clip_vo5","clip_vo6"],thresholdDb:-30,ratio:4,attackMs:50,releaseMs:250,reductionDb:-12}},{id:"clip_tnqhriva",kind:"inline",assetSlug:"clip-track-demo.mp4",startTime:16,duration:6,trimStart:0,volume:1,enabled:!1,linkedOverlayId:"vid-lu4jxr6v",label:"tracking clip audio (muted)"},{id:"clip_vo1",kind:"standalone",assetSlug:"vo-1-describe.mp3",startTime:1,duration:1.149,trimStart:0,volume:1,enabled:!0,label:"VO 1 — You describe it."},{id:"clip_vo2",kind:"standalone",assetSlug:"vo-2-agent.mp3",startTime:5,duration:2.273,trimStart:0,volume:1,enabled:!0,label:"VO 2 — A coding agent builds it."},{id:"clip_vo3",kind:"standalone",assetSlug:"vo-3-generates.mp3",startTime:11,duration:3.474,trimStart:0,volume:1,enabled:!0,label:"VO 3 — It generates the footage…"},{id:"clip_vo4",kind:"standalone",assetSlug:"vo-4-code.mp3",startTime:17,duration:2.508,trimStart:0,volume:1,enabled:!0,label:"VO 4 — Every frame is code."},{id:"clip_vo5",kind:"standalone",assetSlug:"vo-5-director.mp3",startTime:24.6,duration:1.411,trimStart:0,volume:1,enabled:!0,label:"VO 5 — You stay the director."},{id:"clip_vo6",kind:"standalone",assetSlug:"vo-6-madein.mp3",startTime:37.3,duration:2.508,trimStart:0,volume:1,enabled:!0,label:"VO 6 — This video? Made in libi."}]},assets:eg}};var eh=e.i(753492);function ed(e){return`libi:onboarding:${e}`}function eu(e,t){if(Array.isArray(e))return e.map(e=>eu(e,t));if(null!==e&&"object"==typeof e){if(Object.hasOwn(e,"assetSlug")&&Object.hasOwn(e,"fileId"))throw Error(`onboarding: node carries both assetSlug and fileId — ${JSON.stringify(e)} — refusing to let key order pick a winner.`);let A={};for(let[r,i]of Object.entries(e)){if("assetSlug"!==r){A[r]=eu(i,t);continue}if("string"!=typeof i)throw Error(`onboarding: assetSlug must be a string, got ${JSON.stringify(i)}`);let e=t.get(i);if(!e)throw Error(`onboarding: unresolved asset slug ${JSON.stringify(i)} — it is referenced by the composition but was never downloaded.`);A.fileId=e}return A}return e}async function eE(e){let t=ed(e);for(let e of(0,s.getDb)().select({id:o.pieces.id}).from(o.pieces).where((0,n.eq)(o.pieces.description,t)).orderBy((0,et.desc)(o.pieces.createdAt),(0,et.desc)(o.pieces.id)).all())if(await (0,eh.hasManifest)(e.id))return e.id;return null}let eQ={kind:"onboarding_piece",maxConcurrent:1,paramsSchema:S.z.object({version:S.z.literal("v1"),force:S.z.boolean()}),resumable:!1,noProgressTimeoutMs:12e4,mcpToolId:(0,T.makeMcpToolId)("libi","libi.build_onboarding_piece"),async run(e){var t;let A,{version:r,force:i}=e.params,a=ec[r];if(!a)throw Error(`onboarding: no definition for version ${r}`);let{definition:g,assets:c}=a;if(!i){let t=await eE(r);if(t)return l.serverLogger.info({tag:"onboarding",op:"reused",version:r,pieceId:t},"onboarding: demo piece already built — reusing it"),e.reportProgress(c.length,c.length,"files"),{pieceId:t,version:r,bytes:0,assets:0,reused:!0}}let h=function(e){let t=process.env[eo]?.trim(),A=!!t,r=A?t:"https://storage.googleapis.com/libi-public-assets/onboarding";if(A){let e;try{e=new URL(r)}catch{throw Error(`${eo} is not a valid http(s) url: ${r}`)}if("http:"!==e.protocol&&"https:"!==e.protocol)throw Error(`${eo} must be an http(s) url, got ${e.protocol}//… (${r})`)}return{baseUrl:`${r.replace(/\/+$/,"")}/${el("version",e)}`,guard:A?es.assertDevLoopbackOrPublicHttpUrl:es.assertPublicHttpUrl,overridden:A}}(r);l.serverLogger.info({tag:"onboarding",op:"asset_source",version:r,baseUrl:h.baseUrl,overridden:h.overridden,assets:c.length},"onboarding: resolved demo asset base");let d=await ei({name:g.name,description:`libi:onboarding:${r}:building`});if(!d.success||!d.data)throw Error(`onboarding: could not create the demo piece: ${d.error??"unknown"}`);let u=d.data.id;try{e.reportProgress(0,c.length,"files");let i=new Map,a=0;for(let[A,r]of c.entries()){if(e.shouldCancel())throw new eA.CancelledError(e.jobId);try{let e=await (0,en.fetchAndStoreRemoteFile)({url:(t=r.slug,`${h.baseUrl}/${el("slug",t)}`),guard:h.guard,pieceId:u,filename:r.slug,expectSha256:r.sha256,contentType:r.contentType,skipProxyGeneration:!0});i.set(r.slug,e.fileId),a+=e.bytes}catch(e){throw Error(`onboarding: asset ${r.slug} failed: ${e instanceof Error?e.message:String(e)}`,{cause:e})}e.reportProgress(A+1,c.length,"files")}if(e.shouldCancel())throw new eA.CancelledError(e.jobId);let d=eu(g.overlays,i),E=eu(g.audioClips,i),Q={width:g.width,height:g.height,fps:g.fps,overlays:d,audioClips:E};await (0,eh.saveManifest)(u,Q),(0,s.getDb)().update(o.pieces).set({description:ed(r),updatedAt:new Date}).where((0,n.eq)(o.pieces.id,u)).run(),l.serverLogger.info({tag:"onboarding",op:"built",version:r,pieceId:u,assets:i.size,bytes:a,overlays:d.length},"onboarding: demo piece built"),A={pieceId:u,version:r,bytes:a,assets:i.size,reused:!1}}catch(e){try{await (0,er.deletePieceCompletely)(u)}catch(e){l.serverLogger.error({tag:"onboarding",op:"rollback_failed",version:r,pieceId:u,err:e instanceof Error?e.message:String(e)},"onboarding: could not clean up the partial demo piece")}throw e}return(0,V.trackServerEvent)("onboarding_piece_built",{version:r}),A}},eI=globalThis.__libiRunnerRegistry??new Map;function eB(e){return eI.get(e)??null}function eC(){for(let e of[c.trackingRunner,h.trackingProviderRunner,d.proxyGenRunner,u.filmstripGenRunner,E.exportRenderRunner,Q.exportRunner,I.analysisDescribeFrameRunner,B.whisperModelDownloadRunner,C.ttsModelDownloadRunner,f.musicModelDownloadRunner,p.musicGenerateRunner,y.pieceDupRunner,m.extraAnalysisModelRunner,w.remoteFetchRunner,D.matteGenRunner,b.runtimeUpdateRunner,v,Z,eQ,ee])eB(e.kind)||function(e){if(eI.has(e.kind))throw Error(`Runner already registered for kind: ${e.kind}`);eI.set(e.kind,e)}(e)}function ef(){eC();let e=new Map;for(let t of Array.from(eI.values())){if(!t.mcpToolId)continue;let A=Array.isArray(t.mcpToolId)?t.mcpToolId:[t.mcpToolId];e.set(t.kind,A)}return e}globalThis.__libiRunnerRegistry=eI;var ep=e.i(290703);async function ey(e){(0,s.getDb)().insert(o.jobs).values({id:e.id,kind:e.kind,clientKey:e.clientKey,paramsHash:e.paramsHash,paramsJson:e.paramsJson,pieceId:e.pieceId,fileId:e.fileId,status:"queued"}).run()}async function em(e){let[t]=(0,s.getDb)().select().from(o.jobs).where((0,n.eq)(o.jobs.id,e)).limit(1).all();return t??null}async function ew(e,t,A={}){let r=(0,s.getDb)(),i=(0,n.and)((0,n.eq)(o.jobs.kind,e),(0,n.eq)(o.jobs.paramsHash,t)),a=A.excludeTerminal?(0,n.and)(i,(0,n.notInArray)(o.jobs.status,["completed","failed","cancelled"])):i,[l]=r.select().from(o.jobs).where(a).limit(1).all();return l??null}async function eD(e,t){let[A]=(0,s.getDb)().select().from(o.jobs).where((0,n.and)((0,n.eq)(o.jobs.kind,e),(0,n.eq)(o.jobs.paramsHash,t),(0,n.inArray)(o.jobs.status,["running","queued","cancel-requested"]))).limit(1).all();return A??null}async function eb(e,t){let[A]=(0,s.getDb)().select().from(o.jobs).where((0,n.and)((0,n.eq)(o.jobs.kind,e),(0,n.eq)(o.jobs.paramsHash,t),(0,n.inArray)(o.jobs.status,["completed","failed","cancelled"]))).orderBy((0,et.desc)(o.jobs.completedAt)).limit(1).all();return A??null}async function eS(e){let t=(0,s.getDb)(),A=new Date;t.update(o.jobs).set({status:"running",startedAt:A,lastProgressAt:A}).where((0,n.eq)(o.jobs.id,e)).run()}async function eN(e,t){let A=(0,s.getDb)(),r={progressDone:t.done,progressTotal:t.total,lastProgressAt:new Date};void 0!==t.unit&&(r.progressUnit=t.unit),void 0!==t.msPerUnit&&(r.msPerUnit=t.msPerUnit),A.update(o.jobs).set(r).where((0,n.eq)(o.jobs.id,e)).run()}async function eR(e,t){(0,s.getDb)().update(o.jobs).set({partialPath:t}).where((0,n.eq)(o.jobs.id,e)).run()}async function eF(e,t){(0,s.getDb)().update(o.jobs).set({status:"completed",resultJson:t,completedAt:new Date,error:null}).where((0,n.eq)(o.jobs.id,e)).run()}async function ek(e,t){(0,s.getDb)().update(o.jobs).set({status:"failed",error:t,completedAt:new Date}).where((0,n.eq)(o.jobs.id,e)).run()}async function eM(e){(0,s.getDb)().update(o.jobs).set({status:"cancel-requested"}).where((0,n.eq)(o.jobs.id,e)).run()}async function eU(e){(0,s.getDb)().update(o.jobs).set({status:"cancelled",completedAt:new Date}).where((0,n.eq)(o.jobs.id,e)).run()}var eT=e.i(702220);function eL(e){return i.default.join((0,a.getLibiHome)(),"jobs",e,"state.json")}class ev extends t.EventEmitter{cancelFlags=new Map;inflight=new Map;lastEmitAt=new Map;lastProgress=new Map;watchdogTripped=new Set;progressChains=new Map;etaTrackers=new Map;forcedJobs=new Set;discardOutputJobs=new Set;activeByKind=new Map;waiters=new Map;toolCallIdByJob=new Map;jobIdByToolCallId=new Map;toolHintByJob=new Map;attachToolHint(e,t){this.toolHintByJob.set(e,t)}getToolHint(e){return this.toolHintByJob.get(e)??null}attachToolCallId(e,t){let A=this.toolCallIdByJob.get(e);A||(A=new Set,this.toolCallIdByJob.set(e,A)),A.add(t),this.jobIdByToolCallId.set(t,e)}getJobIdForToolCallId(e){return this.jobIdByToolCallId.get(e)??null}emitTerminal(e,t,A={}){let r=this.toolCallIdByJob.get(t);this.emit(e,{jobId:t,...A,toolCallIds:r?Array.from(r):[]})}async enqueue(e,t,A={}){let a=eB(e);if(!a)throw Error(`No runner registered for kind: ${e}`);let c=a.paramsSchema.parse(t),h=(0,g.canonicalHash)(c),d=A.clientKey||`srv-${ex()}`;if(!0===A.forceNew||!1===A.resume){if(a.exclusiveResource){let t=await eD(e,h);if(t)return l.serverLogger.info({jobId:t.id,kind:e},"jobs.force_new.attached_exclusive"),{status:"attached_running",jobId:t.id,clientKey:t.clientKey||d,existingJob:{jobId:t.id,pieceId:t.pieceId,startedAt:t.startedAt?.toISOString()??""}}}let t=await ew(e,h);if(t){(0,s.getDb)().delete(o.jobs).where((0,n.eq)(o.jobs.id,t.id)).run(),this.forcedJobs.delete(t.id),this.discardOutputJobs.delete(t.id);let e=i.default.dirname(eL(t.id));try{r.default.rmSync(e,{recursive:!0,force:!0})}catch(t){l.serverLogger.warn({err:t,oldStateDir:e},"jobs.resume.cleanup_failed")}}let g=`job-${ex()}`;return await ey({id:g,kind:e,clientKey:d,paramsHash:h,paramsJson:JSON.stringify(c),pieceId:A.pieceId??null,fileId:A.fileId??null}),this.forcedJobs.add(g),!0===A.discardOutput&&this.discardOutputJobs.add(g),this.emit("created",{jobId:g,kind:e}),{status:"new",jobId:g,clientKey:d,forced:!0}}let u=await eD(e,h);if(u)return{status:"attached_running",jobId:u.id,clientKey:u.clientKey||d,existingJob:{jobId:u.id,pieceId:u.pieceId,startedAt:u.startedAt?.toISOString()??""}};let E=await eb(e,h);if(E)return{status:"matching_completed",existingJob:{jobId:E.id,pieceId:E.pieceId,completedAt:E.completedAt?.toISOString()??"",status:E.status,result:function(e,t){if(t)try{return JSON.parse(t)}catch(t){l.serverLogger.warn({tag:"jobs",op:"terminal_result_parse_failed",jobId:e,err:t instanceof Error?t.message:String(t)},"Failed to parse cached job result JSON; returning undefined");return}}(E.id,E.resultJson),error:E.error}};let Q=`job-${ex()}`;return await ey({id:Q,kind:e,clientKey:d,paramsHash:h,paramsJson:JSON.stringify(c),pieceId:A.pieceId??null,fileId:A.fileId??null}),this.emit("created",{jobId:Q,kind:e}),{status:"new",jobId:Q,clientKey:d}}async runToCompletion(e,t){let A=t?this.subscribe(e,t):()=>{};try{let t=this.inflight.get(e);if(t)return t;let A=this.runLocked(e);this.inflight.set(e,A);try{return await A}finally{this.inflight.delete(e)}}finally{A()}}subscribe(e,t){let A=A=>{A.jobId===e&&t(A)};return this.on("progress",A),()=>this.off("progress",A)}async getStatus(e){let t=await em(e);if(!t)throw new eA.JobNotFoundError(e);return(0,eA.snapshotFromRow)(t)}async cancel(e){let t=await em(e);if(!t)throw new eA.JobNotFoundError(e);if("completed"===t.status||"failed"===t.status||"cancelled"===t.status)return;await eM(e);let A=this.cancelFlags.get(e);A&&A.abort(),this.emit("cancel-requested",{jobId:e})}async runLocked(e){let t=await em(e);if(!t)throw new eA.JobNotFoundError(e);let A=eB(t.kind);if(!A)throw Error(`No runner registered for kind: ${t.kind}`);await this.acquireSlot(A.kind,A.maxConcurrent);try{let r=await em(e);if(r?.status==="cancel-requested")throw await eU(e),this.emitTerminal("cancelled",e),new eA.CancelledError(e);return await this.runWithSlot(e,r??t,A)}finally{this.releaseSlot(A.kind)}}async acquireSlot(e,t){(this.activeByKind.get(e)??0)<t||await new Promise(t=>{let A=this.waiters.get(e)??[];A.push(t),this.waiters.set(e,A)}),this.activeByKind.set(e,(this.activeByKind.get(e)??0)+1)}releaseSlot(e){this.activeByKind.set(e,Math.max(0,(this.activeByKind.get(e)??0)-1));let t=this.waiters.get(e);t&&t.length>0&&t.shift()()}async runWithSlot(e,t,A){await eS(e);let n=new AbortController;this.cancelFlags.set(e,n);let s=null===A.noProgressTimeoutMs?null:A.noProgressTimeoutMs??6e4,o=null;null!==s&&(await eN(e,{done:0,total:0}),o=setInterval(()=>{(async()=>{let A=await em(e);if(!A||"running"!==A.status||!A.lastProgressAt)return;let r=Date.now()-A.lastProgressAt.getTime();r>s&&(l.serverLogger.warn({jobId:e,kind:t.kind,idleMs:r},"jobs.watchdog.no_progress"),this.watchdogTripped.add(e),n.abort())})().catch(t=>l.serverLogger.warn({err:t,jobId:e},"jobs.watchdog.poll_failed"))},Math.max(10,Math.min(5e3,Math.floor(s/4)))));let a=setInterval(()=>{try{this.emitHeartbeat(e)}catch(t){l.serverLogger.warn({err:t,jobId:e},"jobs.heartbeat.failed")}},15e3);a.unref?.();let g=eL(e),c=null;if(t.partialPath&&r.default.existsSync(t.partialPath))try{c=JSON.parse(r.default.readFileSync(t.partialPath,"utf-8"))}catch(t){l.serverLogger.warn({err:t,jobId:e},"jobs.resume.parse_failed"),c=null}let h={jobId:e,params:JSON.parse(t.paramsJson),resumeState:c,reportProgress:(A,r,i)=>{this.handleProgress(e,t.kind,A,r,i??t.progressUnit)},checkpoint:async A=>{r.default.mkdirSync(i.default.dirname(g),{recursive:!0}),r.default.writeFileSync(g,JSON.stringify(A),"utf-8"),t.partialPath||(await eR(e,g),t.partialPath=g)},shouldCancel:()=>n.signal.aborted,forced:this.forcedJobs.has(e),discardOutput:this.discardOutputJobs.has(e)};try{var d,u;let t=await Promise.race([A.run(h),(d=n.signal,u=()=>this.watchdogTripped.has(e)?Error(`No progress for ${s}ms — watchdog tripped`):new eA.CancelledError(e),new Promise((e,t)=>{d.aborted?t(u()):d.addEventListener("abort",()=>t(u()),{once:!0})}))]);if(r.default.existsSync(g))try{r.default.unlinkSync(g)}catch{}return await eF(e,JSON.stringify(t)),this.emitTerminal("completed",e,{result:t}),t}catch(r){if(this.watchdogTripped.has(e)){this.watchdogTripped.delete(e);let A=`No progress for ${s}ms — watchdog tripped`;try{await ek(e,A)}catch(t){l.serverLogger.error({err:t,jobId:e},"jobs.run.mark_failed_throw")}throw l.serverLogger.error({jobId:e,kind:t.kind,watchdogMs:s},"jobs.run.watchdog_failed"),this.emitTerminal("failed",e,{error:A}),Error(A)}if(r instanceof eA.CancelledError||n.signal.aborted){try{await eU(e)}catch(t){l.serverLogger.error({err:t,jobId:e},"jobs.run.mark_cancelled_throw")}throw this.emitTerminal("cancelled",e),r instanceof eA.CancelledError?r:new eA.CancelledError(e)}let A=r instanceof Error?r.message:String(r);try{await ek(e,A)}catch(t){l.serverLogger.error({err:t,jobId:e},"jobs.run.mark_failed_throw")}throw l.serverLogger.error({jobId:e,kind:t.kind,err:A},"jobs.run.failed"),this.emitTerminal("failed",e,{error:A}),r}finally{o&&clearInterval(o),clearInterval(a),this.cancelFlags.delete(e),this.progressChains.delete(e),this.etaTrackers.delete(e),this.lastProgress.delete(e);let t=this.toolCallIdByJob.get(e);if(t)for(let e of t)this.jobIdByToolCallId.delete(e);this.toolCallIdByJob.delete(e),this.toolHintByJob.delete(e),this.forcedJobs.delete(e),this.discardOutputJobs.delete(e)}}handleProgress(e,t,A,r,i){let n=Date.now();if(A=Math.min(A,r>0?r:A),n-(this.lastEmitAt.get(e)??0)<1e3&&A<r)return;this.lastEmitAt.set(e,n);let s=(this.progressChains.get(e)??Promise.resolve()).then(async()=>{let s=await em(e);if(!s||!s.startedAt)return;let o=this.etaTrackers.get(e);o||(o=new ep.EtaTracker,this.etaTrackers.set(e,o)),o.add(n,A);let a=o.msPerUnit();await eN(e,{done:A,total:r,unit:i,msPerUnit:a}),this.lastProgress.set(e,{kind:t,done:A,total:r,unit:i});let l={jobId:e,kind:t,done:A,total:r,unit:i,msPerUnit:a,etaMs:o.etaMs(r,A)};this.emit("progress",l),this.notifyProgress(l)}).catch(t=>{l.serverLogger.warn({err:t,jobId:e},"jobs.progress.update_failed")});this.progressChains.set(e,s)}notifyProgress(e){let t=this.toolCallIdByJob.get(e.jobId),A=this.toolHintByJob.get(e.jobId),r={jobId:e.jobId,kind:e.kind,done:e.done,total:e.total,unit:e.unit,etaMs:e.etaMs,msSinceProgress:e.msSinceProgress??null,...A?{toolName:A.toolName,toolArgs:A.toolArgs,...A.progressLabel?{progressLabel:A.progressLabel}:{}}:{}};try{if(t&&t.size>0)for(let e of t)eT.notify.jobProgress({...r,toolCallId:e});else eT.notify.jobProgress({...r,toolCallId:void 0})}catch(t){l.serverLogger.warn({err:t,jobId:e.jobId},"jobs.progress.notify_failed")}}emitHeartbeat(e){let t=this.lastProgress.get(e);if(!t)return;let A=this.etaTrackers.get(e);if(!A)return;let r=Date.now(),i=A.lastSampleAt(),n={jobId:e,kind:t.kind,done:t.done,total:t.total,unit:t.unit,msPerUnit:A.msPerUnit(),etaMs:A.etaMs(t.total,t.done,r),msSinceProgress:null!==i?r-i:null};this.emit("progress",n),this.notifyProgress(n)}}function ex(){return(0,A.randomUUID)()}function eY(){return globalThis.__libiJobManager||(eC(),globalThis.__libiJobManager=new ev),globalThis.__libiJobManager}}];
|
|
856
|
+
ctx.fillRect(0, 0, W, H);`,displayName:"Ad end vignette"},{id:"img-zyv32z0t",kind:"image",startTime:37.4,duration:2.1,rect:{x:820,y:140,width:280,height:280},z:10,opacity:1,assetSlug:"logo-mark.png",group:"shoe-brand",keyframes:{rect:{keyframes:[{t:0,value:{x:869.25,y:309.25,width:181.50000000000003,height:181.50000000000003},easing:"ease-out"},{t:.2222222222222222,value:{x:795,y:235,width:330,height:330},easing:"linear"},{t:.3492063492063492,value:{x:785.4497891718671,y:98.38367346938782,width:333.2326530612245,height:333.2326530612245}},{t:1,value:{x:820,y:140,width:280,height:280}}]},opacity:{keyframes:[{t:0,value:0,easing:"ease-out"},{t:.2222222222222222,value:1,easing:"linear"},{t:1,value:1}]}}},{id:"text-hlcq7y7c",kind:"text",startTime:38.1,duration:1.4,rect:{x:460,y:775,width:1e3,height:55},z:10,opacity:1,content:"ENGINEERED TO FLOAT",font:"48px Inter",color:"#9aa3b2",align:"center",fontFamily:"Inter",fontSize:32,fontWeight:500,reveal:{mode:"fade-words",durationMs:500},group:"shoe-brand"},{id:"text-16gcy19w",kind:"text",startTime:40.8,duration:11.2,rect:{x:1010,y:745,width:460,height:80},z:21,opacity:1,content:"Or download the app",font:"48px Inter",color:"#cdd3de",align:"center",fontFamily:"Inter",fontSize:42,fontWeight:500,background:{color:"rgba(255,255,255,0.08)",padding:18,radius:12},reveal:{mode:"fade-words",durationMs:300},group:"end-card"},{id:"img-vxnkonqd",kind:"image",startTime:39.8,duration:12.2,rect:{x:670,y:228,width:320,height:320},z:21,opacity:1,assetSlug:"libi-ring-glyph.png",group:"end-card",keyframes:{rect:{keyframes:[{t:0,value:{x:670,y:228,width:320,height:320},easing:"ease-out"},{t:.062842,value:{x:670,y:228,width:320,height:320},easing:"linear"},{t:.180328,value:{x:663.6,y:221.6,width:332.8,height:332.8},easing:"linear"},{t:1,value:{x:663.6,y:221.6,width:332.8,height:332.8}}]},opacity:{keyframes:[{t:0,value:0,easing:"ease-out"},{t:.062842,value:1,easing:"linear"},{t:.180328,value:1,easing:"linear"},{t:1,value:1}]}},shadow:{color:"rgba(139,180,139,0.55)",blur:70,dx:0,dy:0}},{id:"text-3048dja6",kind:"text",startTime:41.2,duration:10.8,rect:{x:610,y:872,width:700,height:64},z:21,opacity:1,content:"libi.nagellabs.com",font:"48px Inter",color:"#8b93a7",align:"center",fontFamily:"Inter",fontSize:40,fontWeight:400,reveal:{mode:"fade-words",durationMs:300},group:"end-card"}],audioClips:[{id:"clip_i13f0m0n",kind:"inline",assetSlug:"clip-water-impact.mp4",startTime:34.4,duration:6,trimStart:0,volume:.6,enabled:!0,linkedOverlayId:"vid-so51lufn",label:"film audio — splash"},{id:"clip_4t921f5s",kind:"standalone",assetSlug:"music-build-28s.mp3",startTime:0,duration:28,trimStart:0,volume:.85,enabled:!0,label:"music — build (hard cut at 0:28)",duck:{sidechainClipIds:["clip_vo1","clip_vo2","clip_vo3","clip_vo4","clip_vo5","clip_vo6"],thresholdDb:-30,ratio:4,attackMs:50,releaseMs:250,reductionDb:-12}},{id:"clip_g0uxbvkf",kind:"standalone",assetSlug:"sfx-typing.mp3",startTime:.2,duration:3.6,trimStart:0,volume:.5,enabled:!0,label:"SFX typing"},{id:"clip_pj7r0it5",kind:"standalone",assetSlug:"sfx-basshit.mp3",startTime:3.95,duration:1,trimStart:0,volume:.9,enabled:!0,label:"SFX bass hit (Enter)"},{id:"clip_316hr7uq",kind:"standalone",assetSlug:"sfx-clicks.mp3",startTime:4.6,duration:4,trimStart:0,volume:.35,enabled:!0,label:"SFX UI clicks"},{id:"clip_wuk6rzqz",kind:"standalone",assetSlug:"sfx-riser.mp3",startTime:24,duration:4,trimStart:0,volume:.7,enabled:!0,label:"SFX riser → cut"},{id:"clip_v4tmovmb",kind:"inline",assetSlug:"clip-hero-orbit-v2.mp4",startTime:30,duration:4.4,trimStart:0,volume:.6,enabled:!0,linkedOverlayId:"vid-gdgll882",label:"film audio — orbit"},{id:"clip_c44rnjt8",kind:"standalone",assetSlug:"music-anthem-12s.mp3",startTime:30,duration:12,trimStart:0,volume:.9,enabled:!0,label:"music — anthem (0:30–0:42)",duck:{sidechainClipIds:["clip_vo1","clip_vo2","clip_vo3","clip_vo4","clip_vo5","clip_vo6"],thresholdDb:-30,ratio:4,attackMs:50,releaseMs:250,reductionDb:-12}},{id:"clip_tnqhriva",kind:"inline",assetSlug:"clip-track-demo.mp4",startTime:16,duration:6,trimStart:0,volume:1,enabled:!1,linkedOverlayId:"vid-lu4jxr6v",label:"tracking clip audio (muted)"},{id:"clip_vo1",kind:"standalone",assetSlug:"vo-1-describe.mp3",startTime:1,duration:1.149,trimStart:0,volume:1,enabled:!0,label:"VO 1 — You describe it."},{id:"clip_vo2",kind:"standalone",assetSlug:"vo-2-agent.mp3",startTime:5,duration:2.273,trimStart:0,volume:1,enabled:!0,label:"VO 2 — A coding agent builds it."},{id:"clip_vo3",kind:"standalone",assetSlug:"vo-3-generates.mp3",startTime:11,duration:3.474,trimStart:0,volume:1,enabled:!0,label:"VO 3 — It generates the footage…"},{id:"clip_vo4",kind:"standalone",assetSlug:"vo-4-code.mp3",startTime:17,duration:2.508,trimStart:0,volume:1,enabled:!0,label:"VO 4 — Every frame is code."},{id:"clip_vo5",kind:"standalone",assetSlug:"vo-5-director.mp3",startTime:24.6,duration:1.411,trimStart:0,volume:1,enabled:!0,label:"VO 5 — You stay the director."},{id:"clip_vo6",kind:"standalone",assetSlug:"vo-6-madein.mp3",startTime:37.3,duration:2.508,trimStart:0,volume:1,enabled:!0,label:"VO 6 — This video? Made in libi."}]},assets:eg}};var eh=e.i(753492);function ed(e){return`libi:onboarding:${e}`}function eu(e,t){if(Array.isArray(e))return e.map(e=>eu(e,t));if(null!==e&&"object"==typeof e){if(Object.hasOwn(e,"assetSlug")&&Object.hasOwn(e,"fileId"))throw Error(`onboarding: node carries both assetSlug and fileId — ${JSON.stringify(e)} — refusing to let key order pick a winner.`);let A={};for(let[r,i]of Object.entries(e)){if("assetSlug"!==r){A[r]=eu(i,t);continue}if("string"!=typeof i)throw Error(`onboarding: assetSlug must be a string, got ${JSON.stringify(i)}`);let e=t.get(i);if(!e)throw Error(`onboarding: unresolved asset slug ${JSON.stringify(i)} — it is referenced by the composition but was never downloaded.`);A.fileId=e}return A}return e}async function eE(e){let t=ed(e);for(let e of(0,s.getDb)().select({id:o.pieces.id}).from(o.pieces).where((0,n.eq)(o.pieces.description,t)).orderBy((0,et.desc)(o.pieces.createdAt),(0,et.desc)(o.pieces.id)).all())if(await (0,eh.hasManifest)(e.id))return e.id;return null}let eQ={kind:"onboarding_piece",maxConcurrent:1,paramsSchema:S.z.object({version:S.z.literal("v1"),force:S.z.boolean()}),resumable:!1,noProgressTimeoutMs:12e4,mcpToolId:(0,T.makeMcpToolId)("libi","libi.build_onboarding_piece"),async run(e){var t;let A,{version:r,force:i}=e.params,a=ec[r];if(!a)throw Error(`onboarding: no definition for version ${r}`);let{definition:g,assets:c}=a;if(!i){let t=await eE(r);if(t)return l.serverLogger.info({tag:"onboarding",op:"reused",version:r,pieceId:t},"onboarding: demo piece already built — reusing it"),e.reportProgress(c.length,c.length,"files"),{pieceId:t,version:r,bytes:0,assets:0,reused:!0}}let h=function(e){let t=process.env[eo]?.trim(),A=!!t,r=A?t:"https://storage.googleapis.com/libi-public-assets/onboarding";if(A){let e;try{e=new URL(r)}catch{throw Error(`${eo} is not a valid http(s) url: ${r}`)}if("http:"!==e.protocol&&"https:"!==e.protocol)throw Error(`${eo} must be an http(s) url, got ${e.protocol}//… (${r})`)}return{baseUrl:`${r.replace(/\/+$/,"")}/${el("version",e)}`,guard:A?es.assertDevLoopbackOrPublicHttpUrl:es.assertPublicHttpUrl,overridden:A}}(r);l.serverLogger.info({tag:"onboarding",op:"asset_source",version:r,baseUrl:h.baseUrl,overridden:h.overridden,assets:c.length},"onboarding: resolved demo asset base");let d=await ei({name:g.name,description:`libi:onboarding:${r}:building`});if(!d.success||!d.data)throw Error(`onboarding: could not create the demo piece: ${d.error??"unknown"}`);let u=d.data.id;try{e.reportProgress(0,c.length,"files");let i=new Map,a=0;for(let[A,r]of c.entries()){if(e.shouldCancel())throw new eA.CancelledError(e.jobId);try{let e=await (0,en.fetchAndStoreRemoteFile)({url:(t=r.slug,`${h.baseUrl}/${el("slug",t)}`),guard:h.guard,pieceId:u,filename:r.slug,expectSha256:r.sha256,contentType:r.contentType,skipProxyGeneration:!0});i.set(r.slug,e.fileId),a+=e.bytes}catch(e){throw Error(`onboarding: asset ${r.slug} failed: ${e instanceof Error?e.message:String(e)}`,{cause:e})}e.reportProgress(A+1,c.length,"files")}if(e.shouldCancel())throw new eA.CancelledError(e.jobId);let d=eu(g.overlays,i),E=eu(g.audioClips,i),Q={width:g.width,height:g.height,fps:g.fps,overlays:d,audioClips:E};await (0,eh.saveManifest)(u,Q),(0,s.getDb)().update(o.pieces).set({description:ed(r),updatedAt:new Date}).where((0,n.eq)(o.pieces.id,u)).run(),l.serverLogger.info({tag:"onboarding",op:"built",version:r,pieceId:u,assets:i.size,bytes:a,overlays:d.length},"onboarding: demo piece built"),A={pieceId:u,version:r,bytes:a,assets:i.size,reused:!1}}catch(e){try{await (0,er.deletePieceCompletely)(u)}catch(e){l.serverLogger.error({tag:"onboarding",op:"rollback_failed",version:r,pieceId:u,err:e instanceof Error?e.message:String(e)},"onboarding: could not clean up the partial demo piece")}throw e}return(0,V.trackServerEvent)("onboarding_piece_built",{version:r}),A}},eI=globalThis.__libiRunnerRegistry??new Map;function eB(e){return eI.get(e)??null}function eC(){for(let e of[c.trackingRunner,h.trackingProviderRunner,d.proxyGenRunner,u.filmstripGenRunner,E.exportRenderRunner,Q.exportRunner,I.analysisDescribeFrameRunner,B.whisperModelDownloadRunner,C.ttsModelDownloadRunner,f.musicModelDownloadRunner,p.musicGenerateRunner,y.pieceDupRunner,m.extraAnalysisModelRunner,w.remoteFetchRunner,D.matteGenRunner,b.runtimeUpdateRunner,v,Z,eQ,ee])eB(e.kind)||function(e){if(eI.has(e.kind))throw Error(`Runner already registered for kind: ${e.kind}`);eI.set(e.kind,e)}(e)}function ef(){eC();let e=new Map;for(let t of Array.from(eI.values())){if(!t.mcpToolId)continue;let A=Array.isArray(t.mcpToolId)?t.mcpToolId:[t.mcpToolId];e.set(t.kind,A)}return e}globalThis.__libiRunnerRegistry=eI;var ep=e.i(290703);async function ey(e){(0,s.getDb)().insert(o.jobs).values({id:e.id,kind:e.kind,clientKey:e.clientKey,paramsHash:e.paramsHash,paramsJson:e.paramsJson,pieceId:e.pieceId,fileId:e.fileId,status:"queued"}).run()}async function em(e){let[t]=(0,s.getDb)().select().from(o.jobs).where((0,n.eq)(o.jobs.id,e)).limit(1).all();return t??null}async function ew(e,t,A={}){let r=(0,s.getDb)(),i=(0,n.and)((0,n.eq)(o.jobs.kind,e),(0,n.eq)(o.jobs.paramsHash,t)),a=A.excludeTerminal?(0,n.and)(i,(0,n.notInArray)(o.jobs.status,["completed","failed","cancelled"])):i,[l]=r.select().from(o.jobs).where(a).limit(1).all();return l??null}async function eD(e,t){let[A]=(0,s.getDb)().select().from(o.jobs).where((0,n.and)((0,n.eq)(o.jobs.kind,e),(0,n.eq)(o.jobs.paramsHash,t),(0,n.inArray)(o.jobs.status,["running","queued","cancel-requested"]))).limit(1).all();return A??null}async function eb(e,t){let[A]=(0,s.getDb)().select().from(o.jobs).where((0,n.and)((0,n.eq)(o.jobs.kind,e),(0,n.eq)(o.jobs.paramsHash,t),(0,n.inArray)(o.jobs.status,["completed","failed","cancelled"]))).orderBy((0,et.desc)(o.jobs.completedAt)).limit(1).all();return A??null}async function eS(e){let t=(0,s.getDb)(),A=new Date;t.update(o.jobs).set({status:"running",startedAt:A,lastProgressAt:A}).where((0,n.eq)(o.jobs.id,e)).run()}async function eN(e,t){let A=(0,s.getDb)(),r={progressDone:t.done,progressTotal:t.total,lastProgressAt:new Date};void 0!==t.unit&&(r.progressUnit=t.unit),void 0!==t.msPerUnit&&(r.msPerUnit=t.msPerUnit),A.update(o.jobs).set(r).where((0,n.eq)(o.jobs.id,e)).run()}async function eR(e,t){(0,s.getDb)().update(o.jobs).set({partialPath:t}).where((0,n.eq)(o.jobs.id,e)).run()}async function eF(e,t){(0,s.getDb)().update(o.jobs).set({status:"completed",resultJson:t,completedAt:new Date,error:null}).where((0,n.eq)(o.jobs.id,e)).run()}async function ek(e,t){(0,s.getDb)().update(o.jobs).set({status:"failed",error:t,completedAt:new Date}).where((0,n.eq)(o.jobs.id,e)).run()}async function eM(e){(0,s.getDb)().update(o.jobs).set({status:"cancel-requested"}).where((0,n.eq)(o.jobs.id,e)).run()}async function eU(e){(0,s.getDb)().update(o.jobs).set({status:"cancelled",completedAt:new Date}).where((0,n.eq)(o.jobs.id,e)).run()}var eT=e.i(702220);function eL(e){return i.default.join((0,a.getLibiHome)(),"jobs",e,"state.json")}class ev extends t.EventEmitter{cancelFlags=new Map;inflight=new Map;lastEmitAt=new Map;lastProgress=new Map;watchdogTripped=new Set;progressChains=new Map;etaTrackers=new Map;forcedJobs=new Set;discardOutputJobs=new Set;activeByKind=new Map;waiters=new Map;toolCallIdByJob=new Map;jobIdByToolCallId=new Map;toolHintByJob=new Map;attachToolHint(e,t){this.toolHintByJob.set(e,t)}getToolHint(e){return this.toolHintByJob.get(e)??null}attachToolCallId(e,t){let A=this.toolCallIdByJob.get(e);A||(A=new Set,this.toolCallIdByJob.set(e,A)),A.add(t),this.jobIdByToolCallId.set(t,e)}getJobIdForToolCallId(e){return this.jobIdByToolCallId.get(e)??null}emitTerminal(e,t,A={}){let r=this.toolCallIdByJob.get(t);this.emit(e,{jobId:t,...A,toolCallIds:r?Array.from(r):[]})}async enqueue(e,t,A={}){let a=eB(e);if(!a)throw Error(`No runner registered for kind: ${e}`);let c=a.paramsSchema.parse(t),h=(0,g.canonicalHash)(c),d=A.clientKey||`srv-${ex()}`;if(!0===A.forceNew||!1===A.resume){if(a.exclusiveResource){let t=await eD(e,h);if(t)return l.serverLogger.info({jobId:t.id,kind:e},"jobs.force_new.attached_exclusive"),{status:"attached_running",jobId:t.id,clientKey:t.clientKey||d,existingJob:{jobId:t.id,pieceId:t.pieceId,startedAt:t.startedAt?.toISOString()??""}}}let t=await ew(e,h);if(t){(0,s.getDb)().delete(o.jobs).where((0,n.eq)(o.jobs.id,t.id)).run(),this.forcedJobs.delete(t.id),this.discardOutputJobs.delete(t.id);let e=i.default.dirname(eL(t.id));try{r.default.rmSync(e,{recursive:!0,force:!0})}catch(t){l.serverLogger.warn({err:t,oldStateDir:e},"jobs.resume.cleanup_failed")}}let g=`job-${ex()}`;return await ey({id:g,kind:e,clientKey:d,paramsHash:h,paramsJson:JSON.stringify(c),pieceId:A.pieceId??null,fileId:A.fileId??null}),this.forcedJobs.add(g),!0===A.discardOutput&&this.discardOutputJobs.add(g),this.emit("created",{jobId:g,kind:e}),{status:"new",jobId:g,clientKey:d,forced:!0}}let u=await eD(e,h);if(u)return{status:"attached_running",jobId:u.id,clientKey:u.clientKey||d,existingJob:{jobId:u.id,pieceId:u.pieceId,startedAt:u.startedAt?.toISOString()??""}};let E=await eb(e,h);if(E)return{status:"matching_completed",existingJob:{jobId:E.id,pieceId:E.pieceId,completedAt:E.completedAt?.toISOString()??"",status:E.status,result:function(e,t){if(t)try{return JSON.parse(t)}catch(t){l.serverLogger.warn({tag:"jobs",op:"terminal_result_parse_failed",jobId:e,err:t instanceof Error?t.message:String(t)},"Failed to parse cached job result JSON; returning undefined");return}}(E.id,E.resultJson),error:E.error}};let Q=`job-${ex()}`;return await ey({id:Q,kind:e,clientKey:d,paramsHash:h,paramsJson:JSON.stringify(c),pieceId:A.pieceId??null,fileId:A.fileId??null}),this.emit("created",{jobId:Q,kind:e}),{status:"new",jobId:Q,clientKey:d}}async runToCompletion(e,t){let A=t?this.subscribe(e,t):()=>{};try{let t=this.inflight.get(e);if(t)return t;let A=this.runLocked(e);this.inflight.set(e,A);try{return await A}finally{this.inflight.delete(e)}}finally{A()}}subscribe(e,t){let A=A=>{A.jobId===e&&t(A)};return this.on("progress",A),()=>this.off("progress",A)}async getStatus(e){let t=await em(e);if(!t)throw new eA.JobNotFoundError(e);return(0,eA.snapshotFromRow)(t)}async cancel(e){let t=await em(e);if(!t)throw new eA.JobNotFoundError(e);if("completed"===t.status||"failed"===t.status||"cancelled"===t.status)return;await eM(e);let A=this.cancelFlags.get(e);A&&A.abort(),this.emit("cancel-requested",{jobId:e})}async runLocked(e){let t=await em(e);if(!t)throw new eA.JobNotFoundError(e);let A=eB(t.kind);if(!A)throw Error(`No runner registered for kind: ${t.kind}`);await this.acquireSlot(A.kind,A.maxConcurrent);try{let r=await em(e);if(r?.status==="cancel-requested")throw await eU(e),this.emitTerminal("cancelled",e),new eA.CancelledError(e);return await this.runWithSlot(e,r??t,A)}finally{this.releaseSlot(A.kind)}}async acquireSlot(e,t){(this.activeByKind.get(e)??0)<t||await new Promise(t=>{let A=this.waiters.get(e)??[];A.push(t),this.waiters.set(e,A)}),this.activeByKind.set(e,(this.activeByKind.get(e)??0)+1)}releaseSlot(e){this.activeByKind.set(e,Math.max(0,(this.activeByKind.get(e)??0)-1));let t=this.waiters.get(e);t&&t.length>0&&t.shift()()}async runWithSlot(e,t,A){await eS(e);let n=new AbortController;this.cancelFlags.set(e,n);let s=null===A.noProgressTimeoutMs?null:A.noProgressTimeoutMs??6e4,o=null;null!==s&&(await eN(e,{done:0,total:0}),o=setInterval(()=>{(async()=>{let A=await em(e);if(!A||"running"!==A.status||!A.lastProgressAt)return;let r=Date.now()-A.lastProgressAt.getTime();r>s&&(l.serverLogger.warn({jobId:e,kind:t.kind,idleMs:r},"jobs.watchdog.no_progress"),this.watchdogTripped.add(e),n.abort())})().catch(t=>l.serverLogger.warn({err:t,jobId:e},"jobs.watchdog.poll_failed"))},Math.max(10,Math.min(5e3,Math.floor(s/4)))));let a=setInterval(()=>{try{this.emitHeartbeat(e)}catch(t){l.serverLogger.warn({err:t,jobId:e},"jobs.heartbeat.failed")}},15e3);a.unref?.();let g=eL(e),c=null;if(t.partialPath&&r.default.existsSync(t.partialPath))try{c=JSON.parse(r.default.readFileSync(t.partialPath,"utf-8"))}catch(t){l.serverLogger.warn({err:t,jobId:e},"jobs.resume.parse_failed"),c=null}let h={jobId:e,params:JSON.parse(t.paramsJson),resumeState:c,reportProgress:(A,r,i)=>{this.handleProgress(e,t.kind,A,r,i??t.progressUnit)},checkpoint:async A=>{r.default.mkdirSync(i.default.dirname(g),{recursive:!0}),r.default.writeFileSync(g,JSON.stringify(A),"utf-8"),t.partialPath||(await eR(e,g),t.partialPath=g)},shouldCancel:()=>n.signal.aborted,forced:this.forcedJobs.has(e),discardOutput:this.discardOutputJobs.has(e)};try{var d,u;let t=await Promise.race([A.run(h),(d=n.signal,u=()=>this.watchdogTripped.has(e)?Error(`No progress for ${s}ms — watchdog tripped`):new eA.CancelledError(e),new Promise((e,t)=>{d.aborted?t(u()):d.addEventListener("abort",()=>t(u()),{once:!0})}))]);if(r.default.existsSync(g))try{r.default.unlinkSync(g)}catch{}return await eF(e,JSON.stringify(t)),this.emitTerminal("completed",e,{result:t}),t}catch(r){if(this.watchdogTripped.has(e)){this.watchdogTripped.delete(e);let A=`No progress for ${s}ms — watchdog tripped`;try{await ek(e,A)}catch(t){l.serverLogger.error({err:t,jobId:e},"jobs.run.mark_failed_throw")}throw l.serverLogger.error({jobId:e,kind:t.kind,watchdogMs:s},"jobs.run.watchdog_failed"),this.emitTerminal("failed",e,{error:A}),Error(A)}if(r instanceof eA.CancelledError||n.signal.aborted){try{await eU(e)}catch(t){l.serverLogger.error({err:t,jobId:e},"jobs.run.mark_cancelled_throw")}throw this.emitTerminal("cancelled",e),r instanceof eA.CancelledError?r:new eA.CancelledError(e)}let A=r instanceof Error?r.message:String(r);try{await ek(e,A)}catch(t){l.serverLogger.error({err:t,jobId:e},"jobs.run.mark_failed_throw")}throw l.serverLogger.error({jobId:e,kind:t.kind,err:A},"jobs.run.failed"),this.emitTerminal("failed",e,{error:A}),r}finally{o&&clearInterval(o),clearInterval(a),this.cancelFlags.delete(e),this.progressChains.delete(e),this.etaTrackers.delete(e),this.lastProgress.delete(e);let t=this.toolCallIdByJob.get(e);if(t)for(let e of t)this.jobIdByToolCallId.delete(e);this.toolCallIdByJob.delete(e),this.toolHintByJob.delete(e),this.forcedJobs.delete(e),this.discardOutputJobs.delete(e)}}handleProgress(e,t,A,r,i){let n=Date.now();if(A=Math.min(A,r>0?r:A),n-(this.lastEmitAt.get(e)??0)<1e3&&A<r)return;this.lastEmitAt.set(e,n);let s=(this.progressChains.get(e)??Promise.resolve()).then(async()=>{let s=await em(e);if(!s||!s.startedAt)return;let o=this.etaTrackers.get(e);o||(o=new ep.EtaTracker,this.etaTrackers.set(e,o)),o.add(n,A);let a=o.msPerUnit();await eN(e,{done:A,total:r,unit:i,msPerUnit:a}),this.lastProgress.set(e,{kind:t,done:A,total:r,unit:i});let l={jobId:e,kind:t,done:A,total:r,unit:i,msPerUnit:a,etaMs:o.etaMs(r,A)};this.emit("progress",l),this.notifyProgress(l)}).catch(t=>{l.serverLogger.warn({err:t,jobId:e},"jobs.progress.update_failed")});this.progressChains.set(e,s)}notifyProgress(e){let t=this.toolCallIdByJob.get(e.jobId),A=this.toolHintByJob.get(e.jobId),r={jobId:e.jobId,kind:e.kind,done:e.done,total:e.total,unit:e.unit,etaMs:e.etaMs,msSinceProgress:e.msSinceProgress??null,...A?{toolName:A.toolName,toolArgs:A.toolArgs,...A.progressLabel?{progressLabel:A.progressLabel}:{}}:{}};try{if(t&&t.size>0)for(let e of t)eT.notify.jobProgress({...r,toolCallId:e});else eT.notify.jobProgress({...r,toolCallId:void 0})}catch(t){l.serverLogger.warn({err:t,jobId:e.jobId},"jobs.progress.notify_failed")}}emitHeartbeat(e){let t=this.lastProgress.get(e);if(!t)return;let A=this.etaTrackers.get(e);if(!A)return;let r=Date.now(),i=A.lastSampleAt(),n={jobId:e,kind:t.kind,done:t.done,total:t.total,unit:t.unit,msPerUnit:A.msPerUnit(),etaMs:A.etaMs(t.total,t.done,r),msSinceProgress:null!==i?r-i:null};this.emit("progress",n),this.notifyProgress(n)}}function ex(){return(0,A.randomUUID)()}function eY(){return globalThis.__libiJobManager||(eC(),globalThis.__libiJobManager=new ev),globalThis.__libiJobManager}}];
|
|
857
857
|
|
|
858
|
-
//# debugId=
|
|
858
|
+
//# debugId=a113923a-565c-0148-8e48-67981226f105
|
|
859
859
|
//# sourceMappingURL=_0ovzm6d._.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="
|
|
2
|
-
module.exports=[883978,824099,239829,e=>{"use strict";var t=e.i(875225),n=e.i(190793);e.i(945122);var i=e.i(478181),s=e.i(640911);let r={enabled:!0,userId:null,optOutAt:null,firstRunNoticeShown:!1,milestones:[]};function o(e){if(!e)return{...r};try{let t=JSON.parse(e);if(!t||"object"!=typeof t)return{...r};return{enabled:"boolean"!=typeof t.enabled||t.enabled,userId:"string"==typeof t.userId?t.userId:null,optOutAt:"number"==typeof t.optOutAt?t.optOutAt:null,firstRunNoticeShown:!0===t.firstRunNoticeShown,milestones:Array.isArray(t.milestones)?t.milestones.filter(e=>"string"==typeof e):[]}}catch{return{...r}}}function a(e,t){return{...e,...t}}function l(e,t){return e.milestones.includes(t)?{settings:e,added:!1}:{settings:{...e,milestones:[...e.milestones,t]},added:!0}}e.s(["applyOptIn",0,function(e){return{...e,enabled:!0,optOutAt:null}},"applyOptOut",0,function(e,t){return{...e,enabled:!1,optOutAt:t}},"markMilestone",0,l,"mergeAnalyticsSettings",0,a,"parseAnalyticsSettings",0,o],824099);var d=e.i(660526),u=e.i(750227),c=e.i(902157);function g(){let e=d.default.homedir();return"darwin"===process.platform?u.default.join(e,"Movies","libi"):u.default.join(e,"Videos","libi")}e.s(["defaultExportFolder",0,g,"ensureFolderExists",0,function(e){c.default.mkdirSync(e,{recursive:!0})},"isFolderWritable",0,function(e){try{return c.default.accessSync(e,c.default.constants.W_OK),!0}catch{return!1}}],239829);let p={preferredAgent:null,panelChatSize:40,panelEditorSize:40,panelResourcesSize:20,panelChatVisible:!0,panelResourcesVisible:!1,agentApprovalModes:null,agentModelPreferences:null,onboardingPersona:null,personaSelectedAt:null,agentEverConnected:!1,onboardingDemoOfferedAt:null,onboardingDemoDismissedAt:null},f={backgroundJobComplete:!0},m={connected:!1,lastSyncStatus:"idle"},_={folder:null,format:"mp4",quality:"source"};function b(){let[e]=(0,n.getDb)().select({exportDefaults:i.settings.exportDefaults}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all(),s=e?.exportDefaults;if(!s)return{..._};try{let e=JSON.parse(s);if(!e||"object"!=typeof e)return{..._};return{folder:"string"==typeof e.folder&&e.folder?e.folder:null,format:"webm"===e.format?"webm":"mp4",quality:"1080p"===e.quality||"1440p"===e.quality||"4k"===e.quality?e.quality:"source"}}catch{return{..._}}}function S(){let[e]=(0,n.getDb)().select({analytics:i.settings.analytics}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all();return o(e?.analytics??null)}function y(e){let t=(0,n.getDb)(),s=a(S(),e),r={analytics:JSON.stringify(s),updatedAt:new Date};return t.insert(i.settings).values({id:1,...r}).onConflictDoUpdate({target:i.settings.id,set:r}).run(),s}let A={choice:"unset",decidedAt:null};e.s(["getAnalyticsSettings",0,S,"getCodexConnectSetting",0,function(){try{let[e]=(0,n.getDb)().select({codex:i.settings.codex}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all(),s=e?.codex;if(!s)return{...m};let r=JSON.parse(s);if(!r||"object"!=typeof r||"boolean"!=typeof r.connected)return{...m};let o=r.lastSyncStatus;if("ok"!==o&&"error"!==o&&"idle"!==o)return{...m};return{connected:r.connected,lastSyncStatus:o}}catch(e){return s.serverLogger.warn({err:e,tag:"codex-connect",op:"read_degraded"},"getCodexConnectSetting: read failed, returning defaults"),{...m}}},"getCrashReportSettings",0,function(){let[e]=(0,n.getDb)().select({crashReports:i.settings.crashReports}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all();return function(e){if(!e)return{...A};try{let t=JSON.parse(e);if(!t||"object"!=typeof t)return{...A};let n=t.choice;if("unset"!==n&&"on"!==n&&"off"!==n)return{...A};let i="number"==typeof t.decidedAt?t.decidedAt:null;return{choice:n,decidedAt:i}}catch{return{...A}}}(e?.crashReports??null)},"getExportDefaults",0,b,"getNotificationsSetting",0,function(){let[e]=(0,n.getDb)().select({notifications:i.settings.notifications}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all(),s=e?.notifications;if(!s)return{...f};try{let e=JSON.parse(s);if(!e||"object"!=typeof e||"boolean"!=typeof e.backgroundJobComplete)return{...f};return{backgroundJobComplete:e.backgroundJobComplete}}catch{return{...f}}},"getOrCreateAnalyticsUserId",0,function(){let e=S();if(e.userId)return e.userId;let t=crypto.randomUUID();return y({userId:t}),t},"getSettings",0,function(){let e=(0,n.getDb)(),[s]=e.select().from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all();return s?{preferredAgent:s.preferredAgent??null,panelChatSize:s.panelChatSize,panelEditorSize:s.panelEditorSize,panelResourcesSize:s.panelResourcesSize,panelChatVisible:s.panelChatVisible,panelResourcesVisible:s.panelResourcesVisible,agentApprovalModes:s.agentApprovalModes??null,agentModelPreferences:s.agentModelPreferences??null,onboardingPersona:s.onboardingPersona??null,personaSelectedAt:s.personaSelectedAt??null,agentEverConnected:s.agentEverConnected,onboardingDemoOfferedAt:s.onboardingDemoOfferedAt??null,onboardingDemoDismissedAt:s.onboardingDemoDismissedAt??null}:(e.insert(i.settings).values({id:1}).run(),{...p})},"getSkillDigestCacheSetting",0,function(){let[e]=(0,n.getDb)().select({skillDigestCache:i.settings.skillDigestCache}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all(),s=e?.skillDigestCache;if(!s)return null;try{let e=JSON.parse(s);if(!e||"object"!=typeof e||"string"!=typeof e.version||!e.version||!e.digests||"object"!=typeof e.digests)return null;return{version:e.version,digests:e.digests}}catch{return null}},"markAnalyticsMilestoneOnce",0,function(e){let{settings:t,added:n}=l(S(),e);return n&&y({milestones:t.milestones}),n},"resolveExportFolder",0,function(){return b().folder??g()},"setAnalyticsSettings",0,y,"setCodexConnectSetting",0,function(e){let t=(0,n.getDb)(),s={codex:JSON.stringify(e),updatedAt:new Date};t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()},"setCrashReportSettings",0,function(e){let t=(0,n.getDb)(),s={crashReports:JSON.stringify(e),updatedAt:new Date};return t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run(),e},"setExportDefaults",0,function(e){let t=(0,n.getDb)(),s={exportDefaults:JSON.stringify(e),updatedAt:new Date};t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()},"setNotificationsSetting",0,function(e){let t=(0,n.getDb)(),s={notifications:JSON.stringify(e),updatedAt:new Date};t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()},"setSkillDigestCacheSetting",0,function(e){let t=(0,n.getDb)(),s={skillDigestCache:JSON.stringify(e),updatedAt:new Date};t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()},"updateSettings",0,function(e){let t=(0,n.getDb)(),s={updatedAt:new Date};void 0!==e.preferredAgent&&(s.preferredAgent=e.preferredAgent),void 0!==e.panelChatSize&&(s.panelChatSize=e.panelChatSize),void 0!==e.panelEditorSize&&(s.panelEditorSize=e.panelEditorSize),void 0!==e.panelResourcesSize&&(s.panelResourcesSize=e.panelResourcesSize),void 0!==e.panelChatVisible&&(s.panelChatVisible=e.panelChatVisible),void 0!==e.panelResourcesVisible&&(s.panelResourcesVisible=e.panelResourcesVisible),void 0!==e.agentApprovalModes&&(s.agentApprovalModes=e.agentApprovalModes),void 0!==e.agentModelPreferences&&(s.agentModelPreferences=e.agentModelPreferences),void 0!==e.onboardingPersona&&(s.onboardingPersona=e.onboardingPersona),void 0!==e.personaSelectedAt&&(s.personaSelectedAt=e.personaSelectedAt),void 0!==e.agentEverConnected&&(s.agentEverConnected=e.agentEverConnected),void 0!==e.onboardingDemoOfferedAt&&(s.onboardingDemoOfferedAt=e.onboardingDemoOfferedAt),void 0!==e.onboardingDemoDismissedAt&&(s.onboardingDemoDismissedAt=e.onboardingDemoDismissedAt),t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()}],883978)},692855,e=>{"use strict";e.s(["isTestMode",0,function(){let e=process.env.LIBI_TEST_MODE;return"1"===e||"true"===e}])},38657,e=>{"use strict";var t;process.env.NEXT_PUBLIC_LIBI_GA4_MEASUREMENT_ID;let n="1"!==(t=process.env).LIBI_ANALYTICS_DISABLED&&"1"===t.NEXT_PUBLIC_LIBI_ANALYTICS;process.env.NODE_ENV;let i="1"===process.env.LIBI_ANALYTICS_DISABLED;e.s(["ANALYTICS_ENABLED",0,n,"ANALYTICS_KILL_SWITCH",0,i])},260338,e=>{"use strict";e.i(156325),e.i(844988);var t=e.i(518899);e.s(["count",0,function(e){return t.sql`count(${e||t.sql.raw("*")})`.mapWith(Number)}])},884724,e=>{"use strict";let t=new Set(["first_launch","first_export","persona_selected","agent_connected","onboarding_piece_built","persona_prompt_shown","agent_connect_shown","agent_setup_started","agent_setup_command_copied","agent_install_completed","agent_install_failed","agent_sign_in_opened","first_message_sent","piece_created","export_started","export_completed","agent_message_sent","file_uploaded","terminal_session_started","mcp_server_added","codex_connect_toggled","runtime_update_installed","version_restore","overlay_added","overlay_edited","preset_applied","effect_applied","effect_previewed","text_3d_used","overlay_3d_used","chat_slash_command","context_meter_opened","page_view","page_engagement","tool_used","pro_waitlist_joined","announcement_shown","analytics_opt_out","analytics_opt_in"]);e.s(["isEventName",0,function(e){return t.has(e)},"sanitizeParams",0,function(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))null!=i&&("string"==typeof i?t[n]=i.slice(0,100):"number"==typeof i||"boolean"==typeof i?t[n]=i:t[n]=String(i).slice(0,100));return t},"toAgentEventId",0,function(e){return"claude-code"===e||"codex"===e?e:void 0}])},991858,e=>{"use strict";var t=e.i(349129),n=e.i(260338),i=e.i(875225),s=e.i(190793),r=e.i(478181),o=e.i(884724),a=e.i(883978),l=e.i(38657),d=e.i(692855);e.i(640911),e.s(["trackServerEvent",0,function(e,u){try{!function(e,u){try{if((0,d.isTestMode)()||l.ANALYTICS_KILL_SWITCH||!(0,a.getAnalyticsSettings)().enabled)return;let c=(0,o.sanitizeParams)(u),g=(0,s.getDb)();g.insert(r.analyticsQueue).values({id:crypto.randomUUID(),name:e,paramsJson:JSON.stringify(c),nextAttemptAt:new Date(0)}).run();let[{n:p}]=g.select({n:(0,n.count)()}).from(r.analyticsQueue).all();if(p>500){let e=g.select({id:r.analyticsQueue.id}).from(r.analyticsQueue).orderBy((0,t.asc)(r.analyticsQueue.createdAt)).limit(p-500).all().map(e=>e.id);g.delete(r.analyticsQueue).where((0,i.inArray)(r.analyticsQueue.id,e)).run()}}catch{}}(e,u)}catch{}}],991858)}];
|
|
1
|
+
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="464d762e-54cb-67a1-96c1-55b34f7d4b6c")}catch(e){}}();
|
|
2
|
+
module.exports=[883978,824099,239829,e=>{"use strict";var t=e.i(875225),n=e.i(190793);e.i(945122);var i=e.i(478181),s=e.i(640911);let r={enabled:!0,userId:null,optOutAt:null,firstRunNoticeShown:!1,milestones:[]};function o(e){if(!e)return{...r};try{let t=JSON.parse(e);if(!t||"object"!=typeof t)return{...r};return{enabled:"boolean"!=typeof t.enabled||t.enabled,userId:"string"==typeof t.userId?t.userId:null,optOutAt:"number"==typeof t.optOutAt?t.optOutAt:null,firstRunNoticeShown:!0===t.firstRunNoticeShown,milestones:Array.isArray(t.milestones)?t.milestones.filter(e=>"string"==typeof e):[]}}catch{return{...r}}}function a(e,t){return{...e,...t}}function l(e,t){return e.milestones.includes(t)?{settings:e,added:!1}:{settings:{...e,milestones:[...e.milestones,t]},added:!0}}e.s(["applyOptIn",0,function(e){return{...e,enabled:!0,optOutAt:null}},"applyOptOut",0,function(e,t){return{...e,enabled:!1,optOutAt:t}},"markMilestone",0,l,"mergeAnalyticsSettings",0,a,"parseAnalyticsSettings",0,o],824099);var d=e.i(660526),u=e.i(750227),c=e.i(902157);function g(){let e=d.default.homedir();return"darwin"===process.platform?u.default.join(e,"Movies","libi"):u.default.join(e,"Videos","libi")}e.s(["defaultExportFolder",0,g,"ensureFolderExists",0,function(e){c.default.mkdirSync(e,{recursive:!0})},"isFolderWritable",0,function(e){try{return c.default.accessSync(e,c.default.constants.W_OK),!0}catch{return!1}}],239829);let p={preferredAgent:null,panelChatSize:40,panelEditorSize:40,panelResourcesSize:20,panelChatVisible:!0,panelResourcesVisible:!1,agentApprovalModes:null,agentModelPreferences:null,onboardingPersona:null,personaSelectedAt:null,agentEverConnected:!1,onboardingDemoOfferedAt:null,onboardingDemoDismissedAt:null},f={backgroundJobComplete:!0},m={connected:!1,lastSyncStatus:"idle"},_={folder:null,format:"mp4",quality:"source"};function b(){let[e]=(0,n.getDb)().select({exportDefaults:i.settings.exportDefaults}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all(),s=e?.exportDefaults;if(!s)return{..._};try{let e=JSON.parse(s);if(!e||"object"!=typeof e)return{..._};return{folder:"string"==typeof e.folder&&e.folder?e.folder:null,format:"webm"===e.format?"webm":"mp4",quality:"1080p"===e.quality||"1440p"===e.quality||"4k"===e.quality?e.quality:"source"}}catch{return{..._}}}function S(){let[e]=(0,n.getDb)().select({analytics:i.settings.analytics}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all();return o(e?.analytics??null)}function A(e){let t=(0,n.getDb)(),s=a(S(),e),r={analytics:JSON.stringify(s),updatedAt:new Date};return t.insert(i.settings).values({id:1,...r}).onConflictDoUpdate({target:i.settings.id,set:r}).run(),s}let y={choice:"unset",decidedAt:null};e.s(["getAnalyticsSettings",0,S,"getCodexConnectSetting",0,function(){try{let[e]=(0,n.getDb)().select({codex:i.settings.codex}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all(),s=e?.codex;if(!s)return{...m};let r=JSON.parse(s);if(!r||"object"!=typeof r||"boolean"!=typeof r.connected)return{...m};let o=r.lastSyncStatus;if("ok"!==o&&"error"!==o&&"idle"!==o)return{...m};return{connected:r.connected,lastSyncStatus:o}}catch(e){return s.serverLogger.warn({err:e,tag:"codex-connect",op:"read_degraded"},"getCodexConnectSetting: read failed, returning defaults"),{...m}}},"getCrashReportSettings",0,function(){let[e]=(0,n.getDb)().select({crashReports:i.settings.crashReports}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all();return function(e){if(!e)return{...y};try{let t=JSON.parse(e);if(!t||"object"!=typeof t)return{...y};let n=t.choice;if("unset"!==n&&"on"!==n&&"off"!==n)return{...y};let i="number"==typeof t.decidedAt?t.decidedAt:null;return{choice:n,decidedAt:i}}catch{return{...y}}}(e?.crashReports??null)},"getExportDefaults",0,b,"getNotificationsSetting",0,function(){let[e]=(0,n.getDb)().select({notifications:i.settings.notifications}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all(),s=e?.notifications;if(!s)return{...f};try{let e=JSON.parse(s);if(!e||"object"!=typeof e||"boolean"!=typeof e.backgroundJobComplete)return{...f};return{backgroundJobComplete:e.backgroundJobComplete}}catch{return{...f}}},"getOrCreateAnalyticsUserId",0,function(){let e=S();if(e.userId)return e.userId;let t=crypto.randomUUID();return A({userId:t}),t},"getSettings",0,function(){let e=(0,n.getDb)(),[s]=e.select().from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all();return s?{preferredAgent:s.preferredAgent??null,panelChatSize:s.panelChatSize,panelEditorSize:s.panelEditorSize,panelResourcesSize:s.panelResourcesSize,panelChatVisible:s.panelChatVisible,panelResourcesVisible:s.panelResourcesVisible,agentApprovalModes:s.agentApprovalModes??null,agentModelPreferences:s.agentModelPreferences??null,onboardingPersona:s.onboardingPersona??null,personaSelectedAt:s.personaSelectedAt??null,agentEverConnected:s.agentEverConnected,onboardingDemoOfferedAt:s.onboardingDemoOfferedAt??null,onboardingDemoDismissedAt:s.onboardingDemoDismissedAt??null}:(e.insert(i.settings).values({id:1}).run(),{...p})},"getSkillDigestCacheSetting",0,function(){let[e]=(0,n.getDb)().select({skillDigestCache:i.settings.skillDigestCache}).from(i.settings).where((0,t.eq)(i.settings.id,1)).limit(1).all(),s=e?.skillDigestCache;if(!s)return null;try{let e=JSON.parse(s);if(!e||"object"!=typeof e||"string"!=typeof e.version||!e.version||!e.digests||"object"!=typeof e.digests)return null;return{version:e.version,digests:e.digests}}catch{return null}},"markAnalyticsMilestoneOnce",0,function(e){let{settings:t,added:n}=l(S(),e);return n&&A({milestones:t.milestones}),n},"resolveExportFolder",0,function(){return b().folder??g()},"setAnalyticsSettings",0,A,"setCodexConnectSetting",0,function(e){let t=(0,n.getDb)(),s={codex:JSON.stringify(e),updatedAt:new Date};t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()},"setCrashReportSettings",0,function(e){let t=(0,n.getDb)(),s={crashReports:JSON.stringify(e),updatedAt:new Date};return t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run(),e},"setExportDefaults",0,function(e){let t=(0,n.getDb)(),s={exportDefaults:JSON.stringify(e),updatedAt:new Date};t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()},"setNotificationsSetting",0,function(e){let t=(0,n.getDb)(),s={notifications:JSON.stringify(e),updatedAt:new Date};t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()},"setSkillDigestCacheSetting",0,function(e){let t=(0,n.getDb)(),s={skillDigestCache:JSON.stringify(e),updatedAt:new Date};t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()},"updateSettings",0,function(e){let t=(0,n.getDb)(),s={updatedAt:new Date};void 0!==e.preferredAgent&&(s.preferredAgent=e.preferredAgent),void 0!==e.panelChatSize&&(s.panelChatSize=e.panelChatSize),void 0!==e.panelEditorSize&&(s.panelEditorSize=e.panelEditorSize),void 0!==e.panelResourcesSize&&(s.panelResourcesSize=e.panelResourcesSize),void 0!==e.panelChatVisible&&(s.panelChatVisible=e.panelChatVisible),void 0!==e.panelResourcesVisible&&(s.panelResourcesVisible=e.panelResourcesVisible),void 0!==e.agentApprovalModes&&(s.agentApprovalModes=e.agentApprovalModes),void 0!==e.agentModelPreferences&&(s.agentModelPreferences=e.agentModelPreferences),void 0!==e.onboardingPersona&&(s.onboardingPersona=e.onboardingPersona),void 0!==e.personaSelectedAt&&(s.personaSelectedAt=e.personaSelectedAt),void 0!==e.agentEverConnected&&(s.agentEverConnected=e.agentEverConnected),void 0!==e.onboardingDemoOfferedAt&&(s.onboardingDemoOfferedAt=e.onboardingDemoOfferedAt),void 0!==e.onboardingDemoDismissedAt&&(s.onboardingDemoDismissedAt=e.onboardingDemoDismissedAt),t.insert(i.settings).values({id:1,...s}).onConflictDoUpdate({target:i.settings.id,set:s}).run()}],883978)},692855,e=>{"use strict";e.s(["isTestMode",0,function(){let e=process.env.LIBI_TEST_MODE;return"1"===e||"true"===e}])},38657,e=>{"use strict";var t,n;process.env.NEXT_PUBLIC_LIBI_GA4_MEASUREMENT_ID;let i="1"!==(t=process.env).LIBI_ANALYTICS_DISABLED&&"1"===t.NEXT_PUBLIC_LIBI_ANALYTICS;"1"===(n=process.env).LIBI_ANALYTICS_DEBUG||n.NODE_ENV;let s="1"===process.env.LIBI_ANALYTICS_DISABLED;e.s(["ANALYTICS_ENABLED",0,i,"ANALYTICS_KILL_SWITCH",0,s])},260338,e=>{"use strict";e.i(156325),e.i(844988);var t=e.i(518899);e.s(["count",0,function(e){return t.sql`count(${e||t.sql.raw("*")})`.mapWith(Number)}])},884724,e=>{"use strict";let t=new Set(["first_launch","first_export","persona_selected","agent_connected","onboarding_piece_built","persona_prompt_shown","agent_connect_shown","agent_setup_started","agent_setup_command_copied","agent_install_completed","agent_install_failed","agent_sign_in_opened","first_message_sent","piece_created","export_started","export_completed","agent_message_sent","file_uploaded","terminal_session_started","mcp_server_added","codex_connect_toggled","runtime_update_installed","version_restore","overlay_added","overlay_edited","preset_applied","effect_applied","effect_previewed","text_3d_used","overlay_3d_used","chat_slash_command","context_meter_opened","page_view","page_engagement","tool_used","pro_waitlist_joined","announcement_shown","analytics_opt_out","analytics_opt_in"]);e.s(["isEventName",0,function(e){return t.has(e)},"sanitizeParams",0,function(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))null!=i&&("string"==typeof i?t[n]=i.slice(0,100):"number"==typeof i||"boolean"==typeof i?t[n]=i:t[n]=String(i).slice(0,100));return t},"toAgentEventId",0,function(e){return"claude-code"===e||"codex"===e?e:void 0}])},991858,e=>{"use strict";var t=e.i(349129),n=e.i(260338),i=e.i(875225),s=e.i(190793),r=e.i(478181),o=e.i(884724),a=e.i(883978),l=e.i(38657),d=e.i(692855);e.i(640911),e.s(["trackServerEvent",0,function(e,u){try{!function(e,u){try{if((0,d.isTestMode)()||l.ANALYTICS_KILL_SWITCH||!(0,a.getAnalyticsSettings)().enabled)return;let c=(0,o.sanitizeParams)(u),g=(0,s.getDb)();g.insert(r.analyticsQueue).values({id:crypto.randomUUID(),name:e,paramsJson:JSON.stringify(c),nextAttemptAt:new Date(0)}).run();let[{n:p}]=g.select({n:(0,n.count)()}).from(r.analyticsQueue).all();if(p>500){let e=g.select({id:r.analyticsQueue.id}).from(r.analyticsQueue).orderBy((0,t.asc)(r.analyticsQueue.createdAt)).limit(p-500).all().map(e=>e.id);g.delete(r.analyticsQueue).where((0,i.inArray)(r.analyticsQueue.id,e)).run()}}catch{}}(e,u)}catch{}}],991858)}];
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=464d762e-54cb-67a1-96c1-55b34f7d4b6c
|
|
5
5
|
//# sourceMappingURL=_0pwx1vo._.js.map
|