@flowe-ai/cli 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -8
- package/dist/{chunk-ZP43LZEQ.js → chunk-GUTZZ5P5.js} +4 -4
- package/dist/chunk-MM4EMTNC.js +1 -0
- package/dist/cli.js +58 -57
- package/dist/mcp-server.js +9 -9
- package/dist/session-client-2SS65HUQ.js +1 -0
- package/dist/ui/live-session.html +1 -1
- package/dist/ui/micro.html +6 -6
- package/package.json +1 -1
- package/skills/flowe/SKILL.md +3 -2
- package/dist/chunk-QVIYCUHZ.js +0 -1
- package/dist/session-client-74I2RBYA.js +0 -1
package/README.md
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
1
|
# @flowe-ai/cli
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
> Science-backed resets in your terminal and AI chat: 30–90 s micro-resets, live Quick and Deep Resets with Ada, and an MCP App for your AI tools.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
`flowe` runs 30–90 s micro-resets in your terminal with no account, live Quick and Deep Resets with Ada when you sign in, and **MCP App cards (SEP-1865)** inside Claude Desktop, Antigravity, Cursor and VS Code, with plain text in Codex and Claude Code.
|
|
6
6
|
|
|
7
|
-
Docs
|
|
7
|
+
Docs and a live demo: **[cli.flowe.ai](https://cli.flowe.ai)**
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
11
|
+
Fastest: paste this into your AI agent (Claude Code, Codex, Cursor, VS Code or Antigravity). It installs the CLI, connects the app and offers a first reset.
|
|
12
|
+
|
|
13
|
+
```text
|
|
14
|
+
Set up flowe for me: follow https://cli.flowe.ai/setup.md
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
By hand:
|
|
18
|
+
|
|
11
19
|
```bash
|
|
12
20
|
npm install -g @flowe-ai/cli
|
|
13
21
|
```
|
|
@@ -33,11 +41,11 @@ Supporting MCP Apps hosts mount Flowe's self-contained **Dusk + Peek** UI cards
|
|
|
33
41
|
|
|
34
42
|
| Tier | Duration | Auth | Command |
|
|
35
43
|
|---|---|---|---|
|
|
36
|
-
| **Micro-Resets** | 30–90s |
|
|
37
|
-
| **Quick Resets** | 5–15 min |
|
|
38
|
-
| **Deep Resets** |
|
|
44
|
+
| **Micro-Resets** | 30–90s | Free · no account | `flowe reset 60 --protocol box_breath` |
|
|
45
|
+
| **Quick Resets** | 5–15 min | Free account · 5 a week | `flowe quick logic_lock --ambient rain_window_soft` |
|
|
46
|
+
| **Deep Resets** | 30–50 min | Flowe Pro or your team | `flowe deep ht_burnout --open` |
|
|
39
47
|
|
|
40
|
-
###
|
|
48
|
+
### Micro-Resets
|
|
41
49
|
|
|
42
50
|
```bash
|
|
43
51
|
flowe reset # interactive picker
|
|
@@ -55,6 +63,10 @@ flowe quick logic_lock --ambient rain_window_soft
|
|
|
55
63
|
flowe deep ht_burnout --open # opens desktop or prints phone handoff QR
|
|
56
64
|
```
|
|
57
65
|
|
|
66
|
+
### Flowe for Teams
|
|
67
|
+
|
|
68
|
+
Your team's Flowe Pro works in the CLI and the MCP server. Sign in with the email your admin invited; `flowe whoami` shows the team. See [cli.flowe.ai/docs/teams](https://cli.flowe.ai/docs/teams/).
|
|
69
|
+
|
|
58
70
|
### Focus Cycles & Voices
|
|
59
71
|
|
|
60
72
|
```bash
|
|
@@ -66,7 +78,7 @@ flowe voice ada | ellie | sage
|
|
|
66
78
|
|
|
67
79
|
## Privacy & Opt-Out
|
|
68
80
|
|
|
69
|
-
- **
|
|
81
|
+
- **No account needed:** All 12 micro-reset protocols work with no account and store only a local ID in `~/.config/flowe/config.json`.
|
|
70
82
|
- **Keychain tokens:** `flowe login` and inline MCP `flowe_auth` store credentials in your OS Keychain (falling back to `0600` local storage only if unavailable).
|
|
71
83
|
- **Zero code leaves your machine:** Never reads files, prompts, or repository paths.
|
|
72
84
|
- **Full opt-out:** Set `FLOWE_OPT_OUT=1` to disable telemetry and proactive MCP suggestions completely.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{a as W,c as Q,e as Y,i as G}from"./chunk-EC5WRPZP.js";import{readFileSync as ge}from"fs";import{dirname as ye,join as he}from"path";import{fileURLToPath as be}from"url";var xe=ye(be(import.meta.url));function H(){try{let e=ge(he(xe,"..","package.json"),"utf-8");return JSON.parse(e).version}catch{return"0.0.0"}}var at=["logic_lock","deploy_anxiety","context_switch","sprint_prep","quick_reset","executive_reset","presentation_prep","shutdown"],ct=["ht_stress","ht_anxiety","ht_people_pleasing","ht_relationships","ht_confidence","ht_fears","ht_anger","ht_procrastination","ht_burnout"];import{readFileSync as K}from"fs";import{dirname as Se,join as N}from"path";import{fileURLToPath as ve}from"url";var
|
|
1
|
+
import{a as W,c as Q,e as Y,i as G}from"./chunk-EC5WRPZP.js";import{readFileSync as ge}from"fs";import{dirname as ye,join as he}from"path";import{fileURLToPath as be}from"url";var xe=ye(be(import.meta.url));function H(){try{let e=ge(he(xe,"..","package.json"),"utf-8");return JSON.parse(e).version}catch{return"0.0.0"}}var at=["logic_lock","deploy_anxiety","context_switch","sprint_prep","quick_reset","executive_reset","presentation_prep","shutdown"],ct=["ht_stress","ht_anxiety","ht_people_pleasing","ht_relationships","ht_confidence","ht_fears","ht_anger","ht_procrastination","ht_burnout"];import{readFileSync as K}from"fs";import{dirname as Se,join as N}from"path";import{fileURLToPath as ve}from"url";var A=Se(ve(import.meta.url));function Ee(){return N(A,"..","protocols.json")}var g=null;function k(){if(g)return g;try{let e=K(Ee(),"utf-8");return g=JSON.parse(e),g}catch{return g={protocols:{},audio_paths:{},cues_paths:{}},g}}function D(){return Object.values(k().protocols)}function M(e){return e.replace(/_\d+$/,"")}function ft(){let e=new Set;for(let t of D())e.add(M(t.protocol_id));return[...e].sort()}function _t(e){return D().filter(t=>M(t.protocol_id)===e).map(t=>t.duration_seconds).sort((t,r)=>t-r)}function z(e,t){let r=D().filter(n=>n.duration_seconds===e&&(t===void 0||M(n.protocol_id)===t));return r.length===0?null:t!==void 0?r[0]:r[Math.floor(Math.random()*r.length)]}function X(e,t){let r=k(),n=`${e}.${t}`,o=r.audio_paths[n];return o?N(A,"..",o):null}var C=new Map;function Z(e,t){let r=`${e}.${t}`,n=C.get(r);if(n!==void 0)return n;let a=k().cues_paths?.[r];if(!a)return C.set(r,null),null;try{let s=K(N(A,"..",a),"utf-8"),i=JSON.parse(s);return C.set(r,i),i}catch{return C.set(r,null),null}}import{spawn as R}from"child_process";import{platform as Pe}from"os";var d=null;function ee(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?1:Math.min(2,Math.max(.05,e))}function we(e,t=1){let r=ee(t),n=Pe();if(n==="darwin"){let a=r===1?[e]:["-v",String(r),e];return R("afplay",a,{stdio:"ignore"})}if(n==="win32"){let s=["Add-Type -AssemblyName presentationCore;","$p = New-Object System.Windows.Media.MediaPlayer;",`$p.Open([Uri]'${e.replace(/'/g,"''")}');`,`$p.Volume = ${Math.min(1,r)};`,"$p.Play();","Start-Sleep -Milliseconds 300;","while ($p.Position -lt $p.NaturalDuration.TimeSpan -and $p.NaturalDuration.HasTimeSpan) { Start-Sleep -Milliseconds 200 };","$p.Close();"].join(" ");return R("powershell",["-NoProfile","-NonInteractive","-Command",s],{stdio:"ignore"})}let o=Math.round(32768*r);return R("mpg123",["-q","-f",String(o),e],{stdio:"ignore"})}function I(){return d!==null}function xt(){return d?.donePromise??null}function te(e,t={}){if(d)return Promise.reject(new Error("already playing \u2014 call stopAudio first"));let r=ee(t.volume),n=t.spawnPlayer??we,o;try{o=n(e,r)}catch(c){return Promise.reject(c instanceof Error?c:new Error(String(c)))}let a=!1,s=!1,i,u,p=new Promise((c,l)=>{i=c,u=l}),f=()=>{d?.child===o&&(d=null)},_=()=>{a||(a=!0,f(),i())},T=c=>{a||(a=!0,f(),u(c))};return d={child:o,stop:()=>{if(s=!0,f(),!o.killed)try{o.kill("SIGTERM")}catch{}_()},donePromise:p},o.once("error",c=>{if(s){_();return}let l=Object.assign(new Error(`audio playback failed: ${c.message}`),{code:"audio_device"});T(l)}),o.once("exit",(c,l)=>{if(s||l==="SIGTERM"||l==="SIGINT"||c===0||c===null){_();return}let O=Object.assign(new Error(`audio player exited with code ${c}`),{code:"audio_device"});T(O)}),p}function re(){d&&d.stop()}import{nanoid as $e}from"nanoid";import{readFileSync as Te,writeFileSync as Ce,mkdirSync as Fe,existsSync as L,appendFileSync as Oe}from"fs";import{homedir as Ne}from"os";import{join as oe}from"path";var $=oe(Ne(),".cache","flowe"),v=oe($,"pending-events.jsonl"),Ae=5e3;function ke(){let e=process.env.FLOWE_OPT_OUT?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}async function F(e,t,r){if(!(t.telemetry==="off"||ke())){De(),Me(e);try{await Ie(t,r)}catch{}}}function De(){L($)||Fe($,{recursive:!0})}function Me(e){for(let t of e)Oe(v,JSON.stringify(t)+`
|
|
2
2
|
`,"utf-8")}function Re(){return L(v)?Te(v,"utf-8").split(`
|
|
3
|
-
`).filter(t=>t.trim().length>0).map(t=>JSON.parse(t)):[]}function ne(){L(v)&&Ce(v,"","utf-8")}async function Ie(e,t){let r=Re();if(r.length===0)return;let n={version:H(),platform:`${process.platform}-${process.arch}`,node_version:process.version},o=new AbortController,a=setTimeout(()=>o.abort(),
|
|
4
|
-
`,"utf-8"),se(n,r)}function Yt(){let e=ce();if(!y(e))return null;let t;try{t=V(e,"utf-8")}catch{return null}finally{j(e,{force:!0})}let r=t.trim().toLowerCase();return Qe.includes(r)?r:null}import{spawn as Ke}from"child_process";import{openSync as ze,closeSync as Xe}from"fs";var le="FLOWE_FOCUS_DAEMON",U="FLOWE_FOCUS_PRESET",de="FLOWE_FOCUS_AMBIENT_FILE",pe="FLOWE_FOCUS_AMBIENT_ID",
|
|
5
|
-
`)}export{H as a,at as b,ct as c,D as d,
|
|
3
|
+
`).filter(t=>t.trim().length>0).map(t=>JSON.parse(t)):[]}function ne(){L(v)&&Ce(v,"","utf-8")}async function Ie(e,t){let r=Re();if(r.length===0)return;let n={version:H(),platform:`${process.platform}-${process.arch}`,node_version:process.version},o=new AbortController,a=setTimeout(()=>o.abort(),Ae);try{let s={"Content-Type":"application/json"};t&&(s.Authorization=`Bearer ${t}`);let i=await fetch(`${e.backend_url}/api/v1/reset/log`,{method:"POST",headers:s,body:JSON.stringify({events:r,client:n,anonymous_id:e.anonymous_id}),signal:o.signal});(i.ok||i.status===401||i.status===400)&&ne()}finally{clearTimeout(a)}}function Le(e,t,r){if(e.length===0)return[];let o=t*1e3/e.length;return e.map((a,s)=>({label:a,mode:r,start_ms:Math.round(s*o),end_ms:Math.round((s+1)*o)}))}function Rt(){return I()?(re(),!0):!1}async function It(e,t="user_requested",r,n={}){let o=process.env.FLOWE_SILENT_AUDIO==="1"?"silent":n.audioMode??"local";if(o==="local"&&I())throw Object.assign(new Error("a reset is already running"),{code:"agent_busy"});let a=W(),s=n.voice??a.voice,i=z(e,r);if(!i){let _e=r?`${r} at ${e}s`:`${e}s`;throw Object.assign(new Error(`no protocol available for ${_e}`),{code:"protocol_unavailable"})}let u=X(i.protocol_id,s);if(o==="local"&&!u)throw Object.assign(new Error(`no audio available for ${i.protocol_id}:${s}`),{code:"protocol_unavailable"});let p=`reset_${$e(8)}`,f=new Date,_=Math.floor(f.getTime()/1e3),T=_+e;Q();let c=await G();await F([{type:"reset_started",session_id:p,protocol_id:i.protocol_id,duration_seconds:e,voice:s,trigger:t,client_timestamp:f.toISOString()}],a,c),o==="local"&&u&&te(u).then(()=>{if(n.recordOnComplete)try{Y()}catch{}F([{type:"reset_completed",session_id:p,protocol_id:i.protocol_id,duration_seconds:e,voice:s,trigger:t,client_timestamp:new Date().toISOString()}],a,c).catch(()=>{})}).catch(()=>{F([{type:"reset_abandoned",session_id:p,protocol_id:i.protocol_id,duration_seconds:e,voice:s,trigger:t,client_timestamp:new Date().toISOString()}],a,c).catch(()=>{})});let l=Z(i.protocol_id,s),O=l?l.cues:Le(i.text_cues,e,i.category);return{session_id:p,protocol:i.protocol_id,protocol_display_name:i.display_name,duration_seconds:e,voice:s,category:i.category,audio_mode:o,cues:O,rounds:i.rounds,status:"started",started_at_unix:_,ends_at_unix:T,message_for_user:`${e}s ${i.display_name} started \xB7 ${s}`}}import{existsSync as y,mkdirSync as Ve,readFileSync as V,renameSync as se,rmSync as j,writeFileSync as q}from"fs";import{homedir as je}from"os";import{join as h}from"path";var qe="state.json",Be="daemon.pid",Ue="control.txt",Je="daemon.log",We=3e4,Qe=["pause","resume","skip","quit"];function Ye(){return process.env.FLOWE_HOME??h(je(),".flowe")}function b(){return h(Ye(),"sessions","active")}function ae(){return h(b(),qe)}function B(){return h(b(),Be)}function ce(){return h(b(),Ue)}function ue(){return h(b(),Je)}function E(){let e=b();return y(e)||Ve(e,{recursive:!0}),e}function Bt(e){E();let t=ae(),r=`${t}.tmp`;q(r,JSON.stringify(e,null,2),"utf-8"),se(r,t)}function Ut(e={}){let t=ae();if(!y(t))return null;try{let r=V(t,"utf-8"),n=JSON.parse(r);if(n.version!==1)return null;let o=n;if(!Ge(o)||x()!==o.pid)return null;if(!w(o.pid,e.kill))return P(),null;let s=e.now??Date.now,i=e.staleAfterMs??We;return s()-o.updatedAt>i?null:o}catch{return null}}function Ge(e){return e.version===1&&typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)}function P(){let e=b();y(e)&&j(e,{recursive:!0,force:!0})}function ie(e=process.pid){E(),q(B(),String(e),"utf-8")}function x(){let e=B();if(!y(e))return null;try{let t=V(e,"utf-8").trim();if(t.length===0)return null;let r=Number(t);return!Number.isInteger(r)||r<=0?null:r}catch{return null}}function He(){let e=B();y(e)&&j(e,{force:!0})}function w(e,t=(r,n)=>{process.kill(r,n)}){if(!Number.isInteger(e)||e<=0)return!1;try{return t(e,0),!0}catch(r){return r.code==="EPERM"}}function Jt(e={}){let t=e.pidOverride??process.pid,r=x();return r!==null&&r!==t&&w(r,e.kill)?{kind:"busy",pid:r}:r!==null&&r!==t?(P(),ie(t),{kind:"swept",stalePid:r}):(ie(t),{kind:"acquired"})}function Wt(){He()}function Qt(e){let t=x();if(t===null||!w(t))throw t!==null&&P(),new Error("no active focus session");E();let r=ce(),n=`${r}.tmp`;q(n,`${e}
|
|
4
|
+
`,"utf-8"),se(n,r)}function Yt(){let e=ce();if(!y(e))return null;let t;try{t=V(e,"utf-8")}catch{return null}finally{j(e,{force:!0})}let r=t.trim().toLowerCase();return Qe.includes(r)?r:null}import{spawn as Ke}from"child_process";import{openSync as ze,closeSync as Xe}from"fs";var le="FLOWE_FOCUS_DAEMON",U="FLOWE_FOCUS_PRESET",de="FLOWE_FOCUS_AMBIENT_FILE",pe="FLOWE_FOCUS_AMBIENT_ID",me="FLOWE_FOCUS_BREAK_TYPE",fe="FLOWE_FOCUS_LONG_BREAK_TYPE",J=class extends Error{constructor(r){super(`a focus daemon is already running (pid ${r})`);this.existingPid=r;this.name="DaemonAlreadyRunningError"}existingPid};function Ze(e){let t={...process.env,[le]:"1",[U]:e.preset};return e.ambientFilePath&&(t[de]=e.ambientFilePath),e.ambientId&&(t[pe]=e.ambientId),e.breakType&&(t[me]=e.breakType),e.longBreakType&&(t[fe]=e.longBreakType),t}function Zt(e){let t=x();if(t!==null){if(w(t))throw new J(t);P()}E();let r=ue(),n=ze(r,"a"),o=e.spawnArgs?.cmd??process.execPath,a=e.spawnArgs?.args??[...process.execArgv,process.argv[1]??"","focus",e.preset],i=(e.spawnFn??Ke)(o,a,{detached:!0,stdio:["ignore",n,n],env:Ze(e)});if(Xe(n),i.unref(),i.pid===void 0)throw new Error("failed to spawn focus daemon (no pid returned)");let u=e.readyTimeoutMs??(e.spawnFn?0:1500);if(u>0&&!et(i.pid,u))throw new Error("focus daemon did not become ready");return{pid:i.pid,logPath:r}}function et(e,t){let r=Date.now()+t;for(;Date.now()<=r;){if(x()===e)return!0;tt(25)}return!1}function tt(e){let t=new SharedArrayBuffer(4),r=new Int32Array(t);Atomics.wait(r,0,0,e)}function er(){let e=process.env[U];if(e!=="pomodoro"&&e!=="dev"&&e!=="ultradian"&&e!=="test2"&&e!=="test5")throw new Error(`invalid ${U}: ${e??"(unset)"} \u2014 daemon child cannot start`);return{preset:e,ambientFilePath:process.env[de]||void 0,ambientId:process.env[pe]||void 0,breakType:process.env[me]||void 0,longBreakType:process.env[fe]||void 0}}function tr(){return process.env[le]==="1"}function rr(e){return[`detached. pid ${e.pid}.`,`logs: ${e.logPath}`,"status: flowe focus status","pause: flowe focus pause resume: flowe focus resume","skip: flowe focus skip quit: flowe focus quit"].join(`
|
|
5
|
+
`)}export{H as a,at as b,ct as c,D as d,ft as e,_t as f,xt as g,te as h,re as i,ke as j,Rt as k,It as l,Ye as m,Bt as n,Ut as o,P as p,Jt as q,Wt as r,Qt as s,Yt as t,J as u,Zt as v,er as w,tr as x,rr as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as y,d as v,e as C,i as f,j as D}from"./chunk-EC5WRPZP.js";var O="30\u201350 min",F=[{id:"quick_reset",name:"Reset",description:"Quick mental refresh between tasks.",duration_minutes:10,technique:"Yoga Nidra",category:"calm"},{id:"sprint_prep",name:"Lock In",description:"Before deep work or a focus sprint.",duration_minutes:10,technique:"Dopamine priming",category:"focus"},{id:"context_switch",name:"Clear",description:"After meetings, before code.",duration_minutes:8,technique:"Body scan",category:"focus"},{id:"shutdown",name:"Wind Down",description:"End of day, sleep transition.",duration_minutes:15,technique:"Breathing",category:"sleep"},{id:"logic_lock",name:"Unstuck",description:"When a problem keeps circling.",duration_minutes:10,technique:"Open focus",category:"focus"},{id:"deploy_anxiety",name:"Calm Down",description:"Heart racing, high stakes.",duration_minutes:5,technique:"Cyclic sighing",category:"calm"},{id:"executive_reset",name:"Defog",description:"Brain fog, decision fatigue.",duration_minutes:12,technique:"Quiet focus",category:"calm"},{id:"presentation_prep",name:"Steady",description:"Before a presentation or meeting.",duration_minutes:8,technique:"Grounding",category:"focus"}],I=[{id:"ht_stress",name:"Stress",hook:"For the days everything feels too much."},{id:"ht_anxiety",name:"Anxiety",hook:"For the racing 2 a.m. loop you cannot shake."},{id:"ht_people_pleasing",name:"People pleasing",hook:"When saying no still feels impossible."},{id:"ht_relationships",name:"Relationships",hook:"When the same fight keeps showing up."},{id:"ht_confidence",name:"Confidence",hook:"When imposter syndrome will not quiet down."},{id:"ht_fears",name:"Fears and phobias",hook:"For the freeze before the big moment."},{id:"ht_anger",name:"Anger",hook:"When the reaction is bigger than the trigger."},{id:"ht_procrastination",name:"Procrastination",hook:"For the task you cannot seem to start."},{id:"ht_burnout",name:"Burnout",hook:"When nothing feels like it refills you."}];function l(e,t){return Object.assign(new Error(t),{code:e})}function _(e){return(e?.backendUrl??y().backend_url).replace(/\/+$/,"")}async function Q(e={}){let t=e.fetch??globalThis.fetch,r=_(e),s;try{s=await t(`${r}/api/v1/cli/auth/start`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{throw l("network_error",`could not reach ${r}`)}if(!s.ok)throw l("network_error",`failed to start sign-in (${s.status})`);let n=await s.json();return{device_code:n.device_code,user_code:n.user_code,verification_uri:n.verification_uri,verification_uri_complete:n.verification_uri_complete,interval:n.interval,expires_at:n.expires_at}}async function U(e,t={}){let r=t.fetch??globalThis.fetch,s=t.setAuthToken??D,n=_(t),o;try{o=await r(`${n}/api/v1/cli/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e})})}catch{throw l("network_error",`could not reach ${n}`)}if(o.status===410)return{status:"expired"};if(!o.ok)throw l("network_error",`sign-in poll failed (${o.status})`);let i=await o.json();if(i.status==="authorized"&&i.token){await s(i.token);let c=await x({...t,getAuthToken:async()=>i.token}).catch(()=>({authenticated:!0,user_id:i.user_id,is_pro:!1,plan_type:"free"}));return c.first_name&&v(c.first_name),{status:"authorized",user_id:i.user_id,account:c}}return{status:"authorization_pending"}}async function x(e={}){let t=e.fetch??globalThis.fetch,r=e.getAuthToken??f,s=_(e),n=await r();if(!n)return{authenticated:!1,is_pro:!1,plan_type:"guest",quick_reset_quota:null};let o={Authorization:`Bearer ${n}`},[i,c,m]=await Promise.all([t(`${s}/api/v1/me`,{headers:o}).catch(()=>null),t(`${s}/api/v1/user/plan-status`,{headers:o}).catch(()=>null),t(`${s}/api/v1/quota/quick-reset`,{headers:o}).catch(()=>null)]);if(i?.status===401)return{authenticated:!1,is_pro:!1,plan_type:"guest",quick_reset_quota:null};let d=i?.ok?await i.json():null,a=c?.ok?await c.json():null,u=m?.ok?await m.json():null;d?.first_name&&v(d.first_name);let g=a?!a.is_quota_limited:u?.cap===-1;return{authenticated:!0,user_id:d?.user_id,first_name:d?.first_name??y().user_first_name??null,email:d?.email??null,is_pro:g,plan_type:a?.plan_type??(g?"pro":"free"),quick_reset_quota:u,team:a?.plan_source==="team"?q(a.team_info):null,team_paused:q(a?.team_paused)}}function q(e){return e?.team_name?{name:e.team_name,role:e.role??"member",status:e.status,trial_ends_at:e.trial_ends_at??null}:null}function P(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString("en-GB",{day:"numeric",month:"short",timeZone:"UTC"})}function z(e){switch(e.status){case"trial_ended":return`The free trial of your team plan (${e.name}) ended.`;case"canceled":return`Your team plan (${e.name}) is canceled.`;case"paused":return`Your team plan (${e.name}) is paused.`;default:return`Your team plan (${e.name}) is off.`}}function W(e){if(e.team){let t=e.team.status==="trialing"?P(e.team.trial_ends_at):null;return`team: ${e.team.name}${t?` \xB7 trial ends ${t}`:""}`}if(e.team_paused){let t=e.team_paused.status==="trial_ended"?"free trial ended":e.team_paused.status??"off";return`team: ${e.team_paused.name} \xB7 ${t} \xB7 ask your admin to turn it back on`}return null}function G(e){return e.is_pro?e.team?`Flowe Pro from ${e.team.name}`:"Flowe Pro":e.plan_type}async function J(e,t={}){let r=t.fetch??globalThis.fetch,s=t.getAuthToken??f,n=_(t),o=y(),i=await s();if(!i)throw l("auth_required","Sign in with Flowe to run live Quick and Deep Resets.");let c=e.tier==="deep"?"hypnotherapy":"nsdr",m=e.voice??o.voice,d=e.ambient??"none",a;try{a=await r(`${n}/api/v1/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({protocolId:c,sessionType:e.sessionType})})}catch{throw l("network_error","Network unreachable \u2014 try a local 30\u201390s micro-reset.")}if(!a.ok){let h=await a.json().catch(()=>({})),p=h?.error?.code,T=h?.error?.message??h?.message??`server error ${a.status}`;throw a.status===401?l("auth_required","Session expired \u2014 sign in to Flowe again."):a.status===403?l(p==="QUOTA_EXCEEDED"?"quota_exceeded":"subscription_required",T):l("network_error",T)}let u=await a.json(),g=`flowe://session/${u.session_id}`,b=`${n}/session/${u.session_id}`,S,k,w,A,R=[],$="waiting_for_join";if(e.startRoom!==!1)try{let h=await r(`${n}/api/v1/sessions/${encodeURIComponent(u.session_id)}/start`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({voiceId:m,ambient:d})});if(h.ok){let p=await h.json();S=p.room_name,k=p.livekit_url,w=p.livekit_token,A=p.current_phase,R=Array.isArray(p.phases)?p.phases:[],k&&w&&($="live")}}catch{}let E=e.tier==="deep"?"Deep Reset":"Quick Reset";return{session_id:u.session_id,tier:e.tier,protocol_id:u.protocol_id??c,session_type:u.session_type??e.sessionType,session_type_name:u.session_type_name,estimated_duration:u.estimated_duration,voice:m,ambient:d,room_name:S,livekit_url:k,livekit_token:w,current_phase:A,phases:R,join_url:g,web_url:b,status:$,requires_microphone:e.tier==="deep",message_for_user:`${E}: ${u.session_type_name} (${u.estimated_duration} min) ready \xB7 ${b}`}}async function M(e,t={},r={}){let s=r.fetch??globalThis.fetch,n=r.getAuthToken??f,o=_(r),i=await n();if(!i)throw l("auth_required","Sign in with Flowe first.");let c={};if(typeof t.durationMinutes=="number"&&(c.durationMinutes=t.durationMinutes),typeof t.rating=="number"&&(c.userFeedback={rating:t.rating,comments:t.comments}),(await s(`${o}/api/v1/sessions/${encodeURIComponent(e)}/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(c)})).ok){try{C()}catch{}return{completed:!0}}return{completed:!1}}async function Y(e,t={}){let r=t.fetch??globalThis.fetch,s=t.getAuthToken??f,n=_(t),o=await s();if(!o)return{cancelled:!1};try{return{cancelled:(await r(`${n}/api/v1/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${o}`}})).ok}}catch{return{cancelled:!1}}}export{O as a,F as b,I as c,Q as d,U as e,x as f,z as g,W as h,G as i,J as j,M as k,Y as l};
|