"use strict";(()=>{var a={};a.id=83032,a.ids=[83032],a.modules={16698:a=>{a.exports=require("node:async_hooks")},22911:(a,b,c)=>{c.r(b),c.d(b,{handler:()=>Q,patchFetch:()=>P,routeModule:()=>L,serverHooks:()=>O,workAsyncStorage:()=>M,workUnitAsyncStorage:()=>N});var d={};c.r(d),c.d(d,{POST:()=>K,dynamic:()=>I,runtime:()=>J});var e=c(940527),f=c(41752),g=c(633335),h=c(573615),i=c(301769),j=c(200261),k=c(405563),l=c(439285),m=c(443399),n=c(295860),o=c(161730),p=c(728392),q=c(976618),r=c(406527),s=c(986439),t=c(975973),u=c(323054),v=c(561766),w=c(973024),x=c(176760),y=c(693349),z=c(612839),A=c(214873),B=c(304279);function C(a){return null==a?"NULL":"boolean"==typeof a?a?"true":"false":"number"==typeof a?Number.isFinite(a)?String(a):"NULL":`'${a.replace(/'/g,"''")}'`}async function D(a,b){let c=a.email_message;for(let a of["From","To","Cc","Subject","Gmail Message ID","Sender Type"])if(!c[a]&&"Sender Type"!==a)throw Error(`email_message field map is missing "${a}" — schema migration didn't run.`);let d=c.From,e=c.To,f=c.Cc,g=c.Subject,h=c["Gmail Message ID"],i=c["Sender Type"],j=await (0,y.AI)(`
    SELECT
      e.id AS entry_id,
      MAX(CASE WHEN ef.field_id = '${h}' THEN ef.value END) AS message_id,
      MAX(CASE WHEN ef.field_id = '${g}' THEN ef.value END) AS subject,
      MAX(CASE WHEN ef.field_id = '${d}' THEN ef.value END) AS from_relation,
      MAX(CASE WHEN ef.field_id = '${e}' THEN ef.value END) AS to_relation,
      MAX(CASE WHEN ef.field_id = '${f}' THEN ef.value END) AS cc_relation,
      ${i?`MAX(CASE WHEN ef.field_id = '${i}' THEN ef.value END)`:"NULL"} AS sender_type
    FROM entries e
    LEFT JOIN entry_fields ef ON ef.entry_id = e.id
    WHERE e.object_id = '${z.zq.email_message}'
    GROUP BY e.id;
  `),k=a.people["Email Address"],l=k?await (0,y.AI)(`
        SELECT entry_id, value FROM entry_fields WHERE field_id = '${k}';
      `):[],m=new Map;for(let a of l)a.value&&m.set(a.entry_id,a.value.toLowerCase());let n=[];for(let a of j){let b=a.from_relation?.trim()||null,c=b?m.get(b)??null:null,d=E(a.to_relation).map(a=>m.get(a)).filter(a=>!!a),e=E(a.cc_relation).map(a=>m.get(a)).filter(a=>!!a);n.push({entryId:a.entry_id,messageId:a.message_id,subject:a.subject??"",fromAddress:c,fromRelationEntryId:b,toAddresses:d,ccAddresses:e,labelIds:[],headers:[],currentSenderType:a.sender_type})}return n}function E(a){if(!a)return[];let b=a.trim();if(!b)return[];if(b.startsWith("["))try{let a=JSON.parse(b);if(Array.isArray(a))return a.map(String).filter(Boolean)}catch{}return[b]}async function F(a={}){let b=await (0,y.Jv)();if(!b)return{ok:!1,messagesProcessed:0,messagesReclassified:0,messagesDemoted:0,fromRelationsCleared:0,interactionsDeleted:0,peopleDeleted:0,companiesDeleted:0,backupPath:null,error:"No workspace database found."};let c={email_message:await (0,z.W3)(z.zq.email_message),people:await (0,z.W3)(z.zq.people),company:await (0,z.W3)(z.zq.company),interaction:await (0,z.W3)(z.zq.interaction)},d=a.selfEmails??new Set,e=await D(c,d),f=new Set;for(let a of e)a.fromAddress&&f.add(a.fromAddress.toLowerCase());let g={ok:!0,messagesProcessed:e.length,messagesReclassified:0,messagesDemoted:0,fromRelationsCleared:0,interactionsDeleted:0,peopleDeleted:0,companiesDeleted:0,backupPath:null},h=(0,x.join)((0,y.lA)(),"cleanup-backups");(0,w.mkdirSync)(h,{recursive:!0});let i=(0,x.join)(h,`${new Date().toISOString().replace(/[:.]/g,"-")}.jsonl`),j=[],k=c.email_message["Sender Type"],l=c.email_message.From,m=c.interaction.Email,n=c.interaction.Person;if(!k)return{...g,ok:!1,error:"Sender Type field is missing — schema migration didn't run."};let o=[],p=new Set,q=new Set;for(let a of e){let b=(0,A.C)({fromAddress:a.fromAddress,toAddresses:a.toAddresses,ccAddresses:a.ccAddresses,selfEmails:d,subject:a.subject,labelIds:a.labelIds,getHeader:()=>null,senderIsKnownContact:!!a.fromAddress&&f.has(a.fromAddress.toLowerCase())}),c=function(a){switch(a){case"person":return"Person";case"marketing":return"Marketing";case"transactional":return"Transactional";case"notification":return"Notification";case"mailing_list":return"Mailing List";case"automated":return"Automated"}}(b.kind);a.currentSenderType!==c&&(g.messagesReclassified+=1,o.push(`DELETE FROM entry_fields WHERE entry_id = ${C(a.entryId)} AND field_id = ${C(k)}`),o.push(`INSERT INTO entry_fields (entry_id, field_id, value) VALUES (${C(a.entryId)}, ${C(k)}, ${C(c)})`)),b.isBulk&&(g.messagesDemoted+=1,p.add(a.entryId),a.fromRelationEntryId&&(q.add(a.fromRelationEntryId),j.push(JSON.stringify({kind:"email_message_from_relation",messageEntryId:a.entryId,messageId:a.messageId,fromRelationEntryId:a.fromRelationEntryId,fromAddress:a.fromAddress,verdict:b.kind})),l&&(o.push(`DELETE FROM entry_fields WHERE entry_id = ${C(a.entryId)} AND field_id = ${C(l)}`),g.fromRelationsCleared+=1)))}if(p.size>0&&m&&n){let a=Array.from(p).map(C).join(", "),b=await (0,y.AI)(`
      SELECT
        e.id AS interaction_entry_id,
        MAX(CASE WHEN ef.field_id = '${n}' THEN ef.value END) AS person_entry_id
      FROM entries e
      JOIN entry_fields ef_email
        ON ef_email.entry_id = e.id
       AND ef_email.field_id = '${m}'
       AND ef_email.value IN (${a})
      LEFT JOIN entry_fields ef ON ef.entry_id = e.id
      WHERE e.object_id = '${z.zq.interaction}'
      GROUP BY e.id;
    `);if(b.length>0){let a=b.map(a=>a.interaction_entry_id);for(let c of(g.interactionsDeleted=a.length,b))c.person_entry_id&&q.add(c.person_entry_id),j.push(JSON.stringify({kind:"interaction",interactionEntryId:c.interaction_entry_id,personEntryId:c.person_entry_id}));let c=a.map(C).join(", ");o.push(`DELETE FROM entry_fields WHERE entry_id IN (${c})`),o.push(`DELETE FROM entries WHERE id IN (${c})`)}}if(o.length>0&&!await (0,y.eI)(b,o.join(";\n")+";"))return G(i,j),g.backupPath=i,{...g,ok:!1,error:"Failed to apply reclassification + demotion batch."};let r=c.people["Email Address"],s=c.people.Source;if(q.size>0){let a=Array.from(q).map(C).join(", "),c=await (0,y.AI)(`
      SELECT
        e.id AS person_id,
        MAX(CASE WHEN ef.field_id = '${r??""}' THEN ef.value END) AS email
      FROM entries e
      LEFT JOIN entry_fields ef ON ef.entry_id = e.id
      WHERE e.object_id = '${z.zq.people}'
        AND e.id IN (${a})
        AND NOT EXISTS (
          SELECT 1 FROM entry_fields i
          WHERE i.field_id = '${n??""}'
            AND i.value = e.id
        )
        AND NOT EXISTS (
          SELECT 1 FROM entry_fields f
          WHERE f.field_id = '${l??""}'
            AND f.value = e.id
        )
        AND ${s?`EXISTS (SELECT 1 FROM entry_fields s WHERE s.entry_id = e.id AND s.field_id = '${s}' AND s.value = 'Gmail')`:"true"}
      GROUP BY e.id;
    `);if(c.length>0){for(let a of(g.peopleDeleted=c.length,c))j.push(JSON.stringify({kind:"person",personEntryId:a.person_id,email:a.email}));let a=c.map(a=>a.person_id).map(C).join(", ");if(!await (0,y.eI)(b,`DELETE FROM entry_fields WHERE entry_id IN (${a});
DELETE FROM entries WHERE id IN (${a});`))return G(i,j),g.backupPath=i,{...g,ok:!1,error:"Failed to delete orphaned People rows."}}}let t=c.company.Domain,u=c.company.Source;if(t){let a=await (0,y.AI)(`
      SELECT
        e.id AS company_id,
        MAX(CASE WHEN ef.field_id = '${t}' THEN ef.value END) AS domain
      FROM entries e
      LEFT JOIN entry_fields ef ON ef.entry_id = e.id
      WHERE e.object_id = '${z.zq.company}'
        AND ${u?`EXISTS (SELECT 1 FROM entry_fields s WHERE s.entry_id = e.id AND s.field_id = '${u}' AND s.value = 'Gmail')`:"true"}
        AND NOT EXISTS (
          SELECT 1 FROM entry_fields p
          JOIN entry_fields domain_ef
            ON domain_ef.entry_id = e.id
           AND domain_ef.field_id = '${t}'
          WHERE p.field_id = '${c.people["Email Address"]??""}'
            AND LOWER(SPLIT_PART(p.value, '@', 2)) LIKE '%' || domain_ef.value
        )
      GROUP BY e.id;
    `);if(a.length>0){for(let b of(g.companiesDeleted=a.length,a))j.push(JSON.stringify({kind:"company",companyEntryId:b.company_id,domain:b.domain}));let c=a.map(a=>a.company_id).map(C).join(", ");if(!await (0,y.eI)(b,`DELETE FROM entry_fields WHERE entry_id IN (${c});
DELETE FROM entries WHERE id IN (${c});`))return G(i,j),g.backupPath=i,{...g,ok:!1,error:"Failed to delete orphaned Company rows."}}}try{await (0,B.lf)()}catch{}return G(i,j),g.backupPath=i,g}function G(a,b){try{(0,w.writeFileSync)(a,b.join("\n")+(b.length>0?"\n":""),"utf-8")}catch{}}var H=c(43182);let I="force-dynamic",J="nodejs";async function K(a){let b={};try{b=await a.json().catch(()=>({}))}catch{b={}}let c=null;if(!0===b.cleanup)try{c=await F(),(0,H.Hk)("onboarding_email_cleanup_ran",{ok:c.ok,demoted:c.messagesDemoted,people_deleted:c.peopleDeleted,companies_deleted:c.companiesDeleted})}catch(a){c={ok:!1,messagesProcessed:0,messagesReclassified:0,messagesDemoted:0,fromRelationsCleared:0,interactionsDeleted:0,peopleDeleted:0,companiesDeleted:0,backupPath:null,error:a instanceof Error?a.message:"Cleanup failed."}}!0===b.restart&&(0,v.s6)({gmail:{backfillPageToken:null,historyId:void 0,messagesProcessed:0,lastBackfillCompletedAt:void 0},calendar:{backfillPageToken:null,syncToken:void 0,eventsProcessed:0,lastBackfillCompletedAt:void 0}});let d=(0,u.nv)({});return d.started||d.alreadyRunning?((0,H.Hk)("onboarding_sync_started",{already_running:d.alreadyRunning,restart:!0===b.restart,cleanup:!0===b.cleanup}),Response.json({started:d.started,alreadyRunning:d.alreadyRunning,cleanup:c})):Response.json({error:d.reason??"Could not start sync.",cleanup:c},{status:400})}let L=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/onboarding/sync/start/route",pathname:"/api/onboarding/sync/start",filename:"route",bundlePath:"app/api/onboarding/sync/start/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/runner/work/DenchClaw/DenchClaw/apps/web/app/api/onboarding/sync/start/route.ts",nextConfigOutput:"standalone",userland:d}),{workAsyncStorage:M,workUnitAsyncStorage:N,serverHooks:O}=L;function P(){return(0,g.patchFetch)({workAsyncStorage:M,workUnitAsyncStorage:N})}async function Q(a,b,c){var d;let e="/api/onboarding/sync/start/route";"/index"===e&&(e="/");let g=await L.prepare(a,b,{srcPage:e,multiZoneDraftMode:!1});if(!g)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:u,params:v,nextConfig:w,isDraftMode:x,prerenderManifest:y,routerServerContext:z,isOnDemandRevalidate:A,revalidateOnlyGenerated:B,resolvedPathname:C}=g,D=(0,j.normalizeAppPath)(e),E=!!(y.dynamicRoutes[D]||y.routes[C]);if(E&&!x){let a=!!y.routes[C],b=y.dynamicRoutes[D];if(b&&!1===b.fallback&&!a)throw new s.NoFallbackError}let F=null;!E||L.isDev||x||(F="/index"===(F=C)?"/":F);let G=!0===L.isDev||!E,H=E&&!G,I=a.method||"GET",J=(0,i.getTracer)(),K=J.getActiveScopeSpan(),M={params:v,prerenderManifest:y,renderOpts:{experimental:{cacheComponents:!!w.experimental.cacheComponents,authInterrupts:!!w.experimental.authInterrupts},supportsDynamicResponse:G,incrementalCache:(0,h.getRequestMeta)(a,"incrementalCache"),cacheLifeProfiles:null==(d=w.experimental)?void 0:d.cacheLife,isRevalidate:H,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d)=>L.onRequestError(a,b,d,z)},sharedContext:{buildId:u}},N=new k.NodeNextRequest(a),O=new k.NodeNextResponse(b),P=l.NextRequestAdapter.fromNodeNextRequest(N,(0,l.signalFromNodeResponse)(b));try{let d=async c=>L.handle(P,M).finally(()=>{if(!c)return;c.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let d=J.getRootSpanAttributes();if(!d)return;if(d.get("next.span_type")!==m.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${d.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let e=d.get("next.route");if(e){let a=`${I} ${e}`;c.setAttributes({"next.route":e,"http.route":e,"next.span_name":a}),c.updateName(a)}else c.updateName(`${I} ${a.url}`)}),g=async g=>{var i,j;let k=async({previousCacheEntry:f})=>{try{if(!(0,h.getRequestMeta)(a,"minimalMode")&&A&&B&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let e=await d(g);a.fetchMetrics=M.renderOpts.fetchMetrics;let i=M.renderOpts.pendingWaitUntil;i&&c.waitUntil&&(c.waitUntil(i),i=void 0);let j=M.renderOpts.collectedTags;if(!E)return await (0,o.I)(N,O,e,M.renderOpts.pendingWaitUntil),null;{let a=await e.blob(),b=(0,p.toNodeOutgoingHttpHeaders)(e.headers);j&&(b[r.NEXT_CACHE_TAGS_HEADER]=j),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==M.renderOpts.collectedRevalidate&&!(M.renderOpts.collectedRevalidate>=r.INFINITE_CACHE)&&M.renderOpts.collectedRevalidate,d=void 0===M.renderOpts.collectedExpire||M.renderOpts.collectedExpire>=r.INFINITE_CACHE?void 0:M.renderOpts.collectedExpire;return{value:{kind:t.CachedRouteKind.APP_ROUTE,status:e.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:d}}}}catch(b){throw(null==f?void 0:f.isStale)&&await L.onRequestError(a,b,{routerKind:"App Router",routePath:e,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:H,isOnDemandRevalidate:A})},z),b}},l=await L.handleResponse({req:a,nextConfig:w,cacheKey:F,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:y,isRoutePPREnabled:!1,isOnDemandRevalidate:A,revalidateOnlyGenerated:B,responseGenerator:k,waitUntil:c.waitUntil});if(!E)return null;if((null==l||null==(i=l.value)?void 0:i.kind)!==t.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==l||null==(j=l.value)?void 0:j.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});(0,h.getRequestMeta)(a,"minimalMode")||b.setHeader("x-nextjs-cache",A?"REVALIDATED":l.isMiss?"MISS":l.isStale?"STALE":"HIT"),x&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let m=(0,p.fromNodeOutgoingHttpHeaders)(l.value.headers);return(0,h.getRequestMeta)(a,"minimalMode")&&E||m.delete(r.NEXT_CACHE_TAGS_HEADER),!l.cacheControl||b.getHeader("Cache-Control")||m.get("Cache-Control")||m.set("Cache-Control",(0,q.getCacheControlHeader)(l.cacheControl)),await (0,o.I)(N,O,new Response(l.value.body,{headers:m,status:l.value.status||200})),null};K?await g(K):await J.withPropagatedContext(a.headers,()=>J.trace(m.BaseServerSpan.handleRequest,{spanName:`${I} ${a.url}`,kind:i.SpanKind.SERVER,attributes:{"http.method":I,"http.target":a.url}},g))}catch(b){if(b instanceof s.NoFallbackError||await L.onRequestError(a,b,{routerKind:"App Router",routePath:D,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:H,isOnDemandRevalidate:A})}),E)throw b;return await (0,o.I)(N,O,new Response(null,{status:500})),null}}},43182:(a,b,c)=>{let d,e;c.d(b,{Cl:()=>n,Hk:()=>s,ZW:()=>o,_A:()=>q,qU:()=>p});var f=c(977598),g=c(973024),h=c(848161),i=c(176760),j=c(53536);let k="phc_Nt8s1Ny8062TY9aKT8LWiB4nBuoHNYQXRU9MypWfQCW",l=null,m=null;function n(){if(m)return m;try{let a=(0,i.join)(process.env.HOME||(0,h.homedir)(),".openclaw-dench"),b=(0,i.join)(a,"telemetry.json"),c={};if((0,g.existsSync)(b)&&(c=JSON.parse((0,g.readFileSync)(b,"utf-8"))),"string"==typeof c.anonymousId&&c.anonymousId)return m=c.anonymousId,c.anonymousId;let d=(0,f.randomUUID)();return c.anonymousId=d,(0,g.mkdirSync)((0,i.dirname)(b),{recursive:!0}),(0,g.writeFileSync)(b,JSON.stringify(c,null,2)+"\n","utf-8"),m=d,d}catch{let a=(0,f.randomUUID)();return m=a,a}}function o(a){try{let b=(0,i.join)(process.env.HOME||(0,h.homedir)(),".openclaw-dench"),c=(0,i.join)(b,"telemetry.json"),d={};if((0,g.existsSync)(c))try{d=JSON.parse((0,g.readFileSync)(c,"utf-8"))}catch{d={}}"string"==typeof a.name&&a.name.trim()&&(d.name=a.name.trim()),"string"==typeof a.email&&a.email.trim()&&(d.email=a.email.trim()),"string"==typeof a.avatar&&a.avatar.trim()&&(d.avatar=a.avatar.trim()),"string"==typeof a.denchOrgId&&a.denchOrgId.trim()&&(d.denchOrgId=a.denchOrgId.trim()),(0,g.mkdirSync)((0,i.dirname)(c),{recursive:!0}),(0,g.writeFileSync)(c,JSON.stringify(d,null,2)+"\n","utf-8")}catch{}return d=void 0,p()}function p(){if(void 0!==d)return d;try{let a=(0,i.join)(process.env.HOME||(0,h.homedir)(),".openclaw-dench"),b=(0,i.join)(a,"telemetry.json");if(!(0,g.existsSync)(b))return d=null,null;let c=JSON.parse((0,g.readFileSync)(b,"utf-8")),e={};return"string"==typeof c.name&&c.name&&(e.name=c.name),"string"==typeof c.email&&c.email&&(e.email=c.email),"string"==typeof c.avatar&&c.avatar&&(e.avatar=c.avatar),"string"==typeof c.denchOrgId&&c.denchOrgId&&(e.denchOrgId=c.denchOrgId),d=Object.keys(e).length>0?e:null}catch{return d=null,null}}function q(){if(void 0!==e)return e;try{let a=(0,i.join)(process.env.HOME||(0,h.homedir)(),".openclaw-dench"),b=(0,i.join)(a,"telemetry.json");if(!(0,g.existsSync)(b))return e=!0,!0;let c=JSON.parse((0,g.readFileSync)(b,"utf-8"));return e=!1!==c.privacyMode}catch{return e=!0,!0}}let r=!1;function s(a,b,c){let d=k?(l||(l=new j.f2(k,{host:"https://us.i.posthog.com",flushAt:10,flushInterval:3e4})),l):null;if(!d)return;let e=c||n();if(!r){r=!0;let a=p();a&&d.identify({distinctId:e,properties:function(a){let b={};return a.name&&(b.$name=a.name),a.email&&(b.$email=a.email),a.avatar&&(b.$avatar=a.avatar),a.denchOrgId&&(b.dench_org_id=a.denchOrgId),b}(a)})}d.capture({distinctId:e,event:a,properties:{...b,denchclaw_version:"4.0.0",openclaw_version:void 0}})}},51455:a=>{a.exports=require("node:fs/promises")},176760:a=>{a.exports=require("node:path")},200261:a=>{a.exports=require("next/dist/shared/lib/router/utils/app-paths")},257975:a=>{a.exports=require("node:util")},333873:a=>{a.exports=require("path")},380481:a=>{a.exports=require("node:readline")},529294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},663033:a=>{a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},710846:a=>{a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},719771:a=>{a.exports=require("process")},731421:a=>{a.exports=require("node:child_process")},744870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},848161:a=>{a.exports=require("node:os")},973024:a=>{a.exports=require("node:fs")},977598:a=>{a.exports=require("node:crypto")},979428:a=>{a.exports=require("buffer")},986439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")}};var b=require("../../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[76973,22137,53536,34531,93349,66131,27488,69169,99419,23054],()=>b(b.s=22911));module.exports=c})();