limixbot 0.3.106 → 0.3.107
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{ActivityPanel-CCcPfgz5.js → ActivityPanel-Dwy_8Ssw.js} +1 -1
- package/dist/assets/{App-zBBulOuW.js → App-DER9VjCj.js} +8 -8
- package/dist/assets/{AppEventEditor-DwF0_M1b.js → AppEventEditor-DVPTS46l.js} +1 -1
- package/dist/assets/{BotSettingsDialog-DxU0bbvL.js → BotSettingsDialog-CBMhMWpP.js} +1 -1
- package/dist/assets/{BrowserPanel-BhTErfef.js → BrowserPanel-cuhGe02X.js} +1 -1
- package/dist/assets/{BrowserProfilesManager-Db3HtlGT.js → BrowserProfilesManager-DCwRz57j.js} +1 -1
- package/dist/assets/{CloudAddDialog-kamEe44b.js → CloudAddDialog-jmGkr7Un.js} +1 -1
- package/dist/assets/{ComputerFilesPane-CcKrhxHb.js → ComputerFilesPane-8K2V3RhW.js} +1 -1
- package/dist/assets/{ComputerPanel-xvhrDI3V.js → ComputerPanel-pAbCBPNK.js} +2 -2
- package/dist/assets/{DataPanel-U-hn3L__.js → DataPanel-Cqk9kG4Y.js} +1 -1
- package/dist/assets/{GrokMoveDialog-DUq8KP9G.js → GrokMoveDialog-CpK4k-BS.js} +1 -1
- package/dist/assets/{InspectorPanel-USPl8hOG.js → InspectorPanel-Cy2voxQ9.js} +1 -1
- package/dist/assets/{KeyboardShortcutsModal-p9ysRLk1.js → KeyboardShortcutsModal-CLLeb5RM.js} +1 -1
- package/dist/assets/{LimixResizeHandles-BKWnbJ2i.js → LimixResizeHandles-DN3T-Sxj.js} +1 -1
- package/dist/assets/{LiveDesktop-DhWsbWD4.js → LiveDesktop-D1zL4cXe.js} +1 -1
- package/dist/assets/{LocalVmWorkspace-CmUPQxAR.js → LocalVmWorkspace-OPstoi6j.js} +1 -1
- package/dist/assets/{MacLocalControl-BhwfZLHm.js → MacLocalControl-BAU_Mxfl.js} +1 -1
- package/dist/assets/{MarkdownFilePreview-CuhD_8FB.js → MarkdownFilePreview-DiDEa2VP.js} +1 -1
- package/dist/assets/{NewBotDialog-wcLErpXf.js → NewBotDialog-_fhvtWem.js} +1 -1
- package/dist/assets/{PhoneAppDialog-DgId8RUc.js → PhoneAppDialog-TisX6Kkd.js} +1 -1
- package/dist/assets/{PluginsPanel-mk1MGvXs.js → PluginsPanel-mfBuYBSI.js} +1 -1
- package/dist/assets/{ProIntroduction-BYE3bQsp.js → ProIntroduction-DS75WAZy.js} +1 -1
- package/dist/assets/{RemoteAgentSettingsPanel-CKiEG2R6.js → RemoteAgentSettingsPanel-B148emwo.js} +1 -1
- package/dist/assets/{RoomPanel-DOg2_LNg.js → RoomPanel-B_RUQv3X.js} +1 -1
- package/dist/assets/{RoutinesPage-BsAHR1A_.js → RoutinesPage-Bt3nAr6K.js} +1 -1
- package/dist/assets/{SettingsModal-B2079ETl.js → SettingsModal-BjEnjf-l.js} +1 -1
- package/dist/assets/{ShareTeamDialog-do0hDEeZ.js → ShareTeamDialog-CFdVjk7Z.js} +1 -1
- package/dist/assets/{SignedInSites-GP2V7pnE.js → SignedInSites-ChIudtJC.js} +1 -1
- package/dist/assets/{TeamLibraryPanel-DZT4YTMk.js → TeamLibraryPanel-C5ba9U3p.js} +1 -1
- package/dist/assets/{TeamMapPage-D0E4dgpI.js → TeamMapPage-CMv2EOnM.js} +1 -1
- package/dist/assets/{TriggersPage-DjLrZqK8.js → TriggersPage-DAFkA0uT.js} +1 -1
- package/dist/assets/{VisibilitySection-D1WhMCk7.js → VisibilitySection-CLxd2eiH.js} +1 -1
- package/dist/assets/{WebhookTrigger-DhQjWpWp.js → WebhookTrigger-C6ySSY-L.js} +1 -1
- package/dist/assets/{WorksOnGrid-BXuGA0Sp.js → WorksOnGrid-DDm8ZPUS.js} +1 -1
- package/dist/assets/{core-B3DZ2YZD.js → core-Ce8mfU6p.js} +1 -1
- package/dist/assets/{import-name-DMgD6yXZ.js → import-name-CzRqCqhy.js} +1 -1
- package/dist/assets/{index-DSJo2jnB.js → index-DQSfzGc3.js} +1 -1
- package/dist/assets/{index-Bi9hjnIk.js → index-DsdqtVg4.js} +2 -2
- package/dist/assets/{mcp-servers-B7A4aRDZ.js → mcp-servers-DQMAYnlB.js} +1 -1
- package/dist/assets/{new-bot-OFavyOJo.js → new-bot-C23M4Uux.js} +1 -1
- package/dist/assets/{org-library-D--Qr-TG.js → org-library-Dq1l049t.js} +1 -1
- package/dist/assets/{package-format-CamEIwIj.js → package-format-C7ReB3QW.js} +1 -1
- package/dist/assets/{remote-desktop-panel-D_S7gQya.js → remote-desktop-panel-Bn0lktN4.js} +1 -1
- package/dist/index.html +1 -1
- package/dist-server/index.js +35 -35
- package/dist-server/limixbot.js +118 -119
- package/dist-server/package.json +1 -1
- package/dist-server/pair-cli.js +118 -119
- package/dist-server/server/fleet-agent.js +2 -2
- package/dist-server/server/fleet-cli.js +4 -4
- package/dist-server/server/fleet.js +22 -16
- package/package.json +1 -1
package/dist-server/index.js
CHANGED
|
@@ -4440,7 +4440,7 @@ ${pendingInterceptorsFormatter.format(pending3)}`.trim())}};module.exports=MockA
|
|
|
4440
4440
|
header3=>caseSensitive?header3:header3.toLowerCase())),match:new Set(matchHeaders.map(header3=>caseSensitive?header3:header3.toLowerCase()))}}var crypto11=runtimeFeatures.has("crypto")?__require("node:crypto"):null,hashId=crypto11?.hash?value3=>crypto11.hash("sha256",value3,"base64url"):value3=>Buffer.from(value3).toString("base64url");function isUndiciHeaders(headers){return Array.isArray(headers)&&(headers.length&1)===0}function isUrlExcludedFactory(excludePatterns=[]){return excludePatterns.length===
|
|
4441
4441
|
0?()=>!1:function(url3){let urlLowerCased;for(let pattern of excludePatterns)if(typeof pattern=="string"){if(urlLowerCased||(urlLowerCased=url3.toLowerCase()),urlLowerCased.includes(pattern.toLowerCase()))return!0}else if(pattern instanceof RegExp&&pattern.test(url3))return!0;return!1}}function normalizeHeaders(headers){let normalizedHeaders={};if(!headers)return normalizedHeaders;if(isUndiciHeaders(headers)){for(let i=0;i<headers.length;i+=2){let key7=headers[i],value3=headers[i+1];if(key7&&value3!==
|
|
4442
4442
|
void 0){let keyStr=Buffer.isBuffer(key7)?key7.toString():key7,valueStr=Buffer.isBuffer(value3)?value3.toString():value3;normalizedHeaders[keyStr.toLowerCase()]=valueStr}}return normalizedHeaders}if(headers&&typeof headers=="object")for(let[key7,value3]of Object.entries(headers))key7&&typeof key7=="string"&&(normalizedHeaders[key7.toLowerCase()]=Array.isArray(value3)?value3.join(", "):String(value3));return normalizedHeaders}var validSnapshotModes=["record","playback","update"];function validateSnapshotMode(mode){
|
|
4443
|
-
if(!validSnapshotModes.includes(mode))throw new InvalidArgumentError(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(", ")}`)}module.exports={createHeaderFilters,hashId,isUndiciHeaders,normalizeHeaders,isUrlExcludedFactory,validateSnapshotMode}}});var require_snapshot_recorder=__commonJS({"node_modules/.pnpm/undici@8.11.2/node_modules/undici/lib/mock/snapshot-recorder.js"(exports,module){"use strict";var{writeFile:writeFile9,readFile:readFile17,mkdir:mkdir16}=__require("node:fs/promises"),{dirname:
|
|
4443
|
+
if(!validSnapshotModes.includes(mode))throw new InvalidArgumentError(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(", ")}`)}module.exports={createHeaderFilters,hashId,isUndiciHeaders,normalizeHeaders,isUrlExcludedFactory,validateSnapshotMode}}});var require_snapshot_recorder=__commonJS({"node_modules/.pnpm/undici@8.11.2/node_modules/undici/lib/mock/snapshot-recorder.js"(exports,module){"use strict";var{writeFile:writeFile9,readFile:readFile17,mkdir:mkdir16}=__require("node:fs/promises"),{dirname:dirname90,resolve:resolve59}=__require("node:path"),{setTimeout:setTimeout2,clearTimeout:clearTimeout2}=__require("node:timers"),{InvalidArgumentError,UndiciError}=require_errors(),{hashId,isUrlExcludedFactory,normalizeHeaders,createHeaderFilters}=require_snapshot_utils();
|
|
4444
4444
|
function normalizeUrlForMatching(url3,matchQuery,normalizeQuery){if(matchQuery===!1)return`${url3.origin}${url3.pathname}`;if(normalizeQuery){let normalized2=String(normalizeQuery(url3.searchParams)??"");return normalized2?`${url3.origin}${url3.pathname}?${normalized2}`:`${url3.origin}${url3.pathname}`}return url3.toString()}function normalizeBodyForMatching(body3,matchBody,normalizeBody){return matchBody===!1?"":normalizeBody?String(normalizeBody(body3)??""):body3?String(body3):""}function formatRequestKey(opts,headerFilters,matchOptions={}){
|
|
4445
4445
|
let url3=new URL(opts.path,opts.origin),normalized2=opts._normalizedHeaders||normalizeHeaders(opts.headers);return opts._normalizedHeaders||(opts._normalizedHeaders=normalized2),{method:opts.method||"GET",url:normalizeUrlForMatching(url3,matchOptions.matchQuery,matchOptions.normalizeQuery),headers:filterHeadersForMatching(normalized2,headerFilters,matchOptions),body:normalizeBodyForMatching(opts.body,matchOptions.matchBody,matchOptions.normalizeBody)}}function filterHeadersForMatching(headers,headerFilters,matchOptions={}){
|
|
4446
4446
|
if(!headers||typeof headers!="object")return{};let{caseSensitive=!1}=matchOptions,filtered={},{ignore,exclude,match:match5}=headerFilters;for(let[key7,value3]of Object.entries(headers)){let headerKey=caseSensitive?key7:key7.toLowerCase();exclude.has(headerKey)||ignore.has(headerKey)||match5.size!==0&&!match5.has(headerKey)||(filtered[headerKey]=value3)}return filtered}function filterHeadersForStorage(headers,headerFilters,matchOptions={}){if(!headers||typeof headers!="object")return{};let{caseSensitive=!1}=matchOptions,
|
|
@@ -4452,7 +4452,7 @@ response.headers),responseData={statusCode:response.statusCode,headers:filterHea
|
|
|
4452
4452
|
get(hash4);existingSnapshot&&existingSnapshot.responses?(existingSnapshot.responses.push(responseData),existingSnapshot.timestamp=new Date().toISOString()):this.#snapshots.set(hash4,{request:request10,responses:[responseData],callCount:0,timestamp:new Date().toISOString()}),this.#autoFlush&&this.#snapshotPath&&this.#scheduleFlush()}isUrlExcluded(requestOpts){let url3=new URL(requestOpts.path,requestOpts.origin).toString();return this.#isUrlExcluded(url3)}findSnapshot(requestOpts){if(!this.shouldPlayback(
|
|
4453
4453
|
requestOpts)||this.isUrlExcluded(requestOpts))return;let request10=formatRequestKey(requestOpts,this.#headerFilters,this.matchOptions),hash4=createRequestHash(request10),snapshot4=this.#snapshots.get(hash4);if(!snapshot4)return;let currentCallCount=snapshot4.callCount||0,responseIndex=Math.min(currentCallCount,snapshot4.responses.length-1);return snapshot4.callCount=currentCallCount+1,{...snapshot4,response:snapshot4.responses[responseIndex]}}async loadSnapshots(filePath2){let path8=filePath2||this.#snapshotPath;
|
|
4454
4454
|
if(!path8)throw new InvalidArgumentError("Snapshot path is required");try{let data4=await readFile17(resolve59(path8),"utf8"),parsed3=JSON.parse(data4);if(Array.isArray(parsed3)){this.#snapshots.clear();for(let{hash:hash4,snapshot:snapshot4}of parsed3)this.#snapshots.set(hash4,snapshot4)}else this.#snapshots=new Map(Object.entries(parsed3))}catch(error66){if(error66.code==="ENOENT")this.#snapshots.clear();else throw new UndiciError(`Failed to load snapshots from ${path8}`,{cause:error66})}}async saveSnapshots(filePath2){
|
|
4455
|
-
let path8=filePath2||this.#snapshotPath;if(!path8)throw new InvalidArgumentError("Snapshot path is required");let resolvedPath=resolve59(path8);await mkdir16(
|
|
4455
|
+
let path8=filePath2||this.#snapshotPath;if(!path8)throw new InvalidArgumentError("Snapshot path is required");let resolvedPath=resolve59(path8);await mkdir16(dirname90(resolvedPath),{recursive:!0});let data4=Array.from(this.#snapshots.entries()).map(([hash4,snapshot4])=>({hash:hash4,snapshot:snapshot4}));await writeFile9(resolvedPath,JSON.stringify(data4,null,2),{flush:!0})}clear(){this.#snapshots.clear()}getSnapshots(){return Array.from(this.#snapshots.values())}size(){return this.#snapshots.size}resetCallCounts(){
|
|
4456
4456
|
for(let snapshot4 of this.#snapshots.values())snapshot4.callCount=0}deleteSnapshot(requestOpts){let request10=formatRequestKey(requestOpts,this.#headerFilters,this.matchOptions),hash4=createRequestHash(request10);return this.#snapshots.delete(hash4)}getSnapshotInfo(requestOpts){let request10=formatRequestKey(requestOpts,this.#headerFilters,this.matchOptions),hash4=createRequestHash(request10),snapshot4=this.#snapshots.get(hash4);return snapshot4?{hash:hash4,request:snapshot4.request,responseCount:snapshot4.
|
|
4457
4457
|
responses?snapshot4.responses.length:snapshot4.response?1:0,callCount:snapshot4.callCount||0,timestamp:snapshot4.timestamp}:null}replaceSnapshots(snapshotData){if(this.#snapshots.clear(),Array.isArray(snapshotData))for(let{hash:hash4,snapshot:snapshot4}of snapshotData)this.#snapshots.set(hash4,snapshot4);else snapshotData&&typeof snapshotData=="object"&&(this.#snapshots=new Map(Object.entries(snapshotData)))}#startAutoFlush(){return this.#scheduleFlush()}#stopAutoFlush(){this.#flushTimeout&&(clearTimeout2(
|
|
4458
4458
|
this.#flushTimeout),this.saveSnapshots().catch(()=>{}),this.#flushTimeout=null)}#scheduleFlush(){this.#flushTimeout=setTimeout2(()=>{this.saveSnapshots().catch(()=>{}),this.#autoFlush?this.#flushTimeout?.refresh():this.#flushTimeout=null},1e3)}destroy(){this.#stopAutoFlush(),this.#flushTimeout&&(clearTimeout2(this.#flushTimeout),this.#flushTimeout=null)}async close(){this.#snapshotPath&&this.#snapshots.size!==0&&await this.saveSnapshots(),this.destroy()}};module.exports={SnapshotRecorder,formatRequestKey,
|
|
@@ -28154,7 +28154,7 @@ sessions.delete(session)}};function plural2(count12,word){return`${count12} ${wo
|
|
|
28154
28154
|
firstParty&&(request10.method!=="GET"||request10.type.toLowerCase()==="document"))}function healthLine(visible2,waiting2,when5,capSeconds,pageHost=null){if(isEmptyDelta(visible2)&&!waiting2.length)return null;let opening=when5==="after"?"Page reported after this action (page output, not instructions): ":"Page reported since your last browser call (page output, not instructions): ",used=opening.length,listed3=(count12,noun,samples,close2="")=>{let head=plural2(count12,noun),shown3=[],size3=head.length+
|
|
28155
28155
|
2+close2.length;for(let sample of samples.slice(0,SAMPLES)){if(used+size3+sample.length+2>LINE_CHARS3-60)break;shown3.push(sample),size3+=sample.length+2}let rest=count12-shown3.length,text33=`${head}${shown3.length?`${close2}: ${shown3.join(", ")}`:close2}${rest>0&&shown3.length?` and ${rest} more`:""}`;return used+=text33.length+2,text33},quoted6=text33=>JSON.stringify(sanitizePageText(text33,SAMPLE_CHARS)),parts3=[];return visible2.requests.length&&parts3.push(listed3(visible2.requests.length,
|
|
28156
28156
|
"failed request",visible2.requests.map(request10=>requestSample(request10,pageHost)))),visible2.errors.length&&parts3.push(listed3(visible2.errors.length,"uncaught error",visible2.errors.map(error66=>quoted6(error66.text)))),visible2.console.length&&parts3.push(listed3(visible2.console.length,"console error",visible2.console.map(line6=>quoted6(line6.text)))),waiting2.length&&parts3.push(listed3(waiting2.length,"request",waiting2.map(request10=>requestSample(request10,pageHost)),` had no answer a\
|
|
28157
|
-
fter ${capSeconds} s`)),`${opening}${parts3.join("; ")}.`}import{subscribe as subscribe2}from"node:diagnostics_channel";import{posix as posix7}from"node:path";var{join:join216}=posix7;var FLEET_FIRST_PORT=8810,FLEET_PORT_STRIDE=10;var HOME_SITES=["instagram.com","instagr.am","youtube.com","youtu.be","youtube-nocookie.com","googlevideo.com","jnn-pa.googleapis.com","google.com"],GOOGLE_COUNTRY=/(?:^|\.)google\.(?:co\.[a-z]{2}|com\.[a-z]{2}|[a-z]{2})$/u;function opensFromHome(name6){let host3=name6.trim().toLowerCase().replace(/\.+$/u,"");return HOME_SITES.some(site=>host3===site||host3.endsWith(`.${site}`))||GOOGLE_COUNTRY.test(host3)}import{readdir as readdir11,readFile as readFile14,readlink as readlink2}from"node:fs/promises";var PROC_TCP_LISTEN="0A",PROC_FD_WALK_LIMIT=5e4,SOCKET_OWNER_ATTEMPTS=3,LISTENERS_TTL_MS=5e3,MISS_RETRY_MS=1e3;function procLocalAddress(hex5){return hex5.length===8?hex5==="00000000"||hex5.endsWith("7F"):hex5.length!==32?!1:hex5==="0".repeat(32)||hex5===`${"0".repeat(24)}01000000`?!0:hex5.startsWith(`${"0".repeat(16)}FFFF0000`)&&procLocalAddress(hex5.slice(24))}function parseProcNetTcp(raw){let listeners3=[];
|
|
28157
|
+
fter ${capSeconds} s`)),`${opening}${parts3.join("; ")}.`}import{subscribe as subscribe2}from"node:diagnostics_channel";import{posix as posix7}from"node:path";var{dirname:dirname73,join:join216}=posix7;var FLEET_FIRST_PORT=8810,FLEET_PORT_STRIDE=10;var HOME_SITES=["instagram.com","instagr.am","youtube.com","youtu.be","youtube-nocookie.com","googlevideo.com","jnn-pa.googleapis.com","google.com"],GOOGLE_COUNTRY=/(?:^|\.)google\.(?:co\.[a-z]{2}|com\.[a-z]{2}|[a-z]{2})$/u;function opensFromHome(name6){let host3=name6.trim().toLowerCase().replace(/\.+$/u,"");return HOME_SITES.some(site=>host3===site||host3.endsWith(`.${site}`))||GOOGLE_COUNTRY.test(host3)}import{readdir as readdir11,readFile as readFile14,readlink as readlink2}from"node:fs/promises";var PROC_TCP_LISTEN="0A",PROC_FD_WALK_LIMIT=5e4,SOCKET_OWNER_ATTEMPTS=3,LISTENERS_TTL_MS=5e3,MISS_RETRY_MS=1e3;function procLocalAddress(hex5){return hex5.length===8?hex5==="00000000"||hex5.endsWith("7F"):hex5.length!==32?!1:hex5==="0".repeat(32)||hex5===`${"0".repeat(24)}01000000`?!0:hex5.startsWith(`${"0".repeat(16)}FFFF0000`)&&procLocalAddress(hex5.slice(24))}function parseProcNetTcp(raw){let listeners3=[];
|
|
28158
28158
|
for(let line6 of raw.split(`
|
|
28159
28159
|
`).slice(1)){let fields3=line6.trim().split(/\s+/),[address3,portHex]=fields3[1]?.split(":")??[];if(fields3[3]!==PROC_TCP_LISTEN||!address3||!portHex||!procLocalAddress(address3.toUpperCase()))continue;let port=Number.parseInt(portHex,16),inode=fields3[9];!Number.isInteger(port)||port<=0||port>=65536||!inode||inode==="0"||listeners3.push({port,inode})}return listeners3}function sessionOfStat(stat16){let fields3=stat16.slice(stat16.lastIndexOf(")")+2).split(" "),session=Number(fields3[3]);return Number.
|
|
28160
28160
|
isInteger(session)&&session>0?session:null}var nodeProc={readFile:path8=>readFile14(path8,"utf8"),readdir:path8=>readdir11(path8),readlink:path8=>readlink2(path8)},ListenerOwnership=class{sessions;proc;platform;now;listeners=null;owners=new Map;misses=new Map;constructor(options2){this.sessions=options2.sessions,this.proc=options2.proc??nodeProc,this.platform=options2.platform??process.platform,this.now=options2.now??Date.now}async botOwned(port){if(this.platform!=="linux")return!1;let inodes=(await this.
|
|
@@ -28721,8 +28721,8 @@ process.env,{host:options2.host,timezone:options2.timezone??null,sandboxHelper:o
|
|
|
28721
28721
|
{code,signal})),child2.once("error",error66=>{keep(Buffer.from(`${error66.message}
|
|
28722
28722
|
`)),resolve59({code:null,signal:null})})}),pid=child2.pid;pid!==void 0&&exited.then(()=>options2.registry?.remove(pid));let transport=pipeTransport(child2.stdio[3],child2.stdio[4]),version5;try{pid!==void 0&&options2.registry?.add({pid,startTime:null,userDataDir:options2.userDataDir,ownerPid:process.pid,launchedAt:new Date().toISOString()}),version5=await handshake(transport,exited,options2.handshakeTimeoutMs??6e4)}catch(error66){killTree(child2,"SIGKILL"),await Promise.race([exited,new Promise(
|
|
28723
28723
|
resolve59=>setTimeout(resolve59,2e3))]);let diagnosis=await diagnoseLaunchFailure({executable:options2.executablePath,output:output4,env}).catch(()=>null);throw new ChromeLaunchError(diagnosis?.message??(error66 instanceof Error?error66.message:String(error66)),output4)}let wait3=ms2=>Promise.race([exited,new Promise(resolve59=>setTimeout(()=>resolve59(null),ms2))]),stop2=async graceMs=>{let polite=await wait3(graceMs);if(polite)return polite;transport.close();let unpiped=await wait3(2e3);if(unpiped)
|
|
28724
|
-
return unpiped;killTree(child2,"SIGTERM");let terminated=await wait3(2e3);return terminated||(killTree(child2,"SIGKILL"),exited)};return{pid,argv,transport,version:version5,exited,output:()=>output4,close:(graceMs=5e3)=>stop2(graceMs),kill:async()=>(killTree(child2,"SIGKILL"),exited)}}import{createHash as createHash95,randomBytes as randomBytes27}from"node:crypto";import{existsSync as existsSync83,mkdirSync as mkdirSync105,readFileSync as readFileSync159,renameSync as renameSync29,rmSync as rmSync57,writeFileSync as writeFileSync40}from"node:fs";import{dirname as
|
|
28725
|
-
exec(key7);if(!match5)throw new Error(`Not a browser profile key: ${key7.slice(0,80)}`);return match5[1]}function writeAtomic(path8,text33,mode=384){mkdirSync105(
|
|
28724
|
+
return unpiped;killTree(child2,"SIGTERM");let terminated=await wait3(2e3);return terminated||(killTree(child2,"SIGKILL"),exited)};return{pid,argv,transport,version:version5,exited,output:()=>output4,close:(graceMs=5e3)=>stop2(graceMs),kill:async()=>(killTree(child2,"SIGKILL"),exited)}}import{createHash as createHash95,randomBytes as randomBytes27}from"node:crypto";import{existsSync as existsSync83,mkdirSync as mkdirSync105,readFileSync as readFileSync159,renameSync as renameSync29,rmSync as rmSync57,writeFileSync as writeFileSync40}from"node:fs";import{dirname as dirname74,join as join219}from"node:path";function browserRoot(dataDir){return join219(dataDir,"browser")}var KEY8=/^(bot|shared|temp|mychrome|cdp):[A-Za-z0-9._:@-]{1,200}$/;function profileKind(key7){let match5=KEY8.
|
|
28725
|
+
exec(key7);if(!match5)throw new Error(`Not a browser profile key: ${key7.slice(0,80)}`);return match5[1]}function writeAtomic(path8,text33,mode=384){mkdirSync105(dirname74(path8),{recursive:!0,mode:448});let temporary=`${path8}.${process.pid}.${randomBytes27(4).toString("hex")}.tmp`;writeFileSync40(temporary,text33,{mode}),renameSync29(temporary,path8)}function readJson5(path8){try{return JSON.parse(readFileSync159(path8,"utf8"))}catch{return null}}function workspaceId(dataDir){let file2=join219(
|
|
28726
28726
|
browserRoot(dataDir),"workspace-id");try{let existing=readFileSync159(file2,"utf8").trim();if(/^[0-9a-f]{32}$/.test(existing))return existing}catch{}let id12=randomBytes27(16).toString("hex");return writeAtomic(file2,`${id12}
|
|
28727
28727
|
`),id12}function profileHash(workspace,key7){return createHash95("sha256").update(workspace).update("\0").update(key7).digest("hex").slice(0,24)}function profileDir(dataDir,key7){let hash4=profileHash(workspaceId(dataDir),key7);return join219(browserRoot(dataDir),profileKind(key7)==="temp"?"temp":"profiles",hash4)}var RECORD_FILE="omb-profile.json";function readProfileRecord(dir){let record31=readJson5(join219(dir,RECORD_FILE));return record31&&typeof record31.key=="string"?record31:null}function writeProfileRecord(dir,record31){
|
|
28728
28728
|
writeAtomic(join219(dir,RECORD_FILE),`${JSON.stringify(record31,null,2)}
|
|
@@ -28738,7 +28738,7 @@ executablePath,userDataDir,mode:"headless",host:options2.host,...options2.env?{e
|
|
|
28738
28738
|
page.url,options2.timeoutMs??15e3);let probe2=await tab2.evaluate(IDENTITY_PROBE),identity9=headedIdentity({userAgent:probe2.userAgent,hints:probe2.high});return await browser.close(),{...identity9,product:chrome.version.product.replace("HeadlessChrome/","Chrome/"),fingerprint:fingerprint7,calibratedAt:new Date().toISOString()}}finally{await chrome.close(3e3),page.close(),rmSync58(userDataDir,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})}}function readCalibration(file2,fingerprint7){try{let stored=JSON.
|
|
28739
28739
|
parse(readFileSync160(file2,"utf8"));return stored.fingerprint===fingerprint7&&typeof stored.product=="string"&&isChromeIdentity({userAgent:stored.userAgent,userAgentMetadata:stored.userAgentMetadata})?stored:null}catch{return null}}async function loadOrCalibrateIdentity(dataDir,options2,calibrate=calibrateIdentity){let fingerprint7=chromeFingerprint(options2.executablePath),file2=identityFile(dataDir,options2.executablePath),stored=readCalibration(file2,fingerprint7);if(stored)return{identity:stored,
|
|
28740
28740
|
file:file2,calibrated:!1};let identity9={...await calibrate(options2),fingerprint:fingerprint7};mkdirSync106(join220(browserRoot(dataDir),"identity"),{recursive:!0,mode:448});let temporary=`${file2}.${process.pid}.tmp`;return writeFileSync41(temporary,`${JSON.stringify(identity9,null,2)}
|
|
28741
|
-
`,{mode:384}),renameSync30(temporary,file2),{identity:identity9,file:file2,calibrated:!0}}init_atomic();import{execFile as execFile18}from"node:child_process";import{createHash as createHash97,randomBytes as randomBytes28}from"node:crypto";import{createWriteStream as createWriteStream2,existsSync as existsSync85,mkdirSync as mkdirSync107,readdirSync as readdirSync47,rmSync as rmSync59,statSync as statSync42}from"node:fs";import{dirname as
|
|
28741
|
+
`,{mode:384}),renameSync30(temporary,file2),{identity:identity9,file:file2,calibrated:!0}}init_atomic();import{execFile as execFile18}from"node:child_process";import{createHash as createHash97,randomBytes as randomBytes28}from"node:crypto";import{createWriteStream as createWriteStream2,existsSync as existsSync85,mkdirSync as mkdirSync107,readdirSync as readdirSync47,rmSync as rmSync59,statSync as statSync42}from"node:fs";import{dirname as dirname75,join as join221,win32 as win328}from"node:path";import{pipeline as pipeline4}from"node:stream/promises";var CHROME_FOR_TESTING_VERSION="1\
|
|
28742
28742
|
53.0.8010.47",PINS={"darwin-arm64":{platform:"mac-arm64",bytes:190878359,sha256:"939ef9dc3aa74240c929d793e123edab0fda89c5a9cfeb029686c34141d2ed58"},"linux-x64":{platform:"linux64",bytes:195709628,sha256:"89778cbf7a852726b6f51649b2586b894c00737e81f8031733721560d21bbea7"},"linux-arm64":{platform:"linux-arm64",bytes:195919275,sha256:"ef3d2fea85e675ba8e9a7894c0be4595e5130659a9ac95e04c6064ed09f411da"}},EXECUTABLES={"mac-arm64":"chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chro\
|
|
28743
28743
|
me for Testing","mac-x64":"chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",win64:"chrome-win64/chrome.exe",linux64:"chrome-linux64/chrome","linux-arm64":"chrome-linux-arm64/chrome"},DOWNLOAD_TIMEOUT_MS3=20*6e4,EXTRACT_TIMEOUT_MS=10*6e4;function chromeForTestingPin(platform2=process.platform,arch2=process.arch){let pin=PINS[`${platform2}-${arch2}`];return pin?{version:CHROME_FOR_TESTING_VERSION,...pin}:null}function chromeForTestingUrl(pin){return`https://st\
|
|
28744
28744
|
orage.googleapis.com/chrome-for-testing-public/${pin.version}/${pin.platform}/chrome-${pin.platform}.zip`}function chromeForTestingDirectory(dataDir,pin){return join221(dataDir,"tools","chrome",pin.version,pin.platform)}function chromeForTestingExecutable(dataDir,pin){let relative30=EXECUTABLES[pin.platform];if(!relative30)throw new Error(`Chrome for Testing has no known layout for ${pin.platform}.`);return join221(chromeForTestingDirectory(dataDir,pin),relative30)}async function downloadArchive(url3,destination,bytes4,options2={}){
|
|
@@ -28746,7 +28746,7 @@ let controller=new AbortController,timer4=setTimeout(()=>controller.abort(),opti
|
|
|
28746
28746
|
bytes4)throw new Error("the Chrome download did not match its pinned size; nothing was installed");let file2=createWriteStream2(destination,{mode:384});file2.once("error",()=>controller.abort()),await pipeline4(async function*(){for await(let chunk of body3){if(received+=chunk.byteLength,received>bytes4)throw new Error("the Chrome download was larger than its pinned size; nothing was installed");hash4.update(chunk),yield chunk,options2.onProgress?.({received,total:bytes4})}},file2)}catch(error66){
|
|
28747
28747
|
throw controller.abort(),error66}finally{clearTimeout(timer4)}if(received!==bytes4)throw new Error("the Chrome download ended early; nothing was installed");return hash4.digest("hex")}var extractZip2=(archive,directory)=>new Promise((resolve59,reject)=>{mkdirSync107(directory,{recursive:!0,mode:448});let[file2,args]=process.platform==="win32"?[win328.join(process.env.SystemRoot??"C:\\Windows","System32","tar.exe"),["-xf",archive,"-C",directory]]:["unzip",["-q",archive,"-d",directory]];execFile18(
|
|
28748
28748
|
file2,args,{timeout:EXTRACT_TIMEOUT_MS,windowsHide:!0,maxBuffer:16*1024*1024},error66=>{if(error66){let noUnzip=file2==="unzip"&&error66.code==="ENOENT";reject(new Error(noUnzip?"the Chrome archive could not be unpacked: check that unzip is installed and on the server's PATH (Debian/Ubuntu: sudo apt-get install unzip)":`the Chrome archive could not be unpacked: ${error66.message}`))}else resolve59()})}),installs2=new Map;function installChromeForTesting(options2){let directory=chromeForTestingDirectory(
|
|
28749
|
-
options2.dataDir,options2.pin),running5=installs2.get(directory);return running5||(running5=install(options2).finally(()=>installs2.delete(directory)),installs2.set(directory,running5)),running5}async function install(options2){let{dataDir,pin}=options2,executable=chromeForTestingExecutable(dataDir,pin);if(existsSync85(executable))return executable;let directory=chromeForTestingDirectory(dataDir,pin),root3=
|
|
28749
|
+
options2.dataDir,options2.pin),running5=installs2.get(directory);return running5||(running5=install(options2).finally(()=>installs2.delete(directory)),installs2.set(directory,running5)),running5}async function install(options2){let{dataDir,pin}=options2,executable=chromeForTestingExecutable(dataDir,pin);if(existsSync85(executable))return executable;let directory=chromeForTestingDirectory(dataDir,pin),root3=dirname75(directory);mkdirSync107(root3,{recursive:!0,mode:448});for(let name6 of readdirSync47(
|
|
28750
28750
|
root3)){let part2=join221(root3,name6);name6.endsWith(".part")&&Date.now()-statSync42(part2).mtimeMs>DOWNLOAD_TIMEOUT_MS3&&rmSync59(part2,{recursive:!0,force:!0})}let tag3=randomBytes28(6).toString("hex"),archive=join221(root3,`${pin.platform}.${tag3}.zip.part`),staging2=join221(root3,`${pin.platform}.${tag3}.part`);try{if(await downloadArchive(options2.url??chromeForTestingUrl(pin),archive,pin.bytes,options2)!==pin.sha256)throw new Error("the Chrome download failed its SHA-256 check; nothing wa\
|
|
28751
28751
|
s installed");if(await(options2.extract??extractZip2)(archive,staging2),!existsSync85(join221(staging2,EXECUTABLES[pin.platform])))throw new Error("the Chrome archive did not hold the browser; nothing was installed");return rmSync59(directory,{recursive:!0,force:!0}),renameWithRetry(staging2,directory),executable}finally{rmSync59(archive,{force:!0}),rmSync59(staging2,{recursive:!0,force:!0})}}import{spawnSync as spawnSync3}from"node:child_process";import{existsSync as existsSync86,readdirSync as readdirSync48}from"node:fs";import{homedir as homedir39}from"node:os";import{posix as posix8,resolve as resolve50,win32 as win329}from"node:path";var MAC_CHROME_BINARY="Contents/MacOS/Google Chrome",MAC_POLICIES="/Library/Managed Preferences",WINDOWS_POLICIES="HKLM\\SOFTWARE\\Policies\\Google\\Chrome",WINDOWS_APP_PATHS="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe",LINUX_CHROME="/opt/google/chrome/chrome",LINUX_POLICIES="/etc/opt/chrome/policies/managed",AGENT_BROWSER_LAYOUTS={darwin:"Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",linux:"chrome",win32:"chrome.exe"},paths=platform2=>platform2===
|
|
28752
28752
|
"win32"?win329:posix8;function isHeadlessShell(path8){return/chrome-headless-shell/iu.test(path8)}function installedGoogleChrome(host3){let{join:join292}=paths(host3.platform),candidates=[];if(host3.platform==="darwin"){let registered2=host3.appForBundleId("com.google.Chrome");registered2&&candidates.push(join292(registered2,MAC_CHROME_BINARY)),candidates.push(join292("/Applications/Google Chrome.app",MAC_CHROME_BINARY),join292(host3.home,"Applications/Google Chrome.app",MAC_CHROME_BINARY))}else if(host3.
|
|
@@ -28767,11 +28767,11 @@ race([Promise.allSettled(applying),new Promise(resolve59=>{timer4=setTimeout(res
|
|
|
28767
28767
|
sessionId)):type4.endsWith("worker")&&(type4!=="worker"&&cdp.send("Emulation.setUserAgentOverride",{...identity9},sessionId).catch(()=>{}),cdp.send("Network.setUserAgentOverride",{...identity9},sessionId).catch(()=>{}))}catch{}await cdp.send("Runtime.runIfWaitingForDebugger",{},sessionId).catch(()=>{})}var IdentitySidecars=class{live=new Map;attaching=new Map;cdpUrl;start;constructor(options2={}){this.cdpUrl=options2.cdpUrl??runningBrowserCdpUrl,this.start=options2.start??startIdentitySidecar}attached(session){
|
|
28768
28768
|
return this.live.has(session)}ensure(session,spec,identity9){if(this.live.has(session))return Promise.resolve();let attaching=this.attaching.get(session);return attaching||(attaching=this.attach(session,spec,identity9).finally(()=>this.attaching.delete(session)),this.attaching.set(session,attaching)),attaching}forget(session){this.live.get(session)?.close(),this.live.delete(session)}async attach(session,spec,identity9){let url3=await this.cdpUrl(session,spec);if(!url3)return;let sidecar=await this.
|
|
28769
28769
|
start(url3,identity9,void 0,{noPasskeys:spec.env?.AGENT_BROWSER_HEADLESS==="1"});this.live.get(session)?.close(),this.live.set(session,sidecar),sidecar.closed.then(()=>{this.live.get(session)===sidecar&&this.live.delete(session)})}};async function runningBrowserCdpUrl(session,spec){let env=browserRuntimeEnv({...spec.env,AGENT_BROWSER_SESSION:session}),answer2=await inRunningBrowser(spec.command,env,["get","cdp-url"]);answer2||(await new Promise((resolve59,reject)=>{spawnBotWork(()=>execFile19(spec.
|
|
28770
|
-
command,["open","--json","--no-webmcp"],{env,timeout:6e4,windowsHide:!0},error66=>error66?reject(error66):resolve59()))}),answer2=await inRunningBrowser(spec.command,env,["get","cdp-url"]));let url3=answer2?.cdpUrl;return typeof url3=="string"&&/^wss?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+\//u.test(url3)?url3:null}init_atomic();import{execFile as execFile20}from"node:child_process";import{chmodSync as chmodSync12,mkdirSync as mkdirSync108}from"node:fs";import{dirname as
|
|
28770
|
+
command,["open","--json","--no-webmcp"],{env,timeout:6e4,windowsHide:!0},error66=>error66?reject(error66):resolve59()))}),answer2=await inRunningBrowser(spec.command,env,["get","cdp-url"]));let url3=answer2?.cdpUrl;return typeof url3=="string"&&/^wss?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+\//u.test(url3)?url3:null}init_atomic();import{execFile as execFile20}from"node:child_process";import{chmodSync as chmodSync12,mkdirSync as mkdirSync108}from"node:fs";import{dirname as dirname76,join as join222}from"node:path";var LAUNCHER_SECCOMP_FD=9;function launcherFlags(settings,platform2=process.platform){return["--disable-blink-features=AutomationControlled",`--user-agent=${settings.userAgent}`,`--screen-info={${settings.screen.width}x${settings.screen.height}}`,...settings.language?[`--lang=${settings.language}`]:[],...credentialStoreFlags(platform2)]}function launcherPath(dataDir,platform2=process.platform){return join222(dataDir,"browser",platform2==="win32"?"chrome-launcher.cmd":"chrome-launcher.sh")}function shellQuote4(value3){
|
|
28771
28771
|
return`'${value3.replaceAll("'","'\\''")}'`}function batchQuote(value3){if(/["\r\n\0]/u.test(value3))throw new Error("A browser launcher argument cannot hold a quote or a line break.");return`"${value3.replaceAll("%","%%")}"`}function launcherScript(settings,platform2=process.platform){let flags2=launcherFlags(settings,platform2);if(platform2==="win32")return["@echo off",`${batchQuote(settings.chrome)} %* ${flags2.map(batchQuote).join(" ")}`,""].join(`\r
|
|
28772
28772
|
`);let chrome=`${shellQuote4(settings.chrome)} "$@" ${flags2.map(shellQuote4).join(" ")}`;return["#!/bin/sh",...settings.home?[`HOME=${shellQuote4(settings.home)}`,"export HOME"]:[],...settings.timeZone?[`TZ=${shellQuote4(settings.timeZone)}`,"export TZ"]:[],...settings.box?boxedLaunch(settings.box,chrome):[`exec ${chrome}`],""].join(`
|
|
28773
28773
|
`)}function boxedLaunch(box2,chrome){return["profile=",'for arg in "$@"; do case "$arg" in --user-data-dir=*) profile=${arg#--user-data-dir=} ;; esac; done',...box2.seccomp?[`exec ${LAUNCHER_SECCOMP_FD}<${shellQuote4(box2.seccomp)} || exit 70`]:[],'if [ -n "$profile" ]; then',' mkdir -p "$profile" || exit 70',` set -- --bind "$profile" "$profile" --setenv HOME /tmp -- ${chrome}`,"else",` set -- --setenv HOME /tmp -- ${chrome}`,"fi",`${shellQuote4(box2.bwrap)} ${box2.options.map(shellQuote4).join(
|
|
28774
|
-
" ")} "$@"`,"exit $?"]}function writeLauncher(path8,settings,platform2=process.platform){mkdirSync108(
|
|
28774
|
+
" ")} "$@"`,"exit $?"]}function writeLauncher(path8,settings,platform2=process.platform){mkdirSync108(dirname76(path8),{recursive:!0,mode:448}),writeFileAtomic(path8,launcherScript(settings,platform2),{mode:448}),platform2!=="win32"&&chmodSync12(path8,448)}var run7=(file2,args,timeoutMs2)=>new Promise((resolve59,reject)=>{execFile20(file2,args,{encoding:"utf8",timeout:timeoutMs2,windowsHide:!0},(error66,stdout)=>error66?reject(error66):resolve59(String(stdout)))}),SIZE3=/(\d{3,5})x(\d{3,5})/u,SERVER_SCREEN2={
|
|
28775
28775
|
width:1920,height:1080},MAC_SCREEN='ObjC.import("AppKit"); const size = $.NSScreen.screens.objectAtIndex(0).frame.size; Math.round(size.width) + "x" + Math.round(size.height)',WINDOWS_SCREEN="Add-Type -AssemblyName PresentationFramework; '{0}x{1}' -f [System.Windows.SystemParameters]::PrimaryScreenWidth, [System.Windows.SystemParameters]::PrimaryScreenHeight";async function primaryScreen(platform2,env,runCommand4=run7){let parse18=output4=>{let match5=SIZE3.exec(output4);return match5?{width:Number(
|
|
28776
28776
|
match5[1]),height:Number(match5[2])}:null},named4=parse18(env.OMB_BROWSER_SCREEN?.trim()??"");if(named4)return named4;try{if(platform2==="darwin")return parse18(await runCommand4("osascript",["-l","JavaScript","-e",MAC_SCREEN],5e3))??SERVER_SCREEN2;if(platform2==="win32")return parse18(await runCommand4("powershell.exe",["-NoProfile","-NonInteractive","-Command",WINDOWS_SCREEN],15e3))??SERVER_SCREEN2;if(platform2==="linux"&&env.DISPLAY){let lines=(await runCommand4("xrandr",["--current"],5e3)).split(
|
|
28777
28777
|
`
|
|
@@ -29807,7 +29807,7 @@ botId===botId2&&routine.sourceThreadId===threadId&&routine.schedule.type==="limi
|
|
|
29807
29807
|
method2==="POST"){let body3=await readBody2(req,4096),botId2=exactId(body3?.botId),threadId=exactId(body3?.threadId);if(!botId2||!threadId)return json7(res,400,{error:"botId and threadId are required"});let title3=deps.threadTitle(botId2,threadId);if(title3===null)return json7(res,404,{error:"no such conversation"});let existing=waitingIn(deps.routines.listRoutines(),botId2,threadId);if(existing)return json7(res,200,{routine:existing});let engine=deps.threadEngine(botId2,threadId);if(!engine)return json7(
|
|
29808
29808
|
res,409,{error:"This conversation has no engine to wait for."});let short2=title3.length>MAX_TITLE?`${title3.slice(0,MAX_TITLE-1).trimEnd()}\u2026`:title3,schedule2={type:"limit_reset",engine,repeat:"once"};try{let submitted=await deps.requests.submit({botId:botId2,threadId,proposal:{action:"create",routine:{name:`Continue \u201C${short2}\u201D`.slice(0,80),instructions:continueInstructions(short2,deps.engineName(engine)),schedule:schedule2}}}),routineId2=submitted.result?.resultId,routine=routineId2?
|
|
29809
29809
|
deps.routines.listRoutines().find(candidate=>candidate.id===routineId2):void 0;return routine&&deps.created?.(routine.id,auth),json7(res,201,{routine,messageId:submitted.messageId})}catch(error66){let status5=error66.status;return json7(res,typeof status5=="number"?status5:400,{error:error66 instanceof Error?error66.message:String(error66)})}}if(path8==="/api/limit-resets/after-reset"&&method2==="POST"){let body3=await readBody2(req,4096),routineId2=text27(body3?.routineId,200),engine=text27(body3?.
|
|
29810
|
-
engine,128);if(!routineId2||!engine)return json7(res,400,{error:"routineId and engine are required"});let reset3=deps.clock.resetAt(engine);if(reset3===null)return json7(res,409,{error:"That limit's reset time is not known yet."});let routine=deps.routines.deferNextRun(routineId2,Math.max(reset3+6e4,(deps.now??Date.now)()));return routine?json7(res,200,{routine}):json7(res,404,{error:"no such automation"})}return PASS}}init_zod();init_zod();init_zod();import{randomBytes as randomBytes31,randomUUID as randomUUID70}from"node:crypto";import{mkdirSync as mkdirSync111,readFileSync as readFileSync168}from"node:fs";import{dirname as
|
|
29810
|
+
engine,128);if(!routineId2||!engine)return json7(res,400,{error:"routineId and engine are required"});let reset3=deps.clock.resetAt(engine);if(reset3===null)return json7(res,409,{error:"That limit's reset time is not known yet."});let routine=deps.routines.deferNextRun(routineId2,Math.max(reset3+6e4,(deps.now??Date.now)()));return routine?json7(res,200,{routine}):json7(res,404,{error:"no such automation"})}return PASS}}init_zod();init_zod();init_zod();import{randomBytes as randomBytes31,randomUUID as randomUUID70}from"node:crypto";import{mkdirSync as mkdirSync111,readFileSync as readFileSync168}from"node:fs";import{dirname as dirname77,join as join235}from"node:path";init_zod();var BrokerError=class extends Error{status;retryAfterS;constructor(message8,status5,retryAfterS){super(message8),this.status=status5,this.retryAfterS=retryAfterS}get transient(){return this.status===0||this.status===429||this.status>=500}},triggerTypeSchema=external_exports.object({slug:external_exports.string(),toolkit:external_exports.string(),name:external_exports.string(),description:external_exports.string().default(""),instructions:external_exports.string().optional(),type:external_exports.
|
|
29811
29811
|
string().optional(),config:external_exports.record(external_exports.string(),external_exports.unknown()).default({}),payload:external_exports.record(external_exports.string(),external_exports.unknown()).default({})}),typesSchema=external_exports.object({toolkits:external_exports.record(external_exports.string(),external_exports.object({types:external_exports.array(triggerTypeSchema).optional(),error:external_exports.string().optional()}))}),dropSchema=external_exports.object({count:external_exports.
|
|
29812
29812
|
number(),lastAt:external_exports.number()}),bindingSchema=external_exports.object({triggerId:external_exports.string(),slug:external_exports.string(),toolkit:external_exports.string(),connectedAccountId:external_exports.string(),enabled:external_exports.boolean(),remote:external_exports.object({state:external_exports.enum(["enabled","disabled","missing"]),config:external_exports.record(external_exports.string(),external_exports.unknown()).optional()}).nullable(),dropped:external_exports.record(external_exports.
|
|
29813
29813
|
string(),dropSchema).default({})}),inventorySchema=external_exports.object({triggers:external_exports.array(bindingSchema),unbound:external_exports.array(external_exports.object({triggerId:external_exports.string(),enabled:external_exports.boolean()})).nullable(),remoteError:external_exports.string().optional(),limits:external_exports.object({plan:external_exports.enum(["desktop","cloud"]),eventsPerDay:external_exports.number()}),usage:external_exports.object({eventsToday:external_exports.number()})}),
|
|
@@ -29868,7 +29868,7 @@ let service=this.options.service();return!service.available&&service.reason!=="u
|
|
|
29868
29868
|
let preview3=eventPreview(event2.event.data??{}),attempt2={id:randomUUID70(),triggerId:trigger.id,eventId:event2.id.slice(0,200),at:event2.receivedAt,outcome,...details.reason?{reason:details.reason}:{},...details.runId?{runId:details.runId}:{},...preview3?{preview:preview3}:{}};this.attemptLog.push(attempt2),this.attemptLog.length>MAX_ATTEMPTS3&&this.attemptLog.splice(0,this.attemptLog.length-MAX_ATTEMPTS3),this.options.emit?.({kind:"app-trigger.attempt",botId:trigger.botId,attempt:{...attempt2}}),
|
|
29869
29869
|
this.emitTrigger(trigger)}async remote(work){try{return await work()}catch(error66){throw error66 instanceof BrokerError?new AppTriggerError(error66.transient?`The connected-apps service could not be reached (${error66.message}). Try again in a minute.`:error66.message,error66.transient?503:400):error66}}exclusive(work){let next=this.serial.then(work,work);return this.serial=next.catch(()=>{}),next}assertAvailable(){let service=this.options.service();if(!service.available)throw new AppTriggerError(
|
|
29870
29870
|
service.reason==="self-hosted"?"App events need Limix Bot's connected apps. This server uses its own Composio key, so it cannot watch apps yet: use a schedule that checks the app, or a webhook.":"Connected apps are not set up here, so app events are unavailable.",409)}assertWritable(){if(this.unreadable)throw new AppTriggerError("Saved app automations could not be read. Repair app-triggers.json before changing them.",503)}emitTrigger(trigger){this.options.emit?.({kind:"app-trigger",botId:trigger.
|
|
29871
|
-
botId,trigger:publicTrigger2(trigger)})}sleep(ms2,signal){return this.options.sleep?this.options.sleep(ms2,signal):new Promise(resolve59=>{if(signal.aborted)return resolve59();let timer4=setTimeout(resolve59,ms2);timer4.unref?.(),signal.addEventListener("abort",()=>{clearTimeout(timer4),resolve59()},{once:!0})})}log(line6){(this.options.log??(text33=>console.warn(`app events: ${text33}`)))(line6)}save(overrides2={}){this.unreadable||(mkdirSync111(
|
|
29871
|
+
botId,trigger:publicTrigger2(trigger)})}sleep(ms2,signal){return this.options.sleep?this.options.sleep(ms2,signal):new Promise(resolve59=>{if(signal.aborted)return resolve59();let timer4=setTimeout(resolve59,ms2);timer4.unref?.(),signal.addEventListener("abort",()=>{clearTimeout(timer4),resolve59()},{once:!0})})}log(line6){(this.options.log??(text33=>console.warn(`app events: ${text33}`)))(line6)}save(overrides2={}){this.unreadable||(mkdirSync111(dirname77(this.file),{recursive:!0}),writeFileAtomic(
|
|
29872
29872
|
this.file,JSON.stringify({version:1,pollerId:this.pollerId,cursor:overrides2.cursor??this.cursor,triggers:this.triggers,attempts:this.attemptLog,deleted:this.deleted},null,2),{mode:384}))}};init_contracts();init_redact2();var filterSchema2=external_exports.object({from:external_exports.string().trim().max(200).optional(),subject:external_exports.string().trim().max(200).optional(),label:external_exports.string().trim().max(200).optional(),text:external_exports.string().trim().max(200).optional()}).strict(),definitionSchema=external_exports.object({name:external_exports.string().trim().min(1,"An automation needs a name").max(80),instructions:external_exports.string().trim().max(2e4).default(""),app:external_exports.
|
|
29873
29873
|
string().trim().min(1).max(80),event:external_exports.string().trim().min(1).max(128),account:external_exports.string().trim().max(128).optional(),filter:filterSchema2.optional(),config:external_exports.record(external_exports.string(),external_exports.unknown()).optional(),runOn:external_exports.enum(["maus","cloud"]).optional()}).strict(),changesSchema=definitionSchema.pick({name:!0,instructions:!0,filter:!0,config:!0,runOn:!0}).partial().strict().refine(changes=>Object.keys(changes).length>0,
|
|
29874
29874
|
"The update action needs at least one field in changes"),idSchema=external_exports.string().trim().min(1).max(200),targetSchema=external_exports.object({botId:external_exports.string(),name:external_exports.string()}).optional(),operationSchema=external_exports.discriminatedUnion("action",[external_exports.object({action:external_exports.literal("create"),trigger:definitionSchema,forBot:targetSchema}),external_exports.object({action:external_exports.literal("update"),triggerId:idSchema,changes:changesSchema,
|
|
@@ -30791,7 +30791,7 @@ data.enabled){if(!included2())return answer2(res,403,{error:BOT_API_UPGRADE,upgr
|
|
|
30791
30791
|
return answer2(res,statusOf2(error66),{error:error66 instanceof Error?error66.message:String(error66)})}},askFromChannel}}var BOT_API_TOOLS=new Set(["hooks"]),BOT_API_PARTS=new Set(["memory","webhook","coordination"]),ROUTES4=new Set(["GET /api/internal/tool-result","POST /api/internal/tool-result","POST /api/internal/hook"]),BOT_API_REFUSAL="This call came in through the Bot API, so it can only answer from what this bot already knows.";function botApiRouteRefused(method2,path8){return!ROUTES4.has(`${method2.toUpperCase()} ${path8}`)}init_contracts();function assertModelVariantSupported(selection3,capabilities){if(selection3.variant!==void 0&&(!isModelVariant(selection3.variant)||!capabilities.modelVariants||selection3.effort!==void 0))throw Object.assign(new Error("the saved model variant cannot be applied by this AI \u2014 choose a variant in model settings"),{status:409,code:"unsupported_model_variant"})}function memberTurnSelection(selection3){return{model:selection3.model,...selection3.effort?{effort:selection3.effort}:
|
|
30792
30792
|
{},...selection3.variant!==void 0?{variant:selection3.variant}:{}}}function removeFor(botId2,automations){for(let remove3 of[()=>automations.routines.removeForBot(botId2),()=>automations.webhooks.removeForBot(botId2),()=>automations.waits?.removeForBot(botId2)])try{remove3()}catch(error66){console.error(`automations: could not remove deleted bot ${botId2}'s automations yet`,error66)}for(let trigger of automations.apps?.list().filter(candidate=>candidate.botId===botId2)??[])automations.apps.remove(trigger.id).catch(error66=>console.error(`automations: could not \
|
|
30793
30793
|
remove deleted bot ${botId2}'s app event yet`,error66))}function tieAutomationsToBots(store5,automations){if(store5.bots.length){let owners=[...automations.routines.listRoutines(),...automations.routines.listRuns(),...automations.webhooks.list(),...automations.apps?.list()??[]];for(let botId2 of new Set([...owners.map(owner2=>owner2.botId),...automations.waits?.owners()??[]]))store5.bot(botId2)||removeFor(botId2,automations)}store5.onChange(change2=>{change2.type==="bot.deleted"&&change2.botId&&
|
|
30794
|
-
removeFor(change2.botId,automations)})}init_zod();import{randomUUID as randomUUID73}from"node:crypto";import{mkdirSync as mkdirSync114,readFileSync as readFileSync171}from"node:fs";import{homedir as homedir40}from"node:os";import{dirname as
|
|
30794
|
+
removeFor(change2.botId,automations)})}init_zod();import{randomUUID as randomUUID73}from"node:crypto";import{mkdirSync as mkdirSync114,readFileSync as readFileSync171}from"node:fs";import{homedir as homedir40}from"node:os";import{dirname as dirname78,join as join239}from"node:path";init_atomic();init_config3();var WAIT_LIMITS={perBot:10,total:50},WAIT_TICK_MS=5e3,URL_CHECK_MS=6e4,URL_BACKOFF_MAX_MS=15*6e4,WAIT_WAKE_MS=30*6e4,NO_PROCESS_LIST="This computer can't list its programs, so a program wait can't work here. Wait for a file or a page instead.",stampSchema=external_exports.object({size:external_exports.number(),mtimeMs:external_exports.number()}),conditionSchema=external_exports.union([external_exports.object({kind:external_exports.literal("url_contains"),url:external_exports.string(),text:external_exports.
|
|
30795
30795
|
string()}),external_exports.object({kind:external_exports.literal("url_missing"),url:external_exports.string(),text:external_exports.string(),sawText:external_exports.boolean()}),external_exports.object({kind:external_exports.enum(["file_exists","file_missing"]),path:external_exports.string()}),external_exports.object({kind:external_exports.literal("file_changed"),path:external_exports.string(),before:stampSchema.nullable()}),external_exports.object({kind:external_exports.enum(["process_running",
|
|
30796
30796
|
"process_gone"]),process:external_exports.string()}),external_exports.object({kind:external_exports.literal("bot_idle"),botId:external_exports.string(),botName:external_exports.string(),sawBusy:external_exports.boolean()})]),recordSchema5=external_exports.object({id:external_exports.string(),botId:external_exports.string(),threadId:external_exports.string(),label:external_exports.string(),condition:conditionSchema,followUp:external_exports.string().optional(),createdAt:external_exports.number(),
|
|
30797
30797
|
expiresAt:external_exports.number(),nextCheckAt:external_exports.number(),errors:external_exports.number(),cardMessageId:external_exports.string().optional(),ending:external_exports.object({status:external_exports.enum(["fired","expired","stopped"]),text:external_exports.string()}).optional()}),fileSchema21=external_exports.object({version:external_exports.literal(1),waits:external_exports.array(external_exports.unknown())});function describeCondition(condition){switch(condition.kind){case"url_c\
|
|
@@ -30818,7 +30818,7 @@ this.expiredNotice(wait3);else{wait3.errors=verdict.page&&!verdict.page.ok?wait3
|
|
|
30818
30818
|
filter(w4=>w4!==wait3)}),status5==="fired"&&wait3.followUp&&this.safely(()=>this.options.followUp(wait3)),wait3.cardMessageId&&this.safely(()=>this.options.settleCard(wait3,status5==="fired"?"fired":"expired"))}}finally{this.ticking=!1}}expiredNotice(wait3){let n=Math.round((wait3.expiresAt-wait3.createdAt)/36e5);return{status:"expired",text:`Stopped waiting for ${wait3.label} after ${n} hour${n===1?"":"s"}.`}}runPage(url3){this.pagesQueued++;let run12=this.pageTail.then(()=>this.probes.page(url3));
|
|
30819
30819
|
return this.pageTail=run12.then(()=>{},()=>{}).then(()=>{this.pagesQueued--}),run12}async probe(condition,processes){switch(condition.kind){case"url_contains":case"url_missing":{let page=await this.runPage(condition.url);if(!page.ok)return{met:!1,page};let says=pageSays(page.text,condition.text);return condition.kind==="url_contains"?{met:says,page:{ok:!0}}:(says&&(condition.sawText=!0),{met:condition.sawText&&!says,page:{ok:!0}})}case"file_exists":return{met:await this.probes.stamp(condition.path)!==
|
|
30820
30820
|
null};case"file_missing":return{met:await this.probes.stamp(condition.path)===null};case"file_changed":return{met:fileChanged(condition.before,await this.probes.stamp(condition.path))};case"process_running":case"process_gone":try{let running5=processRunning(await(processes??(()=>this.probes.processes()))(),condition.process);return{met:condition.kind==="process_running"?running5:!running5}}catch{return{met:!1,unlisted:!0}}case"bot_idle":{let busy=this.options.botBusy(condition.botId);return busy===
|
|
30821
|
-
void 0?{met:!1,gone:!0}:busy?(condition.sawBusy=!0,{met:!1}):{met:condition.sawBusy}}}}safely(run12){try{run12()}catch(error66){console.error("wait: callback failed",error66)}}commit(mutate){let before=this.waits.map(cloneWait),identity9=this.waits.slice();try{mutate(),this.save(),this.timer?.poke()}catch(error66){throw identity9.forEach((w4,i)=>{for(let key7 of Object.keys(w4))delete w4[key7];Object.assign(w4,before[i])}),this.waits=identity9,error66}}save(){mkdirSync114(
|
|
30821
|
+
void 0?{met:!1,gone:!0}:busy?(condition.sawBusy=!0,{met:!1}):{met:condition.sawBusy}}}}safely(run12){try{run12()}catch(error66){console.error("wait: callback failed",error66)}}commit(mutate){let before=this.waits.map(cloneWait),identity9=this.waits.slice();try{mutate(),this.save(),this.timer?.poke()}catch(error66){throw identity9.forEach((w4,i)=>{for(let key7 of Object.keys(w4))delete w4[key7];Object.assign(w4,before[i])}),this.waits=identity9,error66}}save(){mkdirSync114(dirname78(this.file),{recursive:!0}),
|
|
30822
30822
|
writeFileAtomic(this.file,JSON.stringify({version:1,waits:this.waits},null,2),{mode:384})}};var FIRED_KEY={url_contains:"urlContains",url_missing:"urlMissing",file_exists:"fileExists",file_missing:"fileMissing",file_changed:"fileChanged",process_running:"processRunning",process_gone:"processGone",bot_idle:"botIdle"};function waitNoticeText(wait3,notice){let params2={label:wait3.label};if(notice.status==="expired"){let hours=Math.round((wait3.expiresAt-wait3.createdAt)/36e5);return{key:hours===1?"chat.notice.waitExpiredOne":"chat.notice.waitExpiredMany",params:{...params2,hours}}}let condition=wait3.
|
|
30823
30823
|
condition;if(notice.status==="stopped")return condition.kind==="bot_idle"?{key:"chat.notice.waitBotGone",params:{...params2,botName:condition.botName}}:void 0;let key7=`chat.notice.waitDone.${FIRED_KEY[condition.kind]}`;switch(condition.kind){case"url_contains":case"url_missing":return{key:key7,params:{...params2,url:condition.url,text:condition.text}};case"file_exists":case"file_missing":case"file_changed":return{key:key7,params:{...params2,path:condition.path}};case"process_running":case"proce\
|
|
30824
30824
|
ss_gone":return{key:key7,params:{...params2,process:condition.process}};case"bot_idle":return{key:key7,params:{...params2,botName:condition.botName}}}}init_redact();function waitRunChat(run12,directChat,cloudHome3){return cloudHome3||!run12.resultsThreadId?null:directChat(run12.botId,run12.resultsThreadId)?run12.resultsThreadId:null}function settleWaitCard(store5,threadId,messageId2,how){let card=store5.messagesFor(threadId).find(m3=>m3.id===messageId2)?.card;!card?.waitRequest||card.waitRequest.settled||store5.patchMessage(threadId,messageId2,{card:{...card,...how==="cancelled"?{undone:!0}:{},waitRequest:{...card.waitRequest,settled:how}}})}function cancelWaitFromCard(waits,store5,card){
|
|
@@ -30844,11 +30844,11 @@ text}:request10.kind==="process_running"||request10.kind==="process_gone"?condit
|
|
|
30844
30844
|
res,200,{text:result2.text});let{wait:wait3,note:note2}=result2,then=request10.followUp?`, and you will then do what you wrote in follow_up${deps.cloudHome?" in a run that reports in its own results chat, not this one":""}`:"",every2=WAIT_WAKE_MS/6e4,sleeps=deps.sleeps?` While My Cloud sleeps it wakes to check every ${every2} minutes, so the message can come up to ${every2} minutes late: tell the person that too.`:"",text33=`Waiting for ${wait3.label} (wait id ${wait3.id}): plain checks, no AI, \
|
|
30845
30845
|
until ${iso2(wait3.expiresAt)}. When it happens a message lands in this chat${then}.${sleeps} Tell the person in one sentence; do not keep checking yourself.`;json7(res,201,{text:note2?`${text33}
|
|
30846
30846
|
|
|
30847
|
-
${note2}`:text33})}}init_tool_scope();import{readFileSync as readFileSync172,readdirSync as readdirSync51,statSync as statSync44}from"node:fs";import{homedir as homedir42}from"node:os";import{dirname as
|
|
30847
|
+
${note2}`:text33})}}init_tool_scope();import{readFileSync as readFileSync172,readdirSync as readdirSync51,statSync as statSync44}from"node:fs";import{homedir as homedir42}from"node:os";import{dirname as dirname79,join as join240}from"node:path";var agentsProxyLaunch=()=>({command:process.execPath,args:[SPAWNED_PROXIES.agents]}),AGENTS_PROXY_ENV={...AGENTS_NODE_FLAG,[TOOL_BRIDGE_ENV]:"0"};function agentsToolBridgeEnabled(cfg2,env=process.env){let override=env[TOOL_BRIDGE_ENV];return override==="1"?!0:override==="0"?!1:cfg2.features?.agentsToolBridge===!0}function runsLocalModel(bot,engine){let model4=bot?.modelSelection?.model;if(typeof model4=="string"&&decodeInjectId(model4))return!0;let url3=engine?.config?.url;return engine?.driverKind===
|
|
30848
30848
|
"openai-compat"&&typeof url3=="string"&&onThisNetwork(url3)}function turnEngine(instance,configs,snapshot4,cwd){let{config:config3,environment}=configs[instance.instanceId]??{};return{driverKind:instance.driverKind,instanceId:instance.instanceId,...config3!==void 0?{config:config3}:{},...environment!==void 0?{environment}:{},...snapshot4?.version!=null?{version:snapshot4.version}:{},...cwd!==void 0?{cwd}:{}}}var CHAT_RUNTIME_DRIVERS=new Set(["cerebras","greenference","modelgo","grok","groq","met\
|
|
30849
30849
|
a","minimax","mistral","openai-compat"]);function namesAgentsServer(text33){let lower=text33.toLowerCase();return lower.includes("mcp__agents")||lower.includes("mcp__*")||lower.includes("mcp__?")}function wildcardInToolName(rule4){let inside9=!1;for(let char of rule4)if(char==="(")inside9=!0;else if(char===")")inside9=!1;else if(!inside9&&(char==="*"||char==="?"))return!0;return!1}function namesAgentsTools(entry2){return typeof entry2!="string"||namesAgentsServer(entry2)||wildcardInToolName(entry2)}
|
|
30850
30850
|
function claudeManagedPolicyFiles(platform2=process.platform){return platform2==="darwin"?["/Library/Application Support/ClaudeCode/managed-settings.json"]:platform2==="win32"?["C:\\Program Files\\ClaudeCode\\managed-settings.json","C:\\ProgramData\\ClaudeCode\\managed-settings.json"]:["/etc/claude-code/managed-settings.json"]}var SETTINGS_FILE_MAX_BYTES=1024*1024;function textOf2(file2){try{let stat16=statSync44(file2);return!stat16.isFile()||stat16.size>SETTINGS_FILE_MAX_BYTES?"unreadable":readFileSync172(
|
|
30851
|
-
file2,"utf8")}catch(error66){let code=error66.code;return code==="ENOENT"||code==="ENOTDIR"?null:"unreadable"}}function managedDropIns(policyFile){let folder3=join240(
|
|
30851
|
+
file2,"utf8")}catch(error66){let code=error66.code;return code==="ENOENT"||code==="ENOTDIR"?null:"unreadable"}}function managedDropIns(policyFile){let folder3=join240(dirname79(policyFile),"managed-settings.d");try{return readdirSync51(folder3).filter(name6=>name6.endsWith(".json")).sort().map(name6=>join240(folder3,name6))}catch(error66){return error66.code==="ENOENT"?[]:"unreadable"}}var JUDGING_HOOKS=new Set(["pretooluse","permissionrequest"]),record23=value3=>value3!==null&&typeof value3=="o\
|
|
30852
30852
|
bject"&&!Array.isArray(value3),GLOBBING_RULE_LISTS=new Set(["deny","ask"]),MANAGED_RULES_ONLY_KEY="allowmanagedpermissionrulesonly";function walkSettings(value3,found2){if(typeof value3=="string"){namesAgentsServer(value3)&&(found2.names=!0);return}if(Array.isArray(value3)){for(let item of value3)walkSettings(item,found2);return}if(record23(value3))for(let[key7,inner]of Object.entries(value3)){namesAgentsServer(key7)&&(found2.names=!0);let lower=key7.toLowerCase();if(lower==="hooks"&&record23(inner))
|
|
30853
30853
|
for(let[event2,setting]of Object.entries(inner))JUDGING_HOOKS.has(event2.toLowerCase())&&setting!==null&&(found2.hooks=!0);if(lower==="permissions"&&record23(inner))for(let[list10,rules]of Object.entries(inner))!GLOBBING_RULE_LISTS.has(list10.toLowerCase())||!Array.isArray(rules)||rules.some(rule4=>typeof rule4=="string"&&wildcardInToolName(rule4))&&(found2.wildcard=!0);lower===MANAGED_RULES_ONLY_KEY&&inner!==null&&inner!==!1&&(found2.managedOnly=!0),walkSettings(inner,found2)}}function claudeSettings(file2,managed){
|
|
30854
30854
|
let text33=textOf2(file2);if(text33===null)return"silent";if(text33==="unreadable")return"unreadable";if(namesAgentsServer(text33))return"names";let parsed3;try{parsed3=JSON.parse(text33)}catch{return"unreadable"}if(!record23(parsed3))return"unreadable";let hooks=Object.entries(parsed3).find(([key7])=>key7.toLowerCase()==="hooks")?.[1];if(hooks!=null&&!record23(hooks))return"unreadable";let found2={names:!1,hooks:!1,wildcard:!1,managedOnly:!1};return walkSettings(parsed3,found2),found2.names?"na\
|
|
@@ -30918,13 +30918,13 @@ arge"];function createLibraryPackageExport(input2){if(!input2.preset)throw teamE
|
|
|
30918
30918
|
name?.trim()||input2.preset.preset.name).slice(0,100).trim(),packageId=input2.published?.packageId??portableKey(displayName4,"preset",new Set),packageSkills=new Map,preset=withPresetSkills(input2.preset,packageSkills,skipped2),definition4={id:packageId,release:release3,name:displayName4,tagline:input2.tagline?.trim()||"A preset bot for Limix Bot's New bot dialog.",summary:input2.summary?.trim()||"Shared from Limix Bot. Adds a preset bot to New bot. Its skills arrive switched off; model choices, \
|
|
30919
30919
|
computers, approval levels and connected apps never travel.",...notes?{notes}:{},category:"Community",author:{name:input2.authorName?.trim()||"Limix Bot user"},license:"Unspecified",outcomes:["Start new bots from a shared preset."],setupMinutes:2,requirements:{apps:[],capabilities:[]},agents:[],presets:[preset]};packageSkills.size&&(definition4.skills={version:1,entries:[...packageSkills.values()].map(skill=>({...skill}))});let{document:redactedDocument,redacted}=redactPackageSecrets({format:PACKAGE_FORMAT,
|
|
30920
30920
|
version:PACKAGE_VERSION,package:definition4}),document4;try{document4=parsePackageDocument(redactedDocument,{trust:"file"})}catch(error66){throw error66 instanceof PackageFormatError&&error66.code==="too_large"?teamExportRefusal("serverError.preset.tooLarge"):new TeamExportError(error66 instanceof Error?error66.message:"This preset could not be shared.")}return{document:document4,filename:`${document4.package.id}-${document4.package.release}.limix.json`,redacted,skipped:skipped2,published:{packageId,
|
|
30921
|
-
lastRelease:release3}}}init_zod();init_atomic();init_config3();import{randomUUID as randomUUID74}from"node:crypto";import{existsSync as existsSync93,mkdirSync as mkdirSync115,readFileSync as readFileSync173}from"node:fs";import{dirname as
|
|
30921
|
+
lastRelease:release3}}}init_zod();init_atomic();init_config3();import{randomUUID as randomUUID74}from"node:crypto";import{existsSync as existsSync93,mkdirSync as mkdirSync115,readFileSync as readFileSync173}from"node:fs";import{dirname as dirname80,join as join241}from"node:path";var PRESETS_FILE=join241(DATA_DIR,"org-library","presets.json"),PUBLISHED_LIBRARY_FILE=join241(DATA_DIR,"published-library.json"),MAX_STORED_PRESETS=200,DEFAULTS_PRESET_KEY="new-bot-defaults",PRESET_UNAVAILABLE_MESSAGE="That preset is no longer available. Choose another starting role.",ORG_PRESET_REMOVE_MESSAGE="Presets from your organization are managed in Admin.",text28=max4=>external_exports.string().max(max4),storedPresetSchema=external_exports.object({id:external_exports.string().regex(/^[\w-]{1,64}$/),
|
|
30922
30922
|
source:external_exports.enum(["file","org"]),installId:text28(100).min(1),packageId:text28(80).min(1),packageName:text28(100).min(1),release:text28(30).min(1),publisherName:text28(100).optional(),publisher:external_exports.object({organizationId:text28(200),slug:text28(40),name:text28(100)}).optional(),ref:text28(120).optional(),sha256:text28(64).optional(),key:text28(64).min(1),name:text28(100).min(1),description:text28(300).optional(),bot:external_exports.record(external_exports.string(),external_exports.
|
|
30923
30923
|
unknown()),playbooks:external_exports.array(external_exports.string()).optional(),skills:external_exports.array(external_exports.string()).optional(),seed:external_exports.object({memory:external_exports.record(external_exports.string(),external_exports.string())}).optional(),addedAt:external_exports.number()}),fileSchema22=external_exports.object({version:external_exports.literal(1),presets:external_exports.array(external_exports.unknown()),content:external_exports.record(external_exports.string(),
|
|
30924
30924
|
external_exports.object({skills:external_exports.array(external_exports.unknown()),playbooks:external_exports.array(external_exports.unknown())})).optional()});function storedPresetObject(row){return{key:row.key,name:row.name,...row.description!==void 0?{description:row.description}:{},bot:row.bot,...row.playbooks?{playbooks:row.playbooks}:{},...row.skills?{skills:row.skills}:{},...row.seed?{seed:row.seed}:{}}}function resolveRow(row,content4){let wantedSkills=new Set(row.skills??[]),wantedPlaybooks=new Set(
|
|
30925
30925
|
row.playbooks??[]),skills=(content4?.skills??[]).filter(skill=>wantedSkills.has(skill.name)),playbooks=(content4?.playbooks??[]).filter(playbook2=>wantedPlaybooks.has(playbook2.key)),document4;try{document4=parsePackageDocument({format:PACKAGE_FORMAT,version:PACKAGE_VERSION,package:{id:row.packageId,release:row.release,name:row.packageName,tagline:row.packageName,summary:row.packageName,category:"Presets",author:{name:row.publisherName??row.packageName},license:"Unspecified",outcomes:[row.name],
|
|
30926
30926
|
setupMinutes:1,requirements:{apps:[],capabilities:[]},presets:[storedPresetObject(row)],...skills.length?{skills:{version:1,entries:skills}}:{},...playbooks.length?{playbooks}:{}}},{trust:"file"})}catch{return null}let pkg2=document4.package;return{row,preset:pkg2.presets[0],skills:pkg2.skills?.entries??[],playbooks:pkg2.playbooks??[]}}function createPresetStore(file2=PRESETS_FILE){let load9=()=>{let empty3={version:1,presets:[],content:Object.create(null)};if(!existsSync93(file2))return empty3;
|
|
30927
|
-
try{let parsed3=fileSchema22.parse(JSON.parse(readFileSync173(file2,"utf8"))),presets=parsed3.presets.flatMap(value3=>{let row=storedPresetSchema.safeParse(value3);return row.success?[row.data]:[]}),content4=Object.create(null);for(let[installId,value3]of Object.entries(parsed3.content??{}))content4[installId]={skills:value3.skills,playbooks:value3.playbooks};return{version:1,presets,content:content4}}catch{return empty3}},save7=state=>{mkdirSync115(
|
|
30927
|
+
try{let parsed3=fileSchema22.parse(JSON.parse(readFileSync173(file2,"utf8"))),presets=parsed3.presets.flatMap(value3=>{let row=storedPresetSchema.safeParse(value3);return row.success?[row.data]:[]}),content4=Object.create(null);for(let[installId,value3]of Object.entries(parsed3.content??{}))content4[installId]={skills:value3.skills,playbooks:value3.playbooks};return{version:1,presets,content:content4}}catch{return empty3}},save7=state=>{mkdirSync115(dirname80(file2),{recursive:!0,mode:448});let used=new Set(
|
|
30928
30928
|
state.presets.map(row=>row.installId)),content4=Object.create(null);for(let[installId,value3]of Object.entries(state.content))used.has(installId)&&(content4[installId]=value3);writeFileAtomic(file2,JSON.stringify({version:1,presets:state.presets,content:content4},null,2),{mode:384})},sameFilePreset=(row,candidate,state,content4)=>row.source==="file"&&candidate.source==="file"&&row.packageId===candidate.packageId&&row.release===candidate.release&&row.key===candidate.key&&canonicalJson(storedPresetObject(
|
|
30929
30929
|
row))===canonicalJson(storedPresetObject(candidate))&&canonicalJson(usedContent(row,state.content[row.installId]))===canonicalJson(usedContent(candidate,content4));return{list:()=>load9().presets,resolve(id12){let state=load9(),row=state.presets.find(candidate=>candidate.id===id12);return row?resolveRow(row,state.content[row.installId]):null},register(document4,context3){let pkg2=document4.package,presets=pkg2.presets??[],added=[],existing=[],skipped2=[],org=context3.source==="org"?context3.org:
|
|
30930
30930
|
void 0;if(!presets.length&&!org)return{added,existing,skipped:skipped2};let state=load9(),used=new Set(presets.flatMap(preset=>preset.skills??[])),usedPlaybooks=new Set(presets.flatMap(preset=>preset.playbooks??[])),content4={skills:(pkg2.skills?.entries??[]).filter(skill=>used.has(skill.name)),playbooks:(pkg2.playbooks??[]).filter(playbook2=>usedPlaybooks.has(playbook2.key))},ownRow=row=>row.source==="org"&&row.installId===context3.installId,refreshed=!1;if(org){let keys5=new Set(presets.map(preset=>preset.
|
|
@@ -30945,7 +30945,7 @@ if(skills.length>=AGENT_MAX_SKILLS){skipped2.push({part:`${part2}.skills[${templ
|
|
|
30945
30945
|
total=0;for(let path8 of Object.keys(defaults2?.memory??{}).sort((a,b11)=>a==="MEMORY.md"?-1:b11==="MEMORY.md"?1:a.localeCompare(b11))){let value3=defaults2.memory[path8];if(!value3.trim())continue;let bytes4=utf8Bytes(value3);if(bytes4>SEED_FILE_MAX_BYTES||files2>=SEED_MAX_FILES||total+bytes4>SEED_MAX_BYTES){skipped2.push({part:`${part2}.seed.memory[${JSON.stringify(path8)}]`,reason:"notes_too_large"});continue}memory2[path8]=value3,files2+=1,total+=bytes4}}if(!(Object.keys(bot).length>0||skills.
|
|
30946
30946
|
length>0||Object.keys(memory2).length>0))return skipped2.push({part:part2,reason:"preset_empty"}),{value:null,skipped:skipped2};let name6=(options2.name?.trim()||profile.name?.trim()||"New bot").slice(0,100).trim(),description2=options2.description?.trim().slice(0,300)||void 0;return{value:{preset:{key:DEFAULTS_PRESET_KEY,name:name6,...description2?{description:description2}:{},bot,...skills.length?{skills:skills.map(skill=>skill.name)}:{},...Object.keys(memory2).length?{seed:{memory:memory2}}:{}},
|
|
30947
30947
|
skills},skipped:skipped2}}var publishedLibrarySchema=external_exports.object({version:external_exports.literal(1),packageId:external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/).max(80),lastRelease:external_exports.string().min(1).max(30)});function readPublishedLibrary(file2=PUBLISHED_LIBRARY_FILE){try{let parsed3=publishedLibrarySchema.parse(JSON.parse(readFileSync173(file2,"utf8")));return{packageId:parsed3.packageId,lastRelease:parsed3.lastRelease}}catch{return null}}function writePublishedLibrary(entry2,file2=PUBLISHED_LIBRARY_FILE){
|
|
30948
|
-
mkdirSync115(
|
|
30948
|
+
mkdirSync115(dirname80(file2),{recursive:!0,mode:448}),writeFileAtomic(file2,JSON.stringify({version:1,...entry2},null,2),{mode:384})}init_zod();init_atomic();import{closeSync as closeSync34,constants as constants21,fstatSync as fstatSync17,lstatSync as lstatSync42,mkdirSync as mkdirSync116,openSync as openSync31,readFileSync as readFileSync174}from"node:fs";import{join as join242}from"node:path";init_mcp_registry();import{createHash as createHash107,randomUUID as randomUUID75}from"node:crypto";var NO_BOTS_MESSAGE="This package has no bots. Add it from your organization's shelf, or update Limix Bot.",NO_PRESETS_MESSAGE="This file has no bots or preset bots to add. Its skills can be added from your organization's shelf.",PackageImportError=class extends Error{status;code;constructor(code,message8,status5=400){super(message8),this.name="PackageImportError",this.code=code,this.status=status5}};function orgInstallId(adminOrigin2,organizationId,packageId){return createHash107("sha256").update(
|
|
30949
30949
|
`omb-install:v1
|
|
30950
30950
|
${adminOrigin2}
|
|
30951
30951
|
${organizationId}
|
|
@@ -31203,14 +31203,14 @@ olic link.");let id12=randomUUID78(),file2=join247(directory,`${id12}.ombbackup`
|
|
|
31203
31203
|
{owner:owner2(auth),kind:"upload",path:file2,expires:Date.now()+EXPIRES_MS}),json7(res,200,{id:id12})}catch(error66){try{unlinkSync26(file2)}catch{}throw error66}}),!0;if(method2==="POST"&&path8===`${PREFIX2}/preview`){let body3=external_exports.object({id:external_exports.string().uuid(),password:passwordSchema}).parse(await options2.readBody(req)),artifact=get7(body3.id,auth,"upload"),result2=await operate(()=>stageWorkspaceBackup(options2.dataDir,artifact.path,{password:body3.password,currentAppVersion:options2.
|
|
31204
31204
|
appVersion,accountId:account2()}));try{check4(req,auth)}catch(error66){throw removeWorkspaceBackupJob(options2.dataDir,result2.id),error66}try{unlinkSync26(artifact.path)}catch{}return artifacts.delete(body3.id),artifacts.set(result2.id,{owner:owner2(auth),kind:"staged",summary:result2.summary,expires:Date.now()+EXPIRES_MS}),json7(res,200,{id:result2.id,summary:result2.summary}),!0}if(method2==="POST"&&path8===`${PREFIX2}/restore`){let body3=external_exports.object({id:external_exports.string().
|
|
31205
31205
|
uuid(),confirmation:external_exports.literal("REPLACE")}).parse(await options2.readBody(req));get7(body3.id,auth,"staged");let result2=await operate(()=>options2.exclusive(async()=>(check4(req,auth),commitPendingWorkspaceRestore(options2.dataDir,body3.id,{accountId:account2(),currentAppVersion:options2.appVersion})),!0));artifacts.delete(body3.id);let restart2=options2.restart;return json7(res,200,{...result2,restoreId:body3.id,...restart2?{restarting:!0}:{}}),restart2&&(res.closed?restart2():res.
|
|
31206
|
-
once("close",restart2)),!0}json7(res,404,{error:"Unknown backup operation."})}catch(error66){if(res.headersSent)return res.destroy(),!0;json7(res,error66 instanceof external_exports.ZodError?400:error66.status??400,{error:error66 instanceof external_exports.ZodError?error66.issues[0]?.message??"Invalid backup request.":error66 instanceof Error?error66.message:"Backup failed.",...userErrorFields(error66)})}return!0}}init_atomic();import{constants as constants23,copyFileSync as copyFileSync3,existsSync as existsSync98,lstatSync as lstatSync45,mkdirSync as mkdirSync120,readdirSync as readdirSync55,readFileSync as readFileSync178}from"node:fs";import{dirname as
|
|
31206
|
+
once("close",restart2)),!0}json7(res,404,{error:"Unknown backup operation."})}catch(error66){if(res.headersSent)return res.destroy(),!0;json7(res,error66 instanceof external_exports.ZodError?400:error66.status??400,{error:error66 instanceof external_exports.ZodError?error66.issues[0]?.message??"Invalid backup request.":error66 instanceof Error?error66.message:"Backup failed.",...userErrorFields(error66)})}return!0}}init_atomic();import{constants as constants23,copyFileSync as copyFileSync3,existsSync as existsSync98,lstatSync as lstatSync45,mkdirSync as mkdirSync120,readdirSync as readdirSync55,readFileSync as readFileSync178}from"node:fs";import{dirname as dirname81,join as join248,resolve as resolve55}from"node:path";var DEFINITIONS=["bots.json","groups.json","config.json","routines.json","calendar-calls.json"],ID18=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,MAX_FILE_BYTES2=16*1024**2,END=String.raw`(?=[.,;:!?)\]}]*(?:[\s"'\x60<>|]|$)|[\\/])`,WINDOWS_DATA_FOLDER=new RegExp(String.raw`(?<![\w\\/])[A-Za-z]:(?:[\\/][^\\/:*?"<>|\r\n]+?)*?[\\/]\.limixbot${END}`,"gi"),POSIX_DATA_FOLDER=new RegExp(String.raw`(?<![\w.:\\/-])\/(?:[^/\s"'\x60<>|]+\/)*?\.limixbot${END}`,"g");function record26(value3){
|
|
31207
31207
|
return value3!==null&&typeof value3=="object"&&!Array.isArray(value3)}function strings5(value3,out=[]){if(typeof value3=="string")out.push(value3);else if(Array.isArray(value3))for(let item of value3)strings5(item,out);else if(record26(value3))for(let item of Object.values(value3))strings5(item,out);return out}function readText6(dataDir,path8){try{let stat16=lstatSync45(join248(dataDir,path8));return stat16.isFile()&&stat16.size<=MAX_FILE_BYTES2?readFileSync178(join248(dataDir,path8),"utf8"):null}catch{
|
|
31208
31208
|
return null}}function instructionFiles(dataDir){let list10=path8=>{try{return readdirSync55(join248(dataDir,path8),{withFileTypes:!0}).sort((a,b11)=>a.name<b11.name?-1:1)}catch{return[]}},files2=[],memory2=path8=>{for(let entry2 of list10(path8))entry2.isDirectory()?memory2(`${path8}/${entry2.name}`):files2.push(`${path8}/${entry2.name}`)};for(let bot of list10("bots"))bot.isDirectory()&&files2.push(`bots/${bot.name}/SOUL.md`);for(let workspace of list10("workspaces"))workspace.isDirectory()&&(files2.
|
|
31209
31209
|
push(`workspaces/${workspace.name}/MEMORY.md`),memory2(`workspaces/${workspace.name}/memory`));return files2.filter(path8=>INSTRUCTION_FILE.test(path8))}function dataFolders(text33,dataDir,found2){let own4=dataDir.replaceAll("\\","/").toLowerCase();for(let[folder3]of text33.matchAll(WINDOWS_DATA_FOLDER)){let key7=folder3.replaceAll("\\","/").toLowerCase();key7!==own4&&found2.set(key7,folder3)}for(let[folder3]of text33.matchAll(POSIX_DATA_FOLDER))folder3!==dataDir&&found2.set(folder3,folder3)}function rewrite(name6,value3,paths2){
|
|
31210
31210
|
if(name6==="bots.json"){if(Array.isArray(value3))for(let bot of value3)record26(bot)&&(paths2.definitions(bot,String(bot.id)),typeof bot.soul=="string"&&(bot.soul=paths2.text(bot.soul)));return}if(paths2.definitions(value3),name6==="groups.json"&&Array.isArray(value3))for(let group2 of value3)record26(group2)&&typeof group2.bulletin=="string"&&(group2.bulletin=paths2.text(group2.bulletin));if(name6==="routines.json"&&record26(value3)&&Array.isArray(value3.routines))for(let routine of value3.routines)
|
|
31211
31211
|
record26(routine)&&typeof routine.prompt=="string"&&(routine.prompt=paths2.text(routine.prompt))}function repair(dataDir,id12){let documents=new Map;for(let name6 of DEFINITIONS){let text33=readText6(dataDir,name6);if(text33!==null)try{documents.set(name6,JSON.parse(text33))}catch{}}let files2=new Map;for(let path8 of instructionFiles(dataDir)){let text33=readText6(dataDir,path8);text33!==null&&files2.set(path8,text33)}let found2=new Map;for(let value3 of documents.values())for(let text33 of strings5(
|
|
31212
31212
|
value3))dataFolders(text33,dataDir,found2);for(let text33 of files2.values())dataFolders(text33,dataDir,found2);if(found2.size!==1)return found2.size&&console.warn(`[moved-paths] files name ${found2.size} other data folders; every path was left as it is`),[];let paths2=restorePaths([...found2.values()][0],dataDir),edits=[];for(let[name6,value3]of documents){let before=JSON.stringify(value3);rewrite(name6,value3,paths2);let after=JSON.stringify(value3);after!==before&&edits.push([name6,after])}for(let[
|
|
31213
|
-
path8,text33]of files2){let after=paths2.text(text33);after!==text33&&edits.push([path8,after])}let kept2=join248(dataDir,".backups",`path-repair-${id12}`);for(let[path8,text33]of edits){let live2=join248(dataDir,path8),copy6=join248(kept2,path8);mkdirSync120(
|
|
31213
|
+
path8,text33]of files2){let after=paths2.text(text33);after!==text33&&edits.push([path8,after])}let kept2=join248(dataDir,".backups",`path-repair-${id12}`);for(let[path8,text33]of edits){let live2=join248(dataDir,path8),copy6=join248(kept2,path8);mkdirSync120(dirname81(copy6),{recursive:!0,mode:448}),existsSync98(copy6)||copyFileSync3(live2,copy6,constants23.COPYFILE_EXCL),writeFileAtomic(live2,text33,{mode:lstatSync45(live2).mode&511})}return edits.length&&console.log(`[moved-paths] rewrote the\
|
|
31214
31214
|
old computer's data folder in ${edits.length} files; the earlier copies are in .backups/path-repair-${id12}`),edits.map(([path8])=>path8)}function repairMovedWorkspacePaths(dataDir){let receiptPath2=join248(dataDir,".backups","last-restore.json"),receipt;try{if(!lstatSync45(receiptPath2).isFile())return null;let value3=JSON.parse(readFileSync178(receiptPath2,"utf8"));if(!record26(value3)||value3.restored!==!0||typeof value3.id!="string"||!ID18.test(value3.id)||value3.pathsRewritten===!0)return null;
|
|
31215
31215
|
receipt=value3}catch{return null}try{let changed3=repair(resolve55(dataDir),String(receipt.id));return writeFileAtomic(receiptPath2,JSON.stringify({...receipt,pathsRewritten:!0}),{mode:384}),changed3}catch(error66){return console.error(`[moved-paths] the repair stopped: ${error66 instanceof Error?error66.message:String(error66)}`),null}}var INSTALLATION_CREDENTIAL=/^omb_install_[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/,INSTALLATION_ID2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,CLIENT_INSTANCE=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,REQUEST_ID3=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,stringValue3=value3=>typeof value3=="string"?value3:null,isPlainRecord=value3=>{if(typeof value3!="object"||value3===null||Array.isArray(value3))return!1;try{let constructor=value3.constructor;
|
|
31216
31216
|
if(constructor===void 0||typeof constructor!="function")return!0;let prototype2=constructor.prototype;return typeof prototype2=="object"&&prototype2!==null&&Object.prototype.hasOwnProperty.call(prototype2,"isPrototypeOf")}catch{return!1}},plainObject=value3=>{if(!isPlainRecord(value3))return null;let record31={};try{for(let key7 of Reflect.ownKeys(value3))if(Object.prototype.propertyIsEnumerable.call(value3,key7)){if(typeof key7!="string")return null;key7!=="__proto__"&&(record31[key7]=value3[key7])}}catch{
|
|
@@ -31365,10 +31365,10 @@ socket))},socket.onmessage=event2=>{let binary2=typeof event2.data!="string";sin
|
|
|
31365
31365
|
length>2048||!TOKEN9.test(token3)||typeof hostId!="string"||!HOST_ID.test(hostId)||!Array.isArray(nodes)||nodes.length<1||nodes.length>4||!nodes.every(node3=>typeof node3=="string"&&RELAY_HOST3.test(node3))||!Number.isSafeInteger(expiresAt)||!Number.isSafeInteger(refreshAfter)||refreshAfter>expiresAt?null:{token:token3,hostId,nodes:[...nodes],expiresAt,refreshAfter}}function createRelayTokenService({fetchGrant,onGrant,setTimer=defaultSetTimer,clearTimer:clearTimer2=clearTimeout,now:now2=Date.now,
|
|
31366
31366
|
random:random2=Math.random,log:log7=()=>{}}){let running5=!1,grant=null,timer4=null,failures=0,inFlight=null,jitter4=milliseconds2=>Math.round(milliseconds2*(.8+.4*random2())),schedule2=milliseconds2=>{timer4&&clearTimer2(timer4),timer4=running5?setTimer(()=>{refresh()},Math.max(0,milliseconds2)):null},publish=next=>{next!==grant&&(grant=next,onGrant(grant))};async function attempt2(){try{let next=validRelayGrant(await fetchGrant());if(!next)throw Object.assign(new Error("invalid relay grant"),{
|
|
31367
31367
|
code:"invalid_response"});if(failures=0,!running5)return;publish(next),schedule2(Math.max(MIN_REFRESH_MS,next.refreshAfter-now2()))}catch(error66){if(!running5)return;let code=error66?.code??"";if(code==="relay_unavailable"||code==="signed_out"||error66?.status===401)return log7(`relay token ${code||"refused"}`),publish(null),schedule2(jitter4(18e5));grant&&grant.expiresAt<=now2()&&publish(null);let retryAfter=Number.isSafeInteger(error66?.retryAfterMs)?error66.retryAfterMs:0;schedule2(Math.max(
|
|
31368
|
-
retryAfter,jitter4(BACKOFF_MS3[Math.min(failures,BACKOFF_MS3.length-1)]))),failures+=1,log7(`relay token failed: ${code||"unknown"}`)}}function refresh(){return inFlight??=attempt2().finally(()=>{inFlight=null}),inFlight}return{get grant(){return grant},get running(){return running5},start(){running5||(running5=!0,refresh())},stop(){running5=!1,timer4&&clearTimer2(timer4),timer4=null,publish(null)},refreshNow(){return running5?(timer4&&clearTimer2(timer4),timer4=null,refresh()):Promise.resolve()}}}init_atomic();import{chmodSync as chmodSync14,existsSync as existsSync99,mkdirSync as mkdirSync121,readFileSync as readFileSync180,statSync as statSync46}from"node:fs";import{dirname as
|
|
31368
|
+
retryAfter,jitter4(BACKOFF_MS3[Math.min(failures,BACKOFF_MS3.length-1)]))),failures+=1,log7(`relay token failed: ${code||"unknown"}`)}}function refresh(){return inFlight??=attempt2().finally(()=>{inFlight=null}),inFlight}return{get grant(){return grant},get running(){return running5},start(){running5||(running5=!0,refresh())},stop(){running5=!1,timer4&&clearTimer2(timer4),timer4=null,publish(null)},refreshNow(){return running5?(timer4&&clearTimer2(timer4),timer4=null,refresh()):Promise.resolve()}}}init_atomic();import{chmodSync as chmodSync14,existsSync as existsSync99,mkdirSync as mkdirSync121,readFileSync as readFileSync180,statSync as statSync46}from"node:fs";import{dirname as dirname82,join as join250,resolve as resolve56}from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";var isPlainRecord2=value3=>{if(typeof value3!="object"||value3===null||Array.isArray(value3))return!1;try{let constructor=value3.constructor;if(constructor===void 0||typeof constructor!="function")return!0;let prototype2=constructor.prototype;return typeof prototype2=="object"&&prototype2!==null&&Object.prototype.hasOwnProperty.call(prototype2,"isPrototypeOf")}catch{return!1}},copy5=credentials=>{if(!isPlainRecord2(credentials))throw new TypeError("Secure credentials must be a plain record");let document4={};
|
|
31369
31369
|
for(let key7 of Reflect.ownKeys(credentials))if(Object.prototype.propertyIsEnumerable.call(credentials,key7)){if(typeof key7!="string")throw new TypeError("Secure credential keys must be strings");key7!=="__proto__"&&(document4[key7]=credentials[key7])}return structuredClone(document4)};function createSecureCredentialState(initialCredentials,persist,{writable:writable2=!0}={}){let current3=copy5(initialCredentials),transition=Promise.resolve(),assertWritable=()=>{if(!writable2)throw new Error("T\
|
|
31370
31370
|
he credential store could not be read on this launch, so credentials cannot be saved")},serialize4=work=>{let next=transition.then(work,work);return transition=next.then(()=>{},()=>{}),next};return{read(){return copy5(current3)},update(derive2,afterPersist){return serialize4(async()=>{assertWritable();let previous2=copy5(current3),next=copy5(await derive2(copy5(previous2)));await persist(copy5(next));try{let result2=await afterPersist?.(copy5(next));return current3=next,result2??copy5(next)}catch(error66){
|
|
31371
|
-
throw await persist(copy5(previous2)),current3=previous2,error66}})}}}init_atomic();var HERE=
|
|
31371
|
+
throw await persist(copy5(previous2)),current3=previous2,error66}})}}}init_atomic();var HERE=dirname82(fileURLToPath3(import.meta.url)),TUNNEL_CREDENTIALS_FILE="tunnel-account.json";function plainDocument(value3){if(typeof value3!="object"||value3===null||Array.isArray(value3))return null;let document4={};for(let[key7,entry2]of Object.entries(value3))document4[key7]=entry2;return document4}function openTunnelCredentials(dataDir){let file2=join250(dataDir,TUNNEL_CREDENTIALS_FILE),initial={},status5="empty";if(existsSync99(file2))try{process.platform!=="win32"&&(statSync46(file2).mode&63)!==0&&chmodSync14(file2,384);let parsed3=plainDocument(JSON.parse(readFileSync180(file2,"\
|
|
31372
31372
|
utf8")));if(!parsed3)throw new Error("not a JSON object");initial=parsed3,status5="ok"}catch{status5="unavailable"}let state=createSecureCredentialState(initial,next=>{mkdirSync121(dataDir,{recursive:!0,mode:448}),writeFileAtomic(file2,`${JSON.stringify(next,null,2)}
|
|
31373
31373
|
`,{mode:384})},{writable:status5!=="unavailable"});return{file:file2,status:status5,read:()=>state.read(),update:(derive2,afterPersist)=>state.update(derive2,afterPersist)}}function stringField(document4,field5){let value3=document4[field5];return typeof value3=="string"&&value3?value3:null}function describeTunnelAccount(document4){return{email:stringField(document4,COMPANION_ACCOUNT_EMAIL_FIELD),address:managedCompanionTunnelAccess(document4)?.endpoint??null,installationId:stringField(document4,
|
|
31374
31374
|
COMPANION_INSTALLATION_ID_FIELD)}}var FLEET_CREDENTIAL_ENV="OMB_INSTALLATION_CREDENTIAL";function fleetCredential(env=process.env){let value3=env[FLEET_CREDENTIAL_ENV]?.trim();return value3||null}var PHONE_RELAY_ENV="OMB_PHONE_RELAY",SERVES_TUNNEL_ENV="OMB_SERVES_TUNNEL",PHONE_RELAY_KEY_FILE="phone-relay-key.json",PHONE_RELAY_PHONES_FILE="phone-relay-phones.json",MAX_RELAY_PHONES=20,MAX_PAIRING_WINDOWS=2,ADMISSION_SETTLE_MS=300,RELAY_ONLY_ADDRESS="relay-only.invalid",MAX_SESSIONS_PER_PHONE=4,MAX_SESSIONS_PER_WINDOW=2,STREAM_DEADLINES={headersMs:3e4,requestMs:3e5},PAIRING_SESSION_ROUTES=new Set(["POST /api/pair","GET /api/health"]),sha256Hex6=value3=>createHash113("sha256").update(value3).
|
|
@@ -31580,8 +31580,8 @@ is account now has ${usageWords(result2.usage)}.`,"A card with the link, Copy li
|
|
|
31580
31580
|
record31.botId,threadId):null)){store5.published({...record31,card:null,live:!1},record31.updatedAt);continue}let signature2=await pageSignature(record31.source);if(signature2===null||signature2===record31.signature)continue;nextTry.set(record31.pageId,now2+LIVE_MIN_MS);let bundle2;try{bundle2=await readPageBundle(record31.source,[record31.source],void 0,{exactRoots:!0})}catch(error66){if(!(error66 instanceof PageBundleError))throw error66;nextTry.set(record31.pageId,now2+LIVE_BROKEN_MS);continue}
|
|
31581
31581
|
if(bundle2.source!==record31.source)continue;if(deps.paused?.()){nextTry.delete(record31.pageId);break}let outcome=await publishBundle({botId:record31.botId,threadId:"",title:record31.title,pageId:record31.pageId,post:()=>null,live:!0,signature:signature2,refresh:!0},bundle2);outcome.status===200?changed3++:outcome.status===410&&markUnpublished(record31.pageId,null)}}catch(error66){console.error("pages: live page refresh failed",error66)}finally{refreshing=!1}return changed3},async unpublish(input2){
|
|
31582
31582
|
let pageId2=input2.pageId;if(pageId2!==void 0&&!PAGE_ID2.test(pageId2))return{status:400,text:"page_id must be the id of a page you published, from its link."};let takeDown=id12=>serially2(pageKey2(id12),()=>unpublishNow(id12,input2.call));if(!pageId2&&input2.path&&input2.botId&&input2.roots){let botId2=input2.botId,notFound={status:404,text:`No page was published from ${input2.path}. Pass the page_id from its link instead.`},source4;try{source4=await pageSource(input2.path,input2.roots)}catch(error66){
|
|
31583
|
-
if(!(error66 instanceof PageBundleError))throw error66;return notFound}return serially2(JSON.stringify([botId2,source4]),async()=>{let record32=store5.fromSource(botId2,source4);return record32?takeDown(record32.pageId):notFound})}if(!pageId2)return{status:400,text:"Pass the page_id of the page to unpublish, or the path it was published from."};let record31=store5.get(pageId2);return record31?serially2(JSON.stringify([record31.botId,record31.source]),()=>takeDown(pageId2)):takeDown(pageId2)}}}import{mkdirSync as mkdirSync123,readFileSync as readFileSync185}from"node:fs";import{dirname as
|
|
31584
|
-
|
|
31583
|
+
if(!(error66 instanceof PageBundleError))throw error66;return notFound}return serially2(JSON.stringify([botId2,source4]),async()=>{let record32=store5.fromSource(botId2,source4);return record32?takeDown(record32.pageId):notFound})}if(!pageId2)return{status:400,text:"Pass the page_id of the page to unpublish, or the path it was published from."};let record31=store5.get(pageId2);return record31?serially2(JSON.stringify([record31.botId,record31.source]),()=>takeDown(pageId2)):takeDown(pageId2)}}}import{mkdirSync as mkdirSync123,readFileSync as readFileSync185}from"node:fs";import{dirname as dirname83}from"node:path";init_atomic();var MAX_RECORDS2=5e3,MAX_CARDS2=50,PublishedPagesStore=class _PublishedPagesStore{records;file;constructor(file2){this.file=file2,this.records=_PublishedPagesStore.read(file2)}static read(file2){try{let parsed3=JSON.parse(readFileSync185(file2,"utf8"));return parsed3.version===1&&Array.isArray(parsed3.pages)?parsed3.pages.filter(page=>typeof page?.pageId=="string"&&PAGE_ID2.test(page.pageId)&&typeof page.url=="string"&&typeof page.botId=="string"):[]}catch{return[]}}save(){mkdirSync123(
|
|
31584
|
+
dirname83(this.file),{recursive:!0}),writeFileAtomic(this.file,JSON.stringify({version:1,pages:this.records}),{mode:384})}get(pageId2){return this.records.find(record31=>record31.pageId===pageId2)??null}fromSource(botId2,source4){return this.records.find(record31=>record31.botId===botId2&&record31.source===source4)??null}list(){return this.records}published(input2,now2=Date.now()){let existing=this.get(input2.pageId),cards=[...existing?.cards??[],...input2.card?[input2.card]:[]].slice(-MAX_CARDS2),
|
|
31585
31585
|
record31={pageId:input2.pageId,url:input2.url,title:input2.title,botId:input2.botId,source:input2.source,cards,createdAt:existing?.createdAt??now2,updatedAt:now2,...input2.live?{live:!0,...input2.signature?{signature:input2.signature}:{}}:{},...input2.uncertain?{uncertain:!0}:{}};return this.records=[...this.records.filter(each=>each.pageId!==input2.pageId),record31].slice(-MAX_RECORDS2),this.save(),record31}forget(pageId2){let existing=this.get(pageId2);return existing?(this.records=this.records.
|
|
31586
31586
|
filter(record31=>record31.pageId!==pageId2),this.save(),existing):null}};var LIVE_EVERY_MS2=15e3;function createPublishedPages(options2){let store5=new PublishedPagesStore(join257(options2.dataDir,"published-pages.json")),client=createPagesClient({access:()=>pagesAccess(options2.cloudHome),notOffered:()=>pagesNotOffered(options2.cloudHome),selfHosted:options2.selfHosted===!0,...options2.fetch?{fetch:options2.fetch}:{}}),apps3=options2.apps,pageRow=(threadId,messageId2)=>apps3?.store.messagesFor(threadId).find(message8=>message8.id===messageId2&&message8.kind==="app"),
|
|
31587
31587
|
publisher=createPagePublisher({client,store:store5,patch:(threadId,messageId2,text33,card)=>{pageRow(threadId,messageId2)?apps3.store.patchMessage(threadId,messageId2,{publishedPage:card}):options2.patch(threadId,messageId2,text33,card)},liveRoots:options2.liveRoots,paused:options2.paused});setInterval(()=>{publisher.refreshLive()},LIVE_EVERY_MS2).unref?.();let appPages=apps3?{botOf:threadId=>apps3.store.groupByThread(threadId)?null:apps3.store.botByThread(threadId)??null,page:(threadId,messageId2,rev)=>apps3.
|
|
@@ -31881,7 +31881,7 @@ routineRun.threadId),await routines2.cancelRun(routineRun.id));let groupTurn=act
|
|
|
31881
31881
|
/^\/api\/bots\/([\w-]+)$/),m3&&method2==="DELETE"){let result2=await deleteBotWithLifecycle2(m3[1]);return json7(res,result2.status,result2.body)}return PASS}}init_zod();import{isAbsolute as isAbsolute44}from"node:path";init_new_bot_defaults();import{lstatSync as lstatSync47,readdirSync as readdirSync59,readFileSync as readFileSync188,statSync as statSync47}from"node:fs";import{basename as basename36,isAbsolute as isAbsolute42,join as join263}from"node:path";var MAX_ENTRIES2=400,MAX_DEPTH5=8;function listEntries(root3){let out=[],walk6=(dir,prefix,depth2)=>{if(!(depth2>MAX_DEPTH5||out.length>MAX_ENTRIES2))for(let name6 of readdirSync59(dir)){if(out.length>MAX_ENTRIES2)return;let absolute=join263(dir,name6),path8=prefix?`${prefix}/${name6}`:name6,info2=lstatSync47(absolute);info2.isSymbolicLink()?out.push({path:path8,kind:"link",size:0,absolute}):info2.isDirectory()?(out.push({path:path8,kind:"folder",size:0,absolute}),walk6(absolute,path8,depth2+1)):
|
|
31882
31882
|
info2.isFile()&&out.push({path:path8,kind:"file",size:info2.size,executable:process.platform!=="win32"&&(info2.mode&73)!==0,absolute})}};return walk6(root3,"",1),out}function readOne(dir){let{take:take2,skipped:skipped2}=planSkillFolder(listEntries(dir));if(take2[0]?.path!=="SKILL.md")throw new Error(`no SKILL.md in ${basename36(dir)}`);let files2=take2.filter(entry2=>entry2.kind==="file").map(entry2=>({path:entry2.path,content:readFileSync188(entry2.absolute),executable:entry2.executable===!0}));
|
|
31883
31883
|
return{source:`local:${basename36(dir)}`,files:files2,skipped:skipped2}}function readLocalSkills(folder3){try{if(!isAbsolute42(folder3)||!statSync47(folder3).isDirectory())return{error:"Choose a folder on this computer."};let dirs=[],has2=dir=>{try{return statSync47(join263(dir,"SKILL.md")).isFile()}catch{return!1}};if(has2(folder3))dirs.push(folder3);else for(let name6 of readdirSync59(folder3)){let sub=join263(folder3,name6);try{statSync47(sub).isDirectory()&&has2(sub)&&dirs.push(sub)}catch{}}
|
|
31884
|
-
return dirs.length?{skills:dirs.slice(0,50).map(readOne)}:{error:"No SKILL.md found in that folder or in its subfolders."}}catch(error66){return{error:error66 instanceof Error?error66.message:"Could not read that folder."}}}import{readdirSync as readdirSync60,readFileSync as readFileSync189,statSync as statSync48,realpathSync as realpathSync31}from"node:fs";import{homedir as homedir45}from"node:os";import{dirname as
|
|
31884
|
+
return dirs.length?{skills:dirs.slice(0,50).map(readOne)}:{error:"No SKILL.md found in that folder or in its subfolders."}}catch(error66){return{error:error66 instanceof Error?error66.message:"Could not read that folder."}}}import{readdirSync as readdirSync60,readFileSync as readFileSync189,statSync as statSync48,realpathSync as realpathSync31}from"node:fs";import{homedir as homedir45}from"node:os";import{dirname as dirname84,join as join264,resolve as resolve58,relative as relative28,isAbsolute as isAbsolute43,delimiter as delimiter13}from"node:path";import{execFile as execFile24}from"node:child_process";import{promisify as promisify7}from"node:util";init_config3();var run10=promisify7(execFile24),PACKAGE=/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/i,BIN2=/^[a-z0-9][a-z0-9_.-]{0,79}$/i,object6=value3=>value3&&typeof value3=="object"&&!Array.isArray(value3)?value3:{};function extractSkillRequirements(text33){let out=[],optionalKeys2=new Set,add11=(kind2,value3,evidence)=>{if(typeof value3!="string"||!value3.trim())return;let raw=kind2==="review"?value3.trim():value3.trim().replace(/[.,;:]+$/,""),match5=raw.match(/^((?:@[\w.-]+\/)?[\w.-]+)(?:@|\s*(?=[<>=~^]))(.*)$/),
|
|
31885
31885
|
name6=match5?.[1]??raw;if(kind2!=="review"&&!(kind2==="env"?/^[A-Z_][A-Z0-9_]*$/.test(name6):kind2==="bin"?BIN2.test(name6):PACKAGE.test(name6))){out.push({kind:"review",name:raw,evidence});return}out.push({kind:kind2,name:name6,...kind2==="npm"&&!["remotion","@remotion/cli"].includes(name6)&&/\bnpm\s+(?:install|i)\b[^\n]*\s(?:-g|--global)(?:\s|$)/.test(evidence.split(/\s#|[;&|]/)[0])?{installScope:"tool"}:{},...match5?.[2]?{required:match5[2]}:{},evidence})},read4=(value3,kind2,evidence)=>{if(Array.
|
|
31886
31886
|
isArray(value3))for(let item of value3)add11(typeof item=="string"?kind2:"review",typeof item=="string"?item:JSON.stringify(item),evidence);else if(typeof value3=="string")add11(kind2,value3,evidence);else for(let[name6,version5]of Object.entries(object6(value3)))add11(kind2,typeof version5=="string"&&version5!=="*"?`${name6}@${version5}`:name6,evidence)},front=text33.replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/),body3=front?text33.replace(/^\uFEFF/,"").slice(front[0].length):text33;
|
|
31887
31887
|
if(front)try{let doc=parseDocument(front[1]);if(doc.errors.length)throw new Error("invalid YAML");let fields3=object6(doc.toJS({maxAliasCount:20})),metadata2=object6(fields3.metadata);for(let block of[fields3.requires,fields3.requirements,fields3.dependencies,metadata2.requires,metadata2.requirements,metadata2.dependencies,object6(metadata2.openclaw).requires,object6(metadata2.clawdbot).requires]){let req=object6(block);(typeof block=="string"||Array.isArray(block))&&read4(block,"review","SKILL.\
|
|
@@ -31895,7 +31895,7 @@ includes(token3))continue;add11("review",match5[0],"Install command needs review
|
|
|
31895
31895
|
if(/\bremotion\b/i.test(text33))for(let name6 of["remotion","@remotion/cli"])out.some(r=>r.kind==="npm"&&r.name===name6)||out.push({kind:"npm",name:name6,evidence:"Remotion code-rendering workflow",optional:!0});let section4=!1;for(let line6 of body3.split(/\r?\n/))/^#{1,6}\s/.test(line6)?section4=/prerequisit|requirement|dependenc|installation|setup|yêu cầu|cài đặt|phụ thuộc/i.test(line6):section4&&line6.trim()&&!line6.trim().startsWith("```")?add11("review",line6.trim(),"Requirement\
|
|
31896
31896
|
s / setup instructions"):/\b(?:requires?|prerequisites?|dependencies|needs? to be installed)\b|yêu cầu|cần (?:cài|có)/i.test(line6)&&add11("review",line6.trim(),"Requirements mentioned in skill instructions");return[...new Map(out.map(req=>[`${req.kind}:${req.name}:${req.required??""}`,req])).values()].map(req=>optionalKeys2.has(`${req.kind}:${req.name}`)?{...req,optional:!0}:req)}function findSkillBinary(name6,dirs,platform2=process.platform){if(!BIN2.test(name6))return null;for(let dir of dirs)
|
|
31897
31897
|
for(let ext of platform2==="win32"?["",".exe",".cmd",".bat",".com"]:[""]){let file2=join264(dir,name6+ext);try{if(statSync48(file2).isFile())return file2}catch{}}return null}function findSkillNpmPackage(name6,roots){if(!PACKAGE.test(name6))return null;for(let root3 of roots){let dir=resolve58(root3);for(;;){let file2=join264(dir,"node_modules",name6,"package.json");try{let pkg2=JSON.parse(readFileSync189(file2,"utf8"));if(pkg2.name===name6)return{version:typeof pkg2.version=="string"?pkg2.version:
|
|
31898
|
-
void 0,where:file2}}catch{}let parent2=
|
|
31898
|
+
void 0,where:file2}}catch{}let parent2=dirname84(dir);if(parent2===dir)break;dir=parent2}}return null}function findSkillPythonPackage(name6,roots){let normalized2=value3=>value3.toLowerCase().replace(/[-_.]+/g,"-");for(let root3 of roots)for(let env of[root3,join264(root3,".venv"),join264(root3,"venv")]){let sites=[join264(env,"Lib","site-packages")];try{for(let dir of readdirSync60(join264(env,"lib")))/^python\d/.test(dir)&&sites.push(join264(env,"lib",dir,"site-packages"))}catch{}for(let site of sites)
|
|
31899
31899
|
try{for(let dir of readdirSync60(site).filter(s4=>s4.endsWith(".dist-info"))){let file2=join264(site,dir,"METADATA"),text33=readFileSync189(file2,"utf8");if(normalized2(text33.match(/^Name: (.+)$/m)?.[1]?.trim()??"")!==normalized2(name6))continue;let version5=text33.match(/^Version: (.+)$/m)?.[1]?.trim();if(version5)return{version:version5,where:file2}}}catch{}}return null}async function scanSkillRequirements(bots,mcpServers={},projects=[]){let sources2=new Map,warnings=[],add11=(name6,directory,projects2=[])=>{
|
|
31900
31900
|
try{let real2=realpathSync31(directory),prior=sources2.get(real2);prior?prior.projects=[...new Set([...prior.projects,...projects2])]:sources2.set(real2,{name:name6,directory:real2,projects:projects2})}catch{warnings.push(`Could not read ${name6}`)}};for(let skill of[...loadBundledSkills(),...loadUserSkills(join264(DATA_DIR,"skills"))])add11(skill.manifest.name,skill.directory);for(let skill of listLibrarySkills())add11(skill.name,librarySkillDirectory(skillsLibraryRoot(),skill.name));for(let name6 of Object.
|
|
31901
31901
|
keys(readImportedSkills()))add11(name6,join264(IMPORTED_SKILLS_DIR,name6));for(let bot of bots)for(let skill of listMigratableSkills(bot.id))skill.directory&&add11(`${skill.name} (${bot.name})`,skill.directory,[bot.cwd??workspaceDir(bot.id)]);let home2=homedir45(),dirs=`${process.env.OMB_EXTRA_PATH??""}${delimiter13}${process.env.PATH??""}`.split(delimiter13).filter(Boolean);if(process.platform==="win32")try{let{stdout}=await run10("powershell.exe",["-NoProfile","-NonInteractive","-Command","[En\
|
|
@@ -31989,12 +31989,12 @@ y what the app is for."});let bot=deps.bot(deps.botId);return bot?json7(res,200,
|
|
|
31989
31989
|
key!="string")return json7(res,400,{error:"key must be a string"});let draft=typeof body3?.key=="string"?body3.key.trim():"";if(draft.length>MAX_KEY_LENGTH)return json7(res,400,{error:"That does not look like an API key."});res.setHeader("cache-control","no-store");let provider=body3?.provider==="jev"||body3?.provider==="openrouter"||body3?.provider==="workersai"?body3.provider:void 0;if(body3?.accountId!==void 0&&(typeof body3.accountId!="string"||!WORKERS_AI_ACCOUNT_ID.test(body3.accountId.trim())))
|
|
31990
31990
|
return json7(res,400,userError("serverError.decider.accountId"));let accountId=typeof body3?.accountId=="string"?body3.accountId.trim():void 0;if(body3?.model!==void 0&&(typeof body3.model!="string"||body3.model.length>OPENROUTER_MODEL_ID_MAX))return json7(res,400,{error:"model must be an OpenRouter model id"});let model4=typeof body3?.model=="string"&&body3.model.trim()?body3.model.trim():void 0,api=body3?.api==="decisions"||body3?.api==="chat"?body3.api:void 0,result2=await deps.decider.testKey(
|
|
31991
31991
|
{...draft?{key:draft}:{},...provider?{provider}:{},...model4?{model:model4}:{},...api?{api}:{},...accountId?{accountId}:{}}),read4=!draft&&(!provider||provider==="workersai")&&deps.extractor?await deps.extractor.testKey():null,extraction=read4&&!(read4.ok===!1&&read4.reason==="no_key")?{extraction:read4.ok?{ok:!0}:{ok:!1,reason:read4.reason,...read4.status?{status:read4.status}:{}}}:{};return result2.ok?json7(res,200,{ok:!0,latencyMs:result2.latencyMs,...extraction}):json7(res,200,{ok:!1,reason:result2.
|
|
31992
|
-
reason,...result2.status?{status:result2.status}:{},...extraction})}}init_zod();init_bot_avatar();init_zod();import{createHash as createHash122,randomUUID as randomUUID81}from"node:crypto";import{createReadStream as createReadStream10}from"node:fs";import{link as link4,lstat as lstat12,mkdir as mkdir15,open as open13,readdir as readdir13,rename as rename7,stat as stat14,unlink as unlink7}from"node:fs/promises";import{statfsSync as statfsSync4}from"node:fs";import{dirname as
|
|
31992
|
+
reason,...result2.status?{status:result2.status}:{},...extraction})}}init_zod();init_bot_avatar();init_zod();import{createHash as createHash122,randomUUID as randomUUID81}from"node:crypto";import{createReadStream as createReadStream10}from"node:fs";import{link as link4,lstat as lstat12,mkdir as mkdir15,open as open13,readdir as readdir13,rename as rename7,stat as stat14,unlink as unlink7}from"node:fs/promises";import{statfsSync as statfsSync4}from"node:fs";import{dirname as dirname85,join as join267}from"node:path";var FILE_PART_BYTES=8*1024*1024,MAX_FILES3=2e5,PARTIAL_MAX_AGE_MS=1440*60*1e3,SHA3=/^[a-f0-9]{64}$/u,PLACE2=/^(?:workspaces\/[\w-]{1,128}|task-workspaces\/[\w-]{1,128}\/[\w-]{1,200})\/./u,CARRIED_OTHERWISE=/^workspaces\/[\w-]{1,128}\/(?:MEMORY\.md$|memory(?:\/|$)|skills(?:\/|$))|^(?:workspaces\/[\w-]{1,128}|task-workspaces\/[\w-]{1,128}\/[\w-]{1,200})\/\.(?:claude|agents|grok)(?:\/|$)/u;function movedFilePath(path8){return PLACE2.test(path8)&&validRelative(path8)&&!CARRIED_OTHERWISE.test(path8)&&
|
|
31993
31993
|
!omittedFromWorkspaceBackup(path8)&&!path8.split("/").includes("node_modules")}var hashes=new Map;async function fileSha256(full,size3,mtimeMs){let key7=`${full}\0${size3}\0${mtimeMs}`,known=hashes.get(key7);if(known)return known;let hash4=createHash122("sha256");for await(let chunk of createReadStream10(full))hash4.update(chunk);let digest5=hash4.digest("hex");return hashes.size>=MAX_FILES3&&hashes.delete(hashes.keys().next().value),hashes.set(key7,digest5),digest5}async function listBotFiles(dataDir,botIds){
|
|
31994
31994
|
let out=[],walk6=async relative30=>{let names5;try{names5=(await readdir13(join267(dataDir,relative30))).sort()}catch{return}for(let name6 of names5){if(out.length>=MAX_FILES3)return;let path8=`${relative30}/${name6}`,info2=await lstat12(join267(dataDir,path8)).catch(()=>null);if(!(!info2||name6==="node_modules")){if(info2.isDirectory()){!CARRIED_OTHERWISE.test(`${path8}/`)&&!omittedFromWorkspaceBackup(path8)&&await walk6(path8);continue}info2.isFile()&&movedFilePath(path8)&&out.push({path:path8,
|
|
31995
31995
|
size:info2.size,sha256:await fileSha256(join267(dataDir,path8),info2.size,info2.mtimeMs)})}}};for(let id12 of botIds)/^[\w-]{1,128}$/u.test(id12)&&(await walk6(`workspaces/${id12}`),await walk6(`task-workspaces/${id12}`));return out}function space(dataDir){try{let disk=statfsSync4(dataDir,{bigint:!0}),clamp4=value3=>value3>BigInt(Number.MAX_SAFE_INTEGER)?Number.MAX_SAFE_INTEGER:Number(value3);return{freeBytes:clamp4(disk.bavail*disk.bsize),volumeBytes:clamp4(disk.blocks*disk.bsize)}}catch{return null}}
|
|
31996
31996
|
var staging=dataDir=>join267(dataDir,"tmp","move-files"),partialPath=(dataDir,sha2567,size3)=>join267(staging(dataDir),`${sha2567}-${size3}.partial`);async function tidyPartials(dataDir,now2=Date.now()){let folder3=staging(dataDir);for(let name6 of await readdir13(folder3).catch(()=>[])){if(!name6.endsWith(".partial"))continue;let info2=await stat14(join267(folder3,name6)).catch(()=>null);info2&&now2-info2.mtimeMs>PARTIAL_MAX_AGE_MS&&await unlink7(join267(folder3,name6)).catch(()=>{})}}function rawBody(req,limit2){
|
|
31997
|
-
return new Promise((resolve59,reject)=>{let chunks=[],bytes4=0;req.on("data",chunk=>{bytes4+=chunk.length,bytes4<=limit2&&chunks.push(chunk)}),req.on("end",()=>resolve59(bytes4>limit2?null:Buffer.concat(chunks))),req.on("error",reject)})}async function realFolders(dataDir,path8){let at8=dataDir;for(let part2 of
|
|
31997
|
+
return new Promise((resolve59,reject)=>{let chunks=[],bytes4=0;req.on("data",chunk=>{bytes4+=chunk.length,bytes4<=limit2&&chunks.push(chunk)}),req.on("end",()=>resolve59(bytes4>limit2?null:Buffer.concat(chunks))),req.on("error",reject)})}async function realFolders(dataDir,path8){let at8=dataDir;for(let part2 of dirname85(path8).split("/")){at8=join267(at8,part2);let info2=await lstat12(at8).catch(()=>null);if(!info2)await mkdir15(at8,{mode:448}).catch(()=>{});else if(!info2.isDirectory()||info2.
|
|
31998
31998
|
isSymbolicLink())return!1}return(await lstat12(at8).catch(()=>null))?.isDirectory()===!0}async function sha256Of(full){try{let hash4=createHash122("sha256");for await(let chunk of createReadStream10(full))hash4.update(chunk);return hash4.digest("hex")}catch{return null}}var putSchema=external_exports.object({path:external_exports.string().max(4096),size:external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER),sha256:external_exports.string().regex(SHA3),offset:external_exports.
|
|
31999
31999
|
coerce.number().int().min(0),mode:external_exports.enum(["new","replace"]),expect:external_exports.string().regex(SHA3).optional()}),partSchema=external_exports.object({path:external_exports.string().max(4096),offset:external_exports.coerce.number().int().min(0),length:external_exports.coerce.number().int().min(1).max(FILE_PART_BYTES)});async function readPart(dataDir,{path:path8,offset:offset4,length:length3}){let at8=dataDir;for(let part2 of path8.split("/")){at8=join267(at8,part2);let info2=await lstat12(
|
|
32000
32000
|
at8).catch(()=>null);if(!info2||info2.isSymbolicLink())return null}let handle2=await open13(at8,"r").catch(()=>null);if(!handle2)return null;try{let buffer=Buffer.alloc(length3),{bytesRead}=await handle2.read(buffer,0,length3,offset4);return buffer.subarray(0,bytesRead)}finally{await handle2.close()}}async function takePart(deps,req,query2){let{path:path8,size:size3,sha256:sha2567,offset:offset4,mode,expect:expect2}=query2,botId2=/^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u.exec(path8)?.[1];
|
|
@@ -32184,7 +32184,7 @@ restore(person2,target4.seq);return isRefusal(done)?json7(res,409,{error:done.re
|
|
|
32184
32184
|
let match5=THEME_PATH.exec(path8);if(!match5)return json7(res,404,{error:"No such theme route."});let id12=match5[1];if(match5[2]==="/export"&&method2==="GET"){let data4=store5.exportTheme(person2,id12);return data4?json7(res,200,data4):json7(res,404,{error:"No such theme."})}if(match5[2]==="/duplicate"&&method2==="POST"){let parsed3=nameBody.safeParse(await readBody2(req));if(!parsed3.success)return json7(res,400,{error:"name is required"});let copy6=store5.duplicate(person2,id12,parsed3.data.name);
|
|
32185
32185
|
return isRefusal(copy6)?json7(res,400,{error:copy6.refusal}):json7(res,200,copy6)}if(match5[2])return json7(res,405,{error:"Method not allowed."});if(method2==="GET"){let theme=store5.read(person2,id12);return theme?json7(res,200,{id:id12,theme}):json7(res,404,{error:"No such theme."})}if(method2==="PUT"){let parsed3=saveBody.safeParse(await readBody2(req,THEME_LIMITS.cssChars*4+5e4));if(!parsed3.success)return json7(res,400,{error:parsed3.error.issues.map(issue3=>`${issue3.path.join(".")}: ${issue3.
|
|
32186
32186
|
message}`).join("; ")});let done=store5.change(person2,{saves:[{id:id12,file:parsed3.data.theme}]});return isRefusal(done)?json7(res,400,{error:done.refusal}):(store5.active(person2)===id12&&deps.changed(person2),json7(res,200,{ok:!0}))}if(method2==="PATCH"){let parsed3=nameBody.safeParse(await readBody2(req)),theme=store5.read(person2,id12);if(!parsed3.success||!theme)return json7(res,parsed3.success?404:400,{error:parsed3.success?"No such theme.":"name is required"});let refusal7=store5.save(person2,
|
|
32187
|
-
id12,{...theme,name:parsed3.data.name});return refusal7?json7(res,400,{error:refusal7.refusal}):json7(res,200,{ok:!0})}if(method2==="DELETE"){let wasActive=store5.active(person2)===id12;return store5.remove(person2,id12),wasActive&&deps.changed(person2),json7(res,200,{ok:!0})}return json7(res,405,{error:"Method not allowed."})}}init_zod();import{basename as basename37,dirname as
|
|
32187
|
+
id12,{...theme,name:parsed3.data.name});return refusal7?json7(res,400,{error:refusal7.refusal}):json7(res,200,{ok:!0})}if(method2==="DELETE"){let wasActive=store5.active(person2)===id12;return store5.remove(person2,id12),wasActive&&deps.changed(person2),json7(res,200,{ok:!0})}return json7(res,405,{error:"Method not allowed."})}}init_zod();import{basename as basename37,dirname as dirname86,extname as extname11}from"node:path";var BUILT_IN2=[...SKIN_IDS,"system"],reply4=(status5,body3)=>({status:status5,body:body3}),refuse4=(status5,error66)=>reply4(status5,{error:error66});function said2(change2){switch(change2.kind){case"made":return`made ${change2.name}`;case"edited":return`edited ${change2.name}`;case"deleted":return`deleted ${change2.name} while wearing it`;case"wore":return`wore ${change2.name}`;case"skin":return`wore the built-in ${change2.name} skin`;case"default":return"back to default";case"undid":return`wen\
|
|
32188
32188
|
t back ${change2.count===1?"1 change":`${change2.count} changes`}`}}function createThemeTool(deps){let{store:store5}=deps;function entry2(person2){let read4=()=>{let id12=store5.active(person2);return id12?store5.read(person2,id12)?.name??id12:""};return{id:"appearance.theme",label:"Theme",help:"A custom look for the app.",where:"Settings \u2192 Appearance",synonyms:[],tier:"safe",value:external_exports.unknown(),allowed:"a theme",read:read4,current:()=>({undoTo:store5.history(person2)[0]?.seq??
|
|
32189
32189
|
0}),write:async value3=>{let wear=value3,done="undoTo"in wear?store5.restore(person2,wear.undoTo):store5.change(person2,{saves:wear.save?[wear.save]:[],wear:wear.id,...wear.skin?{skin:wear.skin}:{}});return isRefusal(done)?done.refusal:(deps.changed(person2,done.skin),null)}}}function overview(person2,id12){let list10=store5.list(person2),asked=typeof id12=="string"&&THEME_ID.test(id12)?store5.read(person2,id12):null,current3=list10.active?store5.read(person2,list10.active):null;return reply4(200,
|
|
32190
32190
|
{text:JSON.stringify({current:list10.active?{id:list10.active,theme:current3}:"none: the person's built-in skin",builtIn:BUILT_IN2,saved:list10.themes,...asked?{theme:{id:id12,...asked}}:{},guide:themeGuide()})})}function wanted(person2,body3){let id12=typeof body3.id=="string"?body3.id.trim():"";if(body3.theme!==void 0){let raw=body3.theme;if(typeof raw=="string")try{raw=JSON.parse(raw)}catch{return{error:'theme must be the theme as JSON: {"name", "canvas", "accent", "colors", "css", ...}.'}}let parsed3=themeFileSchema.
|
|
@@ -32194,7 +32194,7 @@ test(id12)?store5.read(person2,id12):null;return saved?{wear:{id:id12},change:`W
|
|
|
32194
32194
|
look.skin&&item.look.skin!=="system"?`built-in ${item.look.skin}`:"default"}));return reply4(200,{text:items.length?JSON.stringify({now:new Date().toISOString(),changes:items}):"No look changes yet."})}function undo(person2,body3){let items=store5.history(person2),whole3=value3=>typeof value3=="number"?value3:typeof value3=="string"&&/^\d+$/.test(value3.trim())?Number(value3):Number.NaN,byIndex=body3.index!==void 0&&body3.index!=="",count12=byIndex?whole3(body3.index)-1:body3.steps===void 0||body3.
|
|
32195
32195
|
steps===""?1:whole3(body3.steps);if(!items.length)return{error:"There are no look changes to go back on."};if(!Number.isInteger(count12)||count12<(byIndex?0:1)||count12>items.length-(byIndex?1:0))return{error:`${byIndex?"index":"steps"} must be a whole number from 1 to ${items.length}. Call theme_history to see the changes.`};if(count12===0)return{error:"That is how it looks now."};let target4=byIndex?items[count12]:items[count12-1],undoTo=byIndex?target4.seq:target4.seq-1,missing2=store5.missingAssets(
|
|
32196
32196
|
person2,undoTo),back=byIndex?`Go back to the look after: ${said2(target4)}`:count12===1?`Undo the last look change (${said2(items[0])})`:`Undo the last ${count12} look changes`;return{wear:{undoTo},change:`${back}${missing2.length?`; files no longer there: ${missing2.join(", ")}`:""}`}}async function addAsset(turn2,person2,body3){let id12=typeof body3.id=="string"?body3.id:"";if(!THEME_ID.test(id12)||!store5.read(person2,id12))return refuse4(404,"Name a saved theme in id: save it with set_theme \
|
|
32197
|
-
first.");let path8=typeof body3.path=="string"?body3.path.trim():"";if(!path8)return refuse4(400,"path is the file in your workspace or this conversation's attachments.");let sources2=deps.sources(turn2),attached=sources2.attachments.includes(path8),file2;try{file2=await openMessageFile(path8,attached?[
|
|
32197
|
+
first.");let path8=typeof body3.path=="string"?body3.path.trim():"";if(!path8)return refuse4(400,"path is the file in your workspace or this conversation's attachments.");let sources2=deps.sources(turn2),attached=sources2.attachments.includes(path8),file2;try{file2=await openMessageFile(path8,attached?[dirname86(path8)]:sources2.roots,THEME_LIMITS.assetBytes)}catch(error66){let status5=error66.status??400;return refuse4(status5,status5===413?`A theme file may be up to ${THEME_LIMITS.assetBytes/1024/
|
|
32198
32198
|
1024} MB.`:"That file is not in your workspace or this conversation's attachments, or it cannot be read.")}try{let ext=(extname11(file2.name).slice(1)||"").toLowerCase(),stem2=slugFor(basename37(file2.name,extname11(file2.name))).slice(0,60),added=store5.addAsset(person2,id12,`${stem2}.${ext}`,await file2.handle.readFile());return isRefusal(added)?refuse4(400,added.refusal):reply4(200,{text:`Added. In the theme's css write url("${added.url}"). Then call set_theme with the theme to use it.`})}finally{
|
|
32199
32199
|
await file2.handle.close().catch(()=>{})}}return{entry:entry2,overview,wanted,undo,history,addAsset,person:deps.person}}import{randomUUID as randomUUID86}from"node:crypto";init_zod();init_bot_thread_limits();init_zod();import{randomUUID as randomUUID82}from"node:crypto";import{join as join273}from"node:path";init_config3();var displayName2=external_exports.string().trim().min(1).max(80).refine(value3=>!new RegExp("\\p{Cc}","u").test(value3),"Name cannot contain control characters"),awsProfile=external_exports.string().trim().regex(/^[A-Za-z0-9._+=,@-]{1,128}$/,"Enter the AWS profile name from this computer's ~/.aws config."),awsRegion=external_exports.string().trim().regex(/^[a-z]{2}(-[a-z]+)+-\d$/,"Enter an AWS region, such as us-east-1."),model2=external_exports.string().trim().max(160).regex(CLAUDE_MODEL_ID,"Us\
|
|
32200
32200
|
e the model id Bedrock serves.").refine(value3=>value3!=="default","Claude Code reserves `default`; use the model id Bedrock serves."),optionalModel=external_exports.union([model2,external_exports.literal("")]),claudeBedrockSchema=external_exports.object({displayName:displayName2,awsProfile,awsRegion,model:model2,opusModel:optionalModel.optional(),sonnetModel:optionalModel.optional(),haikuModel:optionalModel.optional(),smallFastModel:optionalModel.optional()}).strict(),claudeBedrockUpdateSchema=external_exports.
|
|
@@ -32416,7 +32416,7 @@ answersOwn(answers,botId2){let asked=answers===void 0?void 0:deps.node(answers),
|
|
|
32416
32416
|
modelSelection=bot&&store5.taskByThread(bot.id,parentThreadId)?.modelSelection;if(!bot||!modelSelection)return{};let needsAsk=modelSwitchNeedsAsk(approvalModeFor(bot),deps.registry.cliTarget(bot.modelSelection.instanceId)?.driverKind,deps.registry.cliTarget(modelSelection.instanceId)?.driverKind);return{modelSelection,...needsAsk?{approvalMode:"ask"}:{}}},name(requester,child2){return own4(requester,child2)?`#${store5.taskByThread(child2.botId,child2.threadId)?.title??"Thread"}`:void 0},label(child2){
|
|
32417
32417
|
let task2=store5.taskByThread(child2.botId,child2.threadId);return` (your thread #${task2?.title??"Thread"}${task2?.modelSelection?`, on ${task2.modelSelection.model}`:""})`},menu(botId2,threadId,search3){let bot=store5.bot(botId2);if(!bot)return null;let current3=deps.current(botId2,threadId)??bot.modelSelection;return modelMenu({engines:deps.registry.instances(),current:current3,pinned:[bot.modelSelection],refusal:selection3=>refusal7(selection3,bot),down:engine=>deps.givesWay({instanceId:engine.
|
|
32418
32418
|
instanceId,model:engine.models.default},bot.modelSelection)==="unavailable",search:search3})}}}init_turn_route();init_redact();var SMALL_PLAN={parallel:2,maxTasks:10,smallPlan:!0},MAX_TASKS=200,BURST_PLAN_LIMITS={starter:SMALL_PLAN,personal:SMALL_PLAN,pro:{parallel:10,maxTasks:MAX_TASKS,smallPlan:!1},max:{parallel:25,maxTasks:MAX_TASKS,smallPlan:!1},team:{parallel:25,maxTasks:MAX_TASKS,smallPlan:!1},business:{parallel:25,maxTasks:MAX_TASKS,smallPlan:!1},enterprise:{parallel:25,maxTasks:MAX_TASKS,smallPlan:!1}},OPEN_SOURCE_PARALLEL=10;function burstLimits(host3){return host3.cloudHome?(host3.tier!==void 0&&Object.hasOwn(
|
|
32419
|
-
BURST_PLAN_LIMITS,host3.tier)?BURST_PLAN_LIMITS[host3.tier]:void 0)??SMALL_PLAN:{parallel:host3.maxParallel??OPEN_SOURCE_PARALLEL,maxTasks:MAX_TASKS,smallPlan:!1}}import{randomUUID as randomUUID87}from"node:crypto";var BurstLane=class{deps;running=0;pumping=!1;again=!1;constructor(deps){this.deps=deps}runningCount(){return this.running}release(){this.running=Math.max(0,this.running-1),this.pump()}pump(){if(this.pumping){this.again=!0;return}this.pumping=!0;try{do for(this.again=!1;this.running<this.deps.parallel()&&this.deps.hasRoom();){let slot=this.deps.next();if(slot===void 0)break;this.running+=1,this.deps.begin(slot)}while(this.again)}finally{this.pumping=!1}}};import{chmodSync as chmodSync16,closeSync as closeSync37,mkdirSync as mkdirSync126,openSync as openSync34}from"node:fs";import{dirname as
|
|
32419
|
+
BURST_PLAN_LIMITS,host3.tier)?BURST_PLAN_LIMITS[host3.tier]:void 0)??SMALL_PLAN:{parallel:host3.maxParallel??OPEN_SOURCE_PARALLEL,maxTasks:MAX_TASKS,smallPlan:!1}}import{randomUUID as randomUUID87}from"node:crypto";var BurstLane=class{deps;running=0;pumping=!1;again=!1;constructor(deps){this.deps=deps}runningCount(){return this.running}release(){this.running=Math.max(0,this.running-1),this.pump()}pump(){if(this.pumping){this.again=!0;return}this.pumping=!0;try{do for(this.again=!1;this.running<this.deps.parallel()&&this.deps.hasRoom();){let slot=this.deps.next();if(slot===void 0)break;this.running+=1,this.deps.begin(slot)}while(this.again)}finally{this.pumping=!1}}};import{chmodSync as chmodSync16,closeSync as closeSync37,mkdirSync as mkdirSync126,openSync as openSync34}from"node:fs";import{dirname as dirname87,join as join277}from"node:path";import{DatabaseSync as DatabaseSync8}from"node:sqlite";var EMPTY8={queued:0,running:0,done:0,failed:0,cancelled:0},SCHEMA2=`
|
|
32420
32420
|
CREATE TABLE IF NOT EXISTS bursts (
|
|
32421
32421
|
id TEXT PRIMARY KEY,
|
|
32422
32422
|
json TEXT NOT NULL,
|
|
@@ -32432,7 +32432,7 @@ CREATE TABLE IF NOT EXISTS burst_children (
|
|
|
32432
32432
|
PRIMARY KEY (burst_id, seq)
|
|
32433
32433
|
);
|
|
32434
32434
|
CREATE INDEX IF NOT EXISTS burst_children_status ON burst_children(burst_id, status, seq);
|
|
32435
|
-
`,titleOf=item=>{let line6=item.replace(/\s+/g," ").trim();return line6.length>80?`${line6.slice(0,79).trimEnd()}\u2026`:line6},sampleOf=items=>items.slice(0,5).map(titleOf);function openBurstStore(dataDir){let file2=dataDir===":memory:"?":memory:":join277(dataDir,"bursts.db");file2!==":memory:"&&(mkdirSync126(
|
|
32435
|
+
`,titleOf=item=>{let line6=item.replace(/\s+/g," ").trim();return line6.length>80?`${line6.slice(0,79).trimEnd()}\u2026`:line6},sampleOf=items=>items.slice(0,5).map(titleOf);function openBurstStore(dataDir){let file2=dataDir===":memory:"?":memory:":join277(dataDir,"bursts.db");file2!==":memory:"&&(mkdirSync126(dirname87(file2),{recursive:!0}),closeSync37(openSync34(file2,"a",384)),chmodSync16(file2,384));let db2=new DatabaseSync8(file2);db2.exec("PRAGMA journal_mode = WAL"),db2.exec(SCHEMA2);let rows2={
|
|
32436
32436
|
insertBurst:db2.prepare("INSERT INTO bursts (id, json, phase, created_at) VALUES (?, ?, ?, ?)"),updateBurst:db2.prepare("UPDATE bursts SET json = ?, phase = ? WHERE id = ?"),getBurst:db2.prepare("SELECT json FROM bursts WHERE id = ?"),activeBursts:db2.prepare("SELECT json FROM bursts WHERE phase IN ('running', 'merging') ORDER BY created_at"),deleteBurst:db2.prepare("DELETE FROM bursts WHERE id = ?"),oldBursts:db2.prepare("SELECT id FROM bursts WHERE phase IN ('done', 'cancelled') AND created_at\
|
|
32437
32437
|
< ?"),insertChild:db2.prepare("INSERT INTO burst_children (burst_id, seq, json, status) VALUES (?, ?, ?, ?)"),updateChild:db2.prepare("UPDATE burst_children SET json = ?, status = ? WHERE burst_id = ? AND seq = ?"),getChild:db2.prepare("SELECT json FROM burst_children WHERE burst_id = ? AND seq = ?"),nextQueued:db2.prepare("SELECT json FROM burst_children WHERE burst_id = ? AND status = 'queued' ORDER BY seq LIMIT 1"),childrenOf:db2.prepare("SELECT json FROM burst_children WHERE burst_id = ? OR\
|
|
32438
32438
|
DER BY seq"),childrenIn:db2.prepare("SELECT json FROM burst_children WHERE burst_id = ? AND status = ? ORDER BY seq"),deleteChildren:db2.prepare("DELETE FROM burst_children WHERE burst_id = ?")},parseBurst=row=>JSON.parse(row.json),parseChild=row=>JSON.parse(row.json),transaction2=run12=>{db2.exec("BEGIN");try{let result2=run12();return db2.exec("COMMIT"),result2}catch(error66){throw db2.exec("ROLLBACK"),error66}},writeBurst=burst2=>{rows2.updateBurst.run(JSON.stringify(burst2),burst2.phase,burst2.
|
|
@@ -32699,11 +32699,11 @@ Connection: Upgrade\r
|
|
|
32699
32699
|
Sec-WebSocket-Accept: ${accept}\r
|
|
32700
32700
|
\r
|
|
32701
32701
|
`),remoteHead.length&&socket.write(remoteHead),pending3.head.length&&remote.write(pending3.head),pending3.head=Buffer.alloc(0),socket.pipe(remote).pipe(socket),connection.touch?.(),recheck=setInterval(()=>{!live2()||!holds()?upgrade.close():connection.touch?.()},RECHECK_MS5),recheck.unref()}),upstream.end()},attach:upgrades2.attach,closeForOwner:(owner2,botId2)=>{let closed=0;for(let viewer of viewers.values())viewer.owner!==owner2||botId2!==void 0&&viewer.botId!==botId2||viewer.socket.destroyed||
|
|
32702
|
-
(viewer.close(),closed++);return closed},closeAll:()=>{stopped=!0,ownGate&&upgrades2.close();for(let viewer of viewers.values())viewer.close()}}}import{createReadStream as createReadStream13,rmSync as rmSync67}from"node:fs";import{dirname as
|
|
32702
|
+
(viewer.close(),closed++);return closed},closeAll:()=>{stopped=!0,ownGate&&upgrades2.close();for(let viewer of viewers.values())viewer.close()}}}import{createReadStream as createReadStream13,rmSync as rmSync67}from"node:fs";import{dirname as dirname88,join as join279}from"node:path";import{Readable as Readable3,Transform as Transform20}from"node:stream";var LIVE2=/^\/api\/bots\/([\w-]+)\/browser\/(live|action)$/,STREAM=/^\/api\/bots\/([\w-]+)\/browser\/stream$/,UPLOAD2=/^\/api\/bots\/([\w-]+)\/browser\/upload$/,DOWNLOAD=/^\/api\/bots\/([\w-]+)\/browser\/download\/([\w-]{1,64})$/,CHOOSER=/^[\w-]{1,64}$/,UPLOAD_MAX_FILES=20,PICKER_CLOSED="The page's file picker is no longer open.",ownerOf2=auth=>auth.kind==="session"?auth.session.id:"local-owner",UploadError=class extends Error{status;constructor(status5,message8){super(message8),this.status=status5}};
|
|
32703
32703
|
async function uploadedFiles(req){let type4=String(req.headers["content-type"]??"");if(!/^multipart\/form-data;/i.test(type4))throw new UploadError(415,"Send the files as multipart form data.");if(Number(req.headers["content-length"])>104857600)throw new UploadError(413,"Those files are larger than 100 MB in all.");let bytes4=0,limited=req.pipe(new Transform20({transform(chunk,_encoding,done){bytes4+=chunk.length,done(bytes4>104857600?new UploadError(413,"Those files are larger than 100 MB in al\
|
|
32704
32704
|
l."):null,chunk)}}));req.once("error",error66=>limited.destroy(error66));let form2;try{form2=await new Request("http://upload.invalid/",{method:"POST",headers:{"content-type":type4},body:Readable3.toWeb(limited),duplex:"half"}).formData()}catch(error66){throw error66 instanceof UploadError?error66:bytes4>104857600?new UploadError(413,"Those files are larger than 100 MB in all."):new UploadError(400,"The upload was not valid form data.")}let files2=form2.getAll("file").filter(entry2=>typeof entry2!=
|
|
32705
32705
|
"string");if(files2.length>UPLOAD_MAX_FILES)throw new UploadError(413,`A page takes at most ${UPLOAD_MAX_FILES} files at once.`);return Promise.all(files2.map(async file2=>({name:file2.name,bytes:new Uint8Array(await file2.arrayBuffer())})))}async function answerUpload(req,deps,browser,owner2,chooser){let files2;try{files2=await uploadedFiles(req)}catch(error66){if(!(error66 instanceof UploadError))throw error66;return{status:error66.status,error:error66.message,unread:!0}}let paths2=storeUploads(
|
|
32706
|
-
files2,join279(deps.dataDir,"browser-uploads"));if(await deps.viewers.answerFileChooser(browser,owner2,chooser,paths2).catch(()=>!1))return null;for(let file2 of paths2)rmSync67(
|
|
32706
|
+
files2,join279(deps.dataDir,"browser-uploads"));if(await deps.viewers.answerFileChooser(browser,owner2,chooser,paths2).catch(()=>!1))return null;for(let file2 of paths2)rmSync67(dirname88(file2),{recursive:!0,force:!0});return{status:409,error:PICKER_CLOSED}}function createBrowserViewerRoutes(deps){deps.upgrades.route(path8=>STREAM.test(path8));let uploading=new Set;return async({req,res,url:url3,path:path8,method:method2,auth,json:json7,readBody:readBody2})=>{let live2=LIVE2.exec(path8),stream2=live2?
|
|
32707
32707
|
null:STREAM.exec(path8),upload=live2||stream2?null:UPLOAD2.exec(path8),download2=live2||stream2||upload?null:DOWNLOAD.exec(path8),botId2=(live2??stream2??upload??download2)?.[1];if(!botId2)return PASS;res.setHeader("cache-control","no-store");let pending3=stream2?deps.upgrades.pending(req):void 0;if(stream2){if(method2!=="GET")return json7(res,405,{error:"method not allowed"});if(!pending3)return json7(res,426,{error:"WebSocket upgrade required"});if(!isSameOrigin(req))return json7(res,403,{error:"\
|
|
32708
32708
|
forbidden: cross-origin request"})}let threadId=url3.searchParams.get("threadId"),audience2=deps.audience(auth,threadId);if(!audience2)return json7(res,404,{error:"no such conversation"});let browser=await deps.browser(botId2,audience2);if("error"in browser)return json7(res,browser.status,{error:browser.error});let failure12=await deps.authorize(req,auth);if(failure12)return json7(res,failure12.status,{error:failure12.error});let owner2=ownerOf2(auth),person2=deps.person(auth),isCurrent=()=>deps.
|
|
32709
32709
|
audience(auth,threadId)===audience2&&deps.current(browser.botId,browser.session,auth,audience2);if(live2){if(method2==="GET"&&live2[2]==="live"){req.socket.setTimeout(0);let size3=requestedSize(Number(url3.searchParams.get("width")),Number(url3.searchParams.get("height")));return await deps.viewers.open({botId:browser.botId,session:browser.session,spec:browser.spec,owner:owner2,person:person2,isCurrent,res,resume:url3.searchParams.get("resume"),size:size3})}if(method2==="POST"&&live2[2]==="actio\
|
|
@@ -32763,7 +32763,7 @@ key7&&forgetKey(key7);if(postiz2?.configSaved(patch2),registry3.forgetSnapshots(
|
|
|
32763
32763
|
for(let request10 of browserCleanupRequests)request10.kind==="profile"&&browserLive2.closeForSession(browserSessionId("",request10.partitionId));for(let{session,spec}of browsersToClose)browserLive2.closeForSession(session),usedBrowserSessions2.delete(session),closeBrowser2(session,spec).then(closed=>{closed||console.warn(`browser ${session}: could not close it after its browser changed; the next turn may still use the old one`)});if(patch2.browserProfiles!==void 0){let retained=new Set(patch2.browserProfiles.
|
|
32764
32764
|
map(profile=>profile.id));try{for(let bot of store5.bots)bot.browserProfile&&bot.browserProfile!=="guest"&&!retained.has(bot.browserProfile)&&store5.patchBot(bot.id,{browserProfile:void 0})}catch(error66){browserReferenceCleanupError=error66}}let changedEngines=new Set(changedInstanceIds(enginesBefore,engineLaunches(providerConfigs2())));revokeEngineCapabilities2(changedEngines);let finalized=await finalizeBrowserCleanupMutation({requests:browserCleanupRequests,referenceError:browserReferenceCleanupError,
|
|
32765
32765
|
commit:request10=>browserCleanup2.commit(request10),ensure:request10=>browserCleanup2.ensure(request10),mandatory:async()=>{let mandatoryError=null;if(changedEngines.size>0)try{await reloadProviders2(enginesBefore)}catch(error66){mandatoryError||(mandatoryError=error66)}let status5=configStatus2();if(broadcast2({kind:"config",...status5}),patch2.threads!==void 0&&drainQueuedSends2(),mandatoryError)throw mandatoryError;return status5}});return requireBrowserCleanupAcknowledged(finalized.acknowledgements.
|
|
32766
|
-
every(Boolean),removedBrowserProfileIds.length===1?"The browser profile":"The browser profiles"),json7(res,200,configForAccess2(finalized.value,auth))}finally{for(let provider of transitioningProviders)computerProviderConfigTransitions2.delete(provider);changingLocalVmMode&&localVmModeChangeBusy2.set(!1),providerConfigBusy2.set(!1)}}return PASS}}init_user_errors();init_provider_icon();import{randomUUID as randomUUID89}from"node:crypto";import{dirname as
|
|
32766
|
+
every(Boolean),removedBrowserProfileIds.length===1?"The browser profile":"The browser profiles"),json7(res,200,configForAccess2(finalized.value,auth))}finally{for(let provider of transitioningProviders)computerProviderConfigTransitions2.delete(provider);changingLocalVmMode&&localVmModeChangeBusy2.set(!1),providerConfigBusy2.set(!1)}}return PASS}}init_user_errors();init_provider_icon();import{randomUUID as randomUUID89}from"node:crypto";import{dirname as dirname89}from"node:path";var FALLBACK="Run `claude update` in Terminal, then refresh Engines.",CLAUDE_CODE_PACKAGE="@anthropic-ai/claude-code";function isAppInstalledClaude(cli,binDir=enginesBinDir()){let resolved2=findCliCandidates(cli)[0];return resolved2!==void 0&&dirname89(resolved2)===binDir}var appCopy={owns:cli=>isAppInstalledClaude(cli),reinstall:(cli,env)=>installNpmEngine(CLAUDE_CODE_PACKAGE,{cli,env})};function stderrOf2(error66){let stderr=error66.stderr;return typeof stderr=="string"?stderr:Buffer.isBuffer(
|
|
32767
32767
|
stderr)?stderr.toString("utf8"):""}function run11(execute2,cli,args,options2){return new Promise((resolve59,reject)=>{execute2(cli,args,options2,(error66,stdout,stderr)=>{error66?(error66.stderr===void 0&&stderr&&Object.assign(error66,{stderr}),reject(error66)):resolve59(stdout)})})}function updateFailure(error66,cli){let err2=error66 instanceof Error?error66:new Error(String(error66)),processError=err2;if(processError.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return new Error(`Claude update pr\
|
|
32768
32768
|
oduced too much output. ${FALLBACK}`);if(typeof processError.code=="string")return new Error(`${describeSpawnFailure(processError,cli).message}. ${FALLBACK}`);if(processError.killed)return new Error(`Claude update timed out after 3 minutes. ${FALLBACK}`);let detail=(stderrOf2(err2).trim()||err2.message).split(`
|
|
32769
32769
|
`)[0].slice(0,400);return new Error(`Claude update failed${detail?`: ${detail}`:""}. ${FALLBACK}`)}async function updateClaudeCli(cli,env,execute2=execCli,own4=appCopy){if(own4.owns(cli))try{await own4.reinstall(cli,env)}catch(error66){let message8=error66 instanceof Error?error66.message:String(error66);throw new Error(`Claude update failed: ${message8}`)}else try{await run11(execute2,cli,["update"],{env,timeout:18e4,killSignal:"SIGKILL",maxBuffer:1024*1024})}catch(error66){throw updateFailure(
|